diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..97461d9 --- /dev/null +++ b/.classpath @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.cvsignore b/.cvsignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/.cvsignore @@ -0,0 +1 @@ +dist diff --git a/.project b/.project new file mode 100644 index 0000000..577cc17 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + j-Algo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + \ No newline at end of file diff --git a/.settings/CVS/Entries b/.settings/CVS/Entries new file mode 100644 index 0000000..8816426 --- /dev/null +++ b/.settings/CVS/Entries @@ -0,0 +1,4 @@ +D/CVS_backup//// +/org.eclipse.core.resources.prefs/1.1/Wed Dec 8 13:01:51 2010// +/org.eclipse.core.runtime.prefs/1.1/Wed Dec 8 13:01:51 2010// +/org.eclipse.jdt.ui.prefs/1.1/Mon Jan 28 17:45:43 2008// diff --git a/.settings/CVS/Repository b/.settings/CVS/Repository new file mode 100644 index 0000000..32ab986 --- /dev/null +++ b/.settings/CVS/Repository @@ -0,0 +1 @@ +j-algo/.settings diff --git a/.settings/CVS/Root b/.settings/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/.settings/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..cbde628 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Fri Nov 05 10:19:10 CET 2010 +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.core.runtime.prefs b/.settings/org.eclipse.core.runtime.prefs new file mode 100644 index 0000000..76502d0 --- /dev/null +++ b/.settings/org.eclipse.core.runtime.prefs @@ -0,0 +1,3 @@ +#Mon Dec 06 18:38:33 CET 2010 +eclipse.preferences.version=1 +line.separator=\n diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..0215336 --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,3 @@ +#Mon Jan 28 18:06:20 GMT+01:00 2008 +eclipse.preferences.version=1 +internal.default.compliance=default diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..dcfa4c2 --- /dev/null +++ b/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/CVS/Entries b/CVS/Entries new file mode 100644 index 0000000..d484563 --- /dev/null +++ b/CVS/Entries @@ -0,0 +1,24 @@ +/.classpath/1.22/Mon Jan 30 18:56:52 2012// +/.cvsignore/1.5/Mon Feb 18 20:53:48 2008// +/.project/1.3/Sat Aug 12 20:40:10 2006// +D/.settings//// +/COPYING/1.1.1.1/Sat Jul 17 21:04:38 2004// +D/bin//// +D/build//// +/build.xml/1.17/Tue Feb 14 08:41:20 2012// +D/distribution//// +D/doc//// +D/examples//// +D/extlibs//// +D/grammar//// +/j-Algo.bat/1.1/Thu Jun 29 19:42:56 2006/-kb/ +/j-Algo.ico/1.1/Mon Feb 18 20:53:48 2008/-kb/ +/j-Algo.sh/1.4/Mon Dec 1 13:17:36 2008/-kb/ +/module-manifest.mf/1.2/Thu Jun 29 19:42:56 2006/-kb/ +D/pix//// +/program-manifest.mf/1.2/Fri Aug 11 16:43:14 2006/-kb/ +D/relicts//// +D/res//// +D/runtime//// +D/src//// +D/tests//// diff --git a/CVS/Repository b/CVS/Repository new file mode 100644 index 0000000..6a6f7ef --- /dev/null +++ b/CVS/Repository @@ -0,0 +1 @@ +j-algo diff --git a/CVS/Root b/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/bin/CVS/Entries b/bin/CVS/Entries new file mode 100644 index 0000000..e69de29 diff --git a/bin/CVS/Repository b/bin/CVS/Repository new file mode 100644 index 0000000..29b3790 --- /dev/null +++ b/bin/CVS/Repository @@ -0,0 +1 @@ +j-algo/bin diff --git a/bin/CVS/Root b/bin/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/bin/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/bin/c00/AST$ASTTree.class b/bin/c00/AST$ASTTree.class new file mode 100644 index 0000000..877b11f Binary files /dev/null and b/bin/c00/AST$ASTTree.class differ diff --git a/bin/c00/AST$ActualParameters.class b/bin/c00/AST$ActualParameters.class new file mode 100644 index 0000000..1f7b105 Binary files /dev/null and b/bin/c00/AST$ActualParameters.class differ diff --git a/bin/c00/AST$AddIdFactor.class b/bin/c00/AST$AddIdFactor.class new file mode 100644 index 0000000..8aff8e0 Binary files /dev/null and b/bin/c00/AST$AddIdFactor.class differ diff --git a/bin/c00/AST$AssignStm.class b/bin/c00/AST$AssignStm.class new file mode 100644 index 0000000..7067b3e Binary files /dev/null and b/bin/c00/AST$AssignStm.class differ diff --git a/bin/c00/AST$Assignment.class b/bin/c00/AST$Assignment.class new file mode 100644 index 0000000..97c615a Binary files /dev/null and b/bin/c00/AST$Assignment.class differ diff --git a/bin/c00/AST$Block.class b/bin/c00/AST$Block.class new file mode 100644 index 0000000..0425231 Binary files /dev/null and b/bin/c00/AST$Block.class differ diff --git a/bin/c00/AST$BoolExpression.class b/bin/c00/AST$BoolExpression.class new file mode 100644 index 0000000..6b5ab89 Binary files /dev/null and b/bin/c00/AST$BoolExpression.class differ diff --git a/bin/c00/AST$BreakStm.class b/bin/c00/AST$BreakStm.class new file mode 100644 index 0000000..7c6166d Binary files /dev/null and b/bin/c00/AST$BreakStm.class differ diff --git a/bin/c00/AST$CaseSequence.class b/bin/c00/AST$CaseSequence.class new file mode 100644 index 0000000..b126c90 Binary files /dev/null and b/bin/c00/AST$CaseSequence.class differ diff --git a/bin/c00/AST$CompFactor.class b/bin/c00/AST$CompFactor.class new file mode 100644 index 0000000..e26931c Binary files /dev/null and b/bin/c00/AST$CompFactor.class differ diff --git a/bin/c00/AST$CompStm.class b/bin/c00/AST$CompStm.class new file mode 100644 index 0000000..28a0e0b Binary files /dev/null and b/bin/c00/AST$CompStm.class differ diff --git a/bin/c00/AST$ConstDecl.class b/bin/c00/AST$ConstDecl.class new file mode 100644 index 0000000..0b1b885 Binary files /dev/null and b/bin/c00/AST$ConstDecl.class differ diff --git a/bin/c00/AST$ConstDeclarations.class b/bin/c00/AST$ConstDeclarations.class new file mode 100644 index 0000000..8bf8101 Binary files /dev/null and b/bin/c00/AST$ConstDeclarations.class differ diff --git a/bin/c00/AST$ContinueStm.class b/bin/c00/AST$ContinueStm.class new file mode 100644 index 0000000..af296e6 Binary files /dev/null and b/bin/c00/AST$ContinueStm.class differ diff --git a/bin/c00/AST$Declaration.class b/bin/c00/AST$Declaration.class new file mode 100644 index 0000000..18f72b7 Binary files /dev/null and b/bin/c00/AST$Declaration.class differ diff --git a/bin/c00/AST$Declarations.class b/bin/c00/AST$Declarations.class new file mode 100644 index 0000000..720e773 Binary files /dev/null and b/bin/c00/AST$Declarations.class differ diff --git a/bin/c00/AST$DefaultSwitchBlock.class b/bin/c00/AST$DefaultSwitchBlock.class new file mode 100644 index 0000000..dad2141 Binary files /dev/null and b/bin/c00/AST$DefaultSwitchBlock.class differ diff --git a/bin/c00/AST$DivFirstTerm.class b/bin/c00/AST$DivFirstTerm.class new file mode 100644 index 0000000..7694067 Binary files /dev/null and b/bin/c00/AST$DivFirstTerm.class differ diff --git a/bin/c00/AST$DivTerm.class b/bin/c00/AST$DivTerm.class new file mode 100644 index 0000000..20a9b3a Binary files /dev/null and b/bin/c00/AST$DivTerm.class differ diff --git a/bin/c00/AST$DoWhileStm.class b/bin/c00/AST$DoWhileStm.class new file mode 100644 index 0000000..0698c00 Binary files /dev/null and b/bin/c00/AST$DoWhileStm.class differ diff --git a/bin/c00/AST$ElseIfStm.class b/bin/c00/AST$ElseIfStm.class new file mode 100644 index 0000000..b55456f Binary files /dev/null and b/bin/c00/AST$ElseIfStm.class differ diff --git a/bin/c00/AST$EmptyActParams.class b/bin/c00/AST$EmptyActParams.class new file mode 100644 index 0000000..402d996 Binary files /dev/null and b/bin/c00/AST$EmptyActParams.class differ diff --git a/bin/c00/AST$EmptyCaseSeq.class b/bin/c00/AST$EmptyCaseSeq.class new file mode 100644 index 0000000..02e8130 Binary files /dev/null and b/bin/c00/AST$EmptyCaseSeq.class differ diff --git a/bin/c00/AST$EmptyDecls.class b/bin/c00/AST$EmptyDecls.class new file mode 100644 index 0000000..c0eeb3b Binary files /dev/null and b/bin/c00/AST$EmptyDecls.class differ diff --git a/bin/c00/AST$EmptyFormalParams.class b/bin/c00/AST$EmptyFormalParams.class new file mode 100644 index 0000000..5b39611 Binary files /dev/null and b/bin/c00/AST$EmptyFormalParams.class differ diff --git a/bin/c00/AST$EmptyFuncImpls.class b/bin/c00/AST$EmptyFuncImpls.class new file mode 100644 index 0000000..45332e6 Binary files /dev/null and b/bin/c00/AST$EmptyFuncImpls.class differ diff --git a/bin/c00/AST$EmptyGlobDecls.class b/bin/c00/AST$EmptyGlobDecls.class new file mode 100644 index 0000000..6a3f3f6 Binary files /dev/null and b/bin/c00/AST$EmptyGlobDecls.class differ diff --git a/bin/c00/AST$EmptyReturnStm.class b/bin/c00/AST$EmptyReturnStm.class new file mode 100644 index 0000000..782a415 Binary files /dev/null and b/bin/c00/AST$EmptyReturnStm.class differ diff --git a/bin/c00/AST$EmptyStmSeq.class b/bin/c00/AST$EmptyStmSeq.class new file mode 100644 index 0000000..2baf8d6 Binary files /dev/null and b/bin/c00/AST$EmptyStmSeq.class differ diff --git a/bin/c00/AST$EqBoolExpr.class b/bin/c00/AST$EqBoolExpr.class new file mode 100644 index 0000000..5449da7 Binary files /dev/null and b/bin/c00/AST$EqBoolExpr.class differ diff --git a/bin/c00/AST$ExpandBlock.class b/bin/c00/AST$ExpandBlock.class new file mode 100644 index 0000000..a46aea3 Binary files /dev/null and b/bin/c00/AST$ExpandBlock.class differ diff --git a/bin/c00/AST$ExpandFuncCall.class b/bin/c00/AST$ExpandFuncCall.class new file mode 100644 index 0000000..660ede9 Binary files /dev/null and b/bin/c00/AST$ExpandFuncCall.class differ diff --git a/bin/c00/AST$ExpandProgram.class b/bin/c00/AST$ExpandProgram.class new file mode 100644 index 0000000..fa4a1a5 Binary files /dev/null and b/bin/c00/AST$ExpandProgram.class differ diff --git a/bin/c00/AST$ExprListActParams.class b/bin/c00/AST$ExprListActParams.class new file mode 100644 index 0000000..77fa531 Binary files /dev/null and b/bin/c00/AST$ExprListActParams.class differ diff --git a/bin/c00/AST$ExprPrintfStm.class b/bin/c00/AST$ExprPrintfStm.class new file mode 100644 index 0000000..7f2518e Binary files /dev/null and b/bin/c00/AST$ExprPrintfStm.class differ diff --git a/bin/c00/AST$ExprReturnStm.class b/bin/c00/AST$ExprReturnStm.class new file mode 100644 index 0000000..1f1368c Binary files /dev/null and b/bin/c00/AST$ExprReturnStm.class differ diff --git a/bin/c00/AST$Expression.class b/bin/c00/AST$Expression.class new file mode 100644 index 0000000..0768c61 Binary files /dev/null and b/bin/c00/AST$Expression.class differ diff --git a/bin/c00/AST$ExpressionList.class b/bin/c00/AST$ExpressionList.class new file mode 100644 index 0000000..b38275f Binary files /dev/null and b/bin/c00/AST$ExpressionList.class differ diff --git a/bin/c00/AST$Factor.class b/bin/c00/AST$Factor.class new file mode 100644 index 0000000..6cead25 Binary files /dev/null and b/bin/c00/AST$Factor.class differ diff --git a/bin/c00/AST$FactorFirstTerm.class b/bin/c00/AST$FactorFirstTerm.class new file mode 100644 index 0000000..be52b83 Binary files /dev/null and b/bin/c00/AST$FactorFirstTerm.class differ diff --git a/bin/c00/AST$FactorTerm.class b/bin/c00/AST$FactorTerm.class new file mode 100644 index 0000000..d3cf913 Binary files /dev/null and b/bin/c00/AST$FactorTerm.class differ diff --git a/bin/c00/AST$FirstTerm.class b/bin/c00/AST$FirstTerm.class new file mode 100644 index 0000000..97d4a15 Binary files /dev/null and b/bin/c00/AST$FirstTerm.class differ diff --git a/bin/c00/AST$FirstTermExpr.class b/bin/c00/AST$FirstTermExpr.class new file mode 100644 index 0000000..61e7d8f Binary files /dev/null and b/bin/c00/AST$FirstTermExpr.class differ diff --git a/bin/c00/AST$ForStm.class b/bin/c00/AST$ForStm.class new file mode 100644 index 0000000..30a5ec3 Binary files /dev/null and b/bin/c00/AST$ForStm.class differ diff --git a/bin/c00/AST$FormalParameters.class b/bin/c00/AST$FormalParameters.class new file mode 100644 index 0000000..d04479a Binary files /dev/null and b/bin/c00/AST$FormalParameters.class differ diff --git a/bin/c00/AST$FuncCallFactor.class b/bin/c00/AST$FuncCallFactor.class new file mode 100644 index 0000000..6c349e2 Binary files /dev/null and b/bin/c00/AST$FuncCallFactor.class differ diff --git a/bin/c00/AST$FuncCallStm.class b/bin/c00/AST$FuncCallStm.class new file mode 100644 index 0000000..adf7173 Binary files /dev/null and b/bin/c00/AST$FuncCallStm.class differ diff --git a/bin/c00/AST$FuncGlobDecls.class b/bin/c00/AST$FuncGlobDecls.class new file mode 100644 index 0000000..32d4242 Binary files /dev/null and b/bin/c00/AST$FuncGlobDecls.class differ diff --git a/bin/c00/AST$FunctionCall.class b/bin/c00/AST$FunctionCall.class new file mode 100644 index 0000000..3006dad Binary files /dev/null and b/bin/c00/AST$FunctionCall.class differ diff --git a/bin/c00/AST$FunctionHeading.class b/bin/c00/AST$FunctionHeading.class new file mode 100644 index 0000000..7eaed59 Binary files /dev/null and b/bin/c00/AST$FunctionHeading.class differ diff --git a/bin/c00/AST$FunctionImplementations.class b/bin/c00/AST$FunctionImplementations.class new file mode 100644 index 0000000..8a032a6 Binary files /dev/null and b/bin/c00/AST$FunctionImplementations.class differ diff --git a/bin/c00/AST$GlobalDeclarations.class b/bin/c00/AST$GlobalDeclarations.class new file mode 100644 index 0000000..f19c43b Binary files /dev/null and b/bin/c00/AST$GlobalDeclarations.class differ diff --git a/bin/c00/AST$GreatBoolExpr.class b/bin/c00/AST$GreatBoolExpr.class new file mode 100644 index 0000000..cdf759c Binary files /dev/null and b/bin/c00/AST$GreatBoolExpr.class differ diff --git a/bin/c00/AST$GreatEqBoolExpr.class b/bin/c00/AST$GreatEqBoolExpr.class new file mode 100644 index 0000000..b075c85 Binary files /dev/null and b/bin/c00/AST$GreatEqBoolExpr.class differ diff --git a/bin/c00/AST$IdFactor.class b/bin/c00/AST$IdFactor.class new file mode 100644 index 0000000..b67e7d6 Binary files /dev/null and b/bin/c00/AST$IdFactor.class differ diff --git a/bin/c00/AST$InitVarLastDecls.class b/bin/c00/AST$InitVarLastDecls.class new file mode 100644 index 0000000..68db2e0 Binary files /dev/null and b/bin/c00/AST$InitVarLastDecls.class differ diff --git a/bin/c00/AST$InitVarPairDecls.class b/bin/c00/AST$InitVarPairDecls.class new file mode 100644 index 0000000..fdf763c Binary files /dev/null and b/bin/c00/AST$InitVarPairDecls.class differ diff --git a/bin/c00/AST$IntFuncHead.class b/bin/c00/AST$IntFuncHead.class new file mode 100644 index 0000000..c7a917a Binary files /dev/null and b/bin/c00/AST$IntFuncHead.class differ diff --git a/bin/c00/AST$LabelStm.class b/bin/c00/AST$LabelStm.class new file mode 100644 index 0000000..53e9d24 Binary files /dev/null and b/bin/c00/AST$LabelStm.class differ diff --git a/bin/c00/AST$LastConstDecls.class b/bin/c00/AST$LastConstDecls.class new file mode 100644 index 0000000..1d43057 Binary files /dev/null and b/bin/c00/AST$LastConstDecls.class differ diff --git a/bin/c00/AST$LastExprList.class b/bin/c00/AST$LastExprList.class new file mode 100644 index 0000000..a0a8e5e Binary files /dev/null and b/bin/c00/AST$LastExprList.class differ diff --git a/bin/c00/AST$LessBoolExpr.class b/bin/c00/AST$LessBoolExpr.class new file mode 100644 index 0000000..63f7c3a Binary files /dev/null and b/bin/c00/AST$LessBoolExpr.class differ diff --git a/bin/c00/AST$LessEqBoolExpr.class b/bin/c00/AST$LessEqBoolExpr.class new file mode 100644 index 0000000..cceae02 Binary files /dev/null and b/bin/c00/AST$LessEqBoolExpr.class differ diff --git a/bin/c00/AST$MinusExpr.class b/bin/c00/AST$MinusExpr.class new file mode 100644 index 0000000..71df080 Binary files /dev/null and b/bin/c00/AST$MinusExpr.class differ diff --git a/bin/c00/AST$MinusFactorFirstTerm.class b/bin/c00/AST$MinusFactorFirstTerm.class new file mode 100644 index 0000000..3da6055 Binary files /dev/null and b/bin/c00/AST$MinusFactorFirstTerm.class differ diff --git a/bin/c00/AST$ModFirstTerm.class b/bin/c00/AST$ModFirstTerm.class new file mode 100644 index 0000000..b6025d2 Binary files /dev/null and b/bin/c00/AST$ModFirstTerm.class differ diff --git a/bin/c00/AST$ModTerm.class b/bin/c00/AST$ModTerm.class new file mode 100644 index 0000000..d7909f5 Binary files /dev/null and b/bin/c00/AST$ModTerm.class differ diff --git a/bin/c00/AST$MultFirstTerm.class b/bin/c00/AST$MultFirstTerm.class new file mode 100644 index 0000000..31f82b3 Binary files /dev/null and b/bin/c00/AST$MultFirstTerm.class differ diff --git a/bin/c00/AST$MultTerm.class b/bin/c00/AST$MultTerm.class new file mode 100644 index 0000000..a42340c Binary files /dev/null and b/bin/c00/AST$MultTerm.class differ diff --git a/bin/c00/AST$NoBreakPairCaseSeq.class b/bin/c00/AST$NoBreakPairCaseSeq.class new file mode 100644 index 0000000..7d41b72 Binary files /dev/null and b/bin/c00/AST$NoBreakPairCaseSeq.class differ diff --git a/bin/c00/AST$NoDefaultSwitchBlock.class b/bin/c00/AST$NoDefaultSwitchBlock.class new file mode 100644 index 0000000..947c104 Binary files /dev/null and b/bin/c00/AST$NoDefaultSwitchBlock.class differ diff --git a/bin/c00/AST$NonVoidFormalParams.class b/bin/c00/AST$NonVoidFormalParams.class new file mode 100644 index 0000000..2a9b762 Binary files /dev/null and b/bin/c00/AST$NonVoidFormalParams.class differ diff --git a/bin/c00/AST$NotEqBoolExpr.class b/bin/c00/AST$NotEqBoolExpr.class new file mode 100644 index 0000000..d0ab1d1 Binary files /dev/null and b/bin/c00/AST$NotEqBoolExpr.class differ diff --git a/bin/c00/AST$NumFactor.class b/bin/c00/AST$NumFactor.class new file mode 100644 index 0000000..baaf4b0 Binary files /dev/null and b/bin/c00/AST$NumFactor.class differ diff --git a/bin/c00/AST$PairConstDecls.class b/bin/c00/AST$PairConstDecls.class new file mode 100644 index 0000000..e5f30e9 Binary files /dev/null and b/bin/c00/AST$PairConstDecls.class differ diff --git a/bin/c00/AST$PairDecls.class b/bin/c00/AST$PairDecls.class new file mode 100644 index 0000000..d420cb0 Binary files /dev/null and b/bin/c00/AST$PairDecls.class differ diff --git a/bin/c00/AST$PairExprList.class b/bin/c00/AST$PairExprList.class new file mode 100644 index 0000000..7b43916 Binary files /dev/null and b/bin/c00/AST$PairExprList.class differ diff --git a/bin/c00/AST$PairFuncImpls.class b/bin/c00/AST$PairFuncImpls.class new file mode 100644 index 0000000..5ac9043 Binary files /dev/null and b/bin/c00/AST$PairFuncImpls.class differ diff --git a/bin/c00/AST$PairStmSeq.class b/bin/c00/AST$PairStmSeq.class new file mode 100644 index 0000000..0e6f991 Binary files /dev/null and b/bin/c00/AST$PairStmSeq.class differ diff --git a/bin/c00/AST$ParamSections.class b/bin/c00/AST$ParamSections.class new file mode 100644 index 0000000..c6831da Binary files /dev/null and b/bin/c00/AST$ParamSections.class differ diff --git a/bin/c00/AST$PlusExpr.class b/bin/c00/AST$PlusExpr.class new file mode 100644 index 0000000..8e476f4 Binary files /dev/null and b/bin/c00/AST$PlusExpr.class differ diff --git a/bin/c00/AST$PlusFactorFirstTerm.class b/bin/c00/AST$PlusFactorFirstTerm.class new file mode 100644 index 0000000..e5c5899 Binary files /dev/null and b/bin/c00/AST$PlusFactorFirstTerm.class differ diff --git a/bin/c00/AST$Program.class b/bin/c00/AST$Program.class new file mode 100644 index 0000000..b34ffb6 Binary files /dev/null and b/bin/c00/AST$Program.class differ diff --git a/bin/c00/AST$PureIfStm.class b/bin/c00/AST$PureIfStm.class new file mode 100644 index 0000000..686db67 Binary files /dev/null and b/bin/c00/AST$PureIfStm.class differ diff --git a/bin/c00/AST$PurePrintfStm.class b/bin/c00/AST$PurePrintfStm.class new file mode 100644 index 0000000..3ed0b9b Binary files /dev/null and b/bin/c00/AST$PurePrintfStm.class differ diff --git a/bin/c00/AST$RefAssign.class b/bin/c00/AST$RefAssign.class new file mode 100644 index 0000000..a5b1ddc Binary files /dev/null and b/bin/c00/AST$RefAssign.class differ diff --git a/bin/c00/AST$RefIdFactor.class b/bin/c00/AST$RefIdFactor.class new file mode 100644 index 0000000..e7b0a5a Binary files /dev/null and b/bin/c00/AST$RefIdFactor.class differ diff --git a/bin/c00/AST$RefLastPrmSects.class b/bin/c00/AST$RefLastPrmSects.class new file mode 100644 index 0000000..0f7b861 Binary files /dev/null and b/bin/c00/AST$RefLastPrmSects.class differ diff --git a/bin/c00/AST$RefPairPrmSects.class b/bin/c00/AST$RefPairPrmSects.class new file mode 100644 index 0000000..9247f7a Binary files /dev/null and b/bin/c00/AST$RefPairPrmSects.class differ diff --git a/bin/c00/AST$RefVarLastDecls.class b/bin/c00/AST$RefVarLastDecls.class new file mode 100644 index 0000000..aae988e Binary files /dev/null and b/bin/c00/AST$RefVarLastDecls.class differ diff --git a/bin/c00/AST$RefVarPairDecls.class b/bin/c00/AST$RefVarPairDecls.class new file mode 100644 index 0000000..d31c894 Binary files /dev/null and b/bin/c00/AST$RefVarPairDecls.class differ diff --git a/bin/c00/AST$ScanfStm.class b/bin/c00/AST$ScanfStm.class new file mode 100644 index 0000000..e7809bc Binary files /dev/null and b/bin/c00/AST$ScanfStm.class differ diff --git a/bin/c00/AST$Statement.class b/bin/c00/AST$Statement.class new file mode 100644 index 0000000..7f2c853 Binary files /dev/null and b/bin/c00/AST$Statement.class differ diff --git a/bin/c00/AST$StatementSequence.class b/bin/c00/AST$StatementSequence.class new file mode 100644 index 0000000..7d74a8d Binary files /dev/null and b/bin/c00/AST$StatementSequence.class differ diff --git a/bin/c00/AST$SwitchBlock.class b/bin/c00/AST$SwitchBlock.class new file mode 100644 index 0000000..fc7a2b6 Binary files /dev/null and b/bin/c00/AST$SwitchBlock.class differ diff --git a/bin/c00/AST$SwitchStm.class b/bin/c00/AST$SwitchStm.class new file mode 100644 index 0000000..3345afc Binary files /dev/null and b/bin/c00/AST$SwitchStm.class differ diff --git a/bin/c00/AST$Term.class b/bin/c00/AST$Term.class new file mode 100644 index 0000000..fec155d Binary files /dev/null and b/bin/c00/AST$Term.class differ diff --git a/bin/c00/AST$ValueAssign.class b/bin/c00/AST$ValueAssign.class new file mode 100644 index 0000000..de95ef3 Binary files /dev/null and b/bin/c00/AST$ValueAssign.class differ diff --git a/bin/c00/AST$ValueLastPrmSects.class b/bin/c00/AST$ValueLastPrmSects.class new file mode 100644 index 0000000..d4a3adc Binary files /dev/null and b/bin/c00/AST$ValueLastPrmSects.class differ diff --git a/bin/c00/AST$ValuePairPrmSects.class b/bin/c00/AST$ValuePairPrmSects.class new file mode 100644 index 0000000..78892a2 Binary files /dev/null and b/bin/c00/AST$ValuePairPrmSects.class differ diff --git a/bin/c00/AST$VarConstGlobDecls.class b/bin/c00/AST$VarConstGlobDecls.class new file mode 100644 index 0000000..27b54c2 Binary files /dev/null and b/bin/c00/AST$VarConstGlobDecls.class differ diff --git a/bin/c00/AST$VarDecl.class b/bin/c00/AST$VarDecl.class new file mode 100644 index 0000000..4a456c9 Binary files /dev/null and b/bin/c00/AST$VarDecl.class differ diff --git a/bin/c00/AST$VarDeclarations.class b/bin/c00/AST$VarDeclarations.class new file mode 100644 index 0000000..3bdeaa2 Binary files /dev/null and b/bin/c00/AST$VarDeclarations.class differ diff --git a/bin/c00/AST$VarLastDecls.class b/bin/c00/AST$VarLastDecls.class new file mode 100644 index 0000000..5cf7e28 Binary files /dev/null and b/bin/c00/AST$VarLastDecls.class differ diff --git a/bin/c00/AST$VarPairDecls.class b/bin/c00/AST$VarPairDecls.class new file mode 100644 index 0000000..0493637 Binary files /dev/null and b/bin/c00/AST$VarPairDecls.class differ diff --git a/bin/c00/AST$VoidFormalParams.class b/bin/c00/AST$VoidFormalParams.class new file mode 100644 index 0000000..9cda4b9 Binary files /dev/null and b/bin/c00/AST$VoidFormalParams.class differ diff --git a/bin/c00/AST$VoidFuncHead.class b/bin/c00/AST$VoidFuncHead.class new file mode 100644 index 0000000..7f12e5f Binary files /dev/null and b/bin/c00/AST$VoidFuncHead.class differ diff --git a/bin/c00/AST$WhileStm.class b/bin/c00/AST$WhileStm.class new file mode 100644 index 0000000..59aded3 Binary files /dev/null and b/bin/c00/AST$WhileStm.class differ diff --git a/bin/c00/AST.class b/bin/c00/AST.class new file mode 100644 index 0000000..ded42c0 Binary files /dev/null and b/bin/c00/AST.class differ diff --git a/bin/c00/parser/C00Lexer.class b/bin/c00/parser/C00Lexer.class new file mode 100644 index 0000000..df66cb1 Binary files /dev/null and b/bin/c00/parser/C00Lexer.class differ diff --git a/bin/c00/parser/C00Parser$DFA17.class b/bin/c00/parser/C00Parser$DFA17.class new file mode 100644 index 0000000..df1bea3 Binary files /dev/null and b/bin/c00/parser/C00Parser$DFA17.class differ diff --git a/bin/c00/parser/C00Parser$DFA23.class b/bin/c00/parser/C00Parser$DFA23.class new file mode 100644 index 0000000..0591a8a Binary files /dev/null and b/bin/c00/parser/C00Parser$DFA23.class differ diff --git a/bin/c00/parser/C00Parser$actualParameters_return.class b/bin/c00/parser/C00Parser$actualParameters_return.class new file mode 100644 index 0000000..f43b1f2 Binary files /dev/null and b/bin/c00/parser/C00Parser$actualParameters_return.class differ diff --git a/bin/c00/parser/C00Parser$assignment_return.class b/bin/c00/parser/C00Parser$assignment_return.class new file mode 100644 index 0000000..9a2ae80 Binary files /dev/null and b/bin/c00/parser/C00Parser$assignment_return.class differ diff --git a/bin/c00/parser/C00Parser$block_return.class b/bin/c00/parser/C00Parser$block_return.class new file mode 100644 index 0000000..88f6590 Binary files /dev/null and b/bin/c00/parser/C00Parser$block_return.class differ diff --git a/bin/c00/parser/C00Parser$boolExpression_return.class b/bin/c00/parser/C00Parser$boolExpression_return.class new file mode 100644 index 0000000..f8394ca Binary files /dev/null and b/bin/c00/parser/C00Parser$boolExpression_return.class differ diff --git a/bin/c00/parser/C00Parser$caseSequence_return.class b/bin/c00/parser/C00Parser$caseSequence_return.class new file mode 100644 index 0000000..898ec3c Binary files /dev/null and b/bin/c00/parser/C00Parser$caseSequence_return.class differ diff --git a/bin/c00/parser/C00Parser$constDeclarations_return.class b/bin/c00/parser/C00Parser$constDeclarations_return.class new file mode 100644 index 0000000..6b1d9f9 Binary files /dev/null and b/bin/c00/parser/C00Parser$constDeclarations_return.class differ diff --git a/bin/c00/parser/C00Parser$declaration_return.class b/bin/c00/parser/C00Parser$declaration_return.class new file mode 100644 index 0000000..41fdf1e Binary files /dev/null and b/bin/c00/parser/C00Parser$declaration_return.class differ diff --git a/bin/c00/parser/C00Parser$declarations_return.class b/bin/c00/parser/C00Parser$declarations_return.class new file mode 100644 index 0000000..431a91a Binary files /dev/null and b/bin/c00/parser/C00Parser$declarations_return.class differ diff --git a/bin/c00/parser/C00Parser$elseClause_return.class b/bin/c00/parser/C00Parser$elseClause_return.class new file mode 100644 index 0000000..e0d3828 Binary files /dev/null and b/bin/c00/parser/C00Parser$elseClause_return.class differ diff --git a/bin/c00/parser/C00Parser$expression2_return.class b/bin/c00/parser/C00Parser$expression2_return.class new file mode 100644 index 0000000..55fac73 Binary files /dev/null and b/bin/c00/parser/C00Parser$expression2_return.class differ diff --git a/bin/c00/parser/C00Parser$expressionList_return.class b/bin/c00/parser/C00Parser$expressionList_return.class new file mode 100644 index 0000000..e433209 Binary files /dev/null and b/bin/c00/parser/C00Parser$expressionList_return.class differ diff --git a/bin/c00/parser/C00Parser$expression_return.class b/bin/c00/parser/C00Parser$expression_return.class new file mode 100644 index 0000000..7451225 Binary files /dev/null and b/bin/c00/parser/C00Parser$expression_return.class differ diff --git a/bin/c00/parser/C00Parser$factor_return.class b/bin/c00/parser/C00Parser$factor_return.class new file mode 100644 index 0000000..58f7f2a Binary files /dev/null and b/bin/c00/parser/C00Parser$factor_return.class differ diff --git a/bin/c00/parser/C00Parser$firstTerm2_return.class b/bin/c00/parser/C00Parser$firstTerm2_return.class new file mode 100644 index 0000000..fae3e00 Binary files /dev/null and b/bin/c00/parser/C00Parser$firstTerm2_return.class differ diff --git a/bin/c00/parser/C00Parser$firstTerm_return.class b/bin/c00/parser/C00Parser$firstTerm_return.class new file mode 100644 index 0000000..469da89 Binary files /dev/null and b/bin/c00/parser/C00Parser$firstTerm_return.class differ diff --git a/bin/c00/parser/C00Parser$formalParameters_return.class b/bin/c00/parser/C00Parser$formalParameters_return.class new file mode 100644 index 0000000..26cfd46 Binary files /dev/null and b/bin/c00/parser/C00Parser$formalParameters_return.class differ diff --git a/bin/c00/parser/C00Parser$functionCall_return.class b/bin/c00/parser/C00Parser$functionCall_return.class new file mode 100644 index 0000000..258888b Binary files /dev/null and b/bin/c00/parser/C00Parser$functionCall_return.class differ diff --git a/bin/c00/parser/C00Parser$functionHeading_return.class b/bin/c00/parser/C00Parser$functionHeading_return.class new file mode 100644 index 0000000..0970147 Binary files /dev/null and b/bin/c00/parser/C00Parser$functionHeading_return.class differ diff --git a/bin/c00/parser/C00Parser$functionImplementations_return.class b/bin/c00/parser/C00Parser$functionImplementations_return.class new file mode 100644 index 0000000..ae542b6 Binary files /dev/null and b/bin/c00/parser/C00Parser$functionImplementations_return.class differ diff --git a/bin/c00/parser/C00Parser$globalDeclarations_return.class b/bin/c00/parser/C00Parser$globalDeclarations_return.class new file mode 100644 index 0000000..8cb6bbc Binary files /dev/null and b/bin/c00/parser/C00Parser$globalDeclarations_return.class differ diff --git a/bin/c00/parser/C00Parser$paramSections_return.class b/bin/c00/parser/C00Parser$paramSections_return.class new file mode 100644 index 0000000..949f34f Binary files /dev/null and b/bin/c00/parser/C00Parser$paramSections_return.class differ diff --git a/bin/c00/parser/C00Parser$program_return.class b/bin/c00/parser/C00Parser$program_return.class new file mode 100644 index 0000000..f84672c Binary files /dev/null and b/bin/c00/parser/C00Parser$program_return.class differ diff --git a/bin/c00/parser/C00Parser$statementSequence_return.class b/bin/c00/parser/C00Parser$statementSequence_return.class new file mode 100644 index 0000000..11e50b6 Binary files /dev/null and b/bin/c00/parser/C00Parser$statementSequence_return.class differ diff --git a/bin/c00/parser/C00Parser$statement_return.class b/bin/c00/parser/C00Parser$statement_return.class new file mode 100644 index 0000000..80b3b3f Binary files /dev/null and b/bin/c00/parser/C00Parser$statement_return.class differ diff --git a/bin/c00/parser/C00Parser$switchBlock_return.class b/bin/c00/parser/C00Parser$switchBlock_return.class new file mode 100644 index 0000000..dcf4558 Binary files /dev/null and b/bin/c00/parser/C00Parser$switchBlock_return.class differ diff --git a/bin/c00/parser/C00Parser$term2_return.class b/bin/c00/parser/C00Parser$term2_return.class new file mode 100644 index 0000000..6c96ec0 Binary files /dev/null and b/bin/c00/parser/C00Parser$term2_return.class differ diff --git a/bin/c00/parser/C00Parser$term_return.class b/bin/c00/parser/C00Parser$term_return.class new file mode 100644 index 0000000..84a70ee Binary files /dev/null and b/bin/c00/parser/C00Parser$term_return.class differ diff --git a/bin/c00/parser/C00Parser$varDeclarations_return.class b/bin/c00/parser/C00Parser$varDeclarations_return.class new file mode 100644 index 0000000..61508c1 Binary files /dev/null and b/bin/c00/parser/C00Parser$varDeclarations_return.class differ diff --git a/bin/c00/parser/C00Parser.class b/bin/c00/parser/C00Parser.class new file mode 100644 index 0000000..0ea3dd0 Binary files /dev/null and b/bin/c00/parser/C00Parser.class differ diff --git a/bin/c00/parser/ParseException.class b/bin/c00/parser/ParseException.class new file mode 100644 index 0000000..39df82d Binary files /dev/null and b/bin/c00/parser/ParseException.class differ diff --git a/bin/org/jalgo/main/AbstractModuleConnector$SaveStatus.class b/bin/org/jalgo/main/AbstractModuleConnector$SaveStatus.class new file mode 100644 index 0000000..e6424ba Binary files /dev/null and b/bin/org/jalgo/main/AbstractModuleConnector$SaveStatus.class differ diff --git a/bin/org/jalgo/main/AbstractModuleConnector.class b/bin/org/jalgo/main/AbstractModuleConnector.class new file mode 100644 index 0000000..43581af Binary files /dev/null and b/bin/org/jalgo/main/AbstractModuleConnector.class differ diff --git a/bin/org/jalgo/main/IModuleInfo.class b/bin/org/jalgo/main/IModuleInfo.class new file mode 100644 index 0000000..248e257 Binary files /dev/null and b/bin/org/jalgo/main/IModuleInfo.class differ diff --git a/bin/org/jalgo/main/InternalErrorException.class b/bin/org/jalgo/main/InternalErrorException.class new file mode 100644 index 0000000..a62cd72 Binary files /dev/null and b/bin/org/jalgo/main/InternalErrorException.class differ diff --git a/bin/org/jalgo/main/JAlgoMain.class b/bin/org/jalgo/main/JAlgoMain.class new file mode 100644 index 0000000..1c0a115 Binary files /dev/null and b/bin/org/jalgo/main/JAlgoMain.class differ diff --git a/bin/org/jalgo/main/de.properties b/bin/org/jalgo/main/de.properties new file mode 100644 index 0000000..a249274 --- /dev/null +++ b/bin/org/jalgo/main/de.properties @@ -0,0 +1,71 @@ +General.name=j-Algo +General.version=1.01 + +ui.About=Über j-Algo +ui.About_mnemonic=A +ui.About_tooltip=Erfahren Sie mehr über j-Algo +ui.About_module=Über das j-Algo-Modul +ui.About_module_mnemonic=M +ui.About_module_tooltip=Erfahren Sie mehr über das j-Algo-Modul +ui.Close=Schliessen +ui.Close_mnemonic=C +ui.Close_tooltip=Schliesst das aktuell geöffnete Modul. +ui.Exit=Beenden +ui.Exit_mnemonic=B +ui.File=Datei +ui.File_mnemonic=D +ui.Help=Hilfe +ui.Help_mnemonic=H +ui.Help_contents=Inhalt +ui.Help_contents_mnemonic=I +ui.Help_tooltip=Öffnet die Hilfe. +ui.New=Neu +ui.New_mnemonic=N +ui.New_tooltip=Zeigt eine Liste der installierten Module zum Öffnen an. +ui.Open_file=Datei öffnen +ui.Open_file_mnemonic=F +ui.Open_file_tooltip=Öffnet einen Dateiauswahldialog zum Laden einer Datei. +ui.Prefs=Einstellungen +ui.Prefs_mnemonic=E +ui.Save_file=Datei speichern +ui.Save_file_mnemonic=S +ui.Save_file_tooltip=Speichert die aktuelle Arbeit. +ui.Save_as=Speichern unter +ui.Save_as_mnemonic=U +ui.Save_as_tooltip=Öffnet einen Dateiauswahldialog zum Speichern der Daten. +ui.Untitled=Unbenannt +ui.Wish_to_save=Möchten Sie Ihre Arbeit speichern? + +DialogConstants.Cancel=Abbrechen +DialogConstants.Error=Fehler +DialogConstants.Info=Hinweis +DialogConstants.No=Nein +DialogConstants.Ok=Ok +DialogConstants.Question=Frage +DialogConstants.Warning=Achtung +DialogConstants.Yes=Ja + +About.Copyright=(c) Copyright j-Algo-Team 2004-2008. Alle Rechte vorbehalten. +About.URL=Besuchen Sie http://j-algo.binaervarianz.de +About.Authors=Autoren: +About.Author_Names=Malte Blumberg, Alexander Claus, Stephan Creutz, Christopher Friedrich, Cornelius Hald, Anne Kersten, Hauke Menges, Michael Pradel, Babett Schalitz, Matthias Schmidt, Benjamin Scholz, Marco Zimmerling +About.License=Lizenz: +About.GPL=GNU General Public License +AboutModule.Version=\ - Version + +JalgoWindow.No_second_instance=Es ist nicht erlaubt, eine zweite Instanz zu öffnen. +JalgoWindow.Application_terminates=Die Applikation wird beendet! +Storage.Could_not_open_file_4=Datei kann nicht geöffnet werden. +Storage.File_not_valid_5=Die Datei ist keine korrekte j-Algo-Datei. +Storage.Could_not_write_the_file._8=Datei konnte nicht geschrieben werden. +Storage.Maybe_out_of_diskspace_9=Vielleicht haben Sie versucht, auf ein read-only Medium zu schreiben oder die Speicherkapazität reicht nicht mehr aus. +Storage.Module_not_present=Das angeforderte j-Algo-Modul ist nicht installiert. + +Prefs.ShowSplashOnStartup=Logo beim Start anzeigen +Prefs.ShowModuleChooserOnStartup=Modulauswahldialog beim Start anzeigen +Prefs.Language=Sprache (Neustart erforderlich) +Prefs.Skin=Oberfläche (Neustart erforderlich): + +New.Title=Modulauswahl +New.ModuleList=Modulliste +New.info=Modulbeschreibung: \ No newline at end of file diff --git a/bin/org/jalgo/main/en.properties b/bin/org/jalgo/main/en.properties new file mode 100644 index 0000000..3689746 --- /dev/null +++ b/bin/org/jalgo/main/en.properties @@ -0,0 +1,71 @@ +General.name=j-Algo +General.version=1.01 + +ui.About=About j-Algo +ui.About_mnemonic=A +ui.About_tooltip=Get more information about j-Algo +ui.About_module=About the j-Algo-module +ui.About_module_mnemonic=M +ui.About_module_tooltip=Get more information about the j-Algo-module +ui.Close=Close +ui.Close_mnemonic=C +ui.Close_tooltip=Closes the currently opened module +ui.Exit=Exit +ui.Exit_mnemonic=X +ui.File=File +ui.File_mnemonic=F +ui.Help=Help +ui.Help_mnemonic=H +ui.Help_contents=Contents +ui.Help_contents_mnemonic=C +ui.Help_tooltip=Opens the help browser. +ui.New=New +ui.New_mnemonic=N +ui.New_tooltip=Shows a list of all installed modules to choose one. +ui.Open_file=Open file +ui.Open_file_mnemonic=O +ui.Open_file_tooltip=Opens a file chooser dialog for opening a file. +ui.Prefs=Preferences +ui.Prefs_mnemonic=E +ui.Save_file=Save file +ui.Save_file_mnemonic=S +ui.Save_file_tooltip=Saves the current module data. +ui.Save_as=Save as +ui.Save_as_mnemonic=A +ui.Save_as_tooltip=Opens a file chooser dialog for saving a file. +ui.Untitled=Untitled +ui.Wish_to_save=Do you wish to save your work? + +DialogConstants.Cancel=Cancel +DialogConstants.Error=Error +DialogConstants.No=No +DialogConstants.Info=Info +DialogConstants.Ok=Ok +DialogConstants.Question=Question +DialogConstants.Warning=Warning +DialogConstants.Yes=Yes + +About.Copyright=(c) Copyright j-Algo-Team 2004-2008. All rights reserved. +About.URL=Visit http://j-algo.binaervarianz.de +About.Authors=Authors: +About.Author_Names=Malte Blumberg, Alexander Claus, Stephan Creutz, Christopher Friedrich, Cornelius Hald, Anne Kersten, Hauke Menges, Michael Pradel, Babett Schalitz, Matthias Schmidt, Benjamin Scholz, Marco Zimmerling +About.License=License: +About.GPL=GNU General Public License +AboutModule.Version=\ - Version + +JalgoWindow.No_second_instance=It is not allowed to open a 2nd instance. +JalgoWindow.Application_terminates=The application will terminate! +Storage.Could_not_open_file_4=The file could not be opened. +Storage.File_not_valid_5=The file is not a valid j-Algo-file. +Storage.Could_not_write_the_file._8=The file could not be saved. +Storage.Maybe_out_of_diskspace_9=Maybe write protection or out of diskspace. +Storage.Module_not_present=The requested j-Algo-module is not installed. + +Prefs.ShowSplashOnStartup=Show splash screen on startup +Prefs.ShowModuleChooserOnStartup=Show module chooser on startup +Prefs.Language=Language (Restart necessary) +Prefs.Skin=Skin (Restart necessary): + +New.Title=Module Choose Dialog +New.ModuleList=Module liste +New.info=Module information: \ No newline at end of file diff --git a/bin/org/jalgo/main/gui/DialogConstants.class b/bin/org/jalgo/main/gui/DialogConstants.class new file mode 100644 index 0000000..d9ac76a Binary files /dev/null and b/bin/org/jalgo/main/gui/DialogConstants.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoGUIConnector.class b/bin/org/jalgo/main/gui/JAlgoGUIConnector.class new file mode 100644 index 0000000..195da7b Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoGUIConnector.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$1.class b/bin/org/jalgo/main/gui/JAlgoWindow$1.class new file mode 100644 index 0000000..6572a47 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$1.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$2.class b/bin/org/jalgo/main/gui/JAlgoWindow$2.class new file mode 100644 index 0000000..af7d875 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$2.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$3.class b/bin/org/jalgo/main/gui/JAlgoWindow$3.class new file mode 100644 index 0000000..0af88b4 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$3.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$4.class b/bin/org/jalgo/main/gui/JAlgoWindow$4.class new file mode 100644 index 0000000..f491869 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$4.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$5.class b/bin/org/jalgo/main/gui/JAlgoWindow$5.class new file mode 100644 index 0000000..c1a0153 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$5.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$6.class b/bin/org/jalgo/main/gui/JAlgoWindow$6.class new file mode 100644 index 0000000..8afe435 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$6.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow$7.class b/bin/org/jalgo/main/gui/JAlgoWindow$7.class new file mode 100644 index 0000000..3d33a74 Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow$7.class differ diff --git a/bin/org/jalgo/main/gui/JAlgoWindow.class b/bin/org/jalgo/main/gui/JAlgoWindow.class new file mode 100644 index 0000000..0d3760a Binary files /dev/null and b/bin/org/jalgo/main/gui/JAlgoWindow.class differ diff --git a/bin/org/jalgo/main/gui/components/AboutFrame$1.class b/bin/org/jalgo/main/gui/components/AboutFrame$1.class new file mode 100644 index 0000000..b670eca Binary files /dev/null and b/bin/org/jalgo/main/gui/components/AboutFrame$1.class differ diff --git a/bin/org/jalgo/main/gui/components/AboutFrame.class b/bin/org/jalgo/main/gui/components/AboutFrame.class new file mode 100644 index 0000000..73dbea1 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/AboutFrame.class differ diff --git a/bin/org/jalgo/main/gui/components/HelpSystem.class b/bin/org/jalgo/main/gui/components/HelpSystem.class new file mode 100644 index 0000000..ffdca6d Binary files /dev/null and b/bin/org/jalgo/main/gui/components/HelpSystem.class differ diff --git a/bin/org/jalgo/main/gui/components/JToolbarButton$1.class b/bin/org/jalgo/main/gui/components/JToolbarButton$1.class new file mode 100644 index 0000000..2f737d7 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/JToolbarButton$1.class differ diff --git a/bin/org/jalgo/main/gui/components/JToolbarButton$RolloverHandler.class b/bin/org/jalgo/main/gui/components/JToolbarButton$RolloverHandler.class new file mode 100644 index 0000000..70bbae2 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/JToolbarButton$RolloverHandler.class differ diff --git a/bin/org/jalgo/main/gui/components/JToolbarButton.class b/bin/org/jalgo/main/gui/components/JToolbarButton.class new file mode 100644 index 0000000..b21175d Binary files /dev/null and b/bin/org/jalgo/main/gui/components/JToolbarButton.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$1.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$1.class new file mode 100644 index 0000000..00b927d Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$1.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$2.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$2.class new file mode 100644 index 0000000..cfb87e5 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$2.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$3.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$3.class new file mode 100644 index 0000000..1cb90a4 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$3.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$4.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$4.class new file mode 100644 index 0000000..a97be45 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$4.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$5.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$5.class new file mode 100644 index 0000000..5f02849 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$5.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$6.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$6.class new file mode 100644 index 0000000..0a789aa Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$6.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$7.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$7.class new file mode 100644 index 0000000..fdb6538 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$7.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog$MyCellRenderer.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$MyCellRenderer.class new file mode 100644 index 0000000..9f0c959 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog$MyCellRenderer.class differ diff --git a/bin/org/jalgo/main/gui/components/ModuleChooseDialog.class b/bin/org/jalgo/main/gui/components/ModuleChooseDialog.class new file mode 100644 index 0000000..44fa39a Binary files /dev/null and b/bin/org/jalgo/main/gui/components/ModuleChooseDialog.class differ diff --git a/bin/org/jalgo/main/gui/components/PreferencesDialog$1.class b/bin/org/jalgo/main/gui/components/PreferencesDialog$1.class new file mode 100644 index 0000000..1604c87 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/PreferencesDialog$1.class differ diff --git a/bin/org/jalgo/main/gui/components/PreferencesDialog$2.class b/bin/org/jalgo/main/gui/components/PreferencesDialog$2.class new file mode 100644 index 0000000..fab2986 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/PreferencesDialog$2.class differ diff --git a/bin/org/jalgo/main/gui/components/PreferencesDialog$3.class b/bin/org/jalgo/main/gui/components/PreferencesDialog$3.class new file mode 100644 index 0000000..dcb7eb6 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/PreferencesDialog$3.class differ diff --git a/bin/org/jalgo/main/gui/components/PreferencesDialog$4.class b/bin/org/jalgo/main/gui/components/PreferencesDialog$4.class new file mode 100644 index 0000000..8ad6047 Binary files /dev/null and b/bin/org/jalgo/main/gui/components/PreferencesDialog$4.class differ diff --git a/bin/org/jalgo/main/gui/components/PreferencesDialog.class b/bin/org/jalgo/main/gui/components/PreferencesDialog.class new file mode 100644 index 0000000..fcee1be Binary files /dev/null and b/bin/org/jalgo/main/gui/components/PreferencesDialog.class differ diff --git a/bin/org/jalgo/main/gui/event/JAlgoWindowActionHandler.class b/bin/org/jalgo/main/gui/event/JAlgoWindowActionHandler.class new file mode 100644 index 0000000..a800f58 Binary files /dev/null and b/bin/org/jalgo/main/gui/event/JAlgoWindowActionHandler.class differ diff --git a/bin/org/jalgo/main/gui/event/StatusLineUpdater.class b/bin/org/jalgo/main/gui/event/StatusLineUpdater.class new file mode 100644 index 0000000..c61a1ee Binary files /dev/null and b/bin/org/jalgo/main/gui/event/StatusLineUpdater.class differ diff --git a/bin/org/jalgo/main/res.properties b/bin/org/jalgo/main/res.properties new file mode 100644 index 0000000..37e43cc --- /dev/null +++ b/bin/org/jalgo/main/res.properties @@ -0,0 +1,37 @@ +ui.About=/main_pix/about.gif +ui.About_module=/main_pix/about.gif +ui.Close=/main_pix/close.gif +ui.Exit=/main_pix/exit.gif +ui.Help_contents=/main_pix/help.gif +ui.Logo=/main_pix/jalgo.png +ui.Logo_small=/main_pix/logo_small.gif +ui.Open_file=/main_pix/open.gif +ui.Prefs=/main_pix/prefs.gif +ui.Save_file=/main_pix/save.gif +ui.Save_as=/main_pix/save_as.gif +ui.Splash=/main_pix/splash.png +ui.New=/main_pix/new.gif +About.header=/main_pix/aboutHeader.png + +Icon.Redo=/main_pix/redo.gif +Icon.Undo=/main_pix/undo.gif +Icon.Advice=/main_pix/advice.gif +Icon.Advice_Selected=/main_pix/advice_selected.gif +Icon.Abort_algorithm=/main_pix/abortAlg.gif +Icon.Undo_step=/main_pix/undoStep.gif +Icon.Undo_blockstep=/main_pix/undoBlockStep.gif +Icon.Undo_all=/main_pix/undoAll.gif +Icon.Perform_step=/main_pix/performStep.gif +Icon.Perform_blockstep=/main_pix/performBlockStep.gif +Icon.Perform_all=/main_pix/performAll.gif +Icon.Finish_algorithm=/main_pix/finishAlg.gif +Icon.Beamer_mode=/main_pix/beamer.gif +Icon.Clear=/main_pix/clear.gif +Icon.Msg_error=/main_pix/msgError.gif +Icon.Msg_info=/main_pix/msgInfo.gif + +Available_languages.short=de,en +Available_languages.full=Deutsch,English + +Main_HelpSet=/help/jhelp/main_help.hs +Main_DummyHS=/help/jhelp/main_dummy.hs \ No newline at end of file diff --git a/bin/org/jalgo/main/util/ErrorLog.class b/bin/org/jalgo/main/util/ErrorLog.class new file mode 100644 index 0000000..bcc3491 Binary files /dev/null and b/bin/org/jalgo/main/util/ErrorLog.class differ diff --git a/bin/org/jalgo/main/util/Messages.class b/bin/org/jalgo/main/util/Messages.class new file mode 100644 index 0000000..994ca81 Binary files /dev/null and b/bin/org/jalgo/main/util/Messages.class differ diff --git a/bin/org/jalgo/main/util/Settings.class b/bin/org/jalgo/main/util/Settings.class new file mode 100644 index 0000000..08b206a Binary files /dev/null and b/bin/org/jalgo/main/util/Settings.class differ diff --git a/bin/org/jalgo/main/util/Storage.class b/bin/org/jalgo/main/util/Storage.class new file mode 100644 index 0000000..7e77f85 Binary files /dev/null and b/bin/org/jalgo/main/util/Storage.class differ diff --git a/bin/org/jalgo/module/am0c0/ModuleConnector.class b/bin/org/jalgo/module/am0c0/ModuleConnector.class new file mode 100644 index 0000000..4c0b9b1 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/am0c0/ModuleInfo.class b/bin/org/jalgo/module/am0c0/ModuleInfo.class new file mode 100644 index 0000000..dd283df Binary files /dev/null and b/bin/org/jalgo/module/am0c0/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Controller.class b/bin/org/jalgo/module/am0c0/core/Controller.class new file mode 100644 index 0000000..d76f6aa Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Controller.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$EditorState.class b/bin/org/jalgo/module/am0c0/core/Editor$EditorState.class new file mode 100644 index 0000000..45b2681 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$EditorState.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidated.class b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidated.class new file mode 100644 index 0000000..4230126 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidated.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedAM0.class b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedAM0.class new file mode 100644 index 0000000..a20e436 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedAM0.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedC0.class b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedC0.class new file mode 100644 index 0000000..ffefde6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateNotValidatedC0.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateValidated.class b/bin/org/jalgo/module/am0c0/core/Editor$StateValidated.class new file mode 100644 index 0000000..1d79f7e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateValidated.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedAM0.class b/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedAM0.class new file mode 100644 index 0000000..1e1b08a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedAM0.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedC0.class b/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedC0.class new file mode 100644 index 0000000..4038ac7 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor$StateValidatedC0.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Editor.class b/bin/org/jalgo/module/am0c0/core/Editor.class new file mode 100644 index 0000000..c066735 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Editor.class differ diff --git a/bin/org/jalgo/module/am0c0/core/ILoveCandy$1.class b/bin/org/jalgo/module/am0c0/core/ILoveCandy$1.class new file mode 100644 index 0000000..2b3a4e7 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/ILoveCandy$1.class differ diff --git a/bin/org/jalgo/module/am0c0/core/ILoveCandy$TAdapter.class b/bin/org/jalgo/module/am0c0/core/ILoveCandy$TAdapter.class new file mode 100644 index 0000000..1aa6dd2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/ILoveCandy$TAdapter.class differ diff --git a/bin/org/jalgo/module/am0c0/core/ILoveCandy.class b/bin/org/jalgo/module/am0c0/core/ILoveCandy.class new file mode 100644 index 0000000..a8bbfda Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/ILoveCandy.class differ diff --git a/bin/org/jalgo/module/am0c0/core/PresentationAction.class b/bin/org/jalgo/module/am0c0/core/PresentationAction.class new file mode 100644 index 0000000..2c295ae Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/PresentationAction.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Simulator.class b/bin/org/jalgo/module/am0c0/core/Simulator.class new file mode 100644 index 0000000..c809d47 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Simulator.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Subcontroller.class b/bin/org/jalgo/module/am0c0/core/Subcontroller.class new file mode 100644 index 0000000..8da0df6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Subcontroller.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Transformator$TransformationState.class b/bin/org/jalgo/module/am0c0/core/Transformator$TransformationState.class new file mode 100644 index 0000000..98241b8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Transformator$TransformationState.class differ diff --git a/bin/org/jalgo/module/am0c0/core/Transformator.class b/bin/org/jalgo/module/am0c0/core/Transformator.class new file mode 100644 index 0000000..e2a095c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/Transformator.class differ diff --git a/bin/org/jalgo/module/am0c0/core/package-info.class b/bin/org/jalgo/module/am0c0/core/package-info.class new file mode 100644 index 0000000..adead24 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/core/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/de.properties b/bin/org/jalgo/module/am0c0/de.properties new file mode 100644 index 0000000..1ae6961 --- /dev/null +++ b/bin/org/jalgo/module/am0c0/de.properties @@ -0,0 +1,301 @@ +Add.0=Der Datenkeller enthält weniger als zwei Elemente! +Add.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2+d.1):d.3: ... :d.n,h, inp, out) +AddressSolver.0=StubTrans Addresse darf nicht NULL sein! +AM0InputDialog.0=Neue AM Konfiguration +AM0InputDialog.1=Befehlszähler +AM0InputDialog.12=+ +AM0InputDialog.13=- +AM0InputDialog.14=Gib hier eine neue AM Konfiguration ein.
Benutze ':' um die Werte im Datenkeller zu trennen
und ',' auf dem Ein- und Ausgabeband.

+AM0InputDialog.15=OK +AM0InputDialog.16=Abbrechen +AM0InputDialog.17=Intitiale Konfiguration +AM0InputDialog.18=Diese Eingabe für den Hauptspeicher ist nicht korrekt. Er darf nicht leer sein!\n +AM0InputDialog.19=Diese Eingabe für den Hauptspeicher ist nicht korrekt.\n +AM0InputDialog.2=Datenkeller (mit ':' getrennt) +AM0InputDialog.20=Bitte überprüfe folgende Zahlen:\n +AM0InputDialog.21=Adresse: +AM0InputDialog.24=Diese Eingabe für den Hauptspeicher ist nicht korrekt.\n +AM0InputDialog.25=Die Adresse darf nicht negtiv oder 0 sein, aber sie war:\n +AM0InputDialog.26=Diese Hauptspeicheradresse ist nicht korrekt.\n +AM0InputDialog.27=\ Bitte überprüfe folgende Adresse: +AM0InputDialog.28=Diese Hauptspeicheradresse ist nicht korrekt.\n +AM0InputDialog.29=\ Die Adresse darf nicht negativ oder 0 sein, aber sie war:\n +AM0InputDialog.3=Hauptspeicher (Adresse, Wert) +AM0InputDialog.4=Eingabeband (mit Kommata getrennt) +AM0InputDialog.43=es muss mindestens eine Zahl +AM0InputDialog.44=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.45=Dieses Eingabeband ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.46=es muss mindestens eine Zahl +AM0InputDialog.47=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.48=Dieser Datenkeller ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.49=es muss mindestens eine Zahl +AM0InputDialog.5=Ausgabeband (mit Kommata getrennt) +AM0InputDialog.50=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.51=Dieser Befehlszähler ist nicht korrekt.\nEr muss >=1 sein, aber es war:\n +AM0InputDialog.52=Der Befehlszähler darf nicht leer sein!\n +AM0InputDialog.6=Wert: +AM0InputDialog.7=Dieses Ausgabeband ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.74=Hauptspeicherkonfiguration +AM0InputDialog.8=Diese Adresse existiert bereits. Soll der Wert an dieser Adresse überschrieben werden? +AM0InputDialog.87=Datenkellerkonfiguration +AM0InputDialog.9=Diese Adresse existiert nicht:\n +AM0PagingTableModel.0=Befehlszähler +AM0PagingTableModel.1=Datenkeller +AM0PagingTableModel.10=  Zeige Schritte von +AM0PagingTableModel.11= bis +AM0PagingTableModel.12= +AM0PagingTableModel.2=Hauptspeicher +AM0PagingTableModel.3=Eingabeband +AM0PagingTableModel.4=Ausgabeband +AM0PagingTableModel.7=  Zeige Schritte von +AM0PagingTableModel.8= bis +AM0PagingTableModel.9= +AM0Scanner.0=Unbekannter interner Scanner Fehler +AM0Scanner.1=Fehler: konnte Eingabe nicht in Übereinstimmung bringen +AM0Scanner.2=Fehler: Rückgabewert ist zu groß +AtomicTrans.0=Dieser AtomicType ist nicht gültig +AtomicTrans.5=Token muss für AtomicTrans Funktionen NULL sein +AtomicTrans.6=Eine Sprungbefehl muss eine Sprungadresse haben +AtomicTrans.7=Anwenden von AtomicTrans ist nicht erlaubt +BlockTrans.0=blocktrans: W() \u2212 \u2192 bProg0\n\n +BlockTrans.1=blocktrans({ decl statseq return 0;}) := stseqtrans(statseq, update(decl, tab \u2205 ), 1) +BlockTrans.2=für alle decl \u2208 W() und statseq \u2208 W(), +BlockTrans.3=tab \u2205 \u2208 Tab mit graph(tab \u2205 ) = \u2205 +BoolExpTrans.0=boolexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0\n\n +BoolExpTrans.1=boolexptrans(se 1 rel se 2 , tab) :=\n +BoolExpTrans.2=\tsimpleexptrans(se 1 , tab)\n +BoolExpTrans.3=\tsimpleexptrans(se 2 , tab)\n +BoolExpTrans.4=\tREL;\n +BoolExpTrans.5=für alle se 1 , se 2 \u2208 W(), rel \u2208 {==, \!=, <, >, <=, >=} und tab \u2208 Tab +C0Scanner.0=Fehler: Rückgabewert ist zu groß +C0Scanner.177=Unbekannter interner Scanner Fehler +C0Scanner.178=Fehler: konnte Eingabe nicht in Übereinstimmung bringen +Div.0=Der Datenkeller enthält weniger als zwei Elemente! +Div.1=Division mit 0! +Div.2=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2/d.1):d.3: ... :d.n,h, inp, out) +Editor.3=

Die Syntaxüberprüfung war +Editor.4=erfolgreich. Klicke nun auf Start.

+Editor.5=Transformiertes Programm +EditorView.10=AM0-Code +EditorView.12=Konsole +EditorView.13=Optionen +EditorView.14=Editor +EditorView.15=Soll das Programm vor der Transformation gespeichert werden? +EditorView.16=Speichern +EditorView.17=Lädt Code in den Editor +EditorView.18=Speichere den soeben editierten Code. +EditorView.19=Verwende den Code für die Simulation oder Transformation. +EditorView.2=Laden +EditorView.20=Validiere den Code. +EditorView.21=Verwende AM0 Code. +EditorView.22=Verwende C0 Code. +EditorView.23=Zeile: +EditorView.24=\ Spalte: +EditorView.25=Neue Datei +EditorView.4=Speichern +EditorView.6=Validiere +EditorView.7=Start +EditorView.9=C0-Code +Equal.0=Der Datenkeller enthält weniger als zwei Elemente! +Equal.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, falls d.2=d.1, und b=0, falls d.2\!=d.1,
d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +ErrorEvents.RemoveThisToken=Entferne es, um diesen Fehler zu beseitigen. +ErrorEvents.LexicalAnalysis=Lexikalische Analyse +ErrorEvents.SyntacticAnalysis=Syntaktische Analyse +ErrorEvents.FollowingErrors=Folgende Fehler traten während der Validierung auf: +ErrorEvents.FollowingError=Folgender Fehler trat während der Validierung auf: +ErrorEvents.NumberTooLarge=Die eingegebene Zahl %s in Zeile %d, Spalte %d ist zu groß: der maximal erlaubte Wert ist %d. +ErrorEvents.UnexpectedTokenAt=Unerwartetes Terminalsymbol "%s" in Zeile %d, Spalte %d. +ErrorEvents.DontKnowWhatToDo=Kann die Eingabe "%s" auf Zeile %d nicht verarbeiten. +ErrorEvents.UnexpectedEOF=Unerwartetes Dateiende in Zeile %d, Spalte %d. +ErrorEvents.UnexpectedEOL=Unerwartetes Zeilenende in Zeile %d, Spalte %d. +ErrorEvents.InsertRelation=Füge eine der Relationen "==", "!=", ">=", "<=", ">" oder "<" ein, um diesen booleschen Ausdruck zu komplettieren. +ErrorEvents.InsertAmp=Füge "&" ein, um dieses scanf-Statement zu komplettieren. +ErrorEvents.InsertComma=Füge "," ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertAssign=Füge "=" ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertSemicolon=Füge ";" ein, um das vorhergehende Statement zu komplettieren. +ErrorEvents.InsertIdent=Füge einen Variablennamen ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertNumber=Füge eine Zahl ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertNumber_AM0=Füge eine Zahl ein, um dieses AM0-Statement zu komplettieren. +ErrorEvents.InsertSemicolon_AM0=Füge ";" ein, um dieses AM0-Statement zu komplettieren. +GreaterEqual.0=Der Datenkeller enthält weniger als zwei Elemente! +GreaterEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, wenn d.2\u2265d.1, und b=0, wenn d.2<d.1,
d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +GreaterThen.0=Der Datenkeller enthält weniger als zwei Elemente! +GreaterThen.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, wenn d.2>d.1, und b=0, wenn d.2\u2264d.1,
d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +JEditor.0=Eingabe/Ausgabe Fehler +JEditor.1=AM0 Programm (*.am0) +JEditor.13=Eingabe/Ausgabe Fehler +JEditor.3=C0 Programm (*.c0) +JEditor.8=Der Programmcode wurde modifiziert.\nMöchtest du ihn speichern? +JEditor.9=Bestätigen +Jmc.0=Der Datenkeller enthält kein Element! +Jmc.1=Falls d=0:d.2: ... :d.n mit n \u2265 1, dann (e,d.2: ... :d.n,h, inp, out)
sonst (m+1,d.2: ... :d.n,h, inp, out)
Falls das erste Datenkellerelement 0 (logisch falsch) ist wird der PC auf e gesetzt.
Sonst wird er inkrementiert. +Jmp.0=(e,d,h, inp, out) +LesserEqual.0=Der Datenkeller enthält weniger als zwei Elemente. +LesserEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, wenn d.2\u2264d.1, und b=0, wenn d.2>d.1,
, d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +LesserThen.0=Der Datenkeller enthält weniger als zwei Elemente. +LesserThen.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, wenn d.2<d.1, und b=0, wenn d.2\u2265d.1,
, d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +Lit.0=(m+1,z:d,h, inp, out) +Load.0=Diese Hauptspeicherzelle ist nicht definiert. +Load.1=Falls h(n) \u220A \u2115, dann (m+1,h(n):d,h, inp, out) +Mod.0=Der Datenkeller enthält weniger als zwei Elemente. +Mod.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2%.1):d.3: ... :d.n,h, inp, out) +ModuleInfo.2=Franz Gregor, Martin Morgenstern,\n +ModuleInfo.3=\ Max Leuth\u00E4user, David Voigt, Felix Schmitt +ModuleInfo.5=Dieses Modul übersetzt schrittweise C0- in AM0-Programme und simuliert AM0-Programme. +ModuleInfo.8=GNU General Public License. Grafiken vom Tango Desktop Project. +Mul.0=Der Datenkeller enthält weniger als zwei Elemente. +Mul.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2*d.1):d.3: ... :d.n,h, inp, out) +NotEqual.0=Der Datenkeller enthält weniger als zwei Elemente. +NotEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
und b=1, wenn d.2\!=d.1, und b=0, wenn d.2=d.1,
, d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +PresentationAction.0=Präsentationsmodus +Read.0=Ziel < 0 ist nicht erlaubt\! +Read.1=Das Eingabeband ist leer\! +Read.2=Falls inp=first(inp).rest(inp), dann (m+1,d,h[n/first(inp)], rest(inp), out)
und für jedes n \u220A \u2124 und w \u220A \u2124*: first(n:w)=n und rest(n:w)=w +SimpleExpTrans.0=simpleexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0 +SimulationView.11=Zurück +SimulationView.13=Weiter +SimulationView.15=Leeren +SimulationView.17=Alles in einem Schritt +SimulationView.19=Initiale Konfiguration +SimulationView.23=Die Simulation wird nach maximal +SimulationView.24= Schritten nachfragen, ob sie weiter laufen soll. +SimulationView.26=Die Simulation wird nach maximal +SimulationView.27= Schritten nachfragen, ob sie weiter laufen soll. +SimulationView.28=\ \ Nachfragen nach: +SimulationView.29=\ Schritten +SimulationView.3=AM0-Tabelle +SimulationView.31=Befehls Hilfe +SimulationView.32=Zum Anfang der Simulation springen. +SimulationView.33=Ans Ende der Simulation springen. +SimulationView.34=Zurück zum Editor. +SimulationView.35=Einen Schritt zurück gehen. +SimulationView.36=Einen Schritt weiter gehen. +SimulationView.37=Simulation in einem Schritt. +SimulationView.38=Eine Maschinenkonfiguration eingeben. +SimulationView.39=Alles bereinigen. Diese Aktion wird die aktuelle Maschinenkonfiguration sowie alle Übersetzungsschritte entfernen\! +SimulationView.4=AM0-Animation +SimulationView.5=Tabellenanfang +SimulationView.6=Tabellenende +SimulationView.7=Noch nicht gestartet. +SimulationView.9=Zum Editor +Simulator.0=Es tratt ein Fehler bei der Simulation auf.\n +Simulator.1=Der folgende Befehl konnte nicht ausgeführt werden:\n +Simulator.10=Letzter Schritt: +Simulator.12=  Zeige Schritte von +Simulator.13= bis +Simulator.14= +Simulator.15=\ \ Letzter Schritt: +Simulator.17=\ \ Letzter Schritt: +Simulator.19=\ Schritte berechnet.\n +Simulator.20=Möchtest du fortfahren?\n\n +Simulator.21=Wähle 'Nein' zum Stoppen oder 'Ja' zum Fortsetzen der Simulation +Simulator.22=Simulation +Simulator.23=\ \ Letzter Schritt: +Simulator.25=Noch nicht gestartet. +Simulator.3=Grund:\n +Simulator.4=Dieser Sprungbefehl konnte nicht ausgeführt werden:\n +Simulator.6=Grund:\n +Store.0=Der Datenkeller enthält kein Element. +Store.1=Falls d=d.1:d', dann (m+1,d',h[n/d.1], inp, out)
und h[n/d.1](k)={d.1
h(k)
wenn k=n
sonst
+STSeqTrans.0=stseqtrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STSeqTrans.1=stseqtrans(stat 1 stat 2 . . . stat n , tab, a) :=\n +STSeqTrans.2=\tsttrans(stat 1 , tab, a.1)\n +STSeqTrans.3=\tsttrans(stat 2 , tab, a.2)\n +STSeqTrans.4=\t...\n +STSeqTrans.5=\tsttrans(stat n , tab, a.n)\n +STSeqTrans.6=für alle stat 1 , stat 2 , . . . , stat n \u2208 W(), tab \u2208 Tab und a \u2208 N\u2217 +STSeqTrans.7=Es wurde versucht, eine leere statement sequence zu transformieren. +STTrans.AssignError=Das Symbol auf der linken Seite der Zuweisung existiert nicht oder ist ein Konstantensymbol! +STTrans.ScanfError=Das Symbol in diesem scanf-Statement existiert nicht oder ist ein Konstantensymbol! +STTrans.PrintfError=Das Symbol in diesem printf-Statement existiert nicht oder ist ein Konstantensymbol! +STTrans.0=sttrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STTrans.1=sttrans({ stat 1 stat 2 . . . stat n }, tab, a) :=\n +STTrans.10=sttrans(printf("%d",id);, tab, a) :=\n +STTrans.11=\twenn tab(id ) = (var, n) dann WRITE n;\n +STTrans.12=\tfür alle id \u2208 W( Ident ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.13=sttrans(if ( exp ) stat, tab, a) :=\n +STTrans.14=\tboolexptrans(exp, tab)\n +STTrans.15=\tJMC a.1;\n +STTrans.16=\tsttrans(stat , tab, a.2)\n +STTrans.17=\ta.1:\n +STTrans.18=\tfür alle exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.19=\tund a \u2208 N\u2217 +STTrans.2=\tstseqtrans(stat 1, stat 2 . . . stat n , tab, a)\n +STTrans.20=sttrans(if ( exp ) stat 1 else stat 2 , tab, a) :=\n +STTrans.21=\tboolexptrans(exp, tab)\n +STTrans.22=\tJMC a.1;\n +STTrans.23=\tsttrans(stat 1 , tab, a.2)\n +STTrans.24=\tJMP a.3;\n +STTrans.25=\ta.1: sttrans(stat 2 , tab, a.4)\n +STTrans.26=\ta.3:\n +STTrans.27=\tfür alle exp \u2208 W( BoolExpression ), stat 1 , stat 2 \u2208 W( Statement ),\n +STTrans.28=\ttab \u2208 Tab und a \u2208 N\u2217 +STTrans.29=sttrans(while ( exp ) stat, tab, a) :=\n +STTrans.3=\tfür alle stat 1 , stat 2 , . . . , stat n \u2208 W( statement ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.30=\ta.1 : boolexptrans(exp, tab)\n +STTrans.31=\tJMC a.2;\n +STTrans.32=\tsttrans(stat , tab, a.3)\n +STTrans.33=\tJMP a.1;\n +STTrans.34=\ta.2:\n +STTrans.35=\tfür alle exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.36=\tund a \u2208 N\u2217 +STTrans.4=sttrans(id = exp;, tab, a) :=\n +STTrans.5=\twenn tab(id ) = (var, n) dann simpleexptrans(exp, tab) STORE n; +STTrans.6=\tfür alle id \u2208 W( Ident ), exp \u2208 W( SimpleExpression ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.7=sttrans(scanf("%i",&id);, tab, a) :=\n +STTrans.8=\twenn tab(id ) = (var, n) dann READ n;\n +STTrans.9=\tfür alle id \u2208 W( Ident ), tab \u2208 Tab und a \u2208 N\u2217 +Symbol.0=Ungültige Speicheradresse < +Symbol.1=Der Zugriff auf Adressen von Konstanten ist ungültig. +SymbolTable.0=Ein symbol mit id +SymbolTable.1=\ existiert bereits. +SymbolTable.10=Es wurde versucht, den Wert eines nicht existierenden Symbols auszulesen +SymbolTable.11=Es wurde versucht, den SymbolType eines nicht existierenden Symbols auszulesen +SymbolTable.2=Eine Variable it Speicheradresse +SymbolTable.3=\ existiert bereits +SymbolTable.9=Es wurde versucht, den SymbolType eines nicht existierenden Symbols auszulesen +Trans.0=trans: W() \u2212 \u2192 bProg0\n\n +Trans.1=trans( \#include int main() block ) := blocktrans(block) für alle block \u2208 W() +TransformationView.0=Typ +TransformationView.1=ID +TransformationView.10=Anwenden +TransformationView.12=Fertig transformieren +TransformationView.14=Simulieren +TransformationView.16=Zurück zum Editor +TransformationView.18=Definition / Regel +TransformationView.19=Vorschau +TransformationView.2=Adresse +TransformationView.25=Wollen Sie das transformatierte Programm an den Editor schicken? +TransformationView.26=übertrage +TransformationView.3=tab(ID) +TransformationView.32=Fehler +TransformationView.33=Alle anwenden ist im Zustand FINISHED nicht möglich. Internal program error\! +TransformationView.34=Fehler +TransformationView.35=Fehler +TransformationView.4=Fehler +TransformationView.40=Zurück zum Editor. +TransformationView.41=Den letzten Schritt rückgängig machen. +TransformationView.42=Die ausgewählte Transformationsfunktion anwenden. +TransformationView.43=In einem Schritt übersetzen. +TransformationView.44=Übertrage das übersetzte Programm zum Simulator. +TransformationView.5=Fehler +TransformationView.6=Fehler +TransformationView.8=Rückgängig +Transformator.0=Fehler +Transformator.1=Diese Funktion kann nicht weiter transformiert werden, sie ist bereits atomar. +Transformator.11=Fehler +Transformator.12=Die Transformation wurde erfolgreich abgeschlossen. +Transformator.13=Transformation abgeschlossen +Transformator.15=Dieser Index zeigt auf eine nicht anwendbare Transformationsfunktion.\n +Transformator.2=Ungültige Transformation +Transformator.3=Keine Transformationsfunktion am Index +Transformator.5=Diese Funktion kann nicht weiter transformiert werden, sie ist bereits atomar. +Transformator.6=Ungültige Transformation +Transformator.7=Fehler +Transformator.8=Die Transformation wurde erfolgreich abgeschlossen. +Transformator.9=Transformation abgeschlossen +TransformFunction.0=abstrakte transformationsfunktion +Write.0=Diese Ramzelle ist nicht definiert! +Write.1=Falls h \u220A \u2124, dann (m+1,d,h, inp, out:h(n)) +Sub.0=Der Datenkeller enthält weniger als zwei Elemente! +Sub.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2 dann (m+1,(d.2-d.1):d.3: ... :d.n,h, inp, out) diff --git a/bin/org/jalgo/module/am0c0/en.properties b/bin/org/jalgo/module/am0c0/en.properties new file mode 100644 index 0000000..115162e --- /dev/null +++ b/bin/org/jalgo/module/am0c0/en.properties @@ -0,0 +1,301 @@ +Add.0=Stack does not contain 2 or more values. +Add.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2+d.1):d.3: ... :d.n,h, inp, out) +AddressSolver.0=A StubTrans must not have a null address +AM0InputDialog.0=New abstract machine configuration +AM0InputDialog.1=PC +AM0InputDialog.12=Add +AM0InputDialog.13=Delete +AM0InputDialog.14=Enter a new machine configuration here.
Use ':' to separate values in the stack
and ',' to seperate values in the input- and output stream.

+AM0InputDialog.15=OK +AM0InputDialog.16=Cancel +AM0InputDialog.17=Initial configuration +AM0InputDialog.18=This ram element is not valid. It should not be empty\! +AM0InputDialog.19=This ram element is not valid.\n +AM0InputDialog.2=Stack (Separated with ':') +AM0InputDialog.20=Please check this numbers:\n +AM0InputDialog.21=Address: +AM0InputDialog.24=This ram element is not valid.\n +AM0InputDialog.25=The address should not be negative or 0 but it was:\n +AM0InputDialog.26=This ram address is not valid.\n +AM0InputDialog.27=\ Please check this address: +AM0InputDialog.28=This ram address is not valid.\n +AM0InputDialog.29=\ The address should not be negative or 0 but it was:\n +AM0InputDialog.3=RAM (Address, Value) +AM0InputDialog.4=Input (Separated with ',') +AM0InputDialog.43=at least there should be one number +AM0InputDialog.44=or more separated with ',' but it was:\n +AM0InputDialog.45=This input stream is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.46=at least there should be one number +AM0InputDialog.47=or more separated with ',' but it was:\n +AM0InputDialog.48=This stack is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.49=at least there should be one number +AM0InputDialog.5=Output (Separated with ',') +AM0InputDialog.50=or more separated with ':' but it was:\n +AM0InputDialog.51=This program counter is not valid.\nIt has to be a number greater or equals 1 but it was:\n +AM0InputDialog.52=It is not allowed to the leave the program counter empty\! +AM0InputDialog.6=Value: +AM0InputDialog.7=This output stream is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.74=RAM Configuration +AM0InputDialog.8=This address exists already. Do you want to override the value for this address? +AM0InputDialog.87=Stack Configuration +AM0InputDialog.9=This address did not exists:\n +AM0PagingTableModel.0=PC +AM0PagingTableModel.1=Stack +AM0PagingTableModel.10=  Showing steps from +AM0PagingTableModel.11= to +AM0PagingTableModel.12= +AM0PagingTableModel.2=Ram +AM0PagingTableModel.3=Input +AM0PagingTableModel.4=Output +AM0PagingTableModel.7=  Showing steps from +AM0PagingTableModel.8= to +AM0PagingTableModel.9= +AM0Scanner.0=Unknown internal scanner error +AM0Scanner.1=Error: could not match input +AM0Scanner.2=Error: pushback value was too large +AtomicTrans.0=This AtomicType is not valid +AtomicTrans.5=token must be null for AtomicTrans functions +AtomicTrans.6=A jump statement must have a jumpAddress +AtomicTrans.7=Applying AtomicTrans is not allowed. +BlockTrans.0=blocktrans: W() \u2212 \u2192 bProg0\n\n +BlockTrans.1=blocktrans({ decl statseq return 0;}) := stseqtrans(statseq, update(decl, tab \u2205 ), 1) +BlockTrans.2=for all decl \u2208 W() and statseq \u2208 W(), +BlockTrans.3=tab \u2205 \u2208 Tab with graph(tab \u2205 ) = \u2205 +BoolExpTrans.0=boolexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0\n\n +BoolExpTrans.1=boolexptrans(se 1 rel se 2 , tab) :=\n +BoolExpTrans.2=\tsimpleexptrans(se 1 , tab)\n +BoolExpTrans.3=\tsimpleexptrans(se 2 , tab)\n +BoolExpTrans.4=\tREL;\n +BoolExpTrans.5=for all se 1 , se 2 \u2208 W(), rel \u2208 {==, \!=, <, >, <=, >=} and tab \u2208 Tab +C0Scanner.0=Error: pushback value was too large +C0Scanner.177=Unknown internal scanner error +C0Scanner.178=Error: could not match input +Div.0=Stack does not contain 2 or more values. +Div.1=Division by zero. +Div.2=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2/d.1):d.3: ... :d.n,h, inp, out) +Editor.3=

The syntax validation was +Editor.4=successful. Now press the Run button.

+Editor.5=Transformed Program +EditorView.10=AM0-Code +EditorView.12=Console +EditorView.13=Options +EditorView.14=Editor +EditorView.15=Do you want to save your program before translation? +EditorView.16=Save +EditorView.17=Load some code to the editor. +EditorView.18=Save your currently edited code. +EditorView.19=Use the code for simulating or tranformating. +EditorView.2=Load +EditorView.20=Validate your code. +EditorView.21=Use AM0 code now. +EditorView.22=Use C0 code now. +EditorView.23=Line: +EditorView.24=\ Column: +EditorView.25=New file +EditorView.4=Save +EditorView.6=Validate +EditorView.7=Run +EditorView.9=C0-Code +Equal.0=Stack does not contain 2 or more values. +Equal.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2=d.1, and b=0, if d.2\!=d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +ErrorEvents.RemoveThisToken=Delete it to correct this error. +ErrorEvents.LexicalAnalysis=Lexical Analysis +ErrorEvents.SyntacticAnalysis=Syntactic Analysis +ErrorEvents.FollowingErrors=The following errors occured during validation: +ErrorEvents.FollowingError=The following error occured during validation: +ErrorEvents.NumberTooLarge=The number %s at line %d, column %d is too large: the maximum possible value is %d. +ErrorEvents.UnexpectedTokenAt=Unexpected token "%s" at line %d, column %d. +ErrorEvents.DontKnowWhatToDo=Can't process input "%s" on line %d. +ErrorEvents.UnexpectedEOF=Unexpected end-of-file at line %d, column %d. +ErrorEvents.UnexpectedEOL=Unexpected end-of-line at line %d, column %d. +ErrorEvents.InsertRelation=Insert one of the relations "==", "!=", ">=", "<=", ">" or "<" to complete this boolean expression. +ErrorEvents.InsertAmp=Insert "&" to complete this scanf statement. +ErrorEvents.InsertComma=Insert "," to correct this error. +ErrorEvents.InsertAssign=Insert "=" to correct this error. +ErrorEvents.InsertSemicolon=Insert ";" to complete the previous statement. +ErrorEvents.InsertIdent=Insert an identifier to correct this error. +ErrorEvents.InsertNumber=Insert a number to correct this error. +ErrorEvents.InsertNumber_AM0=Insert a number to complete this AM0 statement. +ErrorEvents.InsertSemicolon_AM0=Insert ";" to complete this AM0 statement. +GreaterEqual.0=Stack does not contain 2 or more values. +GreaterEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2\u2265d.1, and b=0, if d.2<d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +GreaterThen.0=Stack does not contain 2 or more values. +GreaterThen.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2>d.1, and b=0, if d.2\u2264d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +JEditor.0=IO Error +JEditor.1=AM0 Program (*.am0) +JEditor.13=IO Error +JEditor.3=C0 Program (*.c0) +JEditor.8=The current code has been modified.\nDo you want to save it? +JEditor.9=Confirm +Jmc.0=Stack does not contain 1 or more values. +Jmc.1=if d=0:d.2: ... :d.n with n \u2265 1 then (e,d.2: ... :d.n,h, inp, out)
else (m+1,d.2: ... :d.n,h, inp, out)
If the first stack element is 0 (logic false), then the program counter will be set to e.
Otherwise the first stack element has an other value (logic true), then the program counter will be incremented. +Jmp.0=(e,d,h, inp, out) +LesserEqual.0=Stack does not contain 2 or more values. +LesserEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2\u2264d.1, and b=0, if d.2>d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +LesserThen.0=Stack does not contain 2 or more values. +LesserThen.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2<d.1, and b=0, if d.2\u2265d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +Lit.0=(m+1,z:d,h, inp, out) +Load.0=This ram cell is not defined. +Load.1=if h(n) \u220A \u2115 then (m+1,h(n):d,h, inp, out) +Mod.0=Stack does not contain 2 or more values. +Mod.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2%.1):d.3: ... :d.n,h, inp, out) +ModuleInfo.2=Franz Gregor, Martin Morgenstern,\n +ModuleInfo.3=\ Max Leuth\u00E4user, David Voigt, Felix Schmitt +ModuleInfo.5=This module step by step compiles C0 programs to AM0 programs and simulates AM0 programs. +ModuleInfo.8=GNU General Public License. Using icons from the Tango Desktop Project. +Mul.0=Stack does not contain 2 or more values. +Mul.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2*d.1):d.3: ... :d.n,h, inp, out) +NotEqual.0=Stack does not contain 2 or more values. +NotEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
and b=1, if d.2\!=d.1, and b=0, if d.2=d.1,
that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +PresentationAction.0=Toggle presentation mode +Read.0=Target < 0 is not allowed\! +Read.1=Input stream is empty. +Read.2=if inp=first(inp).rest(inp) then (m+1,d,h[n/first(inp)], rest(inp), out)
and for every n \u220A \u2124 and w \u220A \u2124*: first(n:w)=n and rest(n:w)=w +SimpleExpTrans.0=simpleexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0 +SimulationView.11=Previous +SimulationView.13=Next +SimulationView.15=Clear +SimulationView.17=All in one step +SimulationView.19=Initial Configuration +SimulationView.23=The simulation will stop after a maximum of +SimulationView.24= steps and you have the choice to continue. +SimulationView.26=The simulation will stop after a maximum of +SimulationView.27= steps and you have the choice to continue. +SimulationView.28=\ \ Ask after: +SimulationView.29=\ steps +SimulationView.3=AM0-Table +SimulationView.31=Command-Hint +SimulationView.32=Show the first few steps of the simulation +SimulationView.33=Show the last final steps of the simulation +SimulationView.34=Return to the editor. +SimulationView.35=Go one step back. +SimulationView.36=Go one step forward +SimulationView.37=Do the whole simulation in one single step. +SimulationView.38=Enter a specific machine configuration. +SimulationView.39=Clear everything. This will delete your current machine configuration and remove every simulation step\! +SimulationView.4=AM0-Animation +SimulationView.5=To the top of the table +SimulationView.6=To the bottom of the table +SimulationView.7=Not started yet. +SimulationView.9=Back to Editor +Simulator.0=The was an error while simulating.\n +Simulator.1=The following command could not be executed:\n +Simulator.10=Latest step: +Simulator.12=  Showing steps from +Simulator.13= to +Simulator.14= +Simulator.15=\ \ Latest step: +Simulator.17=\ \ Latest step: +Simulator.19=\ steps are calculated.\n +Simulator.20=Do you want to continue?\n\n +Simulator.21=Choose 'no' to stop the simulation or 'yes' if you want to go on. +Simulator.22=Simulation +Simulator.23=\ \ Latest step: +Simulator.25=Not started yet. +Simulator.3=Reason:\n +Simulator.4=This jump command could not be executed:\n +Simulator.6=Reason:\n +Store.0=Stack does not contain 1 or more values. +Store.1=if d=d.1:d' then (m+1,d',h[n/d.1], inp, out)
and h[n/d.1](k)={d.1
h(k)
if k=n
otherwise
+STSeqTrans.0=stseqtrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STSeqTrans.1=stseqtrans(stat 1 stat 2 . . . stat n , tab, a) :=\n +STSeqTrans.2=\tsttrans(stat 1 , tab, a.1)\n +STSeqTrans.3=\tsttrans(stat 2 , tab, a.2)\n +STSeqTrans.4=\t...\n +STSeqTrans.5=\tsttrans(stat n , tab, a.n)\n +STSeqTrans.6=for all stat 1 , stat 2 , . . . , stat n \u2208 W(), tab \u2208 Tab and a \u2208 N\u2217 +STSeqTrans.7=It was attempted to translate an empty statement sequence. +STTrans.AssignError=The symbol on the left side of this assignment does not exist or is a constant symbol! +STTrans.ScanfError=The symbol in this scanf statement does not exist or is a constant symbol! +STTrans.PrintfError=The symbol in this printf statement does not exist or is a constant symbol! +STTrans.0=sttrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STTrans.1=sttrans({ stat 1 stat 2 . . . stat n }, tab, a) :=\n +STTrans.10=sttrans(printf("%d",id);, tab, a) :=\n +STTrans.11=\tif tab(id ) = (var, n) then WRITE n;\n +STTrans.12=\tfor all id \u2208 W( Ident ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.13=sttrans(if ( exp ) stat, tab, a) :=\n +STTrans.14=\tboolexptrans(exp, tab)\n +STTrans.15=\tJMC a.1;\n +STTrans.16=\tsttrans(stat , tab, a.2)\n +STTrans.17=\ta.1:\n +STTrans.18=\tfor all exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.19=\tand a \u2208 N\u2217 +STTrans.2=\tstseqtrans(stat 1 stat 2 . . . stat n , tab, a)\n +STTrans.20=sttrans(if ( exp ) stat 1 else stat 2 , tab, a) :=\n +STTrans.21=\tboolexptrans(exp, tab)\n +STTrans.22=\tJMC a.1;\n +STTrans.23=\tsttrans(stat 1 , tab, a.2)\n +STTrans.24=\tJMP a.3;\n +STTrans.25=\ta.1: sttrans(stat 2 , tab, a.4)\n +STTrans.26=\ta.3:\n +STTrans.27=\tfor all exp \u2208 W( BoolExpression ), stat 1 , stat 2 \u2208 W( Statement ),\n +STTrans.28=\ttab \u2208 Tab and a \u2208 N\u2217 +STTrans.29=sttrans(while ( exp ) stat, tab, a) :=\n +STTrans.3=\tfor all stat 1 , stat 2 , . . . , stat n \u2208 W( statement ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.30=\ta.1 : boolexptrans(exp, tab)\n +STTrans.31=\tJMC a.2;\n +STTrans.32=\tsttrans(stat , tab, a.3)\n +STTrans.33=\tJMP a.1;\n +STTrans.34=\ta.2:\n +STTrans.35=\tfor all exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.36=\tand a \u2208 N\u2217 +STTrans.4=sttrans(id = exp;, tab, a) :=\n +STTrans.5=\tif tab(id ) = (var, n) then simpleexptrans(exp, tab) STORE n; +STTrans.6=\tfor all id \u2208 W( Ident ), exp \u2208 W( SimpleExpression ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.7=sttrans(scanf("%i",&id);, tab, a) :=\n +STTrans.8=\tif tab(id ) = (var, n) then READ n;\n +STTrans.9=\tfor all id \u2208 W( Ident ), tab \u2208 Tab and a \u2208 N\u2217 +Symbol.0=The memory address must not be < +Symbol.1=Retrieving the address of a constant symbol is forbidden. +SymbolTable.0=A symbol with id +SymbolTable.1=\ already exists. +SymbolTable.10=It was attempted to retrieve the value of a non-existent symbol +SymbolTable.11=It was attempted to retrieve the SymbolType of an non-existent symbol +SymbolTable.2=A variable with address +SymbolTable.3=\ already exists +SymbolTable.9=It was attempted to retrieve the SymbolType of a non-existent symbol +Trans.0=trans: W() \u2212 \u2192 bProg0\n\n +Trans.1=trans( \#include int main() block ) := blocktrans(block) for all block \u2208 W() +TransformationView.0=Type +TransformationView.1=ID +TransformationView.10=Apply +TransformationView.12=Apply all +TransformationView.14=Simulate +TransformationView.16=Back to Editor +TransformationView.18=Definition / Rule +TransformationView.19=Preview +TransformationView.2=Address +TransformationView.25=Do you want to transmit the even translated program into the editor? +TransformationView.26=Transmit +TransformationView.3=tab(ID) +TransformationView.32=Error +TransformationView.33=Applying all is not possible in state FINISHED. Internal program error\! +TransformationView.34=Error +TransformationView.35=Error +TransformationView.4=Error +TransformationView.40=Return to the editor. +TransformationView.41=Go one step back. +TransformationView.42=Go one step forward and apply the selected transform function +TransformationView.43=Do the whole transformation in one single step. +TransformationView.44=Transfer the resulting AM0 code to the simulator. +TransformationView.5=Error +TransformationView.6=Error +TransformationView.8=One step back +Transformator.0=Error +Transformator.1=This functions is atomic and cannot be transformed anymore. +Transformator.11=Error +Transformator.12=The transformation finished successfully. +Transformator.13=Transformation finished +Transformator.15=This index points to a TransformFunction which cannot be applied.\n +Transformator.2=Invalid transformation +Transformator.3=There is no TransformFunction at index +Transformator.5=This functions is atomic and cannot be transformed anymore. +Transformator.6=Invalid transformation +Transformator.7=Error +Transformator.8=The transformation finished successfully. +Transformator.9=Transformation finished +TransformFunction.0=abstract transform function +Write.0=This ram cell is not defined. +Write.1=if h \u220A \u2124 then (m+1,d,h, inp, out:h(n)) +Sub.0=Stack does not contain 2 or more values. +Sub.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2-d.1):d.3: ... :d.n,h, inp, out) diff --git a/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$1.class b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$1.class new file mode 100644 index 0000000..827ac9a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$2.class b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$2.class new file mode 100644 index 0000000..a5fb2b4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog$2.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/AM0InputDialog.class b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog.class new file mode 100644 index 0000000..4098627 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/AM0InputDialog.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/AMTableRenderer.class b/bin/org/jalgo/module/am0c0/gui/AMTableRenderer.class new file mode 100644 index 0000000..855bc41 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/AMTableRenderer.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/EditorView$1.class b/bin/org/jalgo/module/am0c0/gui/EditorView$1.class new file mode 100644 index 0000000..b95bf51 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/EditorView$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/EditorView$2.class b/bin/org/jalgo/module/am0c0/gui/EditorView$2.class new file mode 100644 index 0000000..c34c757 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/EditorView$2.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/EditorView$ButtonHandler.class b/bin/org/jalgo/module/am0c0/gui/EditorView$ButtonHandler.class new file mode 100644 index 0000000..726c257 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/EditorView$ButtonHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/EditorView.class b/bin/org/jalgo/module/am0c0/gui/EditorView.class new file mode 100644 index 0000000..b7d144b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/EditorView.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/GuiConstants.class b/bin/org/jalgo/module/am0c0/gui/GuiConstants.class new file mode 100644 index 0000000..11ec112 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/GuiConstants.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/SimulationView$1.class b/bin/org/jalgo/module/am0c0/gui/SimulationView$1.class new file mode 100644 index 0000000..6f0ea15 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/SimulationView$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/SimulationView$2.class b/bin/org/jalgo/module/am0c0/gui/SimulationView$2.class new file mode 100644 index 0000000..d6946e8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/SimulationView$2.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/SimulationView$ButtonHandler.class b/bin/org/jalgo/module/am0c0/gui/SimulationView$ButtonHandler.class new file mode 100644 index 0000000..7177c70 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/SimulationView$ButtonHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/SimulationView.class b/bin/org/jalgo/module/am0c0/gui/SimulationView.class new file mode 100644 index 0000000..66cc262 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/SimulationView.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/TransformationView$1.class b/bin/org/jalgo/module/am0c0/gui/TransformationView$1.class new file mode 100644 index 0000000..dbbe1b2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/TransformationView$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/TransformationView$2.class b/bin/org/jalgo/module/am0c0/gui/TransformationView$2.class new file mode 100644 index 0000000..fae999d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/TransformationView$2.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/TransformationView$ButtonHandler.class b/bin/org/jalgo/module/am0c0/gui/TransformationView$ButtonHandler.class new file mode 100644 index 0000000..917347b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/TransformationView$ButtonHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/TransformationView.class b/bin/org/jalgo/module/am0c0/gui/TransformationView.class new file mode 100644 index 0000000..8526313 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/TransformationView.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/View.class b/bin/org/jalgo/module/am0c0/gui/View.class new file mode 100644 index 0000000..078d3cb Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/View.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter$Marker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter$Marker.class new file mode 100644 index 0000000..5b11110 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter$Marker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.class b/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.class new file mode 100644 index 0000000..01cce4d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$1.class b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$1.class new file mode 100644 index 0000000..2d36951 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$2.class b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$2.class new file mode 100644 index 0000000..cb50fe9 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$2.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$3.class b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$3.class new file mode 100644 index 0000000..5ec7068 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$3.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$ExInteger.class b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$ExInteger.class new file mode 100644 index 0000000..a9afe0f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor$ExInteger.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor.class b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor.class new file mode 100644 index 0000000..4730264 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/JEditor.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.class new file mode 100644 index 0000000..26130b5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Backspace.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Backspace.class new file mode 100644 index 0000000..bf798db Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Backspace.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Delete.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Delete.class new file mode 100644 index 0000000..d47a766 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Delete.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$End.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$End.class new file mode 100644 index 0000000..c4e4d0f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$End.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Home.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Home.class new file mode 100644 index 0000000..c9da1b8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Home.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$MacroRecorder.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$MacroRecorder.class new file mode 100644 index 0000000..6061233 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$MacroRecorder.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRecordable.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRecordable.class new file mode 100644 index 0000000..d352eb2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRecordable.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRepeatable.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRepeatable.class new file mode 100644 index 0000000..aafebf7 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$NonRepeatable.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Repeat.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Repeat.class new file mode 100644 index 0000000..a09288d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Repeat.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Wrapper.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Wrapper.class new file mode 100644 index 0000000..3283ea6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$Wrapper.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$backspace_word.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$backspace_word.class new file mode 100644 index 0000000..19282d0 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$backspace_word.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_copy.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_copy.class new file mode 100644 index 0000000..6205785 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_copy.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_cut.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_cut.class new file mode 100644 index 0000000..592ac32 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_cut.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_paste.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_paste.class new file mode 100644 index 0000000..2aa8241 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$clip_paste.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$delete_word.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$delete_word.class new file mode 100644 index 0000000..90a4ffe Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$delete_word.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_end.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_end.class new file mode 100644 index 0000000..66cbebe Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_end.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_home.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_home.class new file mode 100644 index 0000000..af93969 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$document_home.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_break.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_break.class new file mode 100644 index 0000000..70d6331 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_break.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_char.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_char.class new file mode 100644 index 0000000..716fe5d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_char.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_tab.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_tab.class new file mode 100644 index 0000000..ac21d9a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$insert_tab.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_char.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_char.class new file mode 100644 index 0000000..eaefb4e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_char.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_line.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_line.class new file mode 100644 index 0000000..7cb3dda Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_line.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_page.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_page.class new file mode 100644 index 0000000..5c48e52 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_page.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_word.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_word.class new file mode 100644 index 0000000..28c5fb0 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$next_word.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$overwrite.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$overwrite.class new file mode 100644 index 0000000..e7d9ffc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$overwrite.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_char.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_char.class new file mode 100644 index 0000000..1806e48 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_char.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_line.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_line.class new file mode 100644 index 0000000..f63fce8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_line.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_page.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_page.class new file mode 100644 index 0000000..27614f3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_page.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_word.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_word.class new file mode 100644 index 0000000..23d0c9a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$prev_word.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$select_all.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$select_all.class new file mode 100644 index 0000000..b4db1e6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$select_all.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$toggle_rect.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$toggle_rect.class new file mode 100644 index 0000000..350d9d6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler$toggle_rect.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.class new file mode 100644 index 0000000..406a5dd Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler$1.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler$1.class new file mode 100644 index 0000000..cfe9cac Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler$1.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler.class new file mode 100644 index 0000000..cd456e1 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$AdjustHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretBlinker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretBlinker.class new file mode 100644 index 0000000..88e5e39 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretBlinker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretUndo.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretUndo.class new file mode 100644 index 0000000..5ee0f34 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$CaretUndo.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ComponentHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ComponentHandler.class new file mode 100644 index 0000000..2d4d40f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ComponentHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DocumentHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DocumentHandler.class new file mode 100644 index 0000000..35a4bdd Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DocumentHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DragHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DragHandler.class new file mode 100644 index 0000000..a6c21ac Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$DragHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$FocusHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$FocusHandler.class new file mode 100644 index 0000000..8c5e852 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$FocusHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MouseHandler.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MouseHandler.class new file mode 100644 index 0000000..e8be711 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MouseHandler.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MutableCaretEvent.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MutableCaretEvent.class new file mode 100644 index 0000000..cef7890 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$MutableCaretEvent.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ScrollLayout.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ScrollLayout.class new file mode 100644 index 0000000..68de5d5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea$ScrollLayout.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.class new file mode 100644 index 0000000..44966ef Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap$Keyword.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap$Keyword.class new file mode 100644 index 0000000..9ff9857 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap$Keyword.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.class new file mode 100644 index 0000000..be9e569 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.class new file mode 100644 index 0000000..26db4d9 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.class new file mode 100644 index 0000000..64fc43a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.class new file mode 100644 index 0000000..ee8522a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.class new file mode 100644 index 0000000..5cc0f1b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter$Highlight.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter$Highlight.class new file mode 100644 index 0000000..cfc0638 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter$Highlight.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.class new file mode 100644 index 0000000..8bf70c0 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.class new file mode 100644 index 0000000..32be6b0 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.class new file mode 100644 index 0000000..b1c487d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.class new file mode 100644 index 0000000..78c6209 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.class new file mode 100644 index 0000000..6ea42b4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.class new file mode 100644 index 0000000..73aad1c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.class new file mode 100644 index 0000000..b062bab Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker$LineInfo.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker$LineInfo.class new file mode 100644 index 0000000..3499c69 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker$LineInfo.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.class new file mode 100644 index 0000000..d0b90ce Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.class b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.class new file mode 100644 index 0000000..e3a1231 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/jeditor/package-info.class b/bin/org/jalgo/module/am0c0/gui/jeditor/package-info.class new file mode 100644 index 0000000..613c388 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/jeditor/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/gui/package-info.class b/bin/org/jalgo/module/am0c0/gui/package-info.class new file mode 100644 index 0000000..ac18bfe Binary files /dev/null and b/bin/org/jalgo/module/am0c0/gui/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/model/AM0History.class b/bin/org/jalgo/module/am0c0/model/AM0History.class new file mode 100644 index 0000000..996d46c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/AM0History.class differ diff --git a/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$1.class b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$1.class new file mode 100644 index 0000000..4aebffe Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$1.class differ diff --git a/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$2.class b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$2.class new file mode 100644 index 0000000..aea03ac Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel$2.class differ diff --git a/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel.class b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel.class new file mode 100644 index 0000000..80f5d94 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/AM0PagingTableModel.class differ diff --git a/bin/org/jalgo/module/am0c0/model/Address.class b/bin/org/jalgo/module/am0c0/model/Address.class new file mode 100644 index 0000000..9d1d134 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/Address.class differ diff --git a/bin/org/jalgo/module/am0c0/model/AddressException.class b/bin/org/jalgo/module/am0c0/model/AddressException.class new file mode 100644 index 0000000..188a26a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/AddressException.class differ diff --git a/bin/org/jalgo/module/am0c0/model/ArrowIcon.class b/bin/org/jalgo/module/am0c0/model/ArrowIcon.class new file mode 100644 index 0000000..88c2e9e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/ArrowIcon.class differ diff --git a/bin/org/jalgo/module/am0c0/model/C0History.class b/bin/org/jalgo/module/am0c0/model/C0History.class new file mode 100644 index 0000000..a982fcc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/C0History.class differ diff --git a/bin/org/jalgo/module/am0c0/model/CodeObject.class b/bin/org/jalgo/module/am0c0/model/CodeObject.class new file mode 100644 index 0000000..bf08dbc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/CodeObject.class differ diff --git a/bin/org/jalgo/module/am0c0/model/GenericProgram.class b/bin/org/jalgo/module/am0c0/model/GenericProgram.class new file mode 100644 index 0000000..efa9c51 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/GenericProgram.class differ diff --git a/bin/org/jalgo/module/am0c0/model/LineAddress.class b/bin/org/jalgo/module/am0c0/model/LineAddress.class new file mode 100644 index 0000000..9d59ed0 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/LineAddress.class differ diff --git a/bin/org/jalgo/module/am0c0/model/SimulationSet.class b/bin/org/jalgo/module/am0c0/model/SimulationSet.class new file mode 100644 index 0000000..bfd69cc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/SimulationSet.class differ diff --git a/bin/org/jalgo/module/am0c0/model/TreeAddress.class b/bin/org/jalgo/module/am0c0/model/TreeAddress.class new file mode 100644 index 0000000..892a830 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/TreeAddress.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/AM0Program.class b/bin/org/jalgo/module/am0c0/model/am0/AM0Program.class new file mode 100644 index 0000000..bc128b4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/AM0Program.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Add.class b/bin/org/jalgo/module/am0c0/model/am0/Add.class new file mode 100644 index 0000000..c92606f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Add.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.class b/bin/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.class new file mode 100644 index 0000000..4556e3d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/CompareStatement.class b/bin/org/jalgo/module/am0c0/model/am0/CompareStatement.class new file mode 100644 index 0000000..6f4ec4b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/CompareStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Div.class b/bin/org/jalgo/module/am0c0/model/am0/Div.class new file mode 100644 index 0000000..f374915 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Div.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Equal.class b/bin/org/jalgo/module/am0c0/model/am0/Equal.class new file mode 100644 index 0000000..0338dd8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Equal.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/GreaterEqual.class b/bin/org/jalgo/module/am0c0/model/am0/GreaterEqual.class new file mode 100644 index 0000000..c327e3e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/GreaterEqual.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/GreaterThen.class b/bin/org/jalgo/module/am0c0/model/am0/GreaterThen.class new file mode 100644 index 0000000..79b2e10 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/GreaterThen.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/IOStatement.class b/bin/org/jalgo/module/am0c0/model/am0/IOStatement.class new file mode 100644 index 0000000..c3bd455 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/IOStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.class b/bin/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.class new file mode 100644 index 0000000..c625dcc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/InputStream.class b/bin/org/jalgo/module/am0c0/model/am0/InputStream.class new file mode 100644 index 0000000..954ffa6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/InputStream.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Jmc.class b/bin/org/jalgo/module/am0c0/model/am0/Jmc.class new file mode 100644 index 0000000..c819cf7 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Jmc.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Jmp.class b/bin/org/jalgo/module/am0c0/model/am0/Jmp.class new file mode 100644 index 0000000..8652a59 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Jmp.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/JumpStatement.class b/bin/org/jalgo/module/am0c0/model/am0/JumpStatement.class new file mode 100644 index 0000000..578a813 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/JumpStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/LesserEqual.class b/bin/org/jalgo/module/am0c0/model/am0/LesserEqual.class new file mode 100644 index 0000000..97661ce Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/LesserEqual.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/LesserThen.class b/bin/org/jalgo/module/am0c0/model/am0/LesserThen.class new file mode 100644 index 0000000..e601272 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/LesserThen.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Lit.class b/bin/org/jalgo/module/am0c0/model/am0/Lit.class new file mode 100644 index 0000000..489c133 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Lit.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Load.class b/bin/org/jalgo/module/am0c0/model/am0/Load.class new file mode 100644 index 0000000..0a7e4d6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Load.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/MachineConfiguration.class b/bin/org/jalgo/module/am0c0/model/am0/MachineConfiguration.class new file mode 100644 index 0000000..cf48514 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/MachineConfiguration.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/MemoryCell.class b/bin/org/jalgo/module/am0c0/model/am0/MemoryCell.class new file mode 100644 index 0000000..927032e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/MemoryCell.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/MemoryStatement.class b/bin/org/jalgo/module/am0c0/model/am0/MemoryStatement.class new file mode 100644 index 0000000..3bd3df3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/MemoryStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Mod.class b/bin/org/jalgo/module/am0c0/model/am0/Mod.class new file mode 100644 index 0000000..a4dbe8a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Mod.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Mul.class b/bin/org/jalgo/module/am0c0/model/am0/Mul.class new file mode 100644 index 0000000..1e4eb1c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Mul.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/NotEqual.class b/bin/org/jalgo/module/am0c0/model/am0/NotEqual.class new file mode 100644 index 0000000..d466fff Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/NotEqual.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/OutputStream.class b/bin/org/jalgo/module/am0c0/model/am0/OutputStream.class new file mode 100644 index 0000000..3c61f34 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/OutputStream.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/ProgramCounter.class b/bin/org/jalgo/module/am0c0/model/am0/ProgramCounter.class new file mode 100644 index 0000000..cb239bb Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/ProgramCounter.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Ram.class b/bin/org/jalgo/module/am0c0/model/am0/Ram.class new file mode 100644 index 0000000..767f73e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Ram.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Read.class b/bin/org/jalgo/module/am0c0/model/am0/Read.class new file mode 100644 index 0000000..d073d29 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Read.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/SimulationStatement.class b/bin/org/jalgo/module/am0c0/model/am0/SimulationStatement.class new file mode 100644 index 0000000..69512b5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/SimulationStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Stack.class b/bin/org/jalgo/module/am0c0/model/am0/Stack.class new file mode 100644 index 0000000..6ebdd19 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Stack.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Store.class b/bin/org/jalgo/module/am0c0/model/am0/Store.class new file mode 100644 index 0000000..a9bd5ec Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Store.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Stream.class b/bin/org/jalgo/module/am0c0/model/am0/Stream.class new file mode 100644 index 0000000..dfd48fb Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Stream.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Sub.class b/bin/org/jalgo/module/am0c0/model/am0/Sub.class new file mode 100644 index 0000000..f8b367f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Sub.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/Write.class b/bin/org/jalgo/module/am0c0/model/am0/Write.class new file mode 100644 index 0000000..bef1095 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/Write.class differ diff --git a/bin/org/jalgo/module/am0c0/model/am0/package-info.class b/bin/org/jalgo/module/am0c0/model/am0/package-info.class new file mode 100644 index 0000000..d7944fc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/am0/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/C0Program.class b/bin/org/jalgo/module/am0c0/model/c0/C0Program.class new file mode 100644 index 0000000..27955b6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/C0Program.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Block.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Block.class new file mode 100644 index 0000000..5c59554 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Block.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.class b/bin/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.class new file mode 100644 index 0000000..d2dcba6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$ConstIdent.class b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$ConstIdent.class new file mode 100644 index 0000000..33dfe27 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$ConstIdent.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$Ident.class b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$Ident.class new file mode 100644 index 0000000..393fd46 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST$Ident.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST.class b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST.class new file mode 100644 index 0000000..dfa694b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/C0AST.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.class b/bin/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.class new file mode 100644 index 0000000..ca3ba46 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Declaration.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Declaration.class new file mode 100644 index 0000000..a723362 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Declaration.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$CompExprFactor.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$CompExprFactor.class new file mode 100644 index 0000000..c84ad89 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$CompExprFactor.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$IdentFactor.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$IdentFactor.class new file mode 100644 index 0000000..1a18c9b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$IdentFactor.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$NumberFactor.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$NumberFactor.class new file mode 100644 index 0000000..564b5df Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor$NumberFactor.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Factor.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor.class new file mode 100644 index 0000000..4cd6157 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Factor.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Program.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Program.class new file mode 100644 index 0000000..cf796e5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Program.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$BinSimpleExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$BinSimpleExpr.class new file mode 100644 index 0000000..726f896 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$BinSimpleExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$MinusExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$MinusExpr.class new file mode 100644 index 0000000..bc7d4b9 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$MinusExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$PlusExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$PlusExpr.class new file mode 100644 index 0000000..0d4bd1a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$PlusExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryMinusExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryMinusExpr.class new file mode 100644 index 0000000..2c60560 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryMinusExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryPlusExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryPlusExpr.class new file mode 100644 index 0000000..7989563 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnaryPlusExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnarySimpleExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnarySimpleExpr.class new file mode 100644 index 0000000..e3cb2fd Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr$UnarySimpleExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.class b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.class new file mode 100644 index 0000000..f73c800 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$AssignmentStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$AssignmentStatement.class new file mode 100644 index 0000000..93a5279 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$AssignmentStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$CompStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$CompStatement.class new file mode 100644 index 0000000..7008b35 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$CompStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IOStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IOStatement.class new file mode 100644 index 0000000..dbf3c93 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IOStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfElseStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfElseStatement.class new file mode 100644 index 0000000..76c5c7d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfElseStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfStatement.class new file mode 100644 index 0000000..242c6ed Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$IfStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$PrintfStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$PrintfStatement.class new file mode 100644 index 0000000..bfc53c2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$PrintfStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$ScanfStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$ScanfStatement.class new file mode 100644 index 0000000..c472005 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$ScanfStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$WhileStatement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$WhileStatement.class new file mode 100644 index 0000000..d78fcf8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement$WhileStatement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Statement.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement.class new file mode 100644 index 0000000..1c4af88 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Statement.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.class b/bin/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.class new file mode 100644 index 0000000..5a32d44 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term$BinTerm.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$BinTerm.class new file mode 100644 index 0000000..fc9c7bf Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$BinTerm.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term$DivTerm.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$DivTerm.class new file mode 100644 index 0000000..1eaa6b6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$DivTerm.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term$FactorTerm.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$FactorTerm.class new file mode 100644 index 0000000..47bf723 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$FactorTerm.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term$ModTerm.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$ModTerm.class new file mode 100644 index 0000000..1adc92f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$ModTerm.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term$MultTerm.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$MultTerm.class new file mode 100644 index 0000000..234d203 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term$MultTerm.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/Term.class b/bin/org/jalgo/module/am0c0/model/c0/ast/Term.class new file mode 100644 index 0000000..1d16906 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/Term.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.class b/bin/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.class new file mode 100644 index 0000000..8cfc360 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/ast/package-info.class b/bin/org/jalgo/module/am0c0/model/c0/ast/package-info.class new file mode 100644 index 0000000..9ff5bb3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/ast/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/package-info.class b/bin/org/jalgo/module/am0c0/model/c0/package-info.class new file mode 100644 index 0000000..f18d479 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.class b/bin/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.class new file mode 100644 index 0000000..f821528 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans$AtomicType.class b/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans$AtomicType.class new file mode 100644 index 0000000..c9770c5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans$AtomicType.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.class new file mode 100644 index 0000000..ef6fd15 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.class new file mode 100644 index 0000000..bda5cae Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.class new file mode 100644 index 0000000..bbdfb86 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.class b/bin/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.class new file mode 100644 index 0000000..8117de2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.class new file mode 100644 index 0000000..b10338c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/STTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/STTrans.class new file mode 100644 index 0000000..3090d25 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/STTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.class new file mode 100644 index 0000000..e01bff1 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/StubTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/StubTrans.class new file mode 100644 index 0000000..8c09544 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/StubTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol$SymbolType.class b/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol$SymbolType.class new file mode 100644 index 0000000..843e10f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol$SymbolType.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol.class b/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol.class new file mode 100644 index 0000000..02614f4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/Symbol.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolException.class b/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolException.class new file mode 100644 index 0000000..15a775f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolException.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.class b/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.class new file mode 100644 index 0000000..9caf9f1 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/Trans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/Trans.class new file mode 100644 index 0000000..32b5bc4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/Trans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/TransException.class b/bin/org/jalgo/module/am0c0/model/c0/trans/TransException.class new file mode 100644 index 0000000..16411f4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/TransException.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.class b/bin/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.class new file mode 100644 index 0000000..165e02b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.class b/bin/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.class new file mode 100644 index 0000000..b0bae73 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.class differ diff --git a/bin/org/jalgo/module/am0c0/model/c0/trans/package-info.class b/bin/org/jalgo/module/am0c0/model/c0/trans/package-info.class new file mode 100644 index 0000000..772b62d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/c0/trans/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/model/package-info.class b/bin/org/jalgo/module/am0c0/model/package-info.class new file mode 100644 index 0000000..e28025e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/model/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/package-info.class b/bin/org/jalgo/module/am0c0/package-info.class new file mode 100644 index 0000000..b540a88 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/ErrorEvents$AM0ErrorEvents.class b/bin/org/jalgo/module/am0c0/parser/ErrorEvents$AM0ErrorEvents.class new file mode 100644 index 0000000..57fbc87 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/ErrorEvents$AM0ErrorEvents.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/ErrorEvents$C0ErrorEvents.class b/bin/org/jalgo/module/am0c0/parser/ErrorEvents$C0ErrorEvents.class new file mode 100644 index 0000000..fb1513d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/ErrorEvents$C0ErrorEvents.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/ErrorEvents.class b/bin/org/jalgo/module/am0c0/parser/ErrorEvents.class new file mode 100644 index 0000000..eeb4800 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/ErrorEvents.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/Parser.class b/bin/org/jalgo/module/am0c0/parser/Parser.class new file mode 100644 index 0000000..5558db2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/Parser.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/ParserConstants.class b/bin/org/jalgo/module/am0c0/parser/ParserConstants.class new file mode 100644 index 0000000..1f9612e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/ParserConstants.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/ParserUtils.class b/bin/org/jalgo/module/am0c0/parser/ParserUtils.class new file mode 100644 index 0000000..da84849 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/ParserUtils.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/AM0Parser.class b/bin/org/jalgo/module/am0c0/parser/am0/AM0Parser.class new file mode 100644 index 0000000..90f3e01 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/AM0Parser.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/AM0Scanner.class b/bin/org/jalgo/module/am0c0/parser/am0/AM0Scanner.class new file mode 100644 index 0000000..e3577f9 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/AM0Scanner.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$1.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$1.class new file mode 100644 index 0000000..6f37457 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$1.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$10.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$10.class new file mode 100644 index 0000000..2da5138 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$10.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$11.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$11.class new file mode 100644 index 0000000..f4c68da Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$11.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$12.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$12.class new file mode 100644 index 0000000..a3b91cf Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$12.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$13.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$13.class new file mode 100644 index 0000000..0351160 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$13.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$14.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$14.class new file mode 100644 index 0000000..ee9b020 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$14.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$15.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$15.class new file mode 100644 index 0000000..ba971d6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$15.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$16.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$16.class new file mode 100644 index 0000000..5e735fa Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$16.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$17.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$17.class new file mode 100644 index 0000000..d86538b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$17.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$18.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$18.class new file mode 100644 index 0000000..40187b3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$18.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$19.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$19.class new file mode 100644 index 0000000..5c776c1 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$19.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$2.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$2.class new file mode 100644 index 0000000..c435786 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$2.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$20.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$20.class new file mode 100644 index 0000000..60530f4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$20.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$21.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$21.class new file mode 100644 index 0000000..7aa063d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$21.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$22.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$22.class new file mode 100644 index 0000000..dac6d26 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$22.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$23.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$23.class new file mode 100644 index 0000000..728a0c2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$23.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$3.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$3.class new file mode 100644 index 0000000..092c482 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$3.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$4.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$4.class new file mode 100644 index 0000000..449c42e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$4.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$5.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$5.class new file mode 100644 index 0000000..36b31fa Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$5.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$6.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$6.class new file mode 100644 index 0000000..0fa8188 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$6.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$7.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$7.class new file mode 100644 index 0000000..68089dc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$7.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$8.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$8.class new file mode 100644 index 0000000..5581b55 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$8.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$9.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$9.class new file mode 100644 index 0000000..8ff85fe Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$9.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$Terminals.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$Terminals.class new file mode 100644 index 0000000..1c828ea Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser$Terminals.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.class b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.class new file mode 100644 index 0000000..0b21dcf Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/am0/package-info.class b/bin/org/jalgo/module/am0c0/parser/am0/package-info.class new file mode 100644 index 0000000..bbd8395 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/am0/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/C0Parser.class b/bin/org/jalgo/module/am0c0/parser/c0/C0Parser.class new file mode 100644 index 0000000..e4cf990 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/C0Parser.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/C0Scanner.class b/bin/org/jalgo/module/am0c0/parser/c0/C0Scanner.class new file mode 100644 index 0000000..1e9d448 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/C0Scanner.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$1.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$1.class new file mode 100644 index 0000000..43fe872 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$1.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$10.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$10.class new file mode 100644 index 0000000..17ed187 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$10.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$11.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$11.class new file mode 100644 index 0000000..95f59a5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$11.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$12.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$12.class new file mode 100644 index 0000000..453863e Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$12.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$13.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$13.class new file mode 100644 index 0000000..380e485 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$13.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$14.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$14.class new file mode 100644 index 0000000..9885852 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$14.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$15.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$15.class new file mode 100644 index 0000000..3f17445 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$15.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$16.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$16.class new file mode 100644 index 0000000..033a481 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$16.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$17.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$17.class new file mode 100644 index 0000000..d67b90d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$17.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$18.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$18.class new file mode 100644 index 0000000..d2255f2 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$18.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$19.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$19.class new file mode 100644 index 0000000..553c908 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$19.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$2.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$2.class new file mode 100644 index 0000000..563dbc5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$2.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$20.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$20.class new file mode 100644 index 0000000..56306b5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$20.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$21.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$21.class new file mode 100644 index 0000000..d889952 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$21.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$22.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$22.class new file mode 100644 index 0000000..2dd9ed6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$22.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$23.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$23.class new file mode 100644 index 0000000..eedb2a5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$23.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$24.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$24.class new file mode 100644 index 0000000..a1e2f0c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$24.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$25.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$25.class new file mode 100644 index 0000000..47ff087 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$25.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$26.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$26.class new file mode 100644 index 0000000..912da01 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$26.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$27.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$27.class new file mode 100644 index 0000000..7cdc801 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$27.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$28.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$28.class new file mode 100644 index 0000000..da4ee3c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$28.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$29.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$29.class new file mode 100644 index 0000000..e81aef4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$29.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$3.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$3.class new file mode 100644 index 0000000..d7a2883 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$3.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$30.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$30.class new file mode 100644 index 0000000..6b54bd3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$30.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$31.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$31.class new file mode 100644 index 0000000..8b37cdb Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$31.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$32.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$32.class new file mode 100644 index 0000000..8d5b69f Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$32.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$33.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$33.class new file mode 100644 index 0000000..ae0f448 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$33.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$34.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$34.class new file mode 100644 index 0000000..54c2fbf Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$34.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$35.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$35.class new file mode 100644 index 0000000..a247e93 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$35.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$36.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$36.class new file mode 100644 index 0000000..835f82d Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$36.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$37.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$37.class new file mode 100644 index 0000000..444ab7c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$37.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$38.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$38.class new file mode 100644 index 0000000..41cc1be Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$38.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$39.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$39.class new file mode 100644 index 0000000..229a13a Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$39.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$4.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$4.class new file mode 100644 index 0000000..8fedffb Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$4.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$40.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$40.class new file mode 100644 index 0000000..7d29db5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$40.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$41.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$41.class new file mode 100644 index 0000000..63f4ccc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$41.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$5.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$5.class new file mode 100644 index 0000000..a5968bc Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$5.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$6.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$6.class new file mode 100644 index 0000000..314aaed Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$6.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$7.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$7.class new file mode 100644 index 0000000..1d90828 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$7.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$8.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$8.class new file mode 100644 index 0000000..f214929 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$8.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$9.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$9.class new file mode 100644 index 0000000..5357d74 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$9.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$Terminals.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$Terminals.class new file mode 100644 index 0000000..51fd999 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser$Terminals.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.class b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.class new file mode 100644 index 0000000..d1c9bb6 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/c0/package-info.class b/bin/org/jalgo/module/am0c0/parser/c0/package-info.class new file mode 100644 index 0000000..404d4b3 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/c0/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/parser/package-info.class b/bin/org/jalgo/module/am0c0/parser/package-info.class new file mode 100644 index 0000000..4ccc7e5 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/parser/package-info.class differ diff --git a/bin/org/jalgo/module/am0c0/res.properties b/bin/org/jalgo/module/am0c0/res.properties new file mode 100644 index 0000000..ec73c2e --- /dev/null +++ b/bin/org/jalgo/module/am0c0/res.properties @@ -0,0 +1,26 @@ +HelpSet_Name=/help/jhelp/am0c0_help.hs +Main_Icon=/am0c0_pix/logo.gif +back_to_editor_Icon=/am0c0_pix/back_to_editor.png +clear_Icon=/am0c0_pix/clear.png +initial_config_Icon=/am0c0_pix/initial_configuration.png +last_Icon=/am0c0_pix/last.png +next_Icon=/am0c0_pix/next.png +open_Icon=/am0c0_pix/open.png +previous_Icon=/am0c0_pix/previous.png +run_Icon=/am0c0_pix/run.png +save_Icon=/am0c0_pix/save.png +ghost=/am0c0_pix/ilovecandy/ghost.gif +pacman=/am0c0_pix/ilovecandy/pacman.gif +up1=/am0c0_pix/ilovecandy/up1.gif +up2=/am0c0_pix/ilovecandy/up2.gif +up3=/am0c0_pix/ilovecandy/up3.gif +up1=/am0c0_pix/ilovecandy/up1.gif +down1=/am0c0_pix/ilovecandy/down1.gif +down2=/am0c0_pix/ilovecandy/down2.gif +down3=/am0c0_pix/ilovecandy/down3.gif +left1=/am0c0_pix/ilovecandy/left1.gif +left2=/am0c0_pix/ilovecandy/left2.gif +left3=/am0c0_pix/ilovecandy/left3.gif +right1=/am0c0_pix/ilovecandy/right1.gif +right2=/am0c0_pix/ilovecandy/right2.gif +right3=/am0c0_pix/ilovecandy/right3.gif \ No newline at end of file diff --git a/bin/org/jalgo/module/am0c0/tests/AddressSolverTest.class b/bin/org/jalgo/module/am0c0/tests/AddressSolverTest.class new file mode 100644 index 0000000..c417e93 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/AddressSolverTest.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/CParserTest$1.class b/bin/org/jalgo/module/am0c0/tests/CParserTest$1.class new file mode 100644 index 0000000..952e12c Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/CParserTest$1.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/CParserTest$2.class b/bin/org/jalgo/module/am0c0/tests/CParserTest$2.class new file mode 100644 index 0000000..7db657b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/CParserTest$2.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/CParserTest$CTestFixture.class b/bin/org/jalgo/module/am0c0/tests/CParserTest$CTestFixture.class new file mode 100644 index 0000000..5353ff8 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/CParserTest$CTestFixture.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/CParserTest.class b/bin/org/jalgo/module/am0c0/tests/CParserTest.class new file mode 100644 index 0000000..1619f64 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/CParserTest.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/SymbolTableTest.class b/bin/org/jalgo/module/am0c0/tests/SymbolTableTest.class new file mode 100644 index 0000000..9b3467b Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/SymbolTableTest.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/SymbolTest.class b/bin/org/jalgo/module/am0c0/tests/SymbolTest.class new file mode 100644 index 0000000..06b4f54 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/SymbolTest.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/TestUtils.class b/bin/org/jalgo/module/am0c0/tests/TestUtils.class new file mode 100644 index 0000000..6dffcbd Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/TestUtils.class differ diff --git a/bin/org/jalgo/module/am0c0/tests/TransformationTest.class b/bin/org/jalgo/module/am0c0/tests/TransformationTest.class new file mode 100644 index 0000000..d7b47c4 Binary files /dev/null and b/bin/org/jalgo/module/am0c0/tests/TransformationTest.class differ diff --git a/bin/org/jalgo/module/am1simulator/AM1Simulator$1.class b/bin/org/jalgo/module/am1simulator/AM1Simulator$1.class new file mode 100644 index 0000000..7a61064 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/AM1Simulator$1.class differ diff --git a/bin/org/jalgo/module/am1simulator/AM1Simulator.class b/bin/org/jalgo/module/am1simulator/AM1Simulator.class new file mode 100644 index 0000000..7bc6401 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/AM1Simulator.class differ diff --git a/bin/org/jalgo/module/am1simulator/ModuleConnector.class b/bin/org/jalgo/module/am1simulator/ModuleConnector.class new file mode 100644 index 0000000..a0553ef Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/am1simulator/ModuleInfo.class b/bin/org/jalgo/module/am1simulator/ModuleInfo.class new file mode 100644 index 0000000..1ac8489 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/AM1History.class b/bin/org/jalgo/module/am1simulator/model/AM1History.class new file mode 100644 index 0000000..81debee Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/AM1History.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/AM1PagingTableModel.class b/bin/org/jalgo/module/am1simulator/model/AM1PagingTableModel.class new file mode 100644 index 0000000..64d8963 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/AM1PagingTableModel.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/AddressException.class b/bin/org/jalgo/module/am1simulator/model/AddressException.class new file mode 100644 index 0000000..5291a18 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/AddressException.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/ArrowIcon.class b/bin/org/jalgo/module/am1simulator/model/ArrowIcon.class new file mode 100644 index 0000000..d931303 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/ArrowIcon.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/LineAddress.class b/bin/org/jalgo/module/am1simulator/model/LineAddress.class new file mode 100644 index 0000000..ef922ec Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/LineAddress.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/SimulationSet.class b/bin/org/jalgo/module/am1simulator/model/SimulationSet.class new file mode 100644 index 0000000..1316287 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/SimulationSet.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/AM1Program.class b/bin/org/jalgo/module/am1simulator/model/am1/AM1Program.class new file mode 100644 index 0000000..3298cf1 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/AM1Program.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory$Statement.class b/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory$Statement.class new file mode 100644 index 0000000..85eecfc Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory$Statement.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.class new file mode 100644 index 0000000..be770da Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Add.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Add.class new file mode 100644 index 0000000..f09d026 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Add.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Div.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Div.class new file mode 100644 index 0000000..59cf95f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Div.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mod.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mod.class new file mode 100644 index 0000000..294cc88 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mod.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mul.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mul.class new file mode 100644 index 0000000..2c238d8 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Mul.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Sub.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Sub.class new file mode 100644 index 0000000..596120f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory$Sub.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.class new file mode 100644 index 0000000..0f1a10b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$Equal.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$Equal.class new file mode 100644 index 0000000..64f894b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$Equal.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterEqual.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterEqual.class new file mode 100644 index 0000000..33059f1 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterEqual.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterThen.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterThen.class new file mode 100644 index 0000000..48f8de1 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$GreaterThen.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserEqual.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserEqual.class new file mode 100644 index 0000000..f57e214 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserEqual.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserThen.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserThen.class new file mode 100644 index 0000000..2d59ecb Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$LesserThen.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$NotEqual.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$NotEqual.class new file mode 100644 index 0000000..dfd0389 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory$NotEqual.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.class new file mode 100644 index 0000000..2ba5fbf Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Read.class b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Read.class new file mode 100644 index 0000000..a8079f4 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Read.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Readi.class b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Readi.class new file mode 100644 index 0000000..5c8a9f8 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Readi.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Write.class b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Write.class new file mode 100644 index 0000000..38c5e8d Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Write.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Writei.class b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Writei.class new file mode 100644 index 0000000..9c1ecce Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory$Writei.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.class new file mode 100644 index 0000000..f3f0d43 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmc.class b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmc.class new file mode 100644 index 0000000..e5ffdac Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmc.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmp.class b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmp.class new file mode 100644 index 0000000..4e48040 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory$Jmp.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.class new file mode 100644 index 0000000..e549e0b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Load.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Load.class new file mode 100644 index 0000000..3cbd626 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Load.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loada.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loada.class new file mode 100644 index 0000000..fff2e89 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loada.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loadi.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loadi.class new file mode 100644 index 0000000..f827c74 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Loadi.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Store.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Store.class new file mode 100644 index 0000000..52046f5 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Store.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Storei.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Storei.class new file mode 100644 index 0000000..e4a816f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory$Storei.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.class new file mode 100644 index 0000000..41d209f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Call.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Call.class new file mode 100644 index 0000000..d8773e7 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Call.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Init.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Init.class new file mode 100644 index 0000000..28e8ffe Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Init.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Lit.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Lit.class new file mode 100644 index 0000000..9bbedef Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Lit.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Push.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Push.class new file mode 100644 index 0000000..96c2d1e Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Push.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Ret.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Ret.class new file mode 100644 index 0000000..c56e382 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory$Ret.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.class b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.class new file mode 100644 index 0000000..a8e6a89 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/SimulationStatement.class b/bin/org/jalgo/module/am1simulator/model/am1/SimulationStatement.class new file mode 100644 index 0000000..6a7e006 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/SimulationStatement.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/StatementResource$Builder.class b/bin/org/jalgo/module/am1simulator/model/am1/StatementResource$Builder.class new file mode 100644 index 0000000..5b1d825 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/StatementResource$Builder.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/StatementResource.class b/bin/org/jalgo/module/am1simulator/model/am1/StatementResource.class new file mode 100644 index 0000000..2ae5cec Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/StatementResource.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/InputStream.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/InputStream.class new file mode 100644 index 0000000..64f3713 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/InputStream.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.class new file mode 100644 index 0000000..1e88e55 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.class new file mode 100644 index 0000000..9e325d9 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.class new file mode 100644 index 0000000..3d448ab Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.class new file mode 100644 index 0000000..73ab411 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/Ref.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/Ref.class new file mode 100644 index 0000000..2c1b93a Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/Ref.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.class new file mode 100644 index 0000000..32b0ada Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.class new file mode 100644 index 0000000..ea74457 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/Stack.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/Stack.class new file mode 100644 index 0000000..8dba5a2 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/Stack.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/Stream.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/Stream.class new file mode 100644 index 0000000..470437d Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/Stream.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/machine/package-info.class b/bin/org/jalgo/module/am1simulator/model/am1/machine/package-info.class new file mode 100644 index 0000000..a04a25c Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/machine/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/am1/package-info.class b/bin/org/jalgo/module/am1simulator/model/am1/package-info.class new file mode 100644 index 0000000..e8bad80 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/am1/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/model/package-info.class b/bin/org/jalgo/module/am1simulator/model/package-info.class new file mode 100644 index 0000000..de9d808 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/model/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/package-info.class b/bin/org/jalgo/module/am1simulator/package-info.class new file mode 100644 index 0000000..4fb3238 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/AM1Lexer.class b/bin/org/jalgo/module/am1simulator/parser/AM1Lexer.class new file mode 100644 index 0000000..115bd57 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/AM1Lexer.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.class b/bin/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.class new file mode 100644 index 0000000..a083ce6 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/ErrorEvents$AM1ErrorEvents.class b/bin/org/jalgo/module/am1simulator/parser/ErrorEvents$AM1ErrorEvents.class new file mode 100644 index 0000000..69021e1 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/ErrorEvents$AM1ErrorEvents.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/ErrorEvents.class b/bin/org/jalgo/module/am1simulator/parser/ErrorEvents.class new file mode 100644 index 0000000..573b092 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/ErrorEvents.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/Parser.class b/bin/org/jalgo/module/am1simulator/parser/Parser.class new file mode 100644 index 0000000..d9c2404 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/Parser.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/ParserConstants.class b/bin/org/jalgo/module/am1simulator/parser/ParserConstants.class new file mode 100644 index 0000000..ee87aa8 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/ParserConstants.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/ParserUtils.class b/bin/org/jalgo/module/am1simulator/parser/ParserUtils.class new file mode 100644 index 0000000..598ef86 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/ParserUtils.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/AM1Parser.class b/bin/org/jalgo/module/am1simulator/parser/am1/AM1Parser.class new file mode 100644 index 0000000..8302875 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/AM1Parser.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.class b/bin/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.class new file mode 100644 index 0000000..d9d404b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$1.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$1.class new file mode 100644 index 0000000..466666f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$1.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$10.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$10.class new file mode 100644 index 0000000..6b5d46e Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$10.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$11.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$11.class new file mode 100644 index 0000000..e14c176 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$11.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$12.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$12.class new file mode 100644 index 0000000..6bb8849 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$12.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$13.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$13.class new file mode 100644 index 0000000..e84da82 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$13.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$14.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$14.class new file mode 100644 index 0000000..3ec4400 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$14.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$15.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$15.class new file mode 100644 index 0000000..4f4cc60 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$15.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$16.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$16.class new file mode 100644 index 0000000..6198679 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$16.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$17.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$17.class new file mode 100644 index 0000000..26e4ca2 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$17.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$18.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$18.class new file mode 100644 index 0000000..2738b35 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$18.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$19.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$19.class new file mode 100644 index 0000000..b498bd5 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$19.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$2.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$2.class new file mode 100644 index 0000000..aef63c1 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$2.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$20.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$20.class new file mode 100644 index 0000000..bc04d9d Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$20.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$21.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$21.class new file mode 100644 index 0000000..d86826b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$21.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$22.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$22.class new file mode 100644 index 0000000..2b90ddd Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$22.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$23.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$23.class new file mode 100644 index 0000000..9b32ac6 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$23.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$24.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$24.class new file mode 100644 index 0000000..8b41b67 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$24.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$25.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$25.class new file mode 100644 index 0000000..869a3d6 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$25.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$26.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$26.class new file mode 100644 index 0000000..fad79cd Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$26.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$27.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$27.class new file mode 100644 index 0000000..c185877 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$27.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$28.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$28.class new file mode 100644 index 0000000..81cd8c4 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$28.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$29.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$29.class new file mode 100644 index 0000000..45075a9 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$29.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$3.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$3.class new file mode 100644 index 0000000..609e85e Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$3.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$30.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$30.class new file mode 100644 index 0000000..36585fd Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$30.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$31.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$31.class new file mode 100644 index 0000000..f75fdec Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$31.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$32.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$32.class new file mode 100644 index 0000000..d73ac4b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$32.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$33.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$33.class new file mode 100644 index 0000000..4f3a2ea Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$33.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$34.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$34.class new file mode 100644 index 0000000..3e7a58b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$34.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$4.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$4.class new file mode 100644 index 0000000..e484bb0 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$4.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$5.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$5.class new file mode 100644 index 0000000..d923375 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$5.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$6.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$6.class new file mode 100644 index 0000000..50de971 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$6.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$7.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$7.class new file mode 100644 index 0000000..bd85c08 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$7.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$8.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$8.class new file mode 100644 index 0000000..b4b64fd Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$8.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$9.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$9.class new file mode 100644 index 0000000..340299f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$9.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$Terminals.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$Terminals.class new file mode 100644 index 0000000..046262b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser$Terminals.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.class b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.class new file mode 100644 index 0000000..545d27b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/am1/package-info.class b/bin/org/jalgo/module/am1simulator/parser/am1/package-info.class new file mode 100644 index 0000000..6bff6c7 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/am1/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/package-info.class b/bin/org/jalgo/module/am1simulator/parser/package-info.class new file mode 100644 index 0000000..eca0af4 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/parser/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l b/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l new file mode 100644 index 0000000..fbcc888 --- /dev/null +++ b/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l @@ -0,0 +1,76 @@ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +/* Author: Max Leuthäuser */ + +package parser.am1; + +import beaver.Symbol; +import beaver.Scanner; +import parser.ParserConstants; +import parser.am1.GeneratedAM1Parser.Terminals; + +%% + +%class AM1Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Number = 0 | [1-9][0-9]* +Whitespace = [\t\f ] + +%% + +{Whitespace}+ { /* ignore */ } +{LineTerminator} { return symbol(Terminals.EOL, ParserConstants.EOL); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"," { return symbol(Terminals.COMMA, ","); } +"(" { return symbol(Terminals.LBRAKET, "("); } +")" { return symbol(Terminals.RBRAKET, ")"); } +"lokal" { return symbol(Terminals.LOCAL, "lokal"); } +"global" { return symbol(Terminals.GLOBAL, "global"); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +"ADD" { return symbol(Terminals.ADD, "ADD"); } +"MUL" { return symbol(Terminals.MUL, "MUL"); } +"SUB" { return symbol(Terminals.SUB, "SUB"); } +"DIV" { return symbol(Terminals.DIV, "DIV"); } +"MOD" { return symbol(Terminals.MOD, "MOD"); } +"EQ" { return symbol(Terminals.EQ, "EQ"); } +"NE" { return symbol(Terminals.NE, "NE"); } +"LT" { return symbol(Terminals.LT, "LT"); } +"GT" { return symbol(Terminals.GT, "GT"); } +"LE" { return symbol(Terminals.LE, "LE"); } +"GE" { return symbol(Terminals.GE, "GE"); } +"LOAD" { return symbol(Terminals.LOAD, "LOAD"); } +"LOADA" { return symbol(Terminals.LOADA, "LOADA"); } +"LOADI" { return symbol(Terminals.LOADI, "LOADI"); } +"STORE" { return symbol(Terminals.STORE, "STORE"); } +"STOREI" { return symbol(Terminals.STOREI, "STOREI"); } +"LIT" { return symbol(Terminals.LIT, "LIT"); } +"JMP" { return symbol(Terminals.JMP, "JMP"); } +"JMC" { return symbol(Terminals.JMC, "JMC"); } +"WRITE" { return symbol(Terminals.WRITE, "WRITE"); } +"WRITEI" { return symbol(Terminals.WRITEI, "WRITEI"); } +"READ" { return symbol(Terminals.READ, "READ"); } +"READI" { return symbol(Terminals.READI, "READI"); } +"PUSH" { return symbol(Terminals.PUSH, "PUSH"); } +"CALL" { return symbol(Terminals.CALL, "CALL"); } +"INIT" { return symbol(Terminals.INIT, "INIT"); } +"RET" { return symbol(Terminals.RET, "RET"); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } + diff --git a/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g b/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g new file mode 100644 index 0000000..b461615 --- /dev/null +++ b/bin/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g @@ -0,0 +1,145 @@ +// Author: Max Leuthäuser +%header {: +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +:}; +%package "parser.am1"; +%import "parser.ErrorEvents"; +%import "parser.ParserUtils"; +%import "model.LineAddress"; +%import "model.AddressException"; +%import "model.am1.*"; +%import "model.am1.AbstractStatementFactory.Statement"; + +%class "GeneratedAM1Parser"; + +%embed {: + private ArithmeticStatementFactory arithmetic = new ArithmeticStatementFactory(); + private CompareStatementFactory compare = new CompareStatementFactory(); + private IOStatementFactory io = new IOStatementFactory(); + private JumpStatementFactory jump = new JumpStatementFactory(); + private MemoryStatementFactory memory = new MemoryStatementFactory(); + private ProceduralStatementFactory procedural = new ProceduralStatementFactory(); + + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } +:}; + +%init {: + this.report = ErrorEvents.forAm1(); +:}; + +%terminals ADD, MUL, SUB, DIV, MOD; +%terminals EQ, NE, LT, GT, LE, GE; +%terminals LOAD, STORE, LIT; +%terminals LOADA, LOADI, STOREI; +%terminals JMP, JMC; +%terminals WRITE, READ; +%terminals WRITEI, READI; +%terminals PUSH, CALL, INIT, RET; +%terminals EOL, SEMICOLON, COMMA; +%terminals NUMBER, MINUS, LBRAKET, RBRAKET; +%terminals GLOBAL, LOCAL; + +%goal Program; + +%typeof CommandList, Program = "AM1Program"; +%typeof Command = "SimulationStatement"; +%typeof UnsignedNumber, Number = "Integer"; +%typeof Location = "String"; + +Program + = CommandList + ; + +CommandList + = Command.a SEMICOLON + {: AM1Program program = new AM1Program(); program.add(a); return new Symbol(program); :} + | CommandList.a EOL Command.b SEMICOLON + {: a.add(b); return new Symbol(a); :} + ; + +Command + = ADD.a + {: return new Symbol(arithmetic.newStatement(Statement.ADD, new StatementResource.Builder(address(a)).build())); :} + | MUL.a + {: return new Symbol(arithmetic.newStatement(Statement.MUL, new StatementResource.Builder(address(a)).build())); :} + | SUB.a + {: return new Symbol(arithmetic.newStatement(Statement.SUB, new StatementResource.Builder(address(a)).build())); :} + | DIV.a + {: return new Symbol(arithmetic.newStatement(Statement.DIV, new StatementResource.Builder(address(a)).build())); :} + | MOD.a + {: return new Symbol(arithmetic.newStatement(Statement.MOD, new StatementResource.Builder(address(a)).build())); :} + | EQ.a + {: return new Symbol(compare.newStatement(Statement.EQUAL, new StatementResource.Builder(address(a)).build())); :} + | NE.a + {: return new Symbol(compare.newStatement(Statement.NOTEQUAL, new StatementResource.Builder(address(a)).build())); :} + | LT.a + {: return new Symbol(compare.newStatement(Statement.LESSERTHEN, new StatementResource.Builder(address(a)).build())); :} + | GT.a + {: return new Symbol(compare.newStatement(Statement.GREATERTHEN, new StatementResource.Builder(address(a)).build())); :} + | LE.a + {: return new Symbol(compare.newStatement(Statement.LESSEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | GE.a + {: return new Symbol(compare.newStatement(Statement.GREATEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | JMP.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMP, new StatementResource.Builder(address(a)).value(b).build())); :} + | JMC.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMC, new StatementResource.Builder(address(a)).value(b).build())); :} + | LOAD.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOAD, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADA.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADA, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADI, new StatementResource.Builder(address(a)).value(b).build())); :} + | STORE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.STORE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | STOREI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.STOREI, new StatementResource.Builder(address(a)).value(b).build())); :} + | WRITE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | WRITEI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITEI, new StatementResource.Builder(address(a)).value(b).build())); :} + | READ.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.READ, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | READI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.READI, new StatementResource.Builder(address(a)).value(b).build())); :} + | PUSH.a + {: return new Symbol(procedural.newStatement(Statement.PUSH, new StatementResource.Builder(address(a)).build())); :} + | CALL.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.CALL, new StatementResource.Builder(address(a)).value(b).build())); :} + | INIT.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.INIT, new StatementResource.Builder(address(a)).value(b).build())); :} + | RET.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.RET, new StatementResource.Builder(address(a)).value(b).build())); :} + | LIT.a Number.b + {: return new Symbol(procedural.newStatement(Statement.LIT, new StatementResource.Builder(address(a)).value(b).build())); :} + ; + +UnsignedNumber + = NUMBER.a + {: return new Symbol(ParserUtils.safeSymbolToInt(a, (ErrorEvents) report)); :} + ; + +Location + = LOCAL + {: return new Symbol("lokal"); :} + | GLOBAL + {: return new Symbol("global"); :} + ; + +Number + = UnsignedNumber.a + {: return new Symbol(a); :} + | MINUS UnsignedNumber.a + {: return new Symbol(-a); :} + ; + diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$1.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$1.class new file mode 100644 index 0000000..eb470ae Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$1.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$2.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$2.class new file mode 100644 index 0000000..cdd0d7a Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$2.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$Editing.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$Editing.class new file mode 100644 index 0000000..3b92ae9 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$Editing.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$Simulating.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$Simulating.class new file mode 100644 index 0000000..de86268 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$Simulating.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$State.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$State.class new file mode 100644 index 0000000..258a26f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$State.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator$UserInputListener.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator$UserInputListener.class new file mode 100644 index 0000000..7b80d8f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator$UserInputListener.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/Simulator.class b/bin/org/jalgo/module/am1simulator/presenter/Simulator.class new file mode 100644 index 0000000..3fde2b6 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/Simulator.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/UpdateEvent.class b/bin/org/jalgo/module/am1simulator/presenter/UpdateEvent.class new file mode 100644 index 0000000..6dd6795 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/UpdateEvent.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.class b/bin/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.class new file mode 100644 index 0000000..3dd8c2b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/UpdateListener.class b/bin/org/jalgo/module/am1simulator/presenter/UpdateListener.class new file mode 100644 index 0000000..8488dcb Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/UpdateListener.class differ diff --git a/bin/org/jalgo/module/am1simulator/presenter/package-info.class b/bin/org/jalgo/module/am1simulator/presenter/package-info.class new file mode 100644 index 0000000..c6b558b Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/presenter/package-info.class differ diff --git a/bin/org/jalgo/module/am1simulator/res.properties b/bin/org/jalgo/module/am1simulator/res.properties new file mode 100644 index 0000000..dacc26a --- /dev/null +++ b/bin/org/jalgo/module/am1simulator/res.properties @@ -0,0 +1,15 @@ +HelpSet_Name=/help/jhelp/am1simulator_help.hs +back_Icon=/am1simulator_pix/back.png +bottom_Icon=/am1simulator_pix/bottom.png +clear_Icon=/am1simulator_pix/clear.png +editor_Icon=/am1simulator_pix/editor.png +file_Icon=/am1simulator_pix/file.png +forward_Icon=/am1simulator_pix/forward.png +initial_Icon=/am1simulator_pix/initial.png +onestep_Icon=/am1simulator_pix/onestep.png +open_Icon=/am1simulator_pix/open.png +run_Icon=/am1simulator_pix/run.png +save_Icon=/am1simulator_pix/save.png +stop_Icon=/am1simulator_pix/stop.png +top_Icon=/am1simulator_pix/top.png +Main_Icon=/am1simulator_pix/logo.gif \ No newline at end of file diff --git a/bin/org/jalgo/module/am1simulator/view/GUIBuilder.class b/bin/org/jalgo/module/am1simulator/view/GUIBuilder.class new file mode 100644 index 0000000..3088224 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/GUIBuilder.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/GuiUtilities.class b/bin/org/jalgo/module/am1simulator/view/GuiUtilities.class new file mode 100644 index 0000000..a5335a4 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/GuiUtilities.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/ViewContainer$Builder.class b/bin/org/jalgo/module/am1simulator/view/ViewContainer$Builder.class new file mode 100644 index 0000000..1c33937 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/ViewContainer$Builder.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/ViewContainer.class b/bin/org/jalgo/module/am1simulator/view/ViewContainer.class new file mode 100644 index 0000000..8acc4d0 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/ViewContainer.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/AM1InputDialog.class b/bin/org/jalgo/module/am1simulator/view/components/AM1InputDialog.class new file mode 100644 index 0000000..b083994 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/AM1InputDialog.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/AMTableRenderer.class b/bin/org/jalgo/module/am1simulator/view/components/AMTableRenderer.class new file mode 100644 index 0000000..8946dfe Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/AMTableRenderer.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/ConsolePanel.class b/bin/org/jalgo/module/am1simulator/view/components/ConsolePanel.class new file mode 100644 index 0000000..f20e734 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/ConsolePanel.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$1.class b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$1.class new file mode 100644 index 0000000..f554b3e Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$1.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$2.class b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$2.class new file mode 100644 index 0000000..937d06a Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$2.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$3.class b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$3.class new file mode 100644 index 0000000..d96c38f Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel$3.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/EditorPanel.class b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel.class new file mode 100644 index 0000000..47b7ec4 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/EditorPanel.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/MainPanel.class b/bin/org/jalgo/module/am1simulator/view/components/MainPanel.class new file mode 100644 index 0000000..e9b40d3 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/MainPanel.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/PresentationAction.class b/bin/org/jalgo/module/am1simulator/view/components/PresentationAction.class new file mode 100644 index 0000000..9c4e085 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/PresentationAction.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/TablePanel.class b/bin/org/jalgo/module/am1simulator/view/components/TablePanel.class new file mode 100644 index 0000000..3cb49b2 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/TablePanel.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/Toolbar$ButtonType.class b/bin/org/jalgo/module/am1simulator/view/components/Toolbar$ButtonType.class new file mode 100644 index 0000000..aa1d475 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/Toolbar$ButtonType.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/components/Toolbar.class b/bin/org/jalgo/module/am1simulator/view/components/Toolbar.class new file mode 100644 index 0000000..c1f5f66 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/components/Toolbar.class differ diff --git a/bin/org/jalgo/module/am1simulator/view/package-info.class b/bin/org/jalgo/module/am1simulator/view/package-info.class new file mode 100644 index 0000000..bc36545 Binary files /dev/null and b/bin/org/jalgo/module/am1simulator/view/package-info.class differ diff --git a/bin/org/jalgo/module/app/ModuleConnector.class b/bin/org/jalgo/module/app/ModuleConnector.class new file mode 100644 index 0000000..7041bed Binary files /dev/null and b/bin/org/jalgo/module/app/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/app/ModuleInfo.class b/bin/org/jalgo/module/app/ModuleInfo.class new file mode 100644 index 0000000..ad0e84a Binary files /dev/null and b/bin/org/jalgo/module/app/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/app/controller/AlgorithmController$AnimationTimerTask.class b/bin/org/jalgo/module/app/controller/AlgorithmController$AnimationTimerTask.class new file mode 100644 index 0000000..963ce38 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/AlgorithmController$AnimationTimerTask.class differ diff --git a/bin/org/jalgo/module/app/controller/AlgorithmController.class b/bin/org/jalgo/module/app/controller/AlgorithmController.class new file mode 100644 index 0000000..d08f6f9 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/AlgorithmController.class differ diff --git a/bin/org/jalgo/module/app/controller/GraphActionListener$EditMode.class b/bin/org/jalgo/module/app/controller/GraphActionListener$EditMode.class new file mode 100644 index 0000000..a4c3f0f Binary files /dev/null and b/bin/org/jalgo/module/app/controller/GraphActionListener$EditMode.class differ diff --git a/bin/org/jalgo/module/app/controller/GraphActionListener.class b/bin/org/jalgo/module/app/controller/GraphActionListener.class new file mode 100644 index 0000000..499a4f9 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/GraphActionListener.class differ diff --git a/bin/org/jalgo/module/app/controller/GraphController.class b/bin/org/jalgo/module/app/controller/GraphController.class new file mode 100644 index 0000000..a65d788 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/GraphController.class differ diff --git a/bin/org/jalgo/module/app/controller/GraphObserver.class b/bin/org/jalgo/module/app/controller/GraphObserver.class new file mode 100644 index 0000000..acad3a9 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/GraphObserver.class differ diff --git a/bin/org/jalgo/module/app/controller/InterfaceController.class b/bin/org/jalgo/module/app/controller/InterfaceController.class new file mode 100644 index 0000000..ec44b32 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/InterfaceController.class differ diff --git a/bin/org/jalgo/module/app/controller/InterfaceMode.class b/bin/org/jalgo/module/app/controller/InterfaceMode.class new file mode 100644 index 0000000..d18a34d Binary files /dev/null and b/bin/org/jalgo/module/app/controller/InterfaceMode.class differ diff --git a/bin/org/jalgo/module/app/controller/MainController.class b/bin/org/jalgo/module/app/controller/MainController.class new file mode 100644 index 0000000..0a302c5 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/MainController.class differ diff --git a/bin/org/jalgo/module/app/controller/SemiringController.class b/bin/org/jalgo/module/app/controller/SemiringController.class new file mode 100644 index 0000000..9ba407d Binary files /dev/null and b/bin/org/jalgo/module/app/controller/SemiringController.class differ diff --git a/bin/org/jalgo/module/app/controller/package.html b/bin/org/jalgo/module/app/controller/package.html new file mode 100644 index 0000000..5ddde5d --- /dev/null +++ b/bin/org/jalgo/module/app/controller/package.html @@ -0,0 +1,10 @@ + + + + + + +The controller, which connects the core with the view. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.class new file mode 100644 index 0000000..9213adf Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.class new file mode 100644 index 0000000..23c2daf Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.class new file mode 100644 index 0000000..addfb63 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.class new file mode 100644 index 0000000..4bc6af0 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.class new file mode 100644 index 0000000..571efc1 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.class b/bin/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.class new file mode 100644 index 0000000..ab90169 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/UndoManager.class b/bin/org/jalgo/module/app/controller/undoRedo/UndoManager.class new file mode 100644 index 0000000..55af188 Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/UndoManager.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/UndoableAction.class b/bin/org/jalgo/module/app/controller/undoRedo/UndoableAction.class new file mode 100644 index 0000000..af9503a Binary files /dev/null and b/bin/org/jalgo/module/app/controller/undoRedo/UndoableAction.class differ diff --git a/bin/org/jalgo/module/app/controller/undoRedo/package.html b/bin/org/jalgo/module/app/controller/undoRedo/package.html new file mode 100644 index 0000000..fc863b0 --- /dev/null +++ b/bin/org/jalgo/module/app/controller/undoRedo/package.html @@ -0,0 +1,10 @@ + + + + + + +Provides the undo/redo functionality. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/AvailableSemiRings.class b/bin/org/jalgo/module/app/core/AvailableSemiRings.class new file mode 100644 index 0000000..87903e5 Binary files /dev/null and b/bin/org/jalgo/module/app/core/AvailableSemiRings.class differ diff --git a/bin/org/jalgo/module/app/core/Calculation.class b/bin/org/jalgo/module/app/core/Calculation.class new file mode 100644 index 0000000..870f98b Binary files /dev/null and b/bin/org/jalgo/module/app/core/Calculation.class differ diff --git a/bin/org/jalgo/module/app/core/Matrix.class b/bin/org/jalgo/module/app/core/Matrix.class new file mode 100644 index 0000000..4a92399 Binary files /dev/null and b/bin/org/jalgo/module/app/core/Matrix.class differ diff --git a/bin/org/jalgo/module/app/core/SemiRing.class b/bin/org/jalgo/module/app/core/SemiRing.class new file mode 100644 index 0000000..fcd088c Binary files /dev/null and b/bin/org/jalgo/module/app/core/SemiRing.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/AvailableDataTypes.class b/bin/org/jalgo/module/app/core/dataType/AvailableDataTypes.class new file mode 100644 index 0000000..3039cf5 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/AvailableDataTypes.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/DataType.class b/bin/org/jalgo/module/app/core/dataType/DataType.class new file mode 100644 index 0000000..98e788c Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/DataType.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/Infinity.class b/bin/org/jalgo/module/app/core/dataType/Infinity.class new file mode 100644 index 0000000..86b1915 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/Infinity.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/MaxValues.class b/bin/org/jalgo/module/app/core/dataType/MaxValues.class new file mode 100644 index 0000000..692d180 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/MaxValues.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/NumericDataType.class b/bin/org/jalgo/module/app/core/dataType/NumericDataType.class new file mode 100644 index 0000000..ef22c4d Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/NumericDataType.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/Operation$Notation.class b/bin/org/jalgo/module/app/core/dataType/Operation$Notation.class new file mode 100644 index 0000000..bb32000 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/Operation$Notation.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/Operation.class b/bin/org/jalgo/module/app/core/dataType/Operation.class new file mode 100644 index 0000000..73fe865 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/Operation.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/booleanType/BooleanType.class b/bin/org/jalgo/module/app/core/dataType/booleanType/BooleanType.class new file mode 100644 index 0000000..1f5a733 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/booleanType/BooleanType.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/booleanType/Conjunction.class b/bin/org/jalgo/module/app/core/dataType/booleanType/Conjunction.class new file mode 100644 index 0000000..e135f92 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/booleanType/Conjunction.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/booleanType/Disjunction.class b/bin/org/jalgo/module/app/core/dataType/booleanType/Disjunction.class new file mode 100644 index 0000000..aed20b6 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/booleanType/Disjunction.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/booleanType/package.html b/bin/org/jalgo/module/app/core/dataType/booleanType/package.html new file mode 100644 index 0000000..f27352d --- /dev/null +++ b/bin/org/jalgo/module/app/core/dataType/booleanType/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of true and false and the appropriate operations. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.class new file mode 100644 index 0000000..f027c87 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject$StarAlignment.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject$StarAlignment.class new file mode 100644 index 0000000..db9fbc5 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject$StarAlignment.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.class new file mode 100644 index 0000000..18c272b Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.class new file mode 100644 index 0000000..c923509 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.class new file mode 100644 index 0000000..018153e Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.class new file mode 100644 index 0000000..67ceeec Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.class new file mode 100644 index 0000000..c049840 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.class new file mode 100644 index 0000000..5ffb238 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/Union.class b/bin/org/jalgo/module/app/core/dataType/formalLanguage/Union.class new file mode 100644 index 0000000..657b3d7 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/formalLanguage/Union.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/formalLanguage/package.html b/bin/org/jalgo/module/app/core/dataType/formalLanguage/package.html new file mode 100644 index 0000000..f4429f8 --- /dev/null +++ b/bin/org/jalgo/module/app/core/dataType/formalLanguage/package.html @@ -0,0 +1,10 @@ + + + + + + +A formal language and the appropriate operations. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.class b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.class new file mode 100644 index 0000000..065de4f Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.class b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.class new file mode 100644 index 0000000..58670b0 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.class b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.class new file mode 100644 index 0000000..960cf5d Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.class b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.class new file mode 100644 index 0000000..b91d43e Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.class b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.class new file mode 100644 index 0000000..6338f53 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/naturalNumber/package.html b/bin/org/jalgo/module/app/core/dataType/naturalNumber/package.html new file mode 100644 index 0000000..f95ea98 --- /dev/null +++ b/bin/org/jalgo/module/app/core/dataType/naturalNumber/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of natural numbers and the appropriate operations. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/dataType/package.html b/bin/org/jalgo/module/app/core/dataType/package.html new file mode 100644 index 0000000..c94687f --- /dev/null +++ b/bin/org/jalgo/module/app/core/dataType/package.html @@ -0,0 +1,10 @@ + + + + + + +Provides several sets of mathematical structures and the appropriate operations. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.class new file mode 100644 index 0000000..d5770a0 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.class new file mode 100644 index 0000000..7ff726a Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.class new file mode 100644 index 0000000..2764c99 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.class new file mode 100644 index 0000000..314f298 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.class new file mode 100644 index 0000000..8965152 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.class new file mode 100644 index 0000000..e91240d Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.class new file mode 100644 index 0000000..58ea403 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.class b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.class new file mode 100644 index 0000000..1096cf0 Binary files /dev/null and b/bin/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.class differ diff --git a/bin/org/jalgo/module/app/core/dataType/rationalNumber/package.html b/bin/org/jalgo/module/app/core/dataType/rationalNumber/package.html new file mode 100644 index 0000000..d8dbcb1 --- /dev/null +++ b/bin/org/jalgo/module/app/core/dataType/rationalNumber/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of rational numbers and the appropriate operations. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/graph/Edge.class b/bin/org/jalgo/module/app/core/graph/Edge.class new file mode 100644 index 0000000..a11a6d3 Binary files /dev/null and b/bin/org/jalgo/module/app/core/graph/Edge.class differ diff --git a/bin/org/jalgo/module/app/core/graph/Graph.class b/bin/org/jalgo/module/app/core/graph/Graph.class new file mode 100644 index 0000000..7e17750 Binary files /dev/null and b/bin/org/jalgo/module/app/core/graph/Graph.class differ diff --git a/bin/org/jalgo/module/app/core/graph/Node$SerialPoint2D.class b/bin/org/jalgo/module/app/core/graph/Node$SerialPoint2D.class new file mode 100644 index 0000000..855e938 Binary files /dev/null and b/bin/org/jalgo/module/app/core/graph/Node$SerialPoint2D.class differ diff --git a/bin/org/jalgo/module/app/core/graph/Node.class b/bin/org/jalgo/module/app/core/graph/Node.class new file mode 100644 index 0000000..b1a2221 Binary files /dev/null and b/bin/org/jalgo/module/app/core/graph/Node.class differ diff --git a/bin/org/jalgo/module/app/core/graph/package.html b/bin/org/jalgo/module/app/core/graph/package.html new file mode 100644 index 0000000..2a3a8a7 --- /dev/null +++ b/bin/org/jalgo/module/app/core/graph/package.html @@ -0,0 +1,10 @@ + + + + + + +The internal representation of the graph over which is calculated. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/package.html b/bin/org/jalgo/module/app/core/package.html new file mode 100644 index 0000000..dd73a66 --- /dev/null +++ b/bin/org/jalgo/module/app/core/package.html @@ -0,0 +1,10 @@ + + + + + + +The model, who does the internal calculation. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/core/step/AtomicStep.class b/bin/org/jalgo/module/app/core/step/AtomicStep.class new file mode 100644 index 0000000..bfe96cf Binary files /dev/null and b/bin/org/jalgo/module/app/core/step/AtomicStep.class differ diff --git a/bin/org/jalgo/module/app/core/step/GroupStep.class b/bin/org/jalgo/module/app/core/step/GroupStep.class new file mode 100644 index 0000000..6271304 Binary files /dev/null and b/bin/org/jalgo/module/app/core/step/GroupStep.class differ diff --git a/bin/org/jalgo/module/app/core/step/RootStep.class b/bin/org/jalgo/module/app/core/step/RootStep.class new file mode 100644 index 0000000..ecedf38 Binary files /dev/null and b/bin/org/jalgo/module/app/core/step/RootStep.class differ diff --git a/bin/org/jalgo/module/app/core/step/Step.class b/bin/org/jalgo/module/app/core/step/Step.class new file mode 100644 index 0000000..d4e1da1 Binary files /dev/null and b/bin/org/jalgo/module/app/core/step/Step.class differ diff --git a/bin/org/jalgo/module/app/core/step/package.html b/bin/org/jalgo/module/app/core/step/package.html new file mode 100644 index 0000000..2ecf221 --- /dev/null +++ b/bin/org/jalgo/module/app/core/step/package.html @@ -0,0 +1,10 @@ + + + + + + +The steps of calculation, organized in a tree structure. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/coreTest/AllCalculationTests.class b/bin/org/jalgo/module/app/coreTest/AllCalculationTests.class new file mode 100644 index 0000000..ad58c43 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/AllCalculationTests.class differ diff --git a/bin/org/jalgo/module/app/coreTest/AllDataTypeTests.class b/bin/org/jalgo/module/app/coreTest/AllDataTypeTests.class new file mode 100644 index 0000000..c321820 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/AllDataTypeTests.class differ diff --git a/bin/org/jalgo/module/app/coreTest/AllTests.class b/bin/org/jalgo/module/app/coreTest/AllTests.class new file mode 100644 index 0000000..19bc567 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/AllTests.class differ diff --git a/bin/org/jalgo/module/app/coreTest/AvailabilityProblemTest.class b/bin/org/jalgo/module/app/coreTest/AvailabilityProblemTest.class new file mode 100644 index 0000000..70ffe38 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/AvailabilityProblemTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/AvailableDataTypesTest.class b/bin/org/jalgo/module/app/coreTest/AvailableDataTypesTest.class new file mode 100644 index 0000000..8959ec4 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/AvailableDataTypesTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/BooleanOperationsTest.class b/bin/org/jalgo/module/app/coreTest/BooleanOperationsTest.class new file mode 100644 index 0000000..113b5dd Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/BooleanOperationsTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/BooleanTypeTest.class b/bin/org/jalgo/module/app/coreTest/BooleanTypeTest.class new file mode 100644 index 0000000..7e7f94c Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/BooleanTypeTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/CapacityProblemTest.class b/bin/org/jalgo/module/app/coreTest/CapacityProblemTest.class new file mode 100644 index 0000000..625af73 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/CapacityProblemTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/DijkstraComparisonTest.class b/bin/org/jalgo/module/app/coreTest/DijkstraComparisonTest.class new file mode 100644 index 0000000..1f9f170 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/DijkstraComparisonTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/FormalLanguageProblemTest.class b/bin/org/jalgo/module/app/coreTest/FormalLanguageProblemTest.class new file mode 100644 index 0000000..a3f9cde Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/FormalLanguageProblemTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/FormalLanguageTest.class b/bin/org/jalgo/module/app/coreTest/FormalLanguageTest.class new file mode 100644 index 0000000..f5bfe28 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/FormalLanguageTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/GraphTest.class b/bin/org/jalgo/module/app/coreTest/GraphTest.class new file mode 100644 index 0000000..c83b265 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/GraphTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/NaturalAddTest.class b/bin/org/jalgo/module/app/coreTest/NaturalAddTest.class new file mode 100644 index 0000000..a0ff29c Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/NaturalAddTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/NaturalMaximumTest.class b/bin/org/jalgo/module/app/coreTest/NaturalMaximumTest.class new file mode 100644 index 0000000..2635a14 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/NaturalMaximumTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/NaturalMinimumTest.class b/bin/org/jalgo/module/app/coreTest/NaturalMinimumTest.class new file mode 100644 index 0000000..def1c20 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/NaturalMinimumTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/NaturalMultiplyTest.class b/bin/org/jalgo/module/app/coreTest/NaturalMultiplyTest.class new file mode 100644 index 0000000..080fd7b Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/NaturalMultiplyTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/NaturalNumberTest.class b/bin/org/jalgo/module/app/coreTest/NaturalNumberTest.class new file mode 100644 index 0000000..9f6a1a9 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/NaturalNumberTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/PercentageTypeTest.class b/bin/org/jalgo/module/app/coreTest/PercentageTypeTest.class new file mode 100644 index 0000000..e808ad2 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/PercentageTypeTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.class b/bin/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.class new file mode 100644 index 0000000..430ff2f Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/RationalNumberTest.class b/bin/org/jalgo/module/app/coreTest/RationalNumberTest.class new file mode 100644 index 0000000..5a79b6e Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/RationalNumberTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/RationalOperationTest.class b/bin/org/jalgo/module/app/coreTest/RationalOperationTest.class new file mode 100644 index 0000000..f3ac1d1 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/RationalOperationTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/RationalStarOperationTest.class b/bin/org/jalgo/module/app/coreTest/RationalStarOperationTest.class new file mode 100644 index 0000000..f6cf3b1 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/RationalStarOperationTest.class differ diff --git a/bin/org/jalgo/module/app/coreTest/SimpleCalculationTest.class b/bin/org/jalgo/module/app/coreTest/SimpleCalculationTest.class new file mode 100644 index 0000000..703a635 Binary files /dev/null and b/bin/org/jalgo/module/app/coreTest/SimpleCalculationTest.class differ diff --git a/bin/org/jalgo/module/app/de.properties b/bin/org/jalgo/module/app/de.properties new file mode 100644 index 0000000..49231df --- /dev/null +++ b/bin/org/jalgo/module/app/de.properties @@ -0,0 +1,47 @@ +ModuleConnector.Error=Fehler +ModuleConnector.SavingError=Fehler beim Speichern der Datei. +ModuleConnector.IOError=Fehler beim Laden der Datei. +ModuleConnector.ClassError=Falscher Dateityp. + +ControlToolbar.FastBackward=Großer Schritt rückwärts +ControlToolbar.Backward=Einzelschritt rückwärts +ControlToolbar.FastForward=Großer Schritt vorwärts +ControlToolbar.Forward=Einzelschritt vorwärts +ControlToolbar.Animate=Animieren + +FormulaComponent.enlargePanel=Formel vergrößern + +FormulaWindow.Title=Formelansicht + +SemiringComponent.OK=OK +SemiringComponent.Text=Bitte wählen Sie einen Semiring: + +ModuleInfo.Name=Algebraisches Pfadproblem +ModuleInfo.Description=Ein Modul zur Visualisierung des algebraischen Pfadproblems. +ModuleInfo.Author=Elisa Hilprecht, Erik Tittel, Friedrich Gräter, Götz Fabian, Max Seelemann + +EditToolbar.nodeEdit=Knoten bearbeiten +EditToolbar.edgeEdit=Kanten bearbeiten +EditToolbar.addButton=Hinzufügen +EditToolbar.deleteButton=Entfernen +EditToolbar.modifyButton=Gewicht ändern +EditToolbar.undoButton=Rückgängig +EditToolbar.redoButton=Wiederholen +EditToolbar.specialCharButton=Sondernzeichen einfügen + +ModeSwitchComponent.editToggleToolTip=Graph bearbeiten +ModeSwitchComponent.editToggle=Bearbeiten +ModeSwitchComponent.runToggleToolTip=Algorithmus starten +ModeSwitchComponent.runToggle=Durchführen +ModeSwitchComponent.beamerToggle=Beamer-Modus + +AvailableSemiRings.ShortestPathName=Kürzeste-Wege-Problem +AvailableSemiRings.ShortestPathDescription=Der kürzeste Weg. +AvailableSemiRings.CapacityName=Kapazitätsproblem +AvailableSemiRings.CapacityDescription=Eine Strecke mit maximaler Kapazität. +AvailableSemiRings.AvailabilityName=Erreichbarkeitsproblem +AvailableSemiRings.AvailabilityDescription=Vorhandensein eines Weges. +AvailableSemiRings.ReliabilityName=Zuverlässigkeitsproblem +AvailableSemiRings.ReliabilityDescription=Wahrscheinlichkeit der Übertragung auf einem Weg. +AvailableSemiRings.ProcessName=Prozessproblem +AvailableSemiRings.ProcessDescription=Menge von Aktionen, die Zustandsänderung bewirken. \ No newline at end of file diff --git a/bin/org/jalgo/module/app/en.properties b/bin/org/jalgo/module/app/en.properties new file mode 100644 index 0000000..f263f33 --- /dev/null +++ b/bin/org/jalgo/module/app/en.properties @@ -0,0 +1,47 @@ +ModuleConnector.Error=Error +ModuleConnector.SavingError=Saving the file has failed. +ModuleConnector.IOError=The input operation has failed. +ModuleConnector.ClassError=The input operation has failed. + +ControlToolbar.FastBackward=Big Step backward +ControlToolbar.Backward=Single Step backward +ControlToolbar.FastForward=Big Step forward +ControlToolbar.Forward=Single Step forward +ControlToolbar.Animate=Animate + +FormulaComponent.enlargePanel=Enlarge formula + +FormulaWindow.Title=Formula View + +SemiringComponent.OK=OK +SemiringComponent.Text=Please select a semiring: + +ModuleInfo.Name=Algebraic Path Problem +ModuleInfo.Description=A module to visualize the Algebraic Path Problem. +ModuleInfo.Author=Elisa Hilprecht, Erik Tittel, Friedrich Gräter, Götz Fabian, Max Seelemann + +EditToolbar.nodeEdit=Edit Nodes +EditToolbar.edgeEdit=Edit Edges +EditToolbar.addButton=Add +EditToolbar.deleteButton=Delete +EditToolbar.modifyButton=Modify Weight +EditToolbar.undoButton=Undo +EditToolbar.redoButton=Redo +EditToolbar.specialCharButton=Insert special character + +ModeSwitchComponent.editToggleToolTip=Edit Graph +ModeSwitchComponent.editToggle=Edit +ModeSwitchComponent.runToggleToolTip=Start Algorithm +ModeSwitchComponent.runToggle=Run +ModeSwitchComponent.beamerToggle=Beamer Mode + +AvailableSemiRings.ShortestPathName=Shortest Path Problem +AvailableSemiRings.ShortestPathDescription=The shortest Path. +AvailableSemiRings.CapacityName=Capacity Problem +AvailableSemiRings.CapacityDescription=A path with maximum capacity. +AvailableSemiRings.AvailabilityName=Availability Problem +AvailableSemiRings.AvailabilityDescription=The availability of a path. +AvailableSemiRings.ReliabilityName=Reliability Problem +AvailableSemiRings.ReliabilityDescription=The probability of transmission on a path. +AvailableSemiRings.ProcessName=Process Problem +AvailableSemiRings.ProcessDescription=A set of actions that cause a change in state. \ No newline at end of file diff --git a/bin/org/jalgo/module/app/package.html b/bin/org/jalgo/module/app/package.html new file mode 100644 index 0000000..7259e11 --- /dev/null +++ b/bin/org/jalgo/module/app/package.html @@ -0,0 +1,10 @@ + + + + + + +The jAlgo-Modul for the algorithmic path problem. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/res.properties b/bin/org/jalgo/module/app/res.properties new file mode 100644 index 0000000..95a2a4d --- /dev/null +++ b/bin/org/jalgo/module/app/res.properties @@ -0,0 +1,29 @@ +Module_logo=/images/logo.gif +icon_editMode_s=/images/edit_button_s.gif +icon_editMode=/images/edit_button.gif +icon_runMode_s=/images/go_button_s.gif +icon_runMode=/images/go_button.gif +icon_nodeEdit=/images/edit_nodes.gif +icon_edgeEdit=/images/edit_edges.gif +icon_addEdit=/images/plus_button.gif +icon_deleteEdit=/images/minus_button.gif +icon_modifyEdit=/images/modifie_button.gif +icon_animateStart=/images/start_task.gif +icon_animatePause=/images/suspend.gif +icon_StepForward=/images/step_forward.gif +icon_StepBackward=/images/step_backward.gif +icon_GroupStepForward=/images/groupstep_forward.gif +icon_GroupStepBackward=/images/groupstep_backward.gif +graph_component_editmode=/images/graph_component_editmode.gif +graph_component_runmode=/images/graph_component_runmode.gif +helpSet_name=/help/jhelp/app_help.hs +formula_component=/images/formula_component.gif +matrix1_component=/images/matrix1_component.gif +matrix2_component=/images/matrix2_component.gif +matrix_preview=/images/matrix_preview.gif +icon_undoEdit=/images/undo.gif +icon_redoEdit=/images/redo.gif +parenthesis_arc=/images/parenthesis-arc.gif +parenthesis_edge=/images/parenthesis-edge.gif +zoom=/images/zoom.gif +icon_beamerMode=/images/beamermode_button.gif \ No newline at end of file diff --git a/bin/org/jalgo/module/app/view/InterfaceConstants.class b/bin/org/jalgo/module/app/view/InterfaceConstants.class new file mode 100644 index 0000000..65f1a30 Binary files /dev/null and b/bin/org/jalgo/module/app/view/InterfaceConstants.class differ diff --git a/bin/org/jalgo/module/app/view/SemiringComponent$OkayButtonListener.class b/bin/org/jalgo/module/app/view/SemiringComponent$OkayButtonListener.class new file mode 100644 index 0000000..39e8abe Binary files /dev/null and b/bin/org/jalgo/module/app/view/SemiringComponent$OkayButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/SemiringComponent$SemiringDisplay.class b/bin/org/jalgo/module/app/view/SemiringComponent$SemiringDisplay.class new file mode 100644 index 0000000..bdf2311 Binary files /dev/null and b/bin/org/jalgo/module/app/view/SemiringComponent$SemiringDisplay.class differ diff --git a/bin/org/jalgo/module/app/view/SemiringComponent.class b/bin/org/jalgo/module/app/view/SemiringComponent.class new file mode 100644 index 0000000..9e8cf11 Binary files /dev/null and b/bin/org/jalgo/module/app/view/SemiringComponent.class differ diff --git a/bin/org/jalgo/module/app/view/graph/BoxingHighlightPainter.class b/bin/org/jalgo/module/app/view/graph/BoxingHighlightPainter.class new file mode 100644 index 0000000..30f389c Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/BoxingHighlightPainter.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement$CurrentDocumentListener.class b/bin/org/jalgo/module/app/view/graph/EdgeElement$CurrentDocumentListener.class new file mode 100644 index 0000000..9c2c77c Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement$CurrentDocumentListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeShape.class b/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeShape.class new file mode 100644 index 0000000..398a966 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeShape.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeTextField.class b/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeTextField.class new file mode 100644 index 0000000..6ad4e1a Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement$EdgeTextField.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement$InputActionListener.class b/bin/org/jalgo/module/app/view/graph/EdgeElement$InputActionListener.class new file mode 100644 index 0000000..c636d1e Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement$InputActionListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement$TextFieldFocusListener.class b/bin/org/jalgo/module/app/view/graph/EdgeElement$TextFieldFocusListener.class new file mode 100644 index 0000000..b7c8be9 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement$TextFieldFocusListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EdgeElement.class b/bin/org/jalgo/module/app/view/graph/EdgeElement.class new file mode 100644 index 0000000..1b5f3da Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EdgeElement.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$JSpecialCharButton.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$JSpecialCharButton.class new file mode 100644 index 0000000..7888901 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$JSpecialCharButton.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$SpecialCharButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$SpecialCharButtonListener.class new file mode 100644 index 0000000..7fcea08 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$SpecialCharButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$addButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$addButtonListener.class new file mode 100644 index 0000000..c11083c Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$addButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$deleteButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$deleteButtonListener.class new file mode 100644 index 0000000..2345a93 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$deleteButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$edgeModeListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$edgeModeListener.class new file mode 100644 index 0000000..2615772 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$edgeModeListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$modifyButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$modifyButtonListener.class new file mode 100644 index 0000000..173b06e Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$modifyButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$nodeModeListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$nodeModeListener.class new file mode 100644 index 0000000..56ed221 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$nodeModeListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$redoButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$redoButtonListener.class new file mode 100644 index 0000000..ba88e5c Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$redoButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar$undoButtonListener.class b/bin/org/jalgo/module/app/view/graph/EditToolbar$undoButtonListener.class new file mode 100644 index 0000000..c5f5312 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar$undoButtonListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/EditToolbar.class b/bin/org/jalgo/module/app/view/graph/EditToolbar.class new file mode 100644 index 0000000..3af9705 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/EditToolbar.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphComponent$ScalingInformation.class b/bin/org/jalgo/module/app/view/graph/GraphComponent$ScalingInformation.class new file mode 100644 index 0000000..deb4919 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphComponent$ScalingInformation.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphComponent.class b/bin/org/jalgo/module/app/view/graph/GraphComponent.class new file mode 100644 index 0000000..b85ce85 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphComponent.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphElement.class b/bin/org/jalgo/module/app/view/graph/GraphElement.class new file mode 100644 index 0000000..580911f Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphElement.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphTextComponent$EdgeDescriptor.class b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$EdgeDescriptor.class new file mode 100644 index 0000000..42828e4 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$EdgeDescriptor.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphTextComponent$ParsedTuple.class b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$ParsedTuple.class new file mode 100644 index 0000000..1ffcaa1 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$ParsedTuple.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphTextComponent$TextAreaListener.class b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$TextAreaListener.class new file mode 100644 index 0000000..71d0002 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$TextAreaListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphTextComponent$UpdateOperation.class b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$UpdateOperation.class new file mode 100644 index 0000000..42203e0 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphTextComponent$UpdateOperation.class differ diff --git a/bin/org/jalgo/module/app/view/graph/GraphTextComponent.class b/bin/org/jalgo/module/app/view/graph/GraphTextComponent.class new file mode 100644 index 0000000..43d71d9 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/GraphTextComponent.class differ diff --git a/bin/org/jalgo/module/app/view/graph/HighlightState.class b/bin/org/jalgo/module/app/view/graph/HighlightState.class new file mode 100644 index 0000000..7088251 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/HighlightState.class differ diff --git a/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$BeamerToggleListener.class b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$BeamerToggleListener.class new file mode 100644 index 0000000..c979186 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$BeamerToggleListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$EditToggleListener.class b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$EditToggleListener.class new file mode 100644 index 0000000..0e69986 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$EditToggleListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$RunToggleListener.class b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$RunToggleListener.class new file mode 100644 index 0000000..848bc11 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent$RunToggleListener.class differ diff --git a/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent.class b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent.class new file mode 100644 index 0000000..aa4eeab Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/ModeSwitchComponent.class differ diff --git a/bin/org/jalgo/module/app/view/graph/NewEdgeElement.class b/bin/org/jalgo/module/app/view/graph/NewEdgeElement.class new file mode 100644 index 0000000..de6a63e Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/NewEdgeElement.class differ diff --git a/bin/org/jalgo/module/app/view/graph/NodeElement.class b/bin/org/jalgo/module/app/view/graph/NodeElement.class new file mode 100644 index 0000000..b7cdd9e Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/NodeElement.class differ diff --git a/bin/org/jalgo/module/app/view/graph/ShapeHighlightPainter.class b/bin/org/jalgo/module/app/view/graph/ShapeHighlightPainter.class new file mode 100644 index 0000000..d6c7729 Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/ShapeHighlightPainter.class differ diff --git a/bin/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.class b/bin/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.class new file mode 100644 index 0000000..a6085ba Binary files /dev/null and b/bin/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.class differ diff --git a/bin/org/jalgo/module/app/view/graph/package.html b/bin/org/jalgo/module/app/view/graph/package.html new file mode 100644 index 0000000..c004fee --- /dev/null +++ b/bin/org/jalgo/module/app/view/graph/package.html @@ -0,0 +1,10 @@ + + + + + + +The left hand side of the interface. The illustration of the graph. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/view/package.html b/bin/org/jalgo/module/app/view/package.html new file mode 100644 index 0000000..4fb3c91 --- /dev/null +++ b/bin/org/jalgo/module/app/view/package.html @@ -0,0 +1,10 @@ + + + + + + +The interface of the program. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$ControlButtons.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$ControlButtons.class new file mode 100644 index 0000000..21d6058 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$ControlButtons.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$animateListener.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$animateListener.class new file mode 100644 index 0000000..cb95d45 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$animateListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$backwardListener.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$backwardListener.class new file mode 100644 index 0000000..02997c1 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$backwardListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$fastBackwardListener.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$fastBackwardListener.class new file mode 100644 index 0000000..bc3f960 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$fastBackwardListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$fastForwardListener.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$fastForwardListener.class new file mode 100644 index 0000000..0640dc5 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$fastForwardListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar$forwardListener.class b/bin/org/jalgo/module/app/view/run/ControlToolbar$forwardListener.class new file mode 100644 index 0000000..6dc827e Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar$forwardListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/ControlToolbar.class b/bin/org/jalgo/module/app/view/run/ControlToolbar.class new file mode 100644 index 0000000..2313529 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/ControlToolbar.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaComponent$FormulaComponentListener.class b/bin/org/jalgo/module/app/view/run/FormulaComponent$FormulaComponentListener.class new file mode 100644 index 0000000..8ae4967 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaComponent$FormulaComponentListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaComponent.class b/bin/org/jalgo/module/app/view/run/FormulaComponent.class new file mode 100644 index 0000000..e26e73c Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaComponent.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaDisplay$Metrics.class b/bin/org/jalgo/module/app/view/run/FormulaDisplay$Metrics.class new file mode 100644 index 0000000..4ba6219 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaDisplay$Metrics.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaDisplay$MultiLineMetrics.class b/bin/org/jalgo/module/app/view/run/FormulaDisplay$MultiLineMetrics.class new file mode 100644 index 0000000..a8e3a1f Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaDisplay$MultiLineMetrics.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaDisplay$OperatorDescription.class b/bin/org/jalgo/module/app/view/run/FormulaDisplay$OperatorDescription.class new file mode 100644 index 0000000..6e7dcfa Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaDisplay$OperatorDescription.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaDisplay$ParameterDescription.class b/bin/org/jalgo/module/app/view/run/FormulaDisplay$ParameterDescription.class new file mode 100644 index 0000000..e749ab5 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaDisplay$ParameterDescription.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaDisplay.class b/bin/org/jalgo/module/app/view/run/FormulaDisplay.class new file mode 100644 index 0000000..08bba93 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaDisplay.class differ diff --git a/bin/org/jalgo/module/app/view/run/FormulaWindow.class b/bin/org/jalgo/module/app/view/run/FormulaWindow.class new file mode 100644 index 0000000..3d7ac48 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/FormulaWindow.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$Animator.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$Animator.class new file mode 100644 index 0000000..4c2c732 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$Animator.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicMatrixChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicMatrixChanger.class new file mode 100644 index 0000000..c19bc64 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicMatrixChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicStepChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicStepChanger.class new file mode 100644 index 0000000..9a5da90 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$AtomicStepChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$EndChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$EndChanger.class new file mode 100644 index 0000000..0c2ddd1 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$EndChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$GenericGroupStepChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$GenericGroupStepChanger.class new file mode 100644 index 0000000..85e838f Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$GenericGroupStepChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupMatrixChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupMatrixChanger.class new file mode 100644 index 0000000..13237b1 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupMatrixChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupStepChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupStepChanger.class new file mode 100644 index 0000000..6bbc3b6 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$GroupStepChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixChanger.class new file mode 100644 index 0000000..6e85f98 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixComponentListener.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixComponentListener.class new file mode 100644 index 0000000..58f163b Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixComponentListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator$AnimationTask.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator$AnimationTask.class new file mode 100644 index 0000000..0dfe654 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator$AnimationTask.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator.class new file mode 100644 index 0000000..716a844 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$MatrixMoveAnimator.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$NextGroupStepChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$NextGroupStepChanger.class new file mode 100644 index 0000000..f516284 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$NextGroupStepChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepChanger.class new file mode 100644 index 0000000..d43582c Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepToAtomicChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepToAtomicChanger.class new file mode 100644 index 0000000..53d77ca Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$PrevGroupStepToAtomicChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$StartChanger.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$StartChanger.class new file mode 100644 index 0000000..e2a22e9 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$StartChanger.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent$ViewMode.class b/bin/org/jalgo/module/app/view/run/MatrixComponent$ViewMode.class new file mode 100644 index 0000000..f0dae8d Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent$ViewMode.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixComponent.class b/bin/org/jalgo/module/app/view/run/MatrixComponent.class new file mode 100644 index 0000000..144150b Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixComponent.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixDisplay$CellDescriptor.class b/bin/org/jalgo/module/app/view/run/MatrixDisplay$CellDescriptor.class new file mode 100644 index 0000000..b7ddf96 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixDisplay$CellDescriptor.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixLabel.class b/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixLabel.class new file mode 100644 index 0000000..b2cd021 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixLabel.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixNamePanel.class b/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixNamePanel.class new file mode 100644 index 0000000..59dd201 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixDisplay$MatrixNamePanel.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixDisplay$ParenthesisDisplay.class b/bin/org/jalgo/module/app/view/run/MatrixDisplay$ParenthesisDisplay.class new file mode 100644 index 0000000..7578c01 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixDisplay$ParenthesisDisplay.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixDisplay.class b/bin/org/jalgo/module/app/view/run/MatrixDisplay.class new file mode 100644 index 0000000..30e3341 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixDisplay.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent$MatrixComponentListener.class b/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent$MatrixComponentListener.class new file mode 100644 index 0000000..a2de820 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent$MatrixComponentListener.class differ diff --git a/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent.class b/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent.class new file mode 100644 index 0000000..358ee63 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/MatrixPreviewComponent.class differ diff --git a/bin/org/jalgo/module/app/view/run/StepHighlighting.class b/bin/org/jalgo/module/app/view/run/StepHighlighting.class new file mode 100644 index 0000000..9bdd3f5 Binary files /dev/null and b/bin/org/jalgo/module/app/view/run/StepHighlighting.class differ diff --git a/bin/org/jalgo/module/app/view/run/package.html b/bin/org/jalgo/module/app/view/run/package.html new file mode 100644 index 0000000..edb0056 --- /dev/null +++ b/bin/org/jalgo/module/app/view/run/package.html @@ -0,0 +1,10 @@ + + + + + + +The right hand side of the interface. The illustration of the matrixes and the calculation steps. + + + \ No newline at end of file diff --git a/bin/org/jalgo/module/avl/.cvsignore b/bin/org/jalgo/module/avl/.cvsignore new file mode 100644 index 0000000..650b404 --- /dev/null +++ b/bin/org/jalgo/module/avl/.cvsignore @@ -0,0 +1 @@ +GUISim.java diff --git a/bin/org/jalgo/module/avl/Constants.class b/bin/org/jalgo/module/avl/Constants.class new file mode 100644 index 0000000..c6ad13a Binary files /dev/null and b/bin/org/jalgo/module/avl/Constants.class differ diff --git a/bin/org/jalgo/module/avl/Controller.class b/bin/org/jalgo/module/avl/Controller.class new file mode 100644 index 0000000..eddb1d8 Binary files /dev/null and b/bin/org/jalgo/module/avl/Controller.class differ diff --git a/bin/org/jalgo/module/avl/ModuleConnector.class b/bin/org/jalgo/module/avl/ModuleConnector.class new file mode 100644 index 0000000..7c7bb9e Binary files /dev/null and b/bin/org/jalgo/module/avl/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/avl/ModuleInfo.class b/bin/org/jalgo/module/avl/ModuleInfo.class new file mode 100644 index 0000000..17a642b Binary files /dev/null and b/bin/org/jalgo/module/avl/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/avl/NoActionException.class b/bin/org/jalgo/module/avl/NoActionException.class new file mode 100644 index 0000000..e523267 Binary files /dev/null and b/bin/org/jalgo/module/avl/NoActionException.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/AVLTest.class b/bin/org/jalgo/module/avl/algorithm/AVLTest.class new file mode 100644 index 0000000..a8b6544 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/AVLTest.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CalcBalance.class b/bin/org/jalgo/module/avl/algorithm/CalcBalance.class new file mode 100644 index 0000000..f001fb2 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CalcBalance.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CalcHeight.class b/bin/org/jalgo/module/avl/algorithm/CalcHeight.class new file mode 100644 index 0000000..a295fa1 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CalcHeight.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/Command.class b/bin/org/jalgo/module/avl/algorithm/Command.class new file mode 100644 index 0000000..b56819f Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/Command.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CommandFactory.class b/bin/org/jalgo/module/avl/algorithm/CommandFactory.class new file mode 100644 index 0000000..b02a30b Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CommandFactory.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CompareKey.class b/bin/org/jalgo/module/avl/algorithm/CompareKey.class new file mode 100644 index 0000000..add91af Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CompareKey.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CreateNode.class b/bin/org/jalgo/module/avl/algorithm/CreateNode.class new file mode 100644 index 0000000..af303c2 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CreateNode.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/CreateRandomTree.class b/bin/org/jalgo/module/avl/algorithm/CreateRandomTree.class new file mode 100644 index 0000000..677d4b4 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/CreateRandomTree.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/FindSuccessor.class b/bin/org/jalgo/module/avl/algorithm/FindSuccessor.class new file mode 100644 index 0000000..6f32ecc Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/FindSuccessor.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/FindSuccessorStart.class b/bin/org/jalgo/module/avl/algorithm/FindSuccessorStart.class new file mode 100644 index 0000000..4fb167f Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/FindSuccessorStart.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/FindSuccessorStep.class b/bin/org/jalgo/module/avl/algorithm/FindSuccessorStep.class new file mode 100644 index 0000000..b8fe8a8 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/FindSuccessorStep.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/Insert.class b/bin/org/jalgo/module/avl/algorithm/Insert.class new file mode 100644 index 0000000..e929928 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/Insert.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/InsertAVL.class b/bin/org/jalgo/module/avl/algorithm/InsertAVL.class new file mode 100644 index 0000000..964b1aa Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/InsertAVL.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/MacroCommand.class b/bin/org/jalgo/module/avl/algorithm/MacroCommand.class new file mode 100644 index 0000000..060416b Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/MacroCommand.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/NoOperation.class b/bin/org/jalgo/module/avl/algorithm/NoOperation.class new file mode 100644 index 0000000..a5b117a Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/NoOperation.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/Remove.class b/bin/org/jalgo/module/avl/algorithm/Remove.class new file mode 100644 index 0000000..bdd3092 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/Remove.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/RemoveAVL.class b/bin/org/jalgo/module/avl/algorithm/RemoveAVL.class new file mode 100644 index 0000000..44a70e8 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/RemoveAVL.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/RemoveNode.class b/bin/org/jalgo/module/avl/algorithm/RemoveNode.class new file mode 100644 index 0000000..93610cd Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/RemoveNode.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/RotateLeft.class b/bin/org/jalgo/module/avl/algorithm/RotateLeft.class new file mode 100644 index 0000000..3988223 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/RotateLeft.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/RotateRight.class b/bin/org/jalgo/module/avl/algorithm/RotateRight.class new file mode 100644 index 0000000..5e1b137 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/RotateRight.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/Search.class b/bin/org/jalgo/module/avl/algorithm/Search.class new file mode 100644 index 0000000..e4e73db Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/Search.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/SearchAlg.class b/bin/org/jalgo/module/avl/algorithm/SearchAlg.class new file mode 100644 index 0000000..e913082 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/SearchAlg.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/Traverse.class b/bin/org/jalgo/module/avl/algorithm/Traverse.class new file mode 100644 index 0000000..fcbcc60 Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/Traverse.class differ diff --git a/bin/org/jalgo/module/avl/algorithm/UpdateBalance.class b/bin/org/jalgo/module/avl/algorithm/UpdateBalance.class new file mode 100644 index 0000000..733a65e Binary files /dev/null and b/bin/org/jalgo/module/avl/algorithm/UpdateBalance.class differ diff --git a/bin/org/jalgo/module/avl/datastructure/AVLNode.class b/bin/org/jalgo/module/avl/datastructure/AVLNode.class new file mode 100644 index 0000000..cb2e7d6 Binary files /dev/null and b/bin/org/jalgo/module/avl/datastructure/AVLNode.class differ diff --git a/bin/org/jalgo/module/avl/datastructure/Node.class b/bin/org/jalgo/module/avl/datastructure/Node.class new file mode 100644 index 0000000..1bad494 Binary files /dev/null and b/bin/org/jalgo/module/avl/datastructure/Node.class differ diff --git a/bin/org/jalgo/module/avl/datastructure/SearchTree.class b/bin/org/jalgo/module/avl/datastructure/SearchTree.class new file mode 100644 index 0000000..c194163 Binary files /dev/null and b/bin/org/jalgo/module/avl/datastructure/SearchTree.class differ diff --git a/bin/org/jalgo/module/avl/datastructure/Visualizable.class b/bin/org/jalgo/module/avl/datastructure/Visualizable.class new file mode 100644 index 0000000..054f2d4 Binary files /dev/null and b/bin/org/jalgo/module/avl/datastructure/Visualizable.class differ diff --git a/bin/org/jalgo/module/avl/datastructure/WorkNode.class b/bin/org/jalgo/module/avl/datastructure/WorkNode.class new file mode 100644 index 0000000..a4ece9c Binary files /dev/null and b/bin/org/jalgo/module/avl/datastructure/WorkNode.class differ diff --git a/bin/org/jalgo/module/avl/de.properties b/bin/org/jalgo/module/avl/de.properties new file mode 100644 index 0000000..7cc036c --- /dev/null +++ b/bin/org/jalgo/module/avl/de.properties @@ -0,0 +1,135 @@ +Module_name=AVL - Bäume +Module_version=1.0 +Module_authors=Alexander Claus, Ulrike Fischer, Jean Christoph Jung, Sebastian Pape, Matthias Schmidt +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt binäre Suchbäume mit und ohne der AVL-Eigenschaft. +Module_description_2=Es werden die Algorithmen Suchen, Einfügen und Löschen visualisiert. Dabei können die Algorithmen interaktiv gesteuert werden. + +ModuleConnector.No_valid_AVL_file=Keine gültige AVL-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. +GUIController.Is_AVL_tree=Der aktuelle Baum hat die AVL - Eigenschaft\! +GUIController.Wish_to_change_to_AVL_mode=Möchten Sie jetzt in den AVL - Modus wechseln? +GUIController.Changed_to_AVL_mode=AVL-Modus angeschalten +GUIController.Is_no_AVL_tree=Der aktuelle Baum ist kein AVL - Baum\! +PaintArea.Status_message=Stellt den Baum graphisch dar +Hard_exception=Schwerer Ausnahmefehler: +Alg_desc_not_found_error=Xml-Datei nicht gefunden oder anderer Fehler + +Clear_tree=Baum löschen +Clear_tree_tooltip=Löscht den gesamten Baum +Clear_tree_warning=Der gesamte Baum wird gelöscht. +Show_welcome_screen=Willkommensbildschirm anzeigen +Show_welcome_screen_tooltip=Öffnet den Willkommensbildschirm +Wish_to_discard=Möchten Sie Ihre Änderungen verwerfen? + +Abort_algorithm=Algorithmus abbrechen +Abort_algorithm_tooltip=Bricht den laufenden Algorithmus ab +Undo=Schritt zurück +Undo_tooltip=Macht den letzten Schritt im aktuellen Algorithmus rückgängig +Undo_blockstep=Blockschritt zurück +Undo_blockstep_tooltip=Macht den letzen grösseren Schritt im aktuellen Algorithmus rückgängig +Perform=Nächster Schritt +Perform_tooltip=Führt den nächsten Schritt im aktuellen Algorithmus aus +Perform_blockstep=Nächster Blockschritt +Perform_blockstep_tooltip=Führt den nächsten grösseren Schritt im aktuellen Algorithmus aus +Finish_algorithm=Algorithmus beenden +Finish_algorithm_tooltip=Durchläuft den Algorithmus bis zum Ende +Beamer_mode=Beamermodus +AVL_mode=AVL-Modus +Switched_on=angeschalten +Switched_off=abgeschalten + +RGD.Generate_random_tree=Zufallsbaum erstellen +RGD.Node_count=Anzahl der Knoten: +RGD.AVL_property=AVL - Eigenschaft: +RGD.Visualization=Visualisierung: +RGD.No_visualization=keine +RGD.Stepwise=schrittweise +RGD.Automatical=automatisch +RGD.Button_ok=Ok +RGD.Button_cancel=Abbrechen +Warning_only_integers=Bitte nur ganze Zahlen eingeben\! +Warning_only_values_from=Nur Werte von +Warning_to=\ bis +Warning_valid=\ gültig\! +Navigator=Navigator +No_robot_error=Keine Maussprünge möglich. +LogPane.Status_message=Gibt erfolgte Aktionen logbuchartig wieder +LogPane.Update_error=Fehler beim Logbuch-Update +Unreachable_error=Sollte nicht auftreten... +InfoPane.Info=Info +InfoPane.Node_count=Anzahl Knoten: +InfoPane.Height=Baumhöhe: +InfoPane.Average_depth=Durchschnittliche Suchtiefe: +InfoPane.Status_message=Zeigt Informationen über den Baum an +DocuPane.Status_message=Zeigt den Algorithmustext an +DocuPane.Update_error=Fehler bei der Anzeige der Dokumentation: +ControlPane.Label=Kontroll-Bereich +ControlPane.Key=Schlüssel: +ControlPane.Insert_key=Geben Sie hier den Schlüssel ein +ControlPane.Random=Zufallswert +ControlPane.Random_tooltip=Erzeugt einen Zufallswert +ControlPane.Choose_algorithm=Auswahl eines Algorithmus: +ControlPane.Search_tooltip=Startet den Suchen-Algorithmus mit dem gegebenen Schlüssel +ControlPane.Insert_tooltip=Startet den Einfüge-Algorithmus mit dem gegebenen Schlüssel +Controller.aborted=\ abgebrochen +ControlPane.Remove_tooltip=Startet den Löschen-Algorithmus mit dem gegebenen Schlüssel +ControlPane.AVL_property=AVL - Modus +Controller.finished=\ beendet +ControlPane.AVL_test_tooltip=Testet den aktuellen Baum auf die AVL-Eigenschaft +Controller.No_alg_exception=Es läuft kein Algorithmus\! +Controller.No_next_exception=Es gibt keinen weiteren Schritt mehr\! +Controller.No_prev_exception=Es gibt keinen vorherigen Schritt mehr\! +ControlPane.Flow_control=Algorithmussteuerung: +Controller.Key_not_found=Schlüssel nicht im Baum enthalten +Controller.Log_exception=Algorithmusende noch nicht betrachtet +ControlPane.Anim_speed=Animationsgeschwindigkeit: +Controller.Key_exists=Schlüssel existiert bereits\! +Controller.Successful=\ erfolgreich +ControlPane.fast=schnell +ControlPane.slow=langsam +ControlPane.Anim_speed_tooltip=Stellt die Geschwindigkeit der Animation ein + +Alg_name.AVL_test=AVL-Test +Alg_name.Insert=Einfügen +Alg_name.Insert_AVL=AVL-Einfügen +Alg_name.Remove=Löschen +Alg_name.Remove_AVL=AVL-Löschen +Alg_name.Search=Suchen +Alg_name.Create_tree=Suchbaum Erstellen +Alg_name.Create_AVL_tree=AVL-Baum Erstellen + +CreateRandomTree.With=\ mit +CreateRandomTree.Nodes=\ Knoten +CreateRandomTree.Tree_finished=Suchbaum ist fertig +CreateRandomTree.AVL_finished=AVL-Baum ist fertig +Successor_found=nächstgrößeren Schlüssel gefunden +FindSuccessorStart.Step_to_right=einmal rechts gegangen +FindSuccessor.Step_to_left=links gegangen +_of=\ von +Started=\ gestartet +Insert.Key_found=\nSchlüssel muss nicht eingefügt werden +Insert_left=\ --> links einfügen +Insert_right=\ --> rechts einfügen +Insert_finished=Einfügen beendet +Step_undone=Schritt rückgängig gemacht +Key_search=\ suchen +Node_inserted=Knoten eingefügt +Node_removed=Knoten gelöscht +Node_found=\ Knoten gefunden +Key_found=Schlüssel gefunden +Tree_balanced=\nBaum ausgeglichen +Tree_empty_key_not_found=Baum ist leer, Schlüssel nicht gefunden +Remove_aborted=\ \nLöschen abgebrochen +Remove_finished=Löschen beendet +Root_reached_tree_balanced=Wurzel erreicht\nBaum ausgeglichen +Partial_tree_balanced=\nTeilbaum ausgeglichen +N_tree_balanced=\nBaum ausgeglichen +Rotate_left_around=Linksrotation um: +Rotate_right_around=Rechtsrotation um: +Search_not_found=\nnicht gefunden +Search_step_to_left=\ --> nach links gehen +Search_step_to_right=\ --> nach rechts gehen +UpdateBalance.Balance_set_to=Balance auf +UpdateBalance.Balance_set=\ gesetzt diff --git a/bin/org/jalgo/module/avl/en.properties b/bin/org/jalgo/module/avl/en.properties new file mode 100644 index 0000000..772d18f --- /dev/null +++ b/bin/org/jalgo/module/avl/en.properties @@ -0,0 +1,135 @@ +Module_name=AVL - Trees +Module_version=1.0 +Module_authors=Alexander Claus, Ulrike Fischer, Jean Christoph Jung, Sebastian Pape, Matthias Schmidt +Module_license=GNU General Public License +Module_description_1=This module is about binary search trees with and without the AVL - property. +Module_description_2=The algorithms to be visualized are: Searching, Inserting and Deleting. The algorithms can be controlled interactively. + +ModuleConnector.No_valid_AVL_file=No valid AVL - file. +ModuleConnector.Loading_error=Error while loading the file. +ModuleConnector.File_damaged=Maybe the file is damaged. +GUIController.Is_AVL_tree=The current tree has the AVL - property\! +GUIController.Wish_to_change_to_AVL_mode=Do you wish to switch to the AVL - mode? +GUIController.Changed_to_AVL_mode=AVL - mode on +GUIController.Is_no_AVL_tree=The current tree is no AVL - tree\! +PaintArea.Status_message=Displays the tree graphically. +Hard_exception=Hard exception: +Alg_desc_not_found_error=Xml-file not found. + +Clear_tree=Clear tree +Clear_tree_tooltip=Clears the whole tree. +Clear_tree_warning=The tree will be cleared. +Show_welcome_screen=Show welcome screen +Show_welcome_screen_tooltip=Shows the welcome screen +Wish_to_discard=Do you wish to discard your changes? + +Abort_algorithm=Abort algorithm +Abort_algorithm_tooltip=Aborts the currently running algorithm +Undo=Undo +Undo_tooltip=Undoes the last step in current algorithm +Undo_blockstep=Undo block step +Undo_blockstep_tooltip=Undoes the last block step in current algorithm +Perform=Next step +Perform_tooltip=Performs the next step in current algorithm +Perform_blockstep=Next block step +Perform_blockstep_tooltip=Performs the next block step in current algorithm +Finish_algorithm=Finish algorithm +Finish_algorithm_tooltip=Runs the algorithm until it ends +Beamer_mode=Beamer-mode +AVL_mode=AVL - mode +Switched_on=on +Switched_off=off + +RGD.Generate_random_tree=Generate random-tree +RGD.Node_count=Number of nodes: +RGD.AVL_property=AVL - property: +RGD.Visualization=Visualization: +RGD.No_visualization=no visualization +RGD.Stepwise=stepwise +RGD.Automatical=automatically +RGD.Button_ok=Ok +RGD.Button_cancel=Cancel +Warning_only_integers=Please only insert integers\! +Warning_only_values_from=Only values from +Warning_to=\ to +Warning_valid=\ valid\! +Navigator=Navigator +No_robot_error=No mouse jumps possible. +LogPane.Status_message=Displays done actions in the style of a logbook +LogPane.Update_error=Error at log update +Unreachable_error=This error should not occur... +InfoPane.Info=Info +InfoPane.Node_count=Number of nodes: +InfoPane.Height=Tree-height: +InfoPane.Average_depth=Average depth: +InfoPane.Status_message=Shows informations about the tree +DocuPane.Status_message=Shows the algorithm text +DocuPane.Update_error=Error while displaying the documentation: +ControlPane.Label=Control-Center +ControlPane.Key=Key: +ControlPane.Insert_key=Insert key value here +ControlPane.Random=Random +ControlPane.Random_tooltip=Creates a random value +ControlPane.Choose_algorithm=Choose an algorithm: +ControlPane.Search_tooltip=Starts the search algorithm with the given key +ControlPane.Insert_tooltip=Starts the insert algorithm with the given key +Controller.aborted=\ aborted +ControlPane.Remove_tooltip=Starts the delete algorithm with the given key +ControlPane.AVL_property=AVL - mode +Controller.finished=\ finished +ControlPane.AVL_test_tooltip=Checks the current tree for the AVL - property +Controller.No_alg_exception=Currently is no algorithm running\! +Controller.No_next_exception=There is no next step\! +Controller.No_prev_exception=There is no previous step\! +ControlPane.Flow_control=Algorithm control: +Controller.Key_not_found=Key is not contained in tree +Controller.Log_exception=Exception because of unknown algorithm ending +ControlPane.Anim_speed=Animation speed: +Controller.Key_exists=The key exists already\! +Controller.Successful=\ successful +ControlPane.fast=fast +ControlPane.slow=slow +ControlPane.Anim_speed_tooltip=Sets the speed of the animation + +Alg_name.AVL_test=AVL-Test +Alg_name.Insert=Insert +Alg_name.Insert_AVL=AVL-Insert +Alg_name.Remove=Remove +Alg_name.Remove_AVL=AVL-Remove +Alg_name.Search=Search +Alg_name.Create_tree=Create search tree +Alg_name.Create_AVL_tree=Create AVL - tree + +CreateRandomTree.With=\ with +CreateRandomTree.Nodes=\ Nodes +CreateRandomTree.Tree_finished=Search tree is finished +CreateRandomTree.AVL_finished=AVL - tree is finished +Successor_found=successor found +FindSuccessorStart.Step_to_right=one step to the right +FindSuccessor.Step_to_left=step to the left +_of=\ of +Started=\ started +Insert.Key_found=\nKey doesn't have to be inserted +Insert_left=\ --> insert left +Insert_right=\ --> insert right +Insert_finished=Insert finished +Step_undone=Step undone +Key_search=\ search +Node_inserted=Node inserted +Node_removed=Node removed +Node_found=\ Node found +Key_found=Key found +Tree_balanced=\nTree balanced +Tree_empty_key_not_found=Tree is empty, key not found +Remove_aborted=\ \nRemove aborted +Remove_finished=Remove finished +Root_reached_tree_balanced=Root node reached\nTree balanced +Partial_tree_balanced=\nPartial tree balanced +N_tree_balanced=\nTree balanced +Rotate_left_around=Rotate left at: +Rotate_right_around=Rotate right at: +Search_not_found=\nnot found +Search_step_to_left=\ --> step to the left +Search_step_to_right=\ --> step to the right +UpdateBalance.Balance_set_to=Balance set to +UpdateBalance.Balance_set=\ diff --git a/bin/org/jalgo/module/avl/gui/DisplayModeChangeable.class b/bin/org/jalgo/module/avl/gui/DisplayModeChangeable.class new file mode 100644 index 0000000..340cd72 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/DisplayModeChangeable.class differ diff --git a/bin/org/jalgo/module/avl/gui/DocuManager$XmlHandler.class b/bin/org/jalgo/module/avl/gui/DocuManager$XmlHandler.class new file mode 100644 index 0000000..de40910 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/DocuManager$XmlHandler.class differ diff --git a/bin/org/jalgo/module/avl/gui/DocuManager.class b/bin/org/jalgo/module/avl/gui/DocuManager.class new file mode 100644 index 0000000..a6dd9bd Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/DocuManager.class differ diff --git a/bin/org/jalgo/module/avl/gui/GUIConstants.class b/bin/org/jalgo/module/avl/gui/GUIConstants.class new file mode 100644 index 0000000..afc8478 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/GUIConstants.class differ diff --git a/bin/org/jalgo/module/avl/gui/GUIController$1.class b/bin/org/jalgo/module/avl/gui/GUIController$1.class new file mode 100644 index 0000000..c079de1 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/GUIController$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/GUIController$2.class b/bin/org/jalgo/module/avl/gui/GUIController$2.class new file mode 100644 index 0000000..b2eb5b1 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/GUIController$2.class differ diff --git a/bin/org/jalgo/module/avl/gui/GUIController.class b/bin/org/jalgo/module/avl/gui/GUIController.class new file mode 100644 index 0000000..7cf7c21 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/GUIController.class differ diff --git a/bin/org/jalgo/module/avl/gui/Settings.class b/bin/org/jalgo/module/avl/gui/Settings.class new file mode 100644 index 0000000..d116d6b Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/Settings.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/ControlPane.class b/bin/org/jalgo/module/avl/gui/components/ControlPane.class new file mode 100644 index 0000000..498fbf0 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/ControlPane.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/DocuPane$1.class b/bin/org/jalgo/module/avl/gui/components/DocuPane$1.class new file mode 100644 index 0000000..36c287d Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/DocuPane$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/DocuPane.class b/bin/org/jalgo/module/avl/gui/components/DocuPane.class new file mode 100644 index 0000000..a99ccdc Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/DocuPane.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/InfoPane$1.class b/bin/org/jalgo/module/avl/gui/components/InfoPane$1.class new file mode 100644 index 0000000..a7da04f Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/InfoPane$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/InfoPane.class b/bin/org/jalgo/module/avl/gui/components/InfoPane.class new file mode 100644 index 0000000..d0c81b2 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/InfoPane.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/LogPane$1.class b/bin/org/jalgo/module/avl/gui/components/LogPane$1.class new file mode 100644 index 0000000..06680b2 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/LogPane$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/LogPane.class b/bin/org/jalgo/module/avl/gui/components/LogPane.class new file mode 100644 index 0000000..b593d0c Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/LogPane.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/Navigator$1.class b/bin/org/jalgo/module/avl/gui/components/Navigator$1.class new file mode 100644 index 0000000..707fdcc Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/Navigator$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/Navigator.class b/bin/org/jalgo/module/avl/gui/components/Navigator.class new file mode 100644 index 0000000..f54067f Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/Navigator.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/RandomGenerationDialog.class b/bin/org/jalgo/module/avl/gui/components/RandomGenerationDialog.class new file mode 100644 index 0000000..1355f10 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/RandomGenerationDialog.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/WelcomeButton.class b/bin/org/jalgo/module/avl/gui/components/WelcomeButton.class new file mode 100644 index 0000000..95ac60c Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/WelcomeButton.class differ diff --git a/bin/org/jalgo/module/avl/gui/components/WelcomeScreen.class b/bin/org/jalgo/module/avl/gui/components/WelcomeScreen.class new file mode 100644 index 0000000..a95b0b6 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/components/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/AbortAction.class b/bin/org/jalgo/module/avl/gui/event/AbortAction.class new file mode 100644 index 0000000..fee95d3 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/AbortAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/ClearTreeAction.class b/bin/org/jalgo/module/avl/gui/event/ClearTreeAction.class new file mode 100644 index 0000000..d0edf86 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/ClearTreeAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/ControlActionHandler.class b/bin/org/jalgo/module/avl/gui/event/ControlActionHandler.class new file mode 100644 index 0000000..9b1f6da Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/ControlActionHandler.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/FinishAction.class b/bin/org/jalgo/module/avl/gui/event/FinishAction.class new file mode 100644 index 0000000..a5e7b6b Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/FinishAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/PerformAction.class b/bin/org/jalgo/module/avl/gui/event/PerformAction.class new file mode 100644 index 0000000..0cabe37 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/PerformAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/PerformBlockStepAction.class b/bin/org/jalgo/module/avl/gui/event/PerformBlockStepAction.class new file mode 100644 index 0000000..ed6ca1a Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/PerformBlockStepAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.class b/bin/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.class new file mode 100644 index 0000000..9ef4e36 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.class b/bin/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.class new file mode 100644 index 0000000..a76c69b Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/UndoAction.class b/bin/org/jalgo/module/avl/gui/event/UndoAction.class new file mode 100644 index 0000000..d19bf21 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/UndoAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/UndoBlockStepAction.class b/bin/org/jalgo/module/avl/gui/event/UndoBlockStepAction.class new file mode 100644 index 0000000..0438c6a Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/UndoBlockStepAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/WelcomeAction.class b/bin/org/jalgo/module/avl/gui/event/WelcomeAction.class new file mode 100644 index 0000000..9afed8c Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/WelcomeAction.class differ diff --git a/bin/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.class b/bin/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.class new file mode 100644 index 0000000..79aa542 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/Animator.class b/bin/org/jalgo/module/avl/gui/graphics/Animator.class new file mode 100644 index 0000000..74b0e6d Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/Animator.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/GraphicsConstants.class b/bin/org/jalgo/module/avl/gui/graphics/GraphicsConstants.class new file mode 100644 index 0000000..22de144 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/GraphicsConstants.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/PaintArea$1.class b/bin/org/jalgo/module/avl/gui/graphics/PaintArea$1.class new file mode 100644 index 0000000..5a1ee99 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/PaintArea$1.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/PaintArea.class b/bin/org/jalgo/module/avl/gui/graphics/PaintArea.class new file mode 100644 index 0000000..2e60a44 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/PaintArea.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.class b/bin/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.class new file mode 100644 index 0000000..f6db3ee Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.class differ diff --git a/bin/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.class b/bin/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.class new file mode 100644 index 0000000..4a174b5 Binary files /dev/null and b/bin/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.class differ diff --git a/bin/org/jalgo/module/avl/res.properties b/bin/org/jalgo/module/avl/res.properties new file mode 100644 index 0000000..097bcc9 --- /dev/null +++ b/bin/org/jalgo/module/avl/res.properties @@ -0,0 +1,18 @@ +Module_logo=/avl_pix/logo.gif +Algorithm_text_base_de=/avl_algdesc.de.xml +Algorithm_text_base_en=/avl_algdesc.en.xml + +Welcome_load=/avl_pix/welcome_load.gif +Welcome_load_rollover=/avl_pix/welcome_load_rollover.gif +Welcome_load_description_de=/avl_pix/welcome_load_desc_de.gif +Welcome_load_description_en=/avl_pix/welcome_load_desc_en.gif +Welcome_manual=/avl_pix/welcome_manual.gif +Welcome_manual_rollover=/avl_pix/welcome_manual_rollover.gif +Welcome_manual_description_de=/avl_pix/welcome_manual_desc_de.gif +Welcome_manual_description_en=/avl_pix/welcome_manual_desc_en.gif +Welcome_random=/avl_pix/welcome_random.gif +Welcome_random_rollover=/avl_pix/welcome_random_rollover.gif +Welcome_random_description_de=/avl_pix/welcome_random_desc_de.gif +Welcome_random_description_en=/avl_pix/welcome_random_desc_en.gif + +HelpSet_Name=/help/jhelp/avl_help.hs \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/ModuleConnector.class b/bin/org/jalgo/module/bfsdfs/ModuleConnector.class new file mode 100644 index 0000000..f068856 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/bfsdfs/ModuleInfo.class b/bin/org/jalgo/module/bfsdfs/ModuleInfo.class new file mode 100644 index 0000000..e7bc74d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/Algo.class b/bin/org/jalgo/module/bfsdfs/algorithms/Algo.class new file mode 100644 index 0000000..21aaea3 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/Algo.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/AlgoStep.class b/bin/org/jalgo/module/bfsdfs/algorithms/AlgoStep.class new file mode 100644 index 0000000..bfd4418 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/AlgoStep.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/BFS.class b/bin/org/jalgo/module/bfsdfs/algorithms/BFS.class new file mode 100644 index 0000000..7a2ca95 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/BFS.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/BFSStep.class b/bin/org/jalgo/module/bfsdfs/algorithms/BFSStep.class new file mode 100644 index 0000000..f14c692 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/BFSStep.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/DFS.class b/bin/org/jalgo/module/bfsdfs/algorithms/DFS.class new file mode 100644 index 0000000..fe81738 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/DFS.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/DFSStep.class b/bin/org/jalgo/module/bfsdfs/algorithms/DFSStep.class new file mode 100644 index 0000000..6079546 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/DFSStep.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue$Node.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue$Node.class new file mode 100644 index 0000000..0b28b5e Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue$Node.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.class new file mode 100644 index 0000000..abff2c5 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.class new file mode 100644 index 0000000..9deeb3d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.class new file mode 100644 index 0000000..12c2be9 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.class new file mode 100644 index 0000000..f2eb7f2 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.class b/bin/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.class new file mode 100644 index 0000000..314dbb5 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.class new file mode 100644 index 0000000..50108d4 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.class new file mode 100644 index 0000000..01598bb Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.class new file mode 100644 index 0000000..22e223e Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.class new file mode 100644 index 0000000..0c1d4e2 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.class new file mode 100644 index 0000000..43b2462 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.class new file mode 100644 index 0000000..7ff2173 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.class new file mode 100644 index 0000000..42501d4 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.class new file mode 100644 index 0000000..b500e62 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.class new file mode 100644 index 0000000..9516ea9 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.class differ diff --git a/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.class b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.class new file mode 100644 index 0000000..57310c1 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.class b/bin/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.class new file mode 100644 index 0000000..df5d647 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/AddEdge.class b/bin/org/jalgo/module/bfsdfs/controller/AddEdge.class new file mode 100644 index 0000000..6b2ccbb Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/AddEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/AddNode.class b/bin/org/jalgo/module/bfsdfs/controller/AddNode.class new file mode 100644 index 0000000..2a26ec0 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/AddNode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/ComplexStep.class b/bin/org/jalgo/module/bfsdfs/controller/ComplexStep.class new file mode 100644 index 0000000..090aef0 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/ComplexStep.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/DesignStep.class b/bin/org/jalgo/module/bfsdfs/controller/DesignStep.class new file mode 100644 index 0000000..8a3779a Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/DesignStep.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/GraphController.class b/bin/org/jalgo/module/bfsdfs/controller/GraphController.class new file mode 100644 index 0000000..707d1c5 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/GraphController.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.class b/bin/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.class new file mode 100644 index 0000000..dce7568 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/RemoveEdge.class b/bin/org/jalgo/module/bfsdfs/controller/RemoveEdge.class new file mode 100644 index 0000000..7e65970 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/RemoveEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/controller/RemoveNode.class b/bin/org/jalgo/module/bfsdfs/controller/RemoveNode.class new file mode 100644 index 0000000..d6a419a Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/controller/RemoveNode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/de.properties b/bin/org/jalgo/module/bfsdfs/de.properties new file mode 100644 index 0000000..8e649e2 --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/de.properties @@ -0,0 +1,54 @@ +ModuleConnector.No_valid_BFSDFS_file=Keine gültige BFSDFS-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. + +ModuleInfo.description =Demonstriert Breiten- und Tiefensuche in Graphen. + +GUIController.warning=Warnung +GUIController.warning_desc=Achtung, ein Algorithmus läuft gerade! Wenn sie den Graphen bearbeiten wollen, setzen Sie alle Algorithmen zurück. +GUIController.warning_reset=Algorithmen jetzt zurücksetzen +GUIController.warning_abort=Abbrechen +WelcomeScreen.ioError=Datei konnte nicht gelesen werden. + +tab.designButton=Design +tab.bfsButton=Breitensuche +tab.dfsButton=Tiefensuche +tab.beamerButton=Beamermodus +tab.designButton_tooltip=Zeigt das Fenster für die Bearbeitung des Graphen an. +tab.bfsButton_tooltip=Zeigt das Fenster für den Breitensuche-Algorithmus an. +tab.dfsButton_tooltip=Zeigt das Fenster für den Tiefensuche-Algorithmus an. +tab.beamerButton_tooltip=Schaltet den Beamer-Modus an bzw. aus. (Taste: B) + +AlgoTab.startNodeLabel=Startknoten: +AlgoTab.startNodeChooserStatus=Wählen Sie hier den Startknoten aus. +AlgoTab.successorLabel=Nachfolger-Reihenfolge: +AlgoTab.successorChooserStatus=Hier können Sie die Reihenfolge der Nachfolger mittels Drag & Drop ändern. +AlgoTab.randomLabel=Zufall: +AlgoTab.randomBoxStatus=Schalten Sie hier den Nichtdeterminismus an bzw. aus. +AlgoTab.chooserPaneStatus=Hier können Sie den Algorithmus steuern. +AlgoTab.scrollPaneStatus=Hier wird der Graph visualisiert. + +GraphView.scrollPaneStatus=Hier können Sie einen Graphen erstellen oder bearbeiten. + +DFSTab.nodeViewLabel=Laufzeitkeller: +DFSTab.nodeViewStatus=Hier wird der vom Algorithmus benutzte Laufzeitkeller visualisiert. +BFSTab.nodeViewLabel=Warteschlange: +BFSTab.nodeViewStatus=Hier wird die vom Algorithmus benutzte Warteschlange visualisiert. + +ScrollArea.status = Bleiben Sie mit der Maus auf diesem Feld, um die Nachfolger zu scrollen. + +ResetAction.tooltip=Algorithmus zurücksetzen. (Taste: A) +StepBackAction.tooltip=Einen Schritt zurück. (Taste: S) +StepForwardAction.tooltip=Einen Schritt vor. (Taste: D) +PlayAction.tooltip=Algorithmus ablaufen lassen. (Taste: F) +CancelAction.tooltip=Derzeitige Animation abbrechen. (Taste: C) + +animationLabel.text =Animationen deaktivieren +AnimationAction.tooltip=Wählen Sie diese Option, um die Leistung zu erhöhen. + +UndoAction.tooltip=Letzten Schritt rückgängig machen. (Taste: Y) +RedoAction.tooltip=Letzten Schritt wiederholen. (Taste: X) +NodeAction.tooltip=Knoten hinzufügen und verschieben. (Taste: Q) +EdgeAction.tooltip=Gerichtete Kante hinzufügen. (Taste: W) +DoubleEdgeAction.tooltip=Ungerichtete Kante hinzufügen. (Taste: E) +EraserAction.tooltip=Strukturen löschen. (Taste: R) diff --git a/bin/org/jalgo/module/bfsdfs/en.properties b/bin/org/jalgo/module/bfsdfs/en.properties new file mode 100644 index 0000000..ab0ebdd --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/en.properties @@ -0,0 +1,54 @@ +ModuleConnector.No_valid_BFSDFS_file=No valid BFSDFS file. +ModuleConnector.Loading_error=An error occured while loading the file. +ModuleConnector.File_damaged=The file is possibly damaged. + +ModuleInfo.description = Demonstrates breadth first search and depth first search in graphs. + +GUIController.warning=Warning +GUIController.warning_desc=Attention, an algorithm is currently proceeding. If you want to change the graph, you have to reset all running algorithms. +GUIController.warning_reset=Reset algorithms now +GUIController.warning_abort=Cancel +WelcomeScreen.ioError=Could not read file. + +tab.designButton=Design +tab.bfsButton=Breadth First Search +tab.dfsButton=Depth First Search +tab.beamerButton=Beamer Mode +tab.designButton_tooltip=Shows the design window to work on the graph. +tab.bfsButton_tooltip=Shows the breadth first search window. +tab.dfsButton_tooltip=Shows the depth first search window. +tab.beamerButton_tooltip=Turns beamer mode on / off. (Key: B) + +AlgoTab.startNodeLabel=Start Node: +AlgoTab.startNodeChooserStatus=Here you can choose the start node. +AlgoTab.successorLabel=Successor Order: +AlgoTab.successorChooserStatus=Here you can change the order of the successors with Drag & Drop. +AlgoTab.randomLabel=Random: +AlgoTab.randomBoxStatus=Toggles the non-determinism. +AlgoTab.chooserPaneStatus=From here you can control the algorithm. +AlgoTab.scrollPaneStatus=Visualizes the graph. + +GraphView.scrollPaneStatus=From here you can create or edit the graph. + +DFSTab.nodeViewLabel=Stack: +DFSTab.nodeViewStatus=Visualizes the stack used by the algorithm. +BFSTab.nodeViewLabel=Queue: +BFSTab.nodeViewStatus=Visualizes the queue used by the algorithm. + +ScrollArea.status = Keep the mouse in this area to scroll the successors. + +ResetAction.tooltip=Reset the algorithm. (Key: A) +StepBackAction.tooltip=One step back. (Key: S) +StepForwardAction.tooltip=One step forward. (Key: D) +PlayAction.tooltip=Play the algorithm. (Key: F) +CancelAction.tooltip=Cancel the current animation. (Key: C) + +animationLabel.text =Disable Animations +AnimationAction.tooltip=Choose this option to increase the performance. + +UndoAction.tooltip=Undo the last step. (Key: Y) +RedoAction.tooltip=Redo the last step. (Key: X) +NodeAction.tooltip=Add or move a node. (Key: Q) +EdgeAction.tooltip=Add a directed edge. (Key: W) +DoubleEdgeAction.tooltip=Add a double edge. (Key: E) +EraserAction.tooltip=Erase structures. (Key: R) diff --git a/bin/org/jalgo/module/bfsdfs/graph/AlgoGraph.class b/bin/org/jalgo/module/bfsdfs/graph/AlgoGraph.class new file mode 100644 index 0000000..9d0dead Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/AlgoGraph.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.class b/bin/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.class new file mode 100644 index 0000000..089132c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/Edge.class b/bin/org/jalgo/module/bfsdfs/graph/Edge.class new file mode 100644 index 0000000..61daf86 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/Edge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/GraphObserver.class b/bin/org/jalgo/module/bfsdfs/graph/GraphObserver.class new file mode 100644 index 0000000..5886be8 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/GraphObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/Node.class b/bin/org/jalgo/module/bfsdfs/graph/Node.class new file mode 100644 index 0000000..3e3d627 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/Node.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/ObservableGraph.class b/bin/org/jalgo/module/bfsdfs/graph/ObservableGraph.class new file mode 100644 index 0000000..5a57155 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/graph/ObservableGraph.class differ diff --git a/bin/org/jalgo/module/bfsdfs/graph/package.html b/bin/org/jalgo/module/bfsdfs/graph/package.html new file mode 100644 index 0000000..01467d3 --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/graph/package.html @@ -0,0 +1,10 @@ + + + + +

The graph package provide the class ObservableGraph, the graph which BFS / DFS algorithm works on. +It also contains the class AlgoGraph, with represents the result tree for the BFS / DFS algorithm. +The both graph are observable. The observer interface for the class ObservableGraph is GraphObserver and +for the class AlgoGraph AlgoGraphObserver. Class Node and Class Edge represents the basic datatyps of the both graph.

+ + \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.class b/bin/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.class new file mode 100644 index 0000000..b1c824d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/ComponentUtility.class b/bin/org/jalgo/module/bfsdfs/gui/ComponentUtility.class new file mode 100644 index 0000000..21f201b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/ComponentUtility.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUIConstants.class b/bin/org/jalgo/module/bfsdfs/gui/GUIConstants.class new file mode 100644 index 0000000..b887498 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUIConstants.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyBFSObserver.class b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyBFSObserver.class new file mode 100644 index 0000000..1b7c2e8 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyBFSObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyDFSObserver.class b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyDFSObserver.class new file mode 100644 index 0000000..91bef5f Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyDFSObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyGraphObserver.class b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyGraphObserver.class new file mode 100644 index 0000000..7a2df8c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUIController$MyGraphObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUIController.class b/bin/org/jalgo/module/bfsdfs/gui/GUIController.class new file mode 100644 index 0000000..82bd057 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUIController.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GUITest.class b/bin/org/jalgo/module/bfsdfs/gui/GUITest.class new file mode 100644 index 0000000..cb97687 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GUITest.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GraphAnimations.class b/bin/org/jalgo/module/bfsdfs/gui/GraphAnimations.class new file mode 100644 index 0000000..c1623a6 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GraphAnimations.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GraphCalculation.class b/bin/org/jalgo/module/bfsdfs/gui/GraphCalculation.class new file mode 100644 index 0000000..ec16777 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GraphCalculation.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/GraphDrawing.class b/bin/org/jalgo/module/bfsdfs/gui/GraphDrawing.class new file mode 100644 index 0000000..6e8e2a3 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/GraphDrawing.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/PlayAnimation.class b/bin/org/jalgo/module/bfsdfs/gui/PlayAnimation.class new file mode 100644 index 0000000..46fcc6a Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/PlayAnimation.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.class b/bin/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.class new file mode 100644 index 0000000..35de50b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.class b/bin/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.class new file mode 100644 index 0000000..64671da Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab$1.class b/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab$1.class new file mode 100644 index 0000000..ad0fc83 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab$1.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab.class b/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab.class new file mode 100644 index 0000000..15b4717 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/AlgoTab.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/BFSTab.class b/bin/org/jalgo/module/bfsdfs/gui/components/BFSTab.class new file mode 100644 index 0000000..ce05e0d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/BFSTab.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/DFSTab.class b/bin/org/jalgo/module/bfsdfs/gui/components/DFSTab.class new file mode 100644 index 0000000..e8518df Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/DFSTab.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/DesignTab.class b/bin/org/jalgo/module/bfsdfs/gui/components/DesignTab.class new file mode 100644 index 0000000..0d0bbf4 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/DesignTab.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/FormUtility.class b/bin/org/jalgo/module/bfsdfs/gui/components/FormUtility.class new file mode 100644 index 0000000..ce5020c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/FormUtility.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.class b/bin/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.class new file mode 100644 index 0000000..da2c1ea Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/NodeStackView.class b/bin/org/jalgo/module/bfsdfs/gui/components/NodeStackView.class new file mode 100644 index 0000000..f0139ad Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/NodeStackView.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea$ScrollThread.class b/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea$ScrollThread.class new file mode 100644 index 0000000..9e4b323 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea$ScrollThread.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea.class b/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea.class new file mode 100644 index 0000000..3446f44 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/ScrollArea.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.class b/bin/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.class new file mode 100644 index 0000000..9eeda43 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$1.class b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$1.class new file mode 100644 index 0000000..b663bcd Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$1.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$2.class b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$2.class new file mode 100644 index 0000000..cf6e4dd Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$2.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$3.class b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$3.class new file mode 100644 index 0000000..4256b19 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer$3.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer.class b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer.class new file mode 100644 index 0000000..867279d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/TabContainer.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.class b/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.class new file mode 100644 index 0000000..f06927c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.class b/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.class new file mode 100644 index 0000000..6bc224d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/components/package.html b/bin/org/jalgo/module/bfsdfs/gui/components/package.html new file mode 100644 index 0000000..a4fc6b9 --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/gui/components/package.html @@ -0,0 +1,30 @@ + + + + +

+This package contains every component that is visible in the module except the GraphViews. There +are: +

    +
  • The WelcomeScreen with its three WelcomeButtons. Here you can create a new +graph, load an existing graph from file or load the last opened graph.
  • +
  • The TabContainer which represents a simple container class with a card layout that switches +its content by pressing the according button. It handles the three windows DesignTab, +BFSTab and DFSTab. Also, there is a beamer mode button that switches the sizes and +fonts of the components.
  • +
  • The DesignTab which is used to work with the graph. It is possible to add / move nodes, +add edges and erase structures and also undo / redo these steps.
  • +
  • The AlgoTab which is the super class of the other two windows BFSTab and +DFSTab. Here it is possible to control the according algorithm meaning the commands reset, step +back, step forward, play and cancel. Furthermore one can choose the start node, the order of the possible +successors and toggle the non-determinism.
    +They also contain the NodeStackView that visualizes the stack / queue used by the algorithm.
  • +
  • The SuccessorChooser from where the user can change the order of the current successors +per Drag & Drop. It is associated with its two ScrollAreas which are necessary to scroll it.
  • +
  • Some utility classes, such as FormUtility to create a nice GridBagLayout and the +NodeListRenderer that renders the nodes in the start node chooser, so that it contains icons +instead of numbers.
  • +
+

+ + \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/AnimationAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/AnimationAction.class new file mode 100644 index 0000000..892f420 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/AnimationAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/BeamerAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/BeamerAction.class new file mode 100644 index 0000000..b2b4fd3 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/BeamerAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/CancelAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/CancelAction.class new file mode 100644 index 0000000..58564bd Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/CancelAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.class new file mode 100644 index 0000000..78362f8 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/EdgeAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/EdgeAction.class new file mode 100644 index 0000000..c9030e1 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/EdgeAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/EraserAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/EraserAction.class new file mode 100644 index 0000000..0a3b9b6 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/EraserAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/NodeAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/NodeAction.class new file mode 100644 index 0000000..67f370f Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/NodeAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/PlayAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/PlayAction.class new file mode 100644 index 0000000..116dc0c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/PlayAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/RandomAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/RandomAction.class new file mode 100644 index 0000000..19e8a04 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/RandomAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/RedoAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/RedoAction.class new file mode 100644 index 0000000..fbb0f04 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/RedoAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/ResetAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/ResetAction.class new file mode 100644 index 0000000..3702b04 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/ResetAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/StepBackAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/StepBackAction.class new file mode 100644 index 0000000..3759395 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/StepBackAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.class new file mode 100644 index 0000000..11d245f Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/UndoAction.class b/bin/org/jalgo/module/bfsdfs/gui/event/UndoAction.class new file mode 100644 index 0000000..359df60 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/UndoAction.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.class b/bin/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.class new file mode 100644 index 0000000..24772c1 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/event/package.html b/bin/org/jalgo/module/bfsdfs/gui/event/package.html new file mode 100644 index 0000000..90a8df3 --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/gui/event/package.html @@ -0,0 +1,17 @@ + + + + +

+This package contains actions to control: +

    +
  • the graph (Undo, Redo, Node, Edge, DoubleEdge, Eraser) +
  • the algorithm (Reset, StepBack, StepForward, Play, Cancel) +
  • and the animations (AnimationToggleAction) +
+They extend AbstractAction and set a name, a short description +and a small icon. It is easier controlling the actions than controlling the +buttons because there are multiple buttons for each action. +

+ + \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.class new file mode 100644 index 0000000..5fe9d4f Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.class new file mode 100644 index 0000000..f2c9f1b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.class new file mode 100644 index 0000000..1b8b92b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.class new file mode 100644 index 0000000..94e5ebf Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.class new file mode 100644 index 0000000..62031a2 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.class new file mode 100644 index 0000000..72958c8 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.class new file mode 100644 index 0000000..87ca85d Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/EditMode.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/EditMode.class new file mode 100644 index 0000000..4560091 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/EditMode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.class new file mode 100644 index 0000000..b228630 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.class new file mode 100644 index 0000000..6984d22 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphView.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphView.class new file mode 100644 index 0000000..afaec72 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/GraphView.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.class new file mode 100644 index 0000000..9ccba90 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.class new file mode 100644 index 0000000..06b5cf8 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/Repainter.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/Repainter.class new file mode 100644 index 0000000..f271f3b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/Repainter.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView$InputGraphObserver.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView$InputGraphObserver.class new file mode 100644 index 0000000..9adf349 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView$InputGraphObserver.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView.class new file mode 100644 index 0000000..5079180 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/TreeView.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.class new file mode 100644 index 0000000..e66361e Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.class new file mode 100644 index 0000000..d37ca37 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.class new file mode 100644 index 0000000..a332ed6 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.class new file mode 100644 index 0000000..408189c Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.class b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.class new file mode 100644 index 0000000..4da727e Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.class differ diff --git a/bin/org/jalgo/module/bfsdfs/gui/graphview/package.html b/bin/org/jalgo/module/bfsdfs/gui/graphview/package.html new file mode 100644 index 0000000..56cfdca --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/gui/graphview/package.html @@ -0,0 +1,11 @@ + + + + +

This package contains the GraphView, which is a component to show a graph or a tree. InteractiveGraphView and TreeView are child classes from this component, used to create interactivity for creating a graph and to show the result tree of an algorithm.

+

To draw the elements of a graph or tree, the abstract class VisualGraphElement is used. There are different child classes like VisualEdge and VisualNode to draw edges and nodes. The child classes DeletedEdge and DeletedNode are used for the remove animation of this elements only. The classes VisualTempNode and VisualTempEdge are used for drawing a temporary graph element that is not created yet.

+

This classes use the Strategy design pattern to enable different drawing styles. The abstract classes for this strategies are EdgeDrawingStrategy and NodeDrawingStrategy. The implementations are GraphEdgeStrategy and GraphNodeStrategy for drawing the graph elements and AlgoEdgeStrategy, AlgoNodeStrategy and AlgoFinishedNodeStrategy for drawing the different tree elements.

+

For the edit modes of InteractiveGraphView and the animation types for graph or tree elements, there also are two enumerations, called EditMode and AnimationType.

+

Finally, the class Repainter is used for the creation of timers, that repaint specified rectangles of different components after a short while. This is used for animations.

+ + \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/gui/package.html b/bin/org/jalgo/module/bfsdfs/gui/package.html new file mode 100644 index 0000000..f2f618e --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/gui/package.html @@ -0,0 +1,24 @@ + + + + +

+This package contains the GUIController which represents an interface between the GUI and the rest of +the program. It controls user actions and observes the graph and the algorithm. Furthermore there are a few +utility classes: +

    +
  • AddNodeAnimation and RemoveNodeAnimation are used in the NodeStackView to fade the +recently added / removed nodes in / out. They use a separate thread.
  • +
  • PlayAnimation is similar to the two above, but is used to play the algorithm.
  • +
  • GraphAnimations is used to calculate values that are needed to animate the GraphView
  • +
  • ComponentUtlility, GraphCalculation and GraphDrawing contain methods that are used +by classes from various gui packages.
  • +
  • GUIConstants contains all constant values, e.g. constant sizes and fonts.
  • +
  • StatusMouseAdapter is an extended MouseAdapter that is used to easily add a mouseover effect to +various components that updates the status bar of J-Algo
  • +
  • GUITest is used to test the classes. One can write values to the error log or popup a new window +etc.
  • +
+

+ + \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/res.properties b/bin/org/jalgo/module/bfsdfs/res.properties new file mode 100644 index 0000000..e29429b --- /dev/null +++ b/bin/org/jalgo/module/bfsdfs/res.properties @@ -0,0 +1,24 @@ +ui.Logo_small = /bfsdfs_pix/logo.png +HelpSet_Name = /help/jhelp/bfsdfs_help.hs + +WelcomeScreen.newButton = /bfsdfs_pix/ws_new.png +WelcomeScreen.newButton_over = /bfsdfs_pix/ws_new_over.png +WelcomeScreen.newButton_descr_de = /bfsdfs_pix/ws_new_descr_de.png +WelcomeScreen.newButton_descr_en = /bfsdfs_pix/ws_new_descr_en.png +WelcomeScreen.loadButton = /bfsdfs_pix/ws_load.png +WelcomeScreen.loadButton_over = /bfsdfs_pix/ws_load_over.png +WelcomeScreen.loadButton_descr_de = /bfsdfs_pix/ws_load_descr_de.png +WelcomeScreen.loadButton_descr_en = /bfsdfs_pix/ws_load_descr_en.png +WelcomeScreen.lastButton = /bfsdfs_pix/ws_last.png +WelcomeScreen.lastButton_over = /bfsdfs_pix/ws_last_over.png +WelcomeScreen.lastButton_descr_de = /bfsdfs_pix/ws_last_descr_de.png +WelcomeScreen.lastButton_descr_en = /bfsdfs_pix/ws_last_descr_en.png + +icon_doubleedges = /bfsdfs_pix/edit_double_edges.png +icon_edges = /bfsdfs_pix/edit_edges.png +icon_nodeEdit = /bfsdfs_pix/edit_nodes.png + +tab.designButton = /bfsdfs_pix/tab_design.png +tab.bfsButton = /bfsdfs_pix/tab_bfs.png +tab.dfsButton = /bfsdfs_pix/tab_dfs.png +tab.beamerButton = /bfsdfs_pix/beamermode_button.gif \ No newline at end of file diff --git a/bin/org/jalgo/module/bfsdfs/undo/Step.class b/bin/org/jalgo/module/bfsdfs/undo/Step.class new file mode 100644 index 0000000..162efda Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/undo/Step.class differ diff --git a/bin/org/jalgo/module/bfsdfs/undo/Undoable.class b/bin/org/jalgo/module/bfsdfs/undo/Undoable.class new file mode 100644 index 0000000..9f7ed52 Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/undo/Undoable.class differ diff --git a/bin/org/jalgo/module/bfsdfs/undo/UndoableObserver.class b/bin/org/jalgo/module/bfsdfs/undo/UndoableObserver.class new file mode 100644 index 0000000..a48948b Binary files /dev/null and b/bin/org/jalgo/module/bfsdfs/undo/UndoableObserver.class differ diff --git a/bin/org/jalgo/module/c0h0/.grammar/c00-lexer.l b/bin/org/jalgo/module/c0h0/.grammar/c00-lexer.l new file mode 100644 index 0000000..a85da30 --- /dev/null +++ b/bin/org/jalgo/module/c0h0/.grammar/c00-lexer.l @@ -0,0 +1,72 @@ +package org.jalgo.module.c0h0.parser; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.c0h0.parser.ParserConstants; +import org.jalgo.module.c0h0.parser.GeneratedC00Parser.Terminals; + +%% + +%class C0Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Identifier = x[1-9][0-9]* +Number = 0 | [1-9][0-9]* +Comment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +Whitespace = {LineTerminator} | [\t\f ] + +%% + +{Comment} { /* ignore */ } +{Whitespace}+ { /* ignore */ } +"#include" { return symbol(Terminals.INCLUDE, "#include"); } +"" { return symbol(Terminals.STDIO, ""); } +"int" { return symbol(Terminals.INT, "int"); } +"main" { return symbol(Terminals.MAIN, "main"); } +"(" { return symbol(Terminals.LPAREN, "("); } +")" { return symbol(Terminals.RPAREN, ")"); } +"{" { return symbol(Terminals.LBRACKET, "{"); } +"}" { return symbol(Terminals.RBRACKET, "}"); } +"=" { return symbol(Terminals.ASSIGN, "="); } +"," { return symbol(Terminals.COMMA, ","); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"&" { return symbol(Terminals.AMP, "&"); } +"if" { return symbol(Terminals.IF, "if"); } +"else" { return symbol(Terminals.ELSE, "else"); } +"while" { return symbol(Terminals.WHILE, "while"); } +"printf" { return symbol(Terminals.PRINTF, "printf"); } +"scanf" { return symbol(Terminals.SCANF, "scanf"); } +"\"%i\"" { return symbol(Terminals.IFORMAT, "\"%i\""); } +"\"%d\"" { return symbol(Terminals.DFORMAT, "\"%d\""); } +"return" {Whitespace}+ "0" { return symbol(Terminals.RETURN, "return 0"); } +"+" { return symbol(Terminals.PLUS, "+"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"/" { return symbol(Terminals.DIV, "/"); } +"*" { return symbol(Terminals.MULT, "*"); } +"%" { return symbol(Terminals.MOD, "%"); } +"==" { return symbol(Terminals.EQ, "=="); } +"!=" { return symbol(Terminals.NE, "!="); } +">=" { return symbol(Terminals.GE, ">="); } +"<=" { return symbol(Terminals.LE, "<="); } +">" { return symbol(Terminals.GT, ">"); } +"<" { return symbol(Terminals.LT, "<"); } +{Identifier} { return symbol(Terminals.IDENT, yytext()); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } diff --git a/bin/org/jalgo/module/c0h0/.grammar/c00-parser.g b/bin/org/jalgo/module/c0h0/.grammar/c00-parser.g new file mode 100644 index 0000000..4b13a63 --- /dev/null +++ b/bin/org/jalgo/module/c0h0/.grammar/c00-parser.g @@ -0,0 +1,175 @@ +%package "org.jalgo.module.c0h0.parser"; + +%import "org.jalgo.module.c0h0.models.ast.*"; +%import "org.jalgo.module.c0h0.models.ast.Number"; +%import "beaver.Symbol"; + +%class "GeneratedC00Parser"; + +%init {: + this.report = ErrorEvents.createReport(); +:}; + +%embed {: + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + private int convertToInt(String str) { + return Integer.parseInt(str); + } +:}; + +%terminals INCLUDE, STDIO; +%terminals IF, ELSE, WHILE, MAIN, PRINTF, SCANF, RETURN, INT; +%terminals IFORMAT, DFORMAT; +%terminals COMMA, SEMICOLON, AMP, ASSIGN; +%terminals PLUS, MINUS, MULT, DIV, MOD; +%terminals EQ, NE, GE, LE, GT, LT; +%terminals LBRACKET, RBRACKET, LPAREN, RPAREN; +%terminals NUMBER, IDENT; + +%typeof Program = "Program"; +%typeof Declaration = "Declaration"; +%typeof ScanfSequence = "ScanfSequence"; +%typeof PrintfStatement = "PrintfStatement"; +%typeof Block = "Block"; +%typeof Statement = "Statement"; +%typeof Term = "Term"; +%typeof Relation = "Relation"; +%typeof RelationType = "RelationType"; +%typeof Operation = "Operation"; +%typeof OperationType = "OperationType"; +%typeof IDENT = "String"; +%typeof NUMBER = "String"; + +// resolve shift-reduce conflict (dangling else) +%nonassoc ELSE; +%nonassoc IF; + +%goal Program; + +Program + = INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c Block.b PrintfStatement.p RETURN SEMICOLON RBRACKET + {: return new Symbol(new Program(d, c, b, p)); :} + | INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c PrintfStatement.p RETURN SEMICOLON RBRACKET + {: return new Symbol(new Program(d, c, null, p)); :} + ; + +Declaration + = INT IDENT.i + {: return new Symbol(new Declaration(new Var(i))); :} + | Declaration.d COMMA IDENT.i + {: d.addVariable(new Var(i)); return new Symbol(d); :} + ; + +ScanfSequence + = + {: return new Symbol(new ScanfSequence()); :} + | ScanfSequence.s SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON + {: s.addScanf(new Var(i)); return new Symbol(s); :} + ; + +PrintfStatement + = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON + {: return new Symbol(new PrintfStatement(new Var(i))); :} + ; + +Block + = LBRACKET RBRACKET + {: return new Symbol(new Block(true)); :} + | LBRACKET Block.b Statement.stat RBRACKET + {: b.addStatement(stat); return new Symbol(b); :} + | Statement.stat + {: return new Symbol(new Block(stat, true)); :} + | Block.b Statement.stat + {: b.addStatement(stat); return new Symbol(b); :} + ; + +Statement + = SEMICOLON + {: return new Symbol(new Statement()); :} + | IDENT.i ASSIGN Term.t SEMICOLON + {: return new Symbol(new Assignment(new Var(i), t)); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(true), new Block(false))); :} + | IF LPAREN Relation.r RPAREN Statement.s + {: return new Symbol(new If(r, new Block(s, false), new Block(false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + {: return new Symbol(new If(r, b)); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(true), new Block(true))); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE Statement.s2 + {: return new Symbol(new If(r, new Block(true), new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, new Block(true), s2)); :} + | IF LPAREN Relation.r RPAREN Statement.s ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(s, false), new Block(true))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, b, new Block(true))); :} + | IF LPAREN Relation.r RPAREN Statement.s1 ELSE Statement.s2 + {: return new Symbol(new If(r, new Block(s1, false), new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN Statement.s1 ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, new Block(s1, false), s2)); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE Statement.s2 + {: return new Symbol(new If(r, s1, new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, s1, s2)); :} + | WHILE LPAREN Relation.r RPAREN Statement.s + {: return new Symbol(new While(r, new Block(s, false))); :} + | WHILE LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + {: return new Symbol(new While(r, b)); :} + | WHILE LPAREN Relation.r RPAREN LBRACKET RBRACKET + {: return new Symbol(new While(r, new Block(true))); :} + ; + +Term + = IDENT.i + {: return new Symbol(new Var(i)); :} + | NUMBER.n + {: return new Symbol(new Number(convertToInt(n))); :} + | LPAREN Term.t RPAREN + {: return new Symbol(new Term(t)); :} + | PLUS IDENT.i + {: return new Symbol(new Var(i, UnaryType.PLUS)); :} + | PLUS NUMBER.n + {: return new Symbol(new Number(convertToInt(n), UnaryType.PLUS)); :} + | PLUS LPAREN Term.t RPAREN + {: return new Symbol(new Term(t, UnaryType.PLUS)); :} + | MINUS IDENT.i + {: return new Symbol(new Var(i, UnaryType.MINUS)); :} + | MINUS NUMBER.n + {: return new Symbol(new Number(convertToInt(n), UnaryType.MINUS)); :} + | MINUS LPAREN Term.t RPAREN + {: return new Symbol(new Term(t, UnaryType.MINUS)); :} + | Operation.o + {: return new Symbol(o); :} + | Relation.r + {: return new Symbol(r); :} + ; + +Relation + = Term.l RelationType.rel Term.r + {: return new Symbol(new Relation(l, rel, r)); :} + ; + +RelationType + = EQ {: return new Symbol(RelationType.EQ); :} + | NE {: return new Symbol(RelationType.NE); :} + | LE {: return new Symbol(RelationType.LE); :} + | GE {: return new Symbol(RelationType.GE); :} + | LT {: return new Symbol(RelationType.LT); :} + | GT {: return new Symbol(RelationType.GT); :} + ; + +Operation + = Term.l OperationType.op Term.r + {: return new Symbol(new Operation(l, op, r)); :} + ; + +OperationType + = PLUS {: return new Symbol(OperationType.ADD); :} + | MINUS {: return new Symbol(OperationType.SUB); :} + | MULT {: return new Symbol(OperationType.MUL); :} + | DIV {: return new Symbol(OperationType.DIV); :} + | MOD {: return new Symbol(OperationType.MOD); :} + ; \ No newline at end of file diff --git a/bin/org/jalgo/module/c0h0/ModuleConnector.class b/bin/org/jalgo/module/c0h0/ModuleConnector.class new file mode 100644 index 0000000..0cf35db Binary files /dev/null and b/bin/org/jalgo/module/c0h0/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/c0h0/ModuleInfo.class b/bin/org/jalgo/module/c0h0/ModuleInfo.class new file mode 100644 index 0000000..0d048bd Binary files /dev/null and b/bin/org/jalgo/module/c0h0/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/ButtonCommand.class b/bin/org/jalgo/module/c0h0/controller/ButtonCommand.class new file mode 100644 index 0000000..8127281 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/ButtonCommand.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/Controller.class b/bin/org/jalgo/module/c0h0/controller/Controller.class new file mode 100644 index 0000000..c9c0604 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/Controller.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/FileManager$1.class b/bin/org/jalgo/module/c0h0/controller/FileManager$1.class new file mode 100644 index 0000000..d00dcd7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/FileManager$1.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/FileManager$2.class b/bin/org/jalgo/module/c0h0/controller/FileManager$2.class new file mode 100644 index 0000000..7a41a14 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/FileManager$2.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/FileManager$3.class b/bin/org/jalgo/module/c0h0/controller/FileManager$3.class new file mode 100644 index 0000000..acc3562 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/FileManager$3.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/FileManager.class b/bin/org/jalgo/module/c0h0/controller/FileManager.class new file mode 100644 index 0000000..03ec9e3 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/FileManager.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/InterfaceConstants.class b/bin/org/jalgo/module/c0h0/controller/InterfaceConstants.class new file mode 100644 index 0000000..d012b51 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/InterfaceConstants.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/State.class b/bin/org/jalgo/module/c0h0/controller/State.class new file mode 100644 index 0000000..157f5d2 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/State.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/ViewManager.class b/bin/org/jalgo/module/c0h0/controller/ViewManager.class new file mode 100644 index 0000000..18f5383 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/ViewManager.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/ViewState.class b/bin/org/jalgo/module/c0h0/controller/ViewState.class new file mode 100644 index 0000000..0d34242 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/ViewState.class differ diff --git a/bin/org/jalgo/module/c0h0/controller/package-info.class b/bin/org/jalgo/module/c0h0/controller/package-info.class new file mode 100644 index 0000000..c981fbb Binary files /dev/null and b/bin/org/jalgo/module/c0h0/controller/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/gui/ButtonManager.class b/bin/org/jalgo/module/c0h0/gui/ButtonManager.class new file mode 100644 index 0000000..029b8fb Binary files /dev/null and b/bin/org/jalgo/module/c0h0/gui/ButtonManager.class differ diff --git a/bin/org/jalgo/module/c0h0/gui/ModuleContainer.class b/bin/org/jalgo/module/c0h0/gui/ModuleContainer.class new file mode 100644 index 0000000..ce66d51 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/gui/ModuleContainer.class differ diff --git a/bin/org/jalgo/module/c0h0/gui/package-info.class b/bin/org/jalgo/module/c0h0/gui/package-info.class new file mode 100644 index 0000000..522b084 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/gui/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/Generator.class b/bin/org/jalgo/module/c0h0/models/Generator.class new file mode 100644 index 0000000..193e351 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/Generator.class differ diff --git a/bin/org/jalgo/module/c0h0/models/Performer.class b/bin/org/jalgo/module/c0h0/models/Performer.class new file mode 100644 index 0000000..b3096d6 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/Performer.class differ diff --git a/bin/org/jalgo/module/c0h0/models/Visitable.class b/bin/org/jalgo/module/c0h0/models/Visitable.class new file mode 100644 index 0000000..9a2492c Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/Visitable.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/ASTModel.class b/bin/org/jalgo/module/c0h0/models/ast/ASTModel.class new file mode 100644 index 0000000..73ead11 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/ASTModel.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/ASTVisitor.class b/bin/org/jalgo/module/c0h0/models/ast/ASTVisitor.class new file mode 100644 index 0000000..6eb31ec Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/ASTVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Assignment.class b/bin/org/jalgo/module/c0h0/models/ast/Assignment.class new file mode 100644 index 0000000..d04fb14 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Assignment.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Block.class b/bin/org/jalgo/module/c0h0/models/ast/Block.class new file mode 100644 index 0000000..67c2809 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Block.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Declaration.class b/bin/org/jalgo/module/c0h0/models/ast/Declaration.class new file mode 100644 index 0000000..cf3e1fc Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Declaration.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/ErrorInformation.class b/bin/org/jalgo/module/c0h0/models/ast/ErrorInformation.class new file mode 100644 index 0000000..2367aac Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/ErrorInformation.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/If.class b/bin/org/jalgo/module/c0h0/models/ast/If.class new file mode 100644 index 0000000..a85dc5f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/If.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Number.class b/bin/org/jalgo/module/c0h0/models/ast/Number.class new file mode 100644 index 0000000..0e1c9d5 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Number.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Operation.class b/bin/org/jalgo/module/c0h0/models/ast/Operation.class new file mode 100644 index 0000000..1cc102d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Operation.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/OperationType.class b/bin/org/jalgo/module/c0h0/models/ast/OperationType.class new file mode 100644 index 0000000..8d2010a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/OperationType.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/PrintfStatement.class b/bin/org/jalgo/module/c0h0/models/ast/PrintfStatement.class new file mode 100644 index 0000000..14151cd Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/PrintfStatement.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Program.class b/bin/org/jalgo/module/c0h0/models/ast/Program.class new file mode 100644 index 0000000..d8fbdb4 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Program.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Relation.class b/bin/org/jalgo/module/c0h0/models/ast/Relation.class new file mode 100644 index 0000000..b986fe7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Relation.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/RelationType.class b/bin/org/jalgo/module/c0h0/models/ast/RelationType.class new file mode 100644 index 0000000..324ec50 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/RelationType.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/ScanfSequence.class b/bin/org/jalgo/module/c0h0/models/ast/ScanfSequence.class new file mode 100644 index 0000000..01f1162 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/ScanfSequence.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Statement.class b/bin/org/jalgo/module/c0h0/models/ast/Statement.class new file mode 100644 index 0000000..17e9fe9 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Statement.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Symbol.class b/bin/org/jalgo/module/c0h0/models/ast/Symbol.class new file mode 100644 index 0000000..186dc9e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Symbol.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Term.class b/bin/org/jalgo/module/c0h0/models/ast/Term.class new file mode 100644 index 0000000..f3108be Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Term.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/UnaryType.class b/bin/org/jalgo/module/c0h0/models/ast/UnaryType.class new file mode 100644 index 0000000..5ceb515 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/UnaryType.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/Var.class b/bin/org/jalgo/module/c0h0/models/ast/Var.class new file mode 100644 index 0000000..8b000ce Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/Var.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/While.class b/bin/org/jalgo/module/c0h0/models/ast/While.class new file mode 100644 index 0000000..cfecd4d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/While.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/package-info.class b/bin/org/jalgo/module/c0h0/models/ast/package-info.class new file mode 100644 index 0000000..0fc8665 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.class b/bin/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.class new file mode 100644 index 0000000..3d00435 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.class b/bin/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.class new file mode 100644 index 0000000..359da7f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/tools/Iterable.class b/bin/org/jalgo/module/c0h0/models/ast/tools/Iterable.class new file mode 100644 index 0000000..9299bf0 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/tools/Iterable.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/tools/Iterator.class b/bin/org/jalgo/module/c0h0/models/ast/tools/Iterator.class new file mode 100644 index 0000000..8c8caf9 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/tools/Iterator.class differ diff --git a/bin/org/jalgo/module/c0h0/models/ast/tools/package-info.class b/bin/org/jalgo/module/c0h0/models/ast/tools/package-info.class new file mode 100644 index 0000000..0106d8c Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/ast/tools/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor$AddrStack.class b/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor$AddrStack.class new file mode 100644 index 0000000..c6c28ff Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor$AddrStack.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor.class b/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor.class new file mode 100644 index 0000000..3b3481d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/AddressVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/C0CodeModel.class b/bin/org/jalgo/module/c0h0/models/c0model/C0CodeModel.class new file mode 100644 index 0000000..0229269 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/C0CodeModel.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.class b/bin/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.class new file mode 100644 index 0000000..e259845 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.class b/bin/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.class new file mode 100644 index 0000000..ef40ed7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/c0model/package-info.class b/bin/org/jalgo/module/c0h0/models/c0model/package-info.class new file mode 100644 index 0000000..637f4ef Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/c0model/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/Bundle.class b/bin/org/jalgo/module/c0h0/models/flowchart/Bundle.class new file mode 100644 index 0000000..fe17234 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/Bundle.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/Edge.class b/bin/org/jalgo/module/c0h0/models/flowchart/Edge.class new file mode 100644 index 0000000..db893fb Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/Edge.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/Element.class b/bin/org/jalgo/module/c0h0/models/flowchart/Element.class new file mode 100644 index 0000000..05609cc Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/Element.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor$level.class b/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor$level.class new file mode 100644 index 0000000..e8fc408 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor$level.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.class b/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.class new file mode 100644 index 0000000..5c0b7a4 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.class b/bin/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.class new file mode 100644 index 0000000..aa66c02 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/LevelType.class b/bin/org/jalgo/module/c0h0/models/flowchart/LevelType.class new file mode 100644 index 0000000..4c7d487 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/LevelType.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/Vertex.class b/bin/org/jalgo/module/c0h0/models/flowchart/Vertex.class new file mode 100644 index 0000000..bb02117 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/Vertex.class differ diff --git a/bin/org/jalgo/module/c0h0/models/flowchart/package-info.class b/bin/org/jalgo/module/c0h0/models/flowchart/package-info.class new file mode 100644 index 0000000..2990014 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/flowchart/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/h0model/H0CodeModel.class b/bin/org/jalgo/module/c0h0/models/h0model/H0CodeModel.class new file mode 100644 index 0000000..1aa51aa Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/h0model/H0CodeModel.class differ diff --git a/bin/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.class b/bin/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.class new file mode 100644 index 0000000..7fc4548 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/h0model/package-info.class b/bin/org/jalgo/module/c0h0/models/h0model/package-info.class new file mode 100644 index 0000000..7f0baca Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/h0model/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/package-info.class b/bin/org/jalgo/module/c0h0/models/package-info.class new file mode 100644 index 0000000..9768a9b Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.class b/bin/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.class new file mode 100644 index 0000000..7f29b76 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.class differ diff --git a/bin/org/jalgo/module/c0h0/models/tmodel/TRuleModel.class b/bin/org/jalgo/module/c0h0/models/tmodel/TRuleModel.class new file mode 100644 index 0000000..b65dc2b Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/tmodel/TRuleModel.class differ diff --git a/bin/org/jalgo/module/c0h0/models/tmodel/package-info.class b/bin/org/jalgo/module/c0h0/models/tmodel/package-info.class new file mode 100644 index 0000000..8c0cfa4 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/models/tmodel/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/package-info.class b/bin/org/jalgo/module/c0h0/package-info.class new file mode 100644 index 0000000..b435d8a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/C00Parser.class b/bin/org/jalgo/module/c0h0/parser/C00Parser.class new file mode 100644 index 0000000..72fb37f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/C00Parser.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/C0Scanner.class b/bin/org/jalgo/module/c0h0/parser/C0Scanner.class new file mode 100644 index 0000000..3c5b3fc Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/C0Scanner.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/ErrorEvents$C0ErrorEvents.class b/bin/org/jalgo/module/c0h0/parser/ErrorEvents$C0ErrorEvents.class new file mode 100644 index 0000000..66666ab Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/ErrorEvents$C0ErrorEvents.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/ErrorEvents.class b/bin/org/jalgo/module/c0h0/parser/ErrorEvents.class new file mode 100644 index 0000000..6edfd29 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/ErrorEvents.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$1.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$1.class new file mode 100644 index 0000000..a965d05 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$1.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$10.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$10.class new file mode 100644 index 0000000..415b4f5 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$10.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$11.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$11.class new file mode 100644 index 0000000..bfaba69 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$11.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$12.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$12.class new file mode 100644 index 0000000..80527a2 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$12.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$13.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$13.class new file mode 100644 index 0000000..f244da5 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$13.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$14.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$14.class new file mode 100644 index 0000000..f771a50 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$14.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$15.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$15.class new file mode 100644 index 0000000..e7dd828 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$15.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$16.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$16.class new file mode 100644 index 0000000..9e02a01 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$16.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$17.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$17.class new file mode 100644 index 0000000..3300cc0 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$17.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$18.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$18.class new file mode 100644 index 0000000..4d43cb0 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$18.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$19.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$19.class new file mode 100644 index 0000000..02a15c9 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$19.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$2.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$2.class new file mode 100644 index 0000000..0e9d8a2 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$2.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$20.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$20.class new file mode 100644 index 0000000..037116f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$20.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$21.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$21.class new file mode 100644 index 0000000..d1769fc Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$21.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$22.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$22.class new file mode 100644 index 0000000..53794d6 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$22.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$23.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$23.class new file mode 100644 index 0000000..b192f6e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$23.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$24.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$24.class new file mode 100644 index 0000000..890064a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$24.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$25.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$25.class new file mode 100644 index 0000000..1d10796 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$25.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$26.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$26.class new file mode 100644 index 0000000..0b6fb39 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$26.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$27.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$27.class new file mode 100644 index 0000000..8c03d74 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$27.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$28.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$28.class new file mode 100644 index 0000000..13cf05d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$28.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$29.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$29.class new file mode 100644 index 0000000..3f23cf9 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$29.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$3.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$3.class new file mode 100644 index 0000000..5f27cae Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$3.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$30.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$30.class new file mode 100644 index 0000000..24c4595 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$30.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$31.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$31.class new file mode 100644 index 0000000..ee417ef Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$31.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$32.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$32.class new file mode 100644 index 0000000..4ce740f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$32.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$33.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$33.class new file mode 100644 index 0000000..df34e2c Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$33.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$34.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$34.class new file mode 100644 index 0000000..aa00af8 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$34.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$35.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$35.class new file mode 100644 index 0000000..64bd294 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$35.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$36.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$36.class new file mode 100644 index 0000000..61646c6 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$36.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$37.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$37.class new file mode 100644 index 0000000..b89c242 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$37.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$38.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$38.class new file mode 100644 index 0000000..76a5ea4 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$38.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$39.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$39.class new file mode 100644 index 0000000..f39f243 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$39.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$4.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$4.class new file mode 100644 index 0000000..9269127 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$4.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$40.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$40.class new file mode 100644 index 0000000..e53bf7c Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$40.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$41.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$41.class new file mode 100644 index 0000000..9e6c690 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$41.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$42.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$42.class new file mode 100644 index 0000000..a259230 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$42.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$43.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$43.class new file mode 100644 index 0000000..378912e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$43.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$44.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$44.class new file mode 100644 index 0000000..cc60ef7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$44.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$45.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$45.class new file mode 100644 index 0000000..e84ef83 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$45.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$46.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$46.class new file mode 100644 index 0000000..1f80ed0 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$46.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$47.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$47.class new file mode 100644 index 0000000..771564e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$47.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$48.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$48.class new file mode 100644 index 0000000..8a1ae1e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$48.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$49.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$49.class new file mode 100644 index 0000000..88ddaa7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$49.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$5.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$5.class new file mode 100644 index 0000000..b8c4450 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$5.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$50.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$50.class new file mode 100644 index 0000000..9edfa0f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$50.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$51.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$51.class new file mode 100644 index 0000000..b9a2ccb Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$51.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$52.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$52.class new file mode 100644 index 0000000..62ed494 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$52.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$6.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$6.class new file mode 100644 index 0000000..a29c666 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$6.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$7.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$7.class new file mode 100644 index 0000000..0484932 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$7.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$8.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$8.class new file mode 100644 index 0000000..1660ce8 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$8.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$9.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$9.class new file mode 100644 index 0000000..bd8ef7e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$9.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$Terminals.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$Terminals.class new file mode 100644 index 0000000..a06a084 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser$Terminals.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser.class b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser.class new file mode 100644 index 0000000..1afc311 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/GeneratedC00Parser.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/ParserConstants.class b/bin/org/jalgo/module/c0h0/parser/ParserConstants.class new file mode 100644 index 0000000..1d570ce Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/ParserConstants.class differ diff --git a/bin/org/jalgo/module/c0h0/parser/package-info.class b/bin/org/jalgo/module/c0h0/parser/package-info.class new file mode 100644 index 0000000..43920a2 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/parser/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/res.properties b/bin/org/jalgo/module/c0h0/res.properties new file mode 100644 index 0000000..302fe7e --- /dev/null +++ b/bin/org/jalgo/module/c0h0/res.properties @@ -0,0 +1,14 @@ +HelpSet_Name=/help/jhelp/c0h0_help.hs + +logo=/c0h0_pix/logo16.png + +viewC0FlowIcon=/c0h0_pix/viewstateC0Flow.png +viewC0H0Icon=/c0h0_pix/viewstateC0H0.png +viewFlowH0Icon=/c0h0_pix/viewstateFlowH0.png + +transViewOnIcon=/c0h0_pix/transviewOn16.png +transViewOffIcon=/c0h0_pix/transviewOff16.png + +newButtonIcon=/c0h0_pix/newButtonIcon.png +loadButtonIcon=/c0h0_pix/loadButtonIcon.png +exampleButtonIcon=/c0h0_pix/exampleButtonIcon.png diff --git a/bin/org/jalgo/module/c0h0/tests/AddressVisitorTest.class b/bin/org/jalgo/module/c0h0/tests/AddressVisitorTest.class new file mode 100644 index 0000000..09c0a44 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/AddressVisitorTest.class differ diff --git a/bin/org/jalgo/module/c0h0/tests/C00ParserTest.class b/bin/org/jalgo/module/c0h0/tests/C00ParserTest.class new file mode 100644 index 0000000..b36c887 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/C00ParserTest.class differ diff --git a/bin/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.class b/bin/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.class new file mode 100644 index 0000000..830906a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.class differ diff --git a/bin/org/jalgo/module/c0h0/tests/FcVisitorTest.class b/bin/org/jalgo/module/c0h0/tests/FcVisitorTest.class new file mode 100644 index 0000000..7762f74 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/FcVisitorTest.class differ diff --git a/bin/org/jalgo/module/c0h0/tests/H0GeneratingTest.class b/bin/org/jalgo/module/c0h0/tests/H0GeneratingTest.class new file mode 100644 index 0000000..4075246 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/H0GeneratingTest.class differ diff --git a/bin/org/jalgo/module/c0h0/tests/package-info.class b/bin/org/jalgo/module/c0h0/tests/package-info.class new file mode 100644 index 0000000..2f57217 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/tests/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/views/C0View$1.class b/bin/org/jalgo/module/c0h0/views/C0View$1.class new file mode 100644 index 0000000..bb752c6 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/C0View$1.class differ diff --git a/bin/org/jalgo/module/c0h0/views/C0View$2.class b/bin/org/jalgo/module/c0h0/views/C0View$2.class new file mode 100644 index 0000000..d645caf Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/C0View$2.class differ diff --git a/bin/org/jalgo/module/c0h0/views/C0View.class b/bin/org/jalgo/module/c0h0/views/C0View.class new file mode 100644 index 0000000..9e3f90d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/C0View.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameClose.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameClose.class new file mode 100644 index 0000000..4510936 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameClose.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameKey.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameKey.class new file mode 100644 index 0000000..37e22aa Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$FrameKey.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$Obstacle.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Obstacle.class new file mode 100644 index 0000000..037f2a8 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Obstacle.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$Player.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Player.class new file mode 100644 index 0000000..557c154 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Player.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$Tail.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Tail.class new file mode 100644 index 0000000..2b9b1e1 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Tail.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg$Thing.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Thing.class new file mode 100644 index 0000000..3505016 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg$Thing.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter$Egg.class b/bin/org/jalgo/module/c0h0/views/Easter$Egg.class new file mode 100644 index 0000000..434955f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter$Egg.class differ diff --git a/bin/org/jalgo/module/c0h0/views/Easter.class b/bin/org/jalgo/module/c0h0/views/Easter.class new file mode 100644 index 0000000..5c8fe66 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/Easter.class differ diff --git a/bin/org/jalgo/module/c0h0/views/EditView.class b/bin/org/jalgo/module/c0h0/views/EditView.class new file mode 100644 index 0000000..67ffa18 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/EditView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/FlowChartView$1.class b/bin/org/jalgo/module/c0h0/views/FlowChartView$1.class new file mode 100644 index 0000000..1e7685a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/FlowChartView$1.class differ diff --git a/bin/org/jalgo/module/c0h0/views/FlowChartView$EventHandler.class b/bin/org/jalgo/module/c0h0/views/FlowChartView$EventHandler.class new file mode 100644 index 0000000..e044359 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/FlowChartView$EventHandler.class differ diff --git a/bin/org/jalgo/module/c0h0/views/FlowChartView.class b/bin/org/jalgo/module/c0h0/views/FlowChartView.class new file mode 100644 index 0000000..8743654 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/FlowChartView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/H0View$1.class b/bin/org/jalgo/module/c0h0/views/H0View$1.class new file mode 100644 index 0000000..fe10b5f Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/H0View$1.class differ diff --git a/bin/org/jalgo/module/c0h0/views/H0View$2.class b/bin/org/jalgo/module/c0h0/views/H0View$2.class new file mode 100644 index 0000000..f2d7f43 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/H0View$2.class differ diff --git a/bin/org/jalgo/module/c0h0/views/H0View.class b/bin/org/jalgo/module/c0h0/views/H0View.class new file mode 100644 index 0000000..a81f399 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/H0View.class differ diff --git a/bin/org/jalgo/module/c0h0/views/HelpView$1.class b/bin/org/jalgo/module/c0h0/views/HelpView$1.class new file mode 100644 index 0000000..74a86fb Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/HelpView$1.class differ diff --git a/bin/org/jalgo/module/c0h0/views/HelpView$2.class b/bin/org/jalgo/module/c0h0/views/HelpView$2.class new file mode 100644 index 0000000..c653534 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/HelpView$2.class differ diff --git a/bin/org/jalgo/module/c0h0/views/HelpView$3.class b/bin/org/jalgo/module/c0h0/views/HelpView$3.class new file mode 100644 index 0000000..6f43af9 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/HelpView$3.class differ diff --git a/bin/org/jalgo/module/c0h0/views/HelpView.class b/bin/org/jalgo/module/c0h0/views/HelpView.class new file mode 100644 index 0000000..1f2a654 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/HelpView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/LogView.class b/bin/org/jalgo/module/c0h0/views/LogView.class new file mode 100644 index 0000000..5592995 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/LogView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/TerminalView.class b/bin/org/jalgo/module/c0h0/views/TerminalView.class new file mode 100644 index 0000000..56a3771 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/TerminalView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/TextEditor.class b/bin/org/jalgo/module/c0h0/views/TextEditor.class new file mode 100644 index 0000000..95ad09c Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/TextEditor.class differ diff --git a/bin/org/jalgo/module/c0h0/views/TransView.class b/bin/org/jalgo/module/c0h0/views/TransView.class new file mode 100644 index 0000000..c36f7a7 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/TransView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/View.class b/bin/org/jalgo/module/c0h0/views/View.class new file mode 100644 index 0000000..6424b3a Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/View.class differ diff --git a/bin/org/jalgo/module/c0h0/views/WelcomeView.class b/bin/org/jalgo/module/c0h0/views/WelcomeView.class new file mode 100644 index 0000000..5944d5d Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/WelcomeView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/WelcomeViewButton.class b/bin/org/jalgo/module/c0h0/views/WelcomeViewButton.class new file mode 100644 index 0000000..2d84c66 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/WelcomeViewButton.class differ diff --git a/bin/org/jalgo/module/c0h0/views/package-info.class b/bin/org/jalgo/module/c0h0/views/package-info.class new file mode 100644 index 0000000..8a14a2e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/package-info.class differ diff --git a/bin/org/jalgo/module/c0h0/views/teamView.class b/bin/org/jalgo/module/c0h0/views/teamView.class new file mode 100644 index 0000000..9c4084e Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/teamView.class differ diff --git a/bin/org/jalgo/module/c0h0/views/teamViewListener.class b/bin/org/jalgo/module/c0h0/views/teamViewListener.class new file mode 100644 index 0000000..1977400 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/teamViewListener.class differ diff --git a/bin/org/jalgo/module/c0h0/views/teamViewUpdateEvent.class b/bin/org/jalgo/module/c0h0/views/teamViewUpdateEvent.class new file mode 100644 index 0000000..227e034 Binary files /dev/null and b/bin/org/jalgo/module/c0h0/views/teamViewUpdateEvent.class differ diff --git a/bin/org/jalgo/module/dijkstra/ModuleConnector.class b/bin/org/jalgo/module/dijkstra/ModuleConnector.class new file mode 100644 index 0000000..37f49a7 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/dijkstra/ModuleInfo.class b/bin/org/jalgo/module/dijkstra/ModuleInfo.class new file mode 100644 index 0000000..f21d010 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/Action.class b/bin/org/jalgo/module/dijkstra/actions/Action.class new file mode 100644 index 0000000..31006dd Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/Action.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ActionException.class b/bin/org/jalgo/module/dijkstra/actions/ActionException.class new file mode 100644 index 0000000..4422a83 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ActionException.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ActionStack$Node.class b/bin/org/jalgo/module/dijkstra/actions/ActionStack$Node.class new file mode 100644 index 0000000..3dd6693 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ActionStack$Node.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ActionStack.class b/bin/org/jalgo/module/dijkstra/actions/ActionStack.class new file mode 100644 index 0000000..f5b7de1 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ActionStack.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.class b/bin/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.class new file mode 100644 index 0000000..312f5bd Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.class b/bin/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.class new file mode 100644 index 0000000..230bb3e Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.class b/bin/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.class new file mode 100644 index 0000000..e3d5b78 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.class b/bin/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.class new file mode 100644 index 0000000..d4858a6 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/DeleteNodeAction.class b/bin/org/jalgo/module/dijkstra/actions/DeleteNodeAction.class new file mode 100644 index 0000000..eb0506f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/DeleteNodeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.class b/bin/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.class new file mode 100644 index 0000000..203f28c Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.class b/bin/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.class new file mode 100644 index 0000000..680f9f1 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/GotoStepAction.class b/bin/org/jalgo/module/dijkstra/actions/GotoStepAction.class new file mode 100644 index 0000000..a437f33 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/GotoStepAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/GraphAction.class b/bin/org/jalgo/module/dijkstra/actions/GraphAction.class new file mode 100644 index 0000000..a4a7fe7 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/GraphAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/MoveNodeAction.class b/bin/org/jalgo/module/dijkstra/actions/MoveNodeAction.class new file mode 100644 index 0000000..9dca82c Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/MoveNodeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/NewEdgeAction.class b/bin/org/jalgo/module/dijkstra/actions/NewEdgeAction.class new file mode 100644 index 0000000..d3d91f0 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/NewEdgeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/NewNodeAction.class b/bin/org/jalgo/module/dijkstra/actions/NewNodeAction.class new file mode 100644 index 0000000..4603909 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/NewNodeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/RedoAction.class b/bin/org/jalgo/module/dijkstra/actions/RedoAction.class new file mode 100644 index 0000000..11dc468 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/RedoAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/RescaleGraphAction.class b/bin/org/jalgo/module/dijkstra/actions/RescaleGraphAction.class new file mode 100644 index 0000000..59edd0b Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/RescaleGraphAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/SetEditingModeAction.class b/bin/org/jalgo/module/dijkstra/actions/SetEditingModeAction.class new file mode 100644 index 0000000..46cfd10 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/SetEditingModeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/SetStartNodeAction.class b/bin/org/jalgo/module/dijkstra/actions/SetStartNodeAction.class new file mode 100644 index 0000000..3e1c67b Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/SetStartNodeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.class b/bin/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.class new file mode 100644 index 0000000..c35fef3 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/ShowEditPageAction.class b/bin/org/jalgo/module/dijkstra/actions/ShowEditPageAction.class new file mode 100644 index 0000000..9d0ff2b Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/ShowEditPageAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/StartAnimationAction.class b/bin/org/jalgo/module/dijkstra/actions/StartAnimationAction.class new file mode 100644 index 0000000..d7b39fa Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/StartAnimationAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/StopAnimationAction.class b/bin/org/jalgo/module/dijkstra/actions/StopAnimationAction.class new file mode 100644 index 0000000..84df20e Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/StopAnimationAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/UndoAction.class b/bin/org/jalgo/module/dijkstra/actions/UndoAction.class new file mode 100644 index 0000000..52c98ce Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/UndoAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/actions/WeighEdgeAction.class b/bin/org/jalgo/module/dijkstra/actions/WeighEdgeAction.class new file mode 100644 index 0000000..ed0bc3f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/actions/WeighEdgeAction.class differ diff --git a/bin/org/jalgo/module/dijkstra/de.properties b/bin/org/jalgo/module/dijkstra/de.properties new file mode 100644 index 0000000..1878647 --- /dev/null +++ b/bin/org/jalgo/module/dijkstra/de.properties @@ -0,0 +1,86 @@ +Module_name=Dijkstra +Module_version=1.1 +Module_authors=Alexander Claus, Frank Staudinger, Julian Stecklina, Hannes Straß, Steven Voigt, Martin Winter +Module_description_1=Dieses Modul behandelt Dijkstra's Algorithmus zum Finden kürzester Wege in Graphen. +Module_description_2=Es können Graphen modelliert werden, der Algorithmus wird intuitiv visualisiert. +Module_license=GNU General Public License + +Undo=Rückgängig +Undo_tooltip=Macht die letzte Änderung rückgängig. +Redo=Wiederherstellen +Redo_tooltip=Stellt die letzte Änderung wieder her. + +EditModeToolPanel.Tools=Werkzeuge +EditModeToolPanel.Add_move_node=Knoten erstellen/verschieben +EditModeToolPanel.Add_move_node_tooltip=Erstellen und verschieben Sie Knoten auf der Zeichenfläche +EditModeToolPanel.Add_eval_edge=Kante hinzufügen/bewerten +EditModeToolPanel.Add_eval_edge_tooltip=Erstellen und bewerten Sie Kanten intuitiv. +EditModeToolPanel.Remove_node=Knoten löschen +EditModeToolPanel.Remove_node_tooltip=Löschen Sie ausgewählte Knoten durch Klick. +EditModeToolPanel.Remove_edge=Kante löschen +EditModeToolPanel.Remove_edge_tooltip=Löschen Sie ausgewählte Kanten durch Klick. + +AlgorithmModeToolPanel.Tools=Werkzeuge +AlgorithmModeToolPanel.Start_node=Startknoten: +AlgorithmModeToolPanel.Algorithm_step=Algorithmusschritt: +AlgorithmModeToolPanel.Start_animation=Animation starten +AlgorithmModeToolPanel.Of=von +AlgorithmModeToolPanel.Go_to=Gehe zu + +GraphPanel.Graph=Graph +GraphPanel.Arrange_nodes_automatically=Knoten automatisch anordnen +GraphPanel.Arrange_tooltip=Alle Knoten automatisch in einem regelmäßigen Vieleck anordnen. + +NodeListPanel.Node_list=Knotenliste + +EdgeListPanel.Edge_list=Kantenliste +EdgeListPanel.Apply=Anwenden + +MatrixPanel.Distance_matrix=Distanzmatrix +MatrixPanel.Tooltip=Eingabe von Kantengewichten. Kante löschen durch Eingabe von Minus (-). + +AlgorithmModeCalculationTablePanel.Calc_table=Rechentableau + +AlgorithmModeResultTablePanel.Result=Ergebnis + +StatusbarComposite.Start_algorithm=Algorithmus starten +StatusbarComposite.Start_algorithm_tooltip=Wechselt die Ansicht und startet den Algorithmus +StatusbarComposite.Edit_graph=Graph bearbeiten +StatusbarComposite.Edit_graph_tooltip=Wechselt die Ansicht zum Bearbeiten des Graphen +StatusbarComposite.Restart_algorithm=Algorithmus neu starten + +EdgeListParser.Syntax_error_1=Kantenliste: Syntaxfehler im Eingabestring: +EdgeListParser.Syntax_error_2=Syntaxfehler in der Kantenliste: ( +EdgeListParser.Syntax_error_3=). Erwartet: (Startknoten, Gewicht, Endknoten). +EdgeListParser.Syntax_hint_1=Kantenliste muss mit "{" beginnen\! +EdgeListParser.Syntax_hint_2=Kantenliste muss auf "}" enden\! +EdgeListParser.Syntax_hint_3=Kante muss mit "(" beginnen\! +EdgeListParser.Syntax_hint_4=Kante muss auf "(" enden\! +EdgeListParser.Syntax_hint_5=Kanten m\u00FCssen mit "," getrennt werden\! +EdgeListParser.Syntax_hint_6=Einzelne Elemente innerhalb der Kante m\u00FCssen mit "," getrennt werden\! +EdgeListParser.Syntax_error_4=Unerwartetes Ende des Eingabestrings\! Erwartet: Startknoten. +EdgeListParser.Syntax_error_5=Unerwartetes Ende des Eingabestrings\! Erwartet: Endknoten. +NodeListParser.Syntax_error_1=Knotenliste: Syntaxfehler im Eingabestring: " +NodeListParser.Syntax_hint_1=Knotenliste muss mit "{" beginnen\! +NodeListParser.Syntax_hint_2=Knotenliste muss auf "}" enden\! +NodeListParser.Syntax_error_2=Unerwartetes Ende des Eingabestrings\! Erwartet: Knoten. +NodeListParser.Syntax_error_3=Kein zul\u00E4ssiger Knoten: +NodeListParser.Syntax_hint_3=\! Nur Dezimalzahlen von 1 - 9 erlaubt. +NodeListParser.Syntax_hint_4=Knoten m\u00FCssen mit "," getrennt werden\! +DijkstraAlgorithm.Node=Knoten +DijkstraAlgorithm.Is_over=\ ist \u00FCber +DijkstraAlgorithm.Reachable_on_shorter_path=\ auf einem k\u00FCrzeren Wege erreichbar. +DijkstraAlgorithm.Reachable_over_existing_path_shorter=\ ist \u00FCber den bestehenden Weg k\u00FCrzer zu erreichen. +DijkstraAlgorithm.New_node=Neuer Knoten im Rand: +DijkstraAlgorithm.Error_1=Predecessor of border node is null +DijkstraAlgorithm.Error_2=Node equals predecessor +DijkstraAlgorithm.Choosed_as_start_node=\ als Startknoten gew\u00E4hlt. +DijkstraAlgorithm.Fringe_complete_for_start_node=Randknotenmenge f\u00FCr Startknoten komplett. +DijkstraAlgorithm.New_choosen=Neuer gew\u00E4hlter +DijkstraAlgorithm.Fringe_complete=Randknotenmenge komplett +DijkstraAlgorithm.Algorithm_finished=Algorithmus beendet +AlgorithmCalculationTableComposite.Chosen=Gew\u00E4hlt +AlgorithmResultTableComposite.Target_node=Zielknoten +AlgorithmResultTableComposite.Path_length=Wegl\u00E4nge +AlgorithmResultTableComposite.Shortest_path=k\u00FCrzester Weg +AlgorithmCalculationTableComposite.Fringe_node=Randknoten \ No newline at end of file diff --git a/bin/org/jalgo/module/dijkstra/en.properties b/bin/org/jalgo/module/dijkstra/en.properties new file mode 100644 index 0000000..01a69e1 --- /dev/null +++ b/bin/org/jalgo/module/dijkstra/en.properties @@ -0,0 +1,86 @@ +Module_name=Dijkstra +Module_version=1.1 +Module_authors=Alexander Claus, Frank Staudinger, Julian Stecklina, Hannes Straß, Steven Voigt, Martin Winter +Module_description_1=This module is about Dijkstra's algorithm for finding the shortest path in graphs. +Module_description_2=Graphs can be created, the algorithm will be visualized intuitively. +Module_license=GNU General Public License + +Undo=Undo +Undo_tooltip=Undoes the last change. +Redo=Redo +Redo_tooltip=Redoes the last change. + +EditModeToolPanel.Tools=Tools +EditModeToolPanel.Add_move_node=Add/Move node +EditModeToolPanel.Add_move_node_tooltip=Create and move nodes on canvas. +EditModeToolPanel.Add_eval_edge=Add/Evaluate edge +EditModeToolPanel.Add_eval_edge_tooltip=Create and evaluate edges intuitively. +EditModeToolPanel.Remove_node=Remove node +EditModeToolPanel.Remove_node_tooltip=Remove nodes per click. +EditModeToolPanel.Remove_edge=Remove edge +EditModeToolPanel.Remove_edge_tooltip=Remove edges per click. + +AlgorithmModeToolPanel.Tools=Tools +AlgorithmModeToolPanel.Start_node=Start node: +AlgorithmModeToolPanel.Algorithm_step=Algorithm step: +AlgorithmModeToolPanel.Start_animation=Start animation +AlgorithmModeToolPanel.Of=of +AlgorithmModeToolPanel.Go_to=Go to + +GraphPanel.Graph=Graph +GraphPanel.Arrange_nodes_automatically=Arrange nodes automatically +GraphPanel.Arrange_tooltip=Arranges all nodes in a regular polygon. + +NodeListPanel.Node_list=Nodelist + +EdgeListPanel.Edge_list=Edgelist +EdgeListPanel.Apply=Apply + +MatrixPanel.Distance_matrix=Distance matrix +MatrixPanel.Tooltip=Insert edge weights. Type '-' for removing edge. + +AlgorithmModeCalculationTablePanel.Calc_table=Calculation table + +AlgorithmModeResultTablePanel.Result=Result + +StatusbarComposite.Start_algorithm=Start algorithm +StatusbarComposite.Start_algorithm_tooltip=Switches the layout and starts the algorithm +StatusbarComposite.Edit_graph=Edit graph +StatusbarComposite.Edit_graph_tooltip=Switches the layout for editing the graph +StatusbarComposite.Restart_algorithm=Restart algorithm + +EdgeListParser.Syntax_error_1=Edgelist: syntax error in input string: +EdgeListParser.Syntax_error_2=syntax error in edgelist: ( +EdgeListParser.Syntax_error_3=). Expected: (start node, weight, end node). +EdgeListParser.Syntax_hint_1=Edgelist has to start with "{"\! +EdgeListParser.Syntax_hint_2=Edgelist has to end with "}"\! +EdgeListParser.Syntax_hint_3=Edge has to start with "("\! +EdgeListParser.Syntax_hint_4=Edge has to end with ")"\! +EdgeListParser.Syntax_hint_5=Separate edges with ","\! +EdgeListParser.Syntax_hint_6=Separate edge elements with ","\! +EdgeListParser.Syntax_error_4=Unexpected end of input string\! Expected: start node. +EdgeListParser.Syntax_error_5=Unexpected end of input string\! Expected: end node. +NodeListParser.Syntax_error_1=Nodelist: syntax error in input string: +NodeListParser.Syntax_hint_1=Nodelist has to start with "{"\! +NodeListParser.Syntax_hint_2=Nodelist has to end with "}"\! +NodeListParser.Syntax_error_2=Unexpected end of input string\! Expected: node. +NodeListParser.Syntax_error_3=No valid node: +NodeListParser.Syntax_hint_3=\! Only integers from 1 to 9 allowed. +NodeListParser.Syntax_hint_4=Separate nodes with ","\! +DijkstraAlgorithm.Node=Node +DijkstraAlgorithm.Is_over=\ is over +DijkstraAlgorithm.Reachable_on_shorter_path=\ reachable on shorter path. +DijkstraAlgorithm.Reachable_over_existing_path_shorter=\ is reachable shorter over existing path. +DijkstraAlgorithm.New_node=New node in fringe: +DijkstraAlgorithm.Error_1=Predecessor of border node is null +DijkstraAlgorithm.Error_2=Node equals predecessor +DijkstraAlgorithm.Choosed_as_start_node=\ choosed as start node. +DijkstraAlgorithm.Fringe_complete_for_start_node=Fringe complete for start node. +DijkstraAlgorithm.New_choosen=New chosen +DijkstraAlgorithm.Fringe_complete=Fringe complete +DijkstraAlgorithm.Algorithm_finished=Algorithm finished +AlgorithmCalculationTableComposite.Chosen=Chosen +AlgorithmResultTableComposite.Target_node=Target node +AlgorithmResultTableComposite.Path_length=Path length +AlgorithmResultTableComposite.Shortest_path=Shortest Path +AlgorithmCalculationTableComposite.Fringe_node=Fringe node \ No newline at end of file diff --git a/bin/org/jalgo/module/dijkstra/gfx/EdgeVisual.class b/bin/org/jalgo/module/dijkstra/gfx/EdgeVisual.class new file mode 100644 index 0000000..0090774 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gfx/EdgeVisual.class differ diff --git a/bin/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.class b/bin/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.class new file mode 100644 index 0000000..51492ac Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.class differ diff --git a/bin/org/jalgo/module/dijkstra/gfx/NewEdgeLine.class b/bin/org/jalgo/module/dijkstra/gfx/NewEdgeLine.class new file mode 100644 index 0000000..ea5324d Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gfx/NewEdgeLine.class differ diff --git a/bin/org/jalgo/module/dijkstra/gfx/NodeVisual.class b/bin/org/jalgo/module/dijkstra/gfx/NodeVisual.class new file mode 100644 index 0000000..e7f24bf Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gfx/NodeVisual.class differ diff --git a/bin/org/jalgo/module/dijkstra/gfx/Visual.class b/bin/org/jalgo/module/dijkstra/gfx/Visual.class new file mode 100644 index 0000000..8f9b941 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gfx/Visual.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/Controller$_AlgoAnimator.class b/bin/org/jalgo/module/dijkstra/gui/Controller$_AlgoAnimator.class new file mode 100644 index 0000000..89b3851 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/Controller$_AlgoAnimator.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/Controller$_Observable.class b/bin/org/jalgo/module/dijkstra/gui/Controller$_Observable.class new file mode 100644 index 0000000..7152232 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/Controller$_Observable.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/Controller.class b/bin/org/jalgo/module/dijkstra/gui/Controller.class new file mode 100644 index 0000000..2ed0679 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/Controller.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/GUIController$1.class b/bin/org/jalgo/module/dijkstra/gui/GUIController$1.class new file mode 100644 index 0000000..c895e88 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/GUIController$1.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/GUIController$2.class b/bin/org/jalgo/module/dijkstra/gui/GUIController$2.class new file mode 100644 index 0000000..4c5abf8 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/GUIController$2.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/GUIController$3.class b/bin/org/jalgo/module/dijkstra/gui/GUIController$3.class new file mode 100644 index 0000000..9219ca1 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/GUIController$3.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/GUIController.class b/bin/org/jalgo/module/dijkstra/gui/GUIController.class new file mode 100644 index 0000000..5770b27 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/GUIController.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.class b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.class new file mode 100644 index 0000000..a25a4f5 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.class new file mode 100644 index 0000000..f42522d Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.class b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.class new file mode 100644 index 0000000..3b98adc Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.class b/bin/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.class new file mode 100644 index 0000000..40ee03a Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$1.class b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$1.class new file mode 100644 index 0000000..528dc1d Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$1.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$2.class b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$2.class new file mode 100644 index 0000000..19e17cb Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel$2.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.class new file mode 100644 index 0000000..082565f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel$ButtonGroupManager.class b/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel$ButtonGroupManager.class new file mode 100644 index 0000000..b9cfbf1 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel$ButtonGroupManager.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.class new file mode 100644 index 0000000..f21dda3 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/GraphDisplay.class b/bin/org/jalgo/module/dijkstra/gui/components/GraphDisplay.class new file mode 100644 index 0000000..d0dc02d Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/GraphDisplay.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel$1.class b/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel$1.class new file mode 100644 index 0000000..4efa577 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel$1.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel.class new file mode 100644 index 0000000..bfb6be2 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/GraphPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/MatrixPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/MatrixPanel.class new file mode 100644 index 0000000..c0fd207 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/MatrixPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$1.class b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$1.class new file mode 100644 index 0000000..e22db29 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$1.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$2.class b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$2.class new file mode 100644 index 0000000..9817a08 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel$2.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel.class b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel.class new file mode 100644 index 0000000..9f50b9a Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/NodeListPanel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/components/ResultTableModel.class b/bin/org/jalgo/module/dijkstra/gui/components/ResultTableModel.class new file mode 100644 index 0000000..ac62bf6 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/components/ResultTableModel.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.class b/bin/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.class new file mode 100644 index 0000000..1967f41 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.class b/bin/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.class new file mode 100644 index 0000000..75e76fd Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.class b/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.class new file mode 100644 index 0000000..58137fc Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.class b/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.class new file mode 100644 index 0000000..64223d0 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.class b/bin/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.class new file mode 100644 index 0000000..f011e17 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.class b/bin/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.class new file mode 100644 index 0000000..4e92df9 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.class b/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.class new file mode 100644 index 0000000..e41b8b5 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.class b/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.class new file mode 100644 index 0000000..c033f27 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.class differ diff --git a/bin/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.class b/bin/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.class new file mode 100644 index 0000000..8776dd9 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/BorderState.class b/bin/org/jalgo/module/dijkstra/model/BorderState.class new file mode 100644 index 0000000..b58b6c9 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/BorderState.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$1.class b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$1.class new file mode 100644 index 0000000..f36248e Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$1.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$EdgeClosure.class b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$EdgeClosure.class new file mode 100644 index 0000000..5174e41 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$EdgeClosure.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$NodeClosure.class b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$NodeClosure.class new file mode 100644 index 0000000..282f667 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm$NodeClosure.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.class b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.class new file mode 100644 index 0000000..54c575f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/Edge.class b/bin/org/jalgo/module/dijkstra/model/Edge.class new file mode 100644 index 0000000..4ce5dca Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/Edge.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/Graph.class b/bin/org/jalgo/module/dijkstra/model/Graph.class new file mode 100644 index 0000000..64719e8 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/Graph.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/GraphElement.class b/bin/org/jalgo/module/dijkstra/model/GraphElement.class new file mode 100644 index 0000000..96cd643 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/GraphElement.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/Node.class b/bin/org/jalgo/module/dijkstra/model/Node.class new file mode 100644 index 0000000..fc9662b Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/Node.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/Position.class b/bin/org/jalgo/module/dijkstra/model/Position.class new file mode 100644 index 0000000..fd2a2e5 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/Position.class differ diff --git a/bin/org/jalgo/module/dijkstra/model/State.class b/bin/org/jalgo/module/dijkstra/model/State.class new file mode 100644 index 0000000..07b6c1f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/model/State.class differ diff --git a/bin/org/jalgo/module/dijkstra/res.properties b/bin/org/jalgo/module/dijkstra/res.properties new file mode 100644 index 0000000..0b0a464 --- /dev/null +++ b/bin/org/jalgo/module/dijkstra/res.properties @@ -0,0 +1 @@ +Module_logo=/dijkstra_pix/logo.gif HelpSet_Name=/help/jhelp/dijkstra_help.hs \ No newline at end of file diff --git a/bin/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.class b/bin/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.class new file mode 100644 index 0000000..849547f Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.class differ diff --git a/bin/org/jalgo/module/dijkstra/util/EdgeListParser.class b/bin/org/jalgo/module/dijkstra/util/EdgeListParser.class new file mode 100644 index 0000000..06b7252 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/util/EdgeListParser.class differ diff --git a/bin/org/jalgo/module/dijkstra/util/NodeListParser.class b/bin/org/jalgo/module/dijkstra/util/NodeListParser.class new file mode 100644 index 0000000..20bcd87 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/util/NodeListParser.class differ diff --git a/bin/org/jalgo/module/dijkstra/util/ParsingException.class b/bin/org/jalgo/module/dijkstra/util/ParsingException.class new file mode 100644 index 0000000..037dd57 Binary files /dev/null and b/bin/org/jalgo/module/dijkstra/util/ParsingException.class differ diff --git a/bin/org/jalgo/module/ebnf/MainController$Controller.class b/bin/org/jalgo/module/ebnf/MainController$Controller.class new file mode 100644 index 0000000..3eb18e0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/MainController$Controller.class differ diff --git a/bin/org/jalgo/module/ebnf/MainController.class b/bin/org/jalgo/module/ebnf/MainController.class new file mode 100644 index 0000000..f52ab0b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/MainController.class differ diff --git a/bin/org/jalgo/module/ebnf/ModuleConnector.class b/bin/org/jalgo/module/ebnf/ModuleConnector.class new file mode 100644 index 0000000..1a4524b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/ebnf/ModuleInfo.class b/bin/org/jalgo/module/ebnf/ModuleInfo.class new file mode 100644 index 0000000..54faa82 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.class new file mode 100644 index 0000000..63caa0d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.class new file mode 100644 index 0000000..33415c3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.class new file mode 100644 index 0000000..978bce8 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.class new file mode 100644 index 0000000..fa43f7a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.class new file mode 100644 index 0000000..c66d19f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.class new file mode 100644 index 0000000..026c004 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/EbnfController.class b/bin/org/jalgo/module/ebnf/controller/ebnf/EbnfController.class new file mode 100644 index 0000000..5acfd0c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/EbnfController.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.class new file mode 100644 index 0000000..50dab98 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.class new file mode 100644 index 0000000..365ea79 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.class new file mode 100644 index 0000000..1b0cac0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.class b/bin/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.class new file mode 100644 index 0000000..906f2dc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$JJCalls.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$JJCalls.class new file mode 100644 index 0000000..dfe0f1b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$JJCalls.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$LookaheadSuccess.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$LookaheadSuccess.class new file mode 100644 index 0000000..716a10e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser$LookaheadSuccess.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.class new file mode 100644 index 0000000..176ee06 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.class new file mode 100644 index 0000000..c8bbb2b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.class new file mode 100644 index 0000000..1a58e4b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.class new file mode 100644 index 0000000..529ea49 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.class new file mode 100644 index 0000000..c15068c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/Token.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/Token.class new file mode 100644 index 0000000..8ff6805 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/Token.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.class b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.class new file mode 100644 index 0000000..392a8c1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.class new file mode 100644 index 0000000..6f92364 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.class new file mode 100644 index 0000000..26ca9fb Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.class new file mode 100644 index 0000000..350b72b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.class new file mode 100644 index 0000000..2517349 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.class new file mode 100644 index 0000000..ebc8eb6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.class new file mode 100644 index 0000000..019b624 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.class new file mode 100644 index 0000000..d26a312 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.class new file mode 100644 index 0000000..7c5b21a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.class new file mode 100644 index 0000000..8df910e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.class new file mode 100644 index 0000000..5693f02 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.class new file mode 100644 index 0000000..e86662a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.class new file mode 100644 index 0000000..ce963d6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.class new file mode 100644 index 0000000..1426ed0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.class new file mode 100644 index 0000000..6280db5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.class new file mode 100644 index 0000000..43f041b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.class new file mode 100644 index 0000000..5390888 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.class new file mode 100644 index 0000000..cb4d912 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.class b/bin/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.class new file mode 100644 index 0000000..5eb9fcc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/syndia/SynDiaController.class b/bin/org/jalgo/module/ebnf/controller/syndia/SynDiaController.class new file mode 100644 index 0000000..d11b4fd Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/syndia/SynDiaController.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.class b/bin/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.class new file mode 100644 index 0000000..02b5cd5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/trans/TransController.class b/bin/org/jalgo/module/ebnf/controller/trans/TransController.class new file mode 100644 index 0000000..0742c7d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/trans/TransController.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/trans/TransStep.class b/bin/org/jalgo/module/ebnf/controller/trans/TransStep.class new file mode 100644 index 0000000..b256026 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/trans/TransStep.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.class new file mode 100644 index 0000000..186ef12 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.class new file mode 100644 index 0000000..04df308 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.class new file mode 100644 index 0000000..8c0029c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.class new file mode 100644 index 0000000..4ca3d60 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.class new file mode 100644 index 0000000..f330b59 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.class new file mode 100644 index 0000000..433f81b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.class new file mode 100644 index 0000000..f7d7c91 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.class new file mode 100644 index 0000000..6ec732e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.class new file mode 100644 index 0000000..b704d50 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.class new file mode 100644 index 0000000..636cc81 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.class new file mode 100644 index 0000000..9be00d4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.class new file mode 100644 index 0000000..a68214d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.class new file mode 100644 index 0000000..2690b43 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.class new file mode 100644 index 0000000..294f1c0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.class new file mode 100644 index 0000000..682983c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.class new file mode 100644 index 0000000..36f1ce0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.class differ diff --git a/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.class b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.class new file mode 100644 index 0000000..d43b53e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.class differ diff --git a/bin/org/jalgo/module/ebnf/de.properties b/bin/org/jalgo/module/ebnf/de.properties new file mode 100644 index 0000000..346442f --- /dev/null +++ b/bin/org/jalgo/module/ebnf/de.properties @@ -0,0 +1,224 @@ +Module_name=EBNF / Syntax-Diagramme +Module_version=1.0 +Module_authors=Tom Kazimier, Johannes Mey, Michael Thiele, Andr\u00E9 Viergutz, Claas Wilke +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt EBNF-Terme sowie Syntaxdiagramme. +Module_description_2=Es wird der trans()-Algorithmus unterst\u00FCtzt und es ist m\u00F6glich, W\u00F6rter interaktiv zu erzeugen. + +ModuleConnector.No_valid_EBNF_file=Keine g\u00FCltige EBNF- bzw. Syntax-Diagramm-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist m\u00F6glicherweise besch\u00E4digt. +GUIController.Wish_to_change_to_EBNF_mode=M\u00F6chten Sie jetzt in den EBNF - Modus wechseln? + +Show_start_screen=Startbildschirm anzeigen +Show_start_screen_tooltip=\u00D6ffnet den Startbildschirm +Wish_to_discard=M\u00F6chten Sie Ihre \u00C4nderungen verwerfen? +Wish_to_show_Startscreen=M\u00F6chten Sie den Startbildschirm wirklich anzeigen? + +SynDiaModel.NoNullElemException=Fehler beim Einf\u00FCgen in ein Syntaxdiagramm: Am angegebenen Index befindet sich kein NullElement +SynDiaModel.BeginEndException=begin - end < 0 oder (begin - end) % 2 != 0 +SynDiaModel.LeftAndRightPathException=Beim L\u00F6schen einer Verzweigung/Wiederholung ist es nicht m\u00F6glich, den oberen und unteren Pfad zu erhalten! +SynDiaModel.ElementNotFoundException=An dieser Stelle befindet sich kein zu entfernendes Element. +SynDiaModel.DeleteStartDiagramException=Das Startdiagramm darf nicht gel\u00F6scht werden! +SynDiaModel.EmptyNameExeption=Namen f\u00FCr Variablen/Terminalsymbole d\u00FCrfen nicht leer sein. + +Trans.UndoAll=Alle Schritte r\u00FCckg\u00E4ngig machen +Trans.Undo=Den letzten Schritt r\u00FCckg\u00E4ngig machen +Trans.Perform=Den n\u00E4chstm\u00F6glichen Schritt ausf\u00FChren +Trans.PerformAll=Den Algorithmus bis zum Ende ausf\u00FChren +Trans.ShowHelp=Hervorhebung des n\u00E4chsten Schrittes ein/ausschalten + +Trans.Finished=Der Algorithmus ist beendet +Trans.Beachte_top=Achtung: Der Eingang des Diagramms befindet sich auf +Trans.Beachte_bottom=der rechten Seite! +Trans.Sei=Sei +Trans.FirstAd=Fahre mit der Maus \u00FCber ein trans()-Element +Trans.SecondAd=Bei Klick darauf wird der angezeigte, bzw. n\u00E4chste Schritt ausgef\u00FChrt + +Border_Control=Kontrollbereich +Border_Draw=Anzeige der Diagramme +Border_Explanation=Hinweise zum Algorithmus + +SynDia.Control_FitToSize=Gr\u00F6\u00DFe automatisch anpassen an / ausschalten +SynDia.Control_Stairs=Treppenstrukturen ein-/ausblenden +SynDia.Control_ToEbnf=
EBNF-Definition
ansehen/bearbeiten
+SynDia.Control_ToSynDiaDisplay=
Zur Syntaxdiagramm-
anzeige wechseln
+SynDia.Control_ToSynDiaInput=
Zum Syntaxdiagramm-
editor wechseln
+SynDia.Control_ToWordAlgo=
Zum R\u00FCcksprung-
algorithmus wechseln
+SynDia.Control_Save=Hinweis +SynDia.Control_SaveText=Wollen Sie das Diagramm speichern, bevor Sie den Algorithmus ausf\u00FChren? + +Ebnf.Controller_DefinitionCheck_NoStartVar=FEHLER: Die Definition hat keine Startvariable
+Ebnf.Controller_DefinitionCheck_NoRuleForVar_1=FEHLER: Die Variable +Ebnf.Controller_DefinitionCheck_NoRuleForVar_2=hat keine zugeh\u00F6rige Regel
+Ebnf.Controller_DefinitionCheck_NoTermWithVar_1=WARNUNG: Die Variable +Ebnf.Controller_DefinitionCheck_NoTermWithVar_2=kommt in keinem Term einer Regel vor
+Ebnf.Controller_DefinitionCheck_NoTermWithTS_1=WARNUNG: Das Terminalsymbol +Ebnf.Controller_DefinitionCheck_NoTermWithTS_2=kommt in keinem Term einer Regel vor
+Ebnf.Controller_DefinitionCheck_RuleNotReachable_1=WARNUNG: Die Regel +Ebnf.Controller_DefinitionCheck_RuleNotReachable_2=kann nie erreicht werden
+Ebnf.Controller_DefinitionCheck_NotBinaryAlt=WARNUNG: Die Definition beinhaltet nicht bin\u00E4r geklammerte Alternative-Regeln
+Ebnf.Controller_MakeDefinitionStrictError=FEHLER: Die Definition konnte leider nicht bin\u00E4r geklammert werden! + +Ebnf.ChoicePanel_EbnfNotBinary=Die Definition ist noch nicht
bin\u00E4r geklammert! Dies ist

n\u00F6tig um trans() auszuf\u00FChren! +Ebnf.ChoicePanel_EbnfIsBinary=Die Definition ist bin\u00E4r geklammert.
Der trans()-Algorithmus

kann gestartet werden. +Ebnf.ChoicePanel_Border=Bitte W\u00E4hlen Sie... +Ebnf.ChoicePanel_transNotActiveButton=

trans()-Algorithmus
anwenden
+Ebnf.ChoicePanel_transActiveButton=
Zur\u00FCck zum
trans()-Algorithmus
+Ebnf.ChoicePanel_editButton=
Definition
\u00FCberarbeiten
+Ebnf.ChoicePanel_strictButton=
Definition
bin\u00E4r klammern
+Ebnf.ChoicePanel_strictButton2=
Bin\u00E4re Klammerung
wieder entfernen
+Ebnf.ChoicePanel_SaveStrictMode=M\u00F6chten Sie die bin\u00E4re Klammerung in Ihrer Definition speichern? +Ebnf.ChoicePanel_StrictMode=Bin\u00E4re Klammerung beibehalten + +Ebnf.PopupMenu_Edit=bearbeiten +Ebnf.PopupMenu_Rename=umbenennen +Ebnf.PopupMenu_Delete=l\u00F6schen +Ebnf.PopupMenu_SetAsStartRule=als Startregel setzen +Ebnf.PopupMenu_SetAsStartVar=als Startvariable setzen + +Ebnf.DefinitionCorrect=Die Definition is korrekt und vollst\u00E4ndig +Ebnf.CheckDefinition=\u00DCberpr\u00FCfung der Definition +Ebnf.Add=Hinzuf\u00FCgen +Ebnf.Edit=Bearbeiten +Ebnf.Undo=R\u00FCckg\u00E4ngig +Ebnf.33=Symbol: +Ebnf.Change=\u00C4ndern +Ebnf.Cancel=Abbrechen +Ebnf.Insert=Einf\u00FCgen +Ebnf.cancel=Abbrechen +Ebnf.Input_StartVar=Startvariable + +Ebnf.Input_Undo=Die letzte \u00C4nderung r\u00FCckg\u00E4ngig machen +Ebnf.Input_Redo=Die letzte \u00C4nderung wieder herstellen + +Ebnf.RuleIsCorrect=Die von Ihnen eingegebene Regel ist korrekt. + +Ebnf.Input_CheckDefinitionButton=
Defintion
pr\u00FCfen
+Ebnf.Input_InputFinishedButton=
Eingabe
beenden
+Ebnf.Input_RulesBorder=Regeln +Ebnf.Input_TerminalBorder=Terminalsymbole + +Ebnf.Input_Undo=Macht die letzte Aktion r\u00FCckg\u00E4ngig. +Ebnf.Input_Redo=Stellt Vorzustand her. +Ebnf.terminal=Terminalsymbol +Ebnf.variable=Variable +Ebnf.symbol=Das Symbol +Ebnf.isUnknown=konnte nicht zugeordnet werden.
Es kann aber einer Menge hinzugef\u00FCgt werden. + +Ebnf.Error_NoValidVarName=FEHLER: Ung\u00FCltiger Variablen-Name! +Ebnf.Error_NoValidTermrName=FEHLER: Ung\u00FCltiger Terminalsymbol-Name! +Ebnf.Error_NoValidRule=FEHLER: Die eingebene Regel ist ung\u00FCltig! + +Ebnf.Error.Error=FEHLER: +Ebnf.FurtherChars=weitere Sonderzeichen +Ebnf.Error.Undefined=FEHLER: Operation konnte nicht ausgef\u00FChrt werden! +Ebnf.Error.StartVarNull=FEHLER: Es muss eine Variable der Definition als Startvariable gesetzt werden! +Ebnf.Error.StartVarNotInDef=FEHLER: Die neue Startvariable ist nicht in der Definition vorhanden! +Ebnf.Error.InvalidNameInDef=konnte wegen \u00DCberschneidungen mit anderen Symbolnamen der Definition nicht hinzugef\u00FCgt werden! +Ebnf.Error.InvalidSymbolName=ist kein g\u00FCltiger Symbolname! +Ebnf.Error.SymbolOccoursInRule=kommt noch in Regeln vor und kann deshalb nicht gel\u00F6scht werden! +Ebnf.Error.NotASymbol=ist kein Symbol der Definition +Ebnf.Error.NotATerminalSymbol=ist kein Terminalsymbol +Ebnf.Error.NotAVariable=ist keine Variable +Ebnf.Error.NotARuleReplace=FEHLER: Die Regel ist keine Regel der Definition und kann daher nicht ersetzt werden. +Ebnf.Error.RuleIsNull=FEHLER: Die Regel ist leer und kann deshalb nicht hinzugef\u00FCgt werden! +Ebnf.Error.RuleAlreadyExists=Fehler: Es gibt bereits eine Regel f\u00FCr die Variable +Ebnf.Error.ReplacementRuleIsNull=FEHLER: Die neue Regel ist leer und kann deshalb nicht die alte regel ersetzten! +Ebnf.Error.Replacement=Die Regel kann nicht ersetzt werden: +Ebnf.Error.ParseError=FEHLER: Die Regel ist ung\u00FCltig! +Ebnf.Error.BracketError=FEHLER: Die Regel ist falsch geklammert! +Ebnf.Error.AlternativeError=FEHLER: Es kommt ein Alternativstrich au\u00DFerhalb von runden Klammern vor! +Ebnf.Error.StillErrorsInDef=Leider enth\u00E4lt die von Ihnen eingegebene Definition noch Fehler: +Ebnf.Error.SaveError=Beim Speichern der Definition ist ein Fehler aufgetreten +Ebnf.Error.LoadError=Beim Laden der Definition ist ein Fehler aufgetreten +Ebnf.Error.LoadErrorInvalidDef=Die gew\u00E4hlte Datei enth\u00E4lt keine g\u00FCltige EBNF-Definition + +Ebnf.Error.UndoImpossible=Das R\u00FCckg\u00E4ngigmachen der Aktion ist leider nicht m\u00F6glich +Ebnf.Error.RedoImpossible=Das Wiederherstellen der Aktion ist leider nicht m\u00F6glich + +General.Error.LoadError=Beim Laden des Syntaxdiagramms ist ein Fehler aufgetreten + +SynDia.Error.SaveError=Beim Speichern des Syntaxdiagramms ist ein Fehler aufgetreten +SynDia.Error.LoadError=Beim Laden des Syntaxdiagramms ist ein Fehler aufgetreten +SynDia.Error.LoadErrorInvalidDef=Die gew\u00E4hlte Datei enth\u00E4lt kein g\u00FCltiges Syntaxdiagramm + +SynDiaEditor.Error_InternalError=Beim Bearbeiten des Syntaxdiagrammsystems ist ein Fehler aufgetreten. +SynDiaEditor.Error_Appendix=Es wird empfohlen, das aktuelle Modul zu schlie\u00DFen und einen alten Speicherstand zu laden. + +SynDiaEditor.PopupNote_Border=Hinweis +SynDiaEditor.PopupNote_DoNotDeleteStartDiagram=
Das Startdiagramm darf
nicht gel\u00F6scht werden!
+SynDiaEditor.PopupIncomplete_Top=
Folgende Variablen haben
kein zugeh\u00F6riges Diagramm:
+ +SynDiaEditor.NameOfDiagram=Name des Diagramms +SynDiaEditor.ChangeNameOfDiagram=Bitte keinen leeren Namen +SynDiaEditor.DiagramAlreadyExists=Name existiert schon! + +SynDiaEditor.Undo=Macht die letzte Aktion r\u00FCckg\u00E4ngig. +SynDiaEditor.Redo=Stellt Vorzustand her. + +SynDiaEditor.ToolTip_AddSynDia=Einf\u00FCgen eines neuen Syntaxdiagramms +SynDiaEditor.ToolTip_Edit=Editieren von Syntaxdiagramm-, Variablen- und Terminalsymbolnamen +SynDiaEditor.ToolTip_Delete=L\u00F6schen von Syntaydiagrammelementen oder leeren Diagrammen +SynDiaEditor.ToolTip_AddTerminal=Einf\u00FCgen eines Terminalsymbols an einer Raute +SynDiaEditor.ToolTip_AddVariable=Einf\u00FCgen einer Variable an einer Raute +SynDiaEditor.ToolTip_AddBranch=Einf\u00FCgen einer Verzweigung: 1. Rechtsklick befestigt Anfang; 2.Rechtsklick das Ende +SynDiaEditor.ToolTip_AddRepetition=Einf\u00FCgen einer Wiederholung: 1. Rechtsklick befestigt Anfang; 2.Rechtsklick das Ende + +WordAlgo.BgName=word + +WordAlgo.Explanation_BeforeStart=Geben Sie ein Wort ein, das sie generieren wollen, und klicken Sie auf den Button 'Algorithmus Starten', um den Algorithmus zu beginnen. Sie k\u00F6nnen auch kein Wort eingeben, um die Erzeugung beliebiger W\u00F6rter zu \u00FCben. +WordAlgo.Explanation_AlgorithmStart=Bevor der Algorithmus abl\u00E4uft, wird der Ausgang jeder Variable mit einer Marke versehen. Der Algorithmus beginnt am Eingang des Startdiagrammes. +WordAlgo.Explanation_JumpToDiagram=Sprung in das Diagramm, dessen Name die Variable trug. +WordAlgo.Explanation_LeaveDiagram=Das Diagramm wurde verlassen. +WordAlgo.Explanation_LeaveDiagramWithAdress=Wenn noch eine Ruecksprungadresse auf dem Keller liegt, dann klicke die R\u00FCcksprungmarke der Variable an, die mit dieser Adresse gekennzeichnet ist. +WordAlgo.Explanation_LeaveDiagramFinishWithSuccess=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller und der Ausgang des Startdiagrammes wurde ereicht. Der Algorithmus endet erfolgreich. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller, aber der Ausgang des Startdiagrammes wurde nicht ereicht. Der Algorithmus endet nicht erfolgreich. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller, aber das erzeugte Wort entspricht nicht dem eingegebenen. Der Algorithmus endet nicht erfolgreich. +WordAlgo.Explanation_ReturnToDiagram=Die R\u00FCcksprungadresse wurde vom Keller entfernt und der R\u00FCcksprung vollzogen. +WordAlgo.Explanation_Split= +WordAlgo.Explanation_Terminal=Das im Terminalzeichen enthaltene Symbol wurde ans Ende des erzeugten Wortes angeh\u00E4ngt. +WordAlgo.Explanation_Variable=Die R\u00FCcksprungadresse der Variable wurde auf den Keller gelegt. \nKlicke jetzt auf das Syntaxdiagramm, dessen Name in der angeklickten Variable notiert ist. +WordAlgo.Explanation_ContinueDiagram=Setze den Weg durch das Diagram fort. Klicke dazu auf ein TerminalSymbol, eine Variable oder einen leeren Pfad, der erreicht werden kann. + +WordAlgo.Warning_JumpToDiagram=Der Name des betretenen Syntaxdiagrammes stimmt nicht mit dem Name der verlassenen Variable \u00FCberein. Der Sprung wird nicht durchgef\u00FChrt. +WordAlgo.Warning_ReturnToDiagram=Die ausgew\u00E4hlte R\u00FCcksprungadresse stimmt nicht mit der obersten R\u00FCcksprungadresse vom Keller \u00FCberein. +WordAlgo.Warning_Terminal=Das erzeugte Wort kann nicht mehr zum eingegebenen Wort fuehren. Der Algorithmus wird beendet. +WordAlgo.Warning_WordNotValid=Das eingebene Wort ist ung\u00FCltig! +WordAlgo.Warning_WordNotValidToolTip=Es d\u00FCrfen nur Terminalsymbole verwendet werden, die auch in den Diagrammen enthalten sind. + +WordAlgo.MouseOver_Variable=Diese Variable kann erreicht werden. Klicke, um den Weg zu dieser Variable zu w\u00E4hlen. +WordAlgo.MouseOver_ReturnAdress=Klicke, um zu dieser Variable zur\u00FCck zu springen. +WordAlgo.MouseOver_Terminal=Dieses Terminalsymbol kann erreicht werden. Klicke, um den Weg zu diesem TerminalSymbol zu w\u00E4hlen. +WordAlgo.MouseOver_Diagram=Klicke, um zu diesem Diagram zu Springen. +WordAlgo.MouseOver_DiagramExit=Der Ausgang des Diagrammes kann erreicht werden. Klicke, um das Diagram zu verlassen. +WordAlgo.MouseOver_Split=Diese Verzweigung kann erreicht werden. Klicke, um diese Verzweigung zu passieren. + +WordAlgo.GuiControlPanel_Description=Steuerung +WordAlgo.GuiControlPanel_StartLabel=
Algorithmus
starten
+WordAlgo.GuiControlPanel_StopLabel=
Algorithmus
zur\u00FCcksetzen
+WordAlgo.GuiControlPanel_RandomWordLabel=
Erzeuge
Zufallswort
+WordAlgo.GuiControlPanel_StartTooltip=Startet den Algorithmus. +WordAlgo.GuiControlPanel_StopTooltip=Setzt den Algorithmus auf den Anfang zur\u00FCck. +WordAlgo.GuiControlPanel_RandomWordTooltip=Erzeugt ein Zufallswort, das mit dem Algorithmus generiert werden kann. +WordAlgo.GuiControlPanel_FinishSuccess=Der Algorithmus wurde erfolgreich beendet. +WordAlgo.GuiControlPanel_FinishUnsuccess=Der Algorithmus wurde fehlerhaft beendet. +WordAlgo.GuiControlPanel_RandomWordError=Fehler bei Worterzeugung. + +WordAlgo.GuiExplanationPanel_Description=Erkl\u00E4rung +WordAlgo.GuiStackPanel_Description=Keller + +WordAlgo.ToolBar_Undo=Den letzten Schritt r\u00FCckg\u00E4ngig machen +WordAlgo.ToolBar_Redo=Den letzten Schritt wiederherstellen + +WordAlgo.Menu_Title=R\u00FCcksprung-Algorithmus +WordAlgo.Menu_Start=Algorithmus starten +WordAlgo.Menu_Reset=Algorithmus zur\u00FCcksetzen +WordAlgo.Menu_Undo=Schritt r\u00FCckg\u00E4ngig +WordAlgo.Menu_Redo=Schritt wiederherstellen +WordAlgo.Menu_UndoAll=Alle Schritte R\u00FCckg\u00E4ngig +WordAlgo.Menu_RedoAll=Alle Schritte wiederherstellen +WordAlgo.Menu_Exit=Algorithmus verlassen +InputPanel.next=Weiter +InputPanel.Variables=Variablen +InputPanel.insertlpar=( einf\u00FCgen diff --git a/bin/org/jalgo/module/ebnf/en.properties b/bin/org/jalgo/module/ebnf/en.properties new file mode 100644 index 0000000..8af4954 --- /dev/null +++ b/bin/org/jalgo/module/ebnf/en.properties @@ -0,0 +1,224 @@ +Module_name=EBNF / Syntax-Diagramme +Module_version=1.0 +Module_authors=Tom Kazimier, Johannes Mey, Michael Thiele, André Viergutz, Claas Wilke +Module_license=GNU General Public License +Module_description_1=This module handles EBNF definitions and syntax diagrams. +Module_description_2=The trans() algorithm and interactvive word creation are supported. + +ModuleConnector.No_valid_EBNF_file=This is not a valid EBNF definition or syntax diagram file. +ModuleConnector.Loading_error=Error loading the file. +ModuleConnector.File_damaged=The file is possibly damaged. +GUIController.Wish_to_change_to_EBNF_mode=Do you want to switch to EBNF mode? + +Show_start_screen=Show selcome screen +Show_start_screen_tooltip=Shows the selcome screen +Wish_to_discard=Do you wish to discard your changes? +Wish_to_show_Startscreen=Do you really want to show the start screen? + +SynDiaModel.NoNullElemException=Error inserting into the diagram: At the given index is no null element +SynDiaModel.BeginEndException=begin - end < 0 or (begin - end) % 2 != 0 +SynDiaModel.LeftAndRightPathException=It is impossible to keep the the upper or lower path when deleting a branch or repetition +SynDiaModel.ElementNotFoundException=There is no removable element at this position! +SynDiaModel.DeleteStartDiagramException=The start diagram can not be removed! +SynDiaModel.EmptyNameExeption=Variable and terminal symbol names must not be empty! + +Trans.UndoAll=Undo all steps +Trans.Undo=Undo the last step +Trans.Perform=Perform the next possible step +Trans.PerformAll=Complete the algorithm +Trans.ShowHelp=Switch accentuation of the next algorithm step on/off + +Trans.Finished=The algorithm has finished +Trans.Beachte_top=Attention: Enter the repetition at the right side! +Trans.Beachte_bottom= +Trans.Sei=Be +Trans.FirstAd=Move the mouse over a trans()-element +Trans.SecondAd=By clicking this, the next transformation step will be performed + +Border_Control=control area +Border_Draw=diagram display +Border_Explanation=algorithm advices + +SynDia.Control_FitToSize=automatically fit to size on/off +SynDia.Control_Stairs=show/hide stairs in syntax diagrams +SynDia.Control_ToEbnf=
View/edit
EBNF definition
+SynDia.Control_ToSynDiaDisplay=
To syntax
diagram display
+SynDia.Control_ToSynDiaInput=
To syntax
diagram editor
+SynDia.Control_ToWordAlgo=
To word
algorithm
+SynDia.Control_Save=Asvise +SynDia.Control_SaveText=Would you like to save the diagram before starting the algorithm? + +Ebnf.Controller_DefinitionCheck_NoStartVar=ERROR: the definition has no start variable
+Ebnf.Controller_DefinitionCheck_NoRuleForVar_1=ERROR: The variable +Ebnf.Controller_DefinitionCheck_NoRuleForVar_2=has no associated rule
+Ebnf.Controller_DefinitionCheck_NoTermWithVar_1=WARNING: The variable +Ebnf.Controller_DefinitionCheck_NoTermWithVar_2=appears in no term of any rule
+Ebnf.Controller_DefinitionCheck_NoTermWithTS_1=WARNING: The terminal symbol +Ebnf.Controller_DefinitionCheck_NoTermWithTS_2=appears in no term of any rule
+Ebnf.Controller_DefinitionCheck_RuleNotReachable_1=WARNING: The rule +Ebnf.Controller_DefinitionCheck_RuleNotReachable_2=can not be reached
+Ebnf.Controller_DefinitionCheck_NotBinaryAlt=WARNING: The definition includes not binary bracketed alternative rules
+Ebnf.Controller_MakeDefinitionStrictError=ERROR: The definition could not be bracketed binary! + +Ebnf.ChoicePanel_EbnfNotBinary=The definition hast not been

made binary yet! This is
necessary to execute trans()! +Ebnf.ChoicePanel_EbnfIsBinary=The definition is bracketed binary.

The trans() algorithm

could be started. +Ebnf.ChoicePanel_Border=Please choose... +Ebnf.ChoicePanel_transNotActiveButton=

Do
trans() algorithm
+Ebnf.ChoicePanel_transActiveButton=
Back to
trans() algorithm
+Ebnf.ChoicePanel_editButton=
Overwork
definition
+Ebnf.ChoicePanel_strictButton=
Bracket
definition binary
+Ebnf.ChoicePanel_strictButton2=
Remove binary
binary brackets
+Ebnf.ChoicePanel_SaveStrictMode=Do you wish to save the binary brackets in your definition? +Ebnf.ChoicePanel_StrictMode=Keep binary brackets + +Ebnf.PopupMenu_Edit=Edit +Ebnf.PopupMenu_Rename=Rename +Ebnf.PopupMenu_Delete=Delete +Ebnf.PopupMenu_SetAsStartRule=Set as start rule +Ebnf.PopupMenu_SetAsStartVar=Set as start variable + +Ebnf.DefinitionCorrect=The definition is correct and complete. +Ebnf.CheckDefinition=Check of definition +Ebnf.Add=Add +Ebnf.Edit=Edit +Ebnf.Undo=Undo +Ebnf.33=Symbol: +Ebnf.Change=Change +Ebnf.Cancel=Cancel +Ebnf.Insert=Insert +Ebnf.cancel=Cancel +Ebnf.Input_StartVar=start variable + +Ebnf.Input_Undo=Undoes the latest change +Ebnf.Input_Redo=Redo + +Ebnf.RuleIsCorrect=The rule you inserted is accurate. + +Ebnf.Input_CheckDefinitionButton=
Check
definition
+Ebnf.Input_InputFinishedButton=
Input
finished
+Ebnf.Input_RulesBorder=Rules +Ebnf.Input_TerminalBorder=Terminal symbols + +Ebnf.Input_Undo=Undoes the last action. +Ebnf.Input_Redo=Redoes the last action. +Ebnf.terminal=Terminal symbol +Ebnf.variable=Variable +Ebnf.symbol=The Symbol +Ebnf.isUnknown=could not be assigned properly.
It is possible to assign it to a set of the definition. + +Ebnf.Error_NoValidVarName=ERROR: Illegal variable name! +Ebnf.Error_NoValidTermrName=ERROR: Illegal terminalsymbol name! +Ebnf.Error_NoValidRule=ERROR: The entered rule is illegal! + +Ebnf.Error.Error=ERROR: +Ebnf.FurtherChars=further special characters +Ebnf.Error.Undefined=ERROR: Operation could not be done! +Ebnf.Error.StartVarNull=ERROR: A variable of the definition must be set as start variable! +Ebnf.Error.StartVarNotInDef=ERROR: The new start variable is not part of the definition! +Ebnf.Error.InvalidNameInDef=could not be added to the definition because of an overlapping with other symbols! +Ebnf.Error.InvalidSymbolName=is no valid symbol name! +Ebnf.Error.SymbolOccoursInRule=still occurs in rules and could therefore not be deleted!! +Ebnf.Error.NotASymbol=is no symbol of the definition +Ebnf.Error.NotATerminalSymbol=is no terminal symbol +Ebnf.Error.NotAVariable=is no variable +Ebnf.Error.NotARuleReplace=ERROR: The rule is not part of the definition and could therefore not be replaced! +Ebnf.Error.RuleIsNull=ERROR: The rule is empty and could therefore not be added! +Ebnf.Error.RuleAlreadyExists=ERROR: There is already a rule for this variable! +Ebnf.Error.ReplacementRuleIsNull=ERROR: The new rule is empty and can't therefore replace the old one! +Ebnf.Error.Replacement=The rule can not be replaced: +Ebnf.Error.ParseError=ERROR: The rule is invalid! +Ebnf.Error.BracketError=ERROR: The rule ist not bracketed properly! +Ebnf.Error.AlternativeError=ERROR: An alternative bar occurs outside of a a pair of parentheses! +Ebnf.Error.StillErrorsInDef=Unfortunately there are still mistakes in your definition: +Ebnf.Error.SaveError=An error occured on saving the definiton +Ebnf.Error.LoadError=An error occured on loading the definitonn +Ebnf.Error.LoadErrorInvalidDef=The chosen file does not include a valid EBNF definition + +Ebnf.Error.UndoImpossible=Unfortunately the undo of this action is not possible +Ebnf.Error.RedoImpossible=Unfortunately the redo of this action is not possible + +General.Error.LoadError=An error occured on loading the syntax diagram system + +SynDia.Error.SaveError=An error occured on saving the syntax diagram system +SynDia.Error.LoadError=An error occured on loading the syntax diagram system +SynDia.Error.LoadErrorInvalidDef=The file does not contain a valid syntax diagram system + +SynDiaEditor.Error_InternalError=An error occured on editing the syntax diagram system. +SynDiaEditor.Error_Appendix=It is recommended to close the active module and to reload an older save point. + +SynDiaEditor.PopupNote_Border=Hint +SynDiaEditor.PopupNote_DoNotDeleteStartDiagram=
The start diagram
must not be deleted!
+SynDiaEditor.PopupIncomplete_Top=
These variables do
not have a diagram:
+ +SynDiaEditor.NameOfDiagram=name of the diagram +SynDiaEditor.ChangeNameOfDiagram=no empty name please +SynDiaEditor.DiagramAlreadyExists=name already exists + +SynDiaEditor.Undo=undoes last action +SynDiaEditor.Redo=redoes last undone action + +SynDiaEditor.ToolTip_AddSynDia=insert a new syntax diagram +SynDiaEditor.ToolTip_Edit=edit syntax diagrams, variables and terminal symbol names +SynDiaEditor.ToolTip_Delete=delete syntax diagram elements and empty diagrams +SynDiaEditor.ToolTip_AddTerminal=insert a terminal symbol at a rhombus +SynDiaEditor.ToolTip_AddVariable=insert a variable at a rhombus +SynDiaEditor.ToolTip_AddBranch=insert a branch: 1st click fixes beginning; 2nd click the end +SynDiaEditor.ToolTip_AddRepetition=insert a repetition: 1st click fixes beginning; 2nd click the end + +WordAlgo.BgName=word + +WordAlgo.Explanation_BeforeStart=Enter a word you want to generate and click the button 'Start algorithm' to start the algorithm. You can also start the algorithm without entering a word. +WordAlgo.Explanation_AlgorithmStart=Before the algorithm starts, each variable gets its own return adress. The algorithm starts at the beginning of the start diagram. +WordAlgo.Explanation_JumpToDiagram=Jump to the diagram which has the same name than the left variable. +WordAlgo.Explanation_LeaveDiagram=The algorithm has left the diagram. +WordAlgo.Explanation_LeaveDiagramWithAdress=If there is still a return adress on the stack, click the return adress from the variable which return adress equals the highest adress on the stack. +WordAlgo.Explanation_LeaveDiagramFinishWithSuccess=There is no return adress on the stack anymore and the exit of the start diagram has been reached. The algorithm terminates with success. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess=There is no return adress on the stack anymore, but the exit of the start diagram has not been reached. The algorithm terminates without succes. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2=Ther is no return adress on the stack anymore, but the enterred word wasn't generated. The algorithm terminates without success. +WordAlgo.Explanation_ReturnToDiagram=The return adress was popped from the stack. The algorithm returned to the diagram. +WordAlgo.Explanation_Split= +WordAlgo.Explanation_Terminal=The symbol of the terminal symbol was added to the output. +WordAlgo.Explanation_Variable=The return adress of the variable was pushed onto the stack.\nClick onto the syntax diagram which has the same name than the left Variable to jump to the diagram. +WordAlgo.Explanation_ContinueDiagram=Click on a terminal symbol, a variable or a empty branch to continue the way through the syntax diagram. + +WordAlgo.Warning_JumpToDiagram=The name of the clicked diagram does not euqal to the name of the left variable. The jump was not performed. +WordAlgo.Warning_ReturnToDiagram=The clicked return adress does not equal to the name of the highest return adress on the stack. The return was not performed. +WordAlgo.Warning_Terminal=The generated output can not become the entered word anymore. Algorithm terminates without success. +WordAlgo.Warning_WordNotValid=The entered word is not valid. +WordAlgo.Warning_WordNotValidToolTip=A valid word can only contain terminal symbols which are also in at least on of the syntax diagrams. + +WordAlgo.MouseOver_Variable=This variable can be reached. Click to go to the variable. +WordAlgo.MouseOver_ReturnAdress=Click to return to this return adress. +WordAlgo.MouseOver_Terminal=This terminal symbol can be reached. Click to pass the terminal symbol. +WordAlgo.MouseOver_Diagram=Click, to jump to this syntax diagram. +WordAlgo.MouseOver_DiagramExit=The exit of the syntax diagram can be reached. Click to leave the diagram. +WordAlgo.MouseOver_Split=This branch can be reached. Click to pass the branch. + +WordAlgo.GuiControlPanel_Description=Control +WordAlgo.GuiControlPanel_StartLabel=
Start
algorithm
+WordAlgo.GuiControlPanel_StopLabel=
Reset
algorithm
+WordAlgo.GuiControlPanel_RandomWordLabel=
Generate a
random word
+WordAlgo.GuiControlPanel_StartTooltip=Starts the algorithm. +WordAlgo.GuiControlPanel_StopTooltip=Resets the algorithm to the beginning. +WordAlgo.GuiControlPanel_RandomWordTooltip=Generates a random word which can be also generated by the algorithm. +WordAlgo.GuiControlPanel_FinishSuccess=The algorithm terminated successfully. +WordAlgo.GuiControlPanel_FinishUnsuccess=The algorithm terminated unsuccessfully. +WordAlgo.GuiControlPanel_RandomWordError=Error during word generation. + +WordAlgo.GuiExplanationPanel_Description=Explanation +WordAlgo.GuiStackPanel_Description=Stack + +WordAlgo.ToolBar_Undo=Undo the last step +WordAlgo.ToolBar_Redo=Redo the last step + +WordAlgo.Menu_Title=Word-Algorithm +WordAlgo.Menu_Start=Start algorithm +WordAlgo.Menu_Reset=Reset algorithm +WordAlgo.Menu_Undo=Undo the last step +WordAlgo.Menu_Redo=Redo the last step +WordAlgo.Menu_UndoAll=Undo all steps +WordAlgo.Menu_RedoAll=Redo all steps +WordAlgo.Menu_Exit=Leave algorithm +InputPanel.next=Nect +InputPanel.Variables=Variablen +InputPanel.insertlpar=add ( \ No newline at end of file diff --git a/bin/org/jalgo/module/ebnf/gui/EbnfFont.class b/bin/org/jalgo/module/ebnf/gui/EbnfFont.class new file mode 100644 index 0000000..b397ae2 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/EbnfFont.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/FontNotInitializedException.class b/bin/org/jalgo/module/ebnf/gui/FontNotInitializedException.class new file mode 100644 index 0000000..a1a0953 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/FontNotInitializedException.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/GUIConstants.class b/bin/org/jalgo/module/ebnf/gui/GUIConstants.class new file mode 100644 index 0000000..163467e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/GUIConstants.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/StartAction.class b/bin/org/jalgo/module/ebnf/gui/StartAction.class new file mode 100644 index 0000000..17fc0b5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/StartAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/StartButton.class b/bin/org/jalgo/module/ebnf/gui/StartButton.class new file mode 100644 index 0000000..b97f109 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/StartButton.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/StartScreen.class b/bin/org/jalgo/module/ebnf/gui/StartScreen.class new file mode 100644 index 0000000..dcef3c9 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/StartScreen.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/StartScreenActionHandler.class b/bin/org/jalgo/module/ebnf/gui/StartScreenActionHandler.class new file mode 100644 index 0000000..ca50aca Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/StartScreenActionHandler.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.class b/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.class new file mode 100644 index 0000000..9209561 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.class new file mode 100644 index 0000000..29a6acc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.class new file mode 100644 index 0000000..685dec4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.class new file mode 100644 index 0000000..bba2ff4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField$1.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField$1.class new file mode 100644 index 0000000..7a67a3f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.class new file mode 100644 index 0000000..7b1084d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.class new file mode 100644 index 0000000..948b031 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.class new file mode 100644 index 0000000..a944d1d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1.class b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1.class new file mode 100644 index 0000000..8d737fb Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddTerminalListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddTerminalListener.class new file mode 100644 index 0000000..0b8d1dc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddTerminalListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddVariableListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddVariableListener.class new file mode 100644 index 0000000..e16ea6f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$1AddVariableListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$2.class b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$2.class new file mode 100644 index 0000000..4a74029 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController.class b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController.class new file mode 100644 index 0000000..a2d9123 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/GuiController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.class b/bin/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.class new file mode 100644 index 0000000..f22b81a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$1.class b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$1.class new file mode 100644 index 0000000..aa7d9b4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$MyOwnFocusTraversalPolicy.class b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$MyOwnFocusTraversalPolicy.class new file mode 100644 index 0000000..a862ecf Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel$MyOwnFocusTraversalPolicy.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel.class b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel.class new file mode 100644 index 0000000..fb6a3fc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/InputPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/ModifyDefinitionActionListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/ModifyDefinitionActionListener.class new file mode 100644 index 0000000..98943fb Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/ModifyDefinitionActionListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/RedoAction.class b/bin/org/jalgo/module/ebnf/gui/ebnf/RedoAction.class new file mode 100644 index 0000000..6e5f1b0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/RedoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/RenderConstants.class b/bin/org/jalgo/module/ebnf/gui/ebnf/RenderConstants.class new file mode 100644 index 0000000..58412f7 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/RenderConstants.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/RuleViewPanel.class b/bin/org/jalgo/module/ebnf/gui/ebnf/RuleViewPanel.class new file mode 100644 index 0000000..f8c435e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/RuleViewPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel$Type.class b/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel$Type.class new file mode 100644 index 0000000..8a2c3b5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel$Type.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel.class b/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel.class new file mode 100644 index 0000000..662970d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/TermPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/UndoAction.class b/bin/org/jalgo/module/ebnf/gui/ebnf/UndoAction.class new file mode 100644 index 0000000..7c220d9 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/UndoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/ebnf/ViewPanelSizeListener.class b/bin/org/jalgo/module/ebnf/gui/ebnf/ViewPanelSizeListener.class new file mode 100644 index 0000000..a35126d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/ebnf/ViewPanelSizeListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/AbstractSDGuiController.class b/bin/org/jalgo/module/ebnf/gui/syndia/AbstractSDGuiController.class new file mode 100644 index 0000000..2c5df48 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/AbstractSDGuiController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.class new file mode 100644 index 0000000..e418b1c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.class new file mode 100644 index 0000000..f83448f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.class new file mode 100644 index 0000000..9bdc3b6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.class b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.class new file mode 100644 index 0000000..b984898 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.class new file mode 100644 index 0000000..a5ff3da Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.class new file mode 100644 index 0000000..592a371 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.class new file mode 100644 index 0000000..dfc601b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$1.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$1.class new file mode 100644 index 0000000..0cc71c3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$10.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$10.class new file mode 100644 index 0000000..b18ed04 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$10.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$11.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$11.class new file mode 100644 index 0000000..8b54896 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$11.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$2.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$2.class new file mode 100644 index 0000000..99e825e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$3.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$3.class new file mode 100644 index 0000000..d282aab Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$4.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$4.class new file mode 100644 index 0000000..9b8383b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$5.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$5.class new file mode 100644 index 0000000..47b0fde Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$6.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$6.class new file mode 100644 index 0000000..f98b0ae Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$7.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$7.class new file mode 100644 index 0000000..b09a11f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$7.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$8.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$8.class new file mode 100644 index 0000000..11f4a50 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$8.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$9.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$9.class new file mode 100644 index 0000000..845f87a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel$9.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.class new file mode 100644 index 0000000..081fe21 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.class new file mode 100644 index 0000000..07120b1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$1.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$1.class new file mode 100644 index 0000000..2f1e684 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$2.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$2.class new file mode 100644 index 0000000..31f7886 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$3.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$3.class new file mode 100644 index 0000000..bb10d1d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$4.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$4.class new file mode 100644 index 0000000..ec00b55 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$5.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$5.class new file mode 100644 index 0000000..4580a1d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$6.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$6.class new file mode 100644 index 0000000..1844e69 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$7.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$7.class new file mode 100644 index 0000000..13e3452 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$7.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$8.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$8.class new file mode 100644 index 0000000..af536ae Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$8.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$9.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$9.class new file mode 100644 index 0000000..9e29f90 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController$9.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/GuiController.class b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController.class new file mode 100644 index 0000000..af5c348 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/GuiController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/OkActionListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/OkActionListener.class new file mode 100644 index 0000000..6914250 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/OkActionListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/RedoAction.class b/bin/org/jalgo/module/ebnf/gui/syndia/RedoAction.class new file mode 100644 index 0000000..af73db5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/RedoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.class b/bin/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.class new file mode 100644 index 0000000..65cb692 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/UndoAction.class b/bin/org/jalgo/module/ebnf/gui/syndia/UndoAction.class new file mode 100644 index 0000000..d2f43c4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/UndoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.class new file mode 100644 index 0000000..6cf0816 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$1.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$1.class new file mode 100644 index 0000000..0d2c1c3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$2.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$2.class new file mode 100644 index 0000000..d093f54 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$3.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$3.class new file mode 100644 index 0000000..7161b90 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$4.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$4.class new file mode 100644 index 0000000..2726d09 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$5.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$5.class new file mode 100644 index 0000000..34dc697 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$6.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$6.class new file mode 100644 index 0000000..008bde2 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.class new file mode 100644 index 0000000..5eb5629 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.class new file mode 100644 index 0000000..f59594d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$1.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$1.class new file mode 100644 index 0000000..847ad55 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$2.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$2.class new file mode 100644 index 0000000..7d57a37 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.class new file mode 100644 index 0000000..1e68439 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel$1.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel$1.class new file mode 100644 index 0000000..e73a135 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.class new file mode 100644 index 0000000..0af65c5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.class new file mode 100644 index 0000000..58fd7f5 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.class b/bin/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.class new file mode 100644 index 0000000..3251e40 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$1.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$1.class new file mode 100644 index 0000000..b4ba3b4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$2.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$2.class new file mode 100644 index 0000000..0d96992 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$3.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$3.class new file mode 100644 index 0000000..d80727a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$4.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$4.class new file mode 100644 index 0000000..1f782ce Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$5.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$5.class new file mode 100644 index 0000000..79d3bb2 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$6.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$6.class new file mode 100644 index 0000000..23cb618 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel.class b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel.class new file mode 100644 index 0000000..39c86b2 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ControlPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel$1.class b/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel$1.class new file mode 100644 index 0000000..9abd425 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel.class b/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel.class new file mode 100644 index 0000000..5a3c8fe Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/DrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.class b/bin/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.class new file mode 100644 index 0000000..19d0f50 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.class b/bin/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.class new file mode 100644 index 0000000..6216ac7 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/GUIController$1.class b/bin/org/jalgo/module/ebnf/gui/trans/GUIController$1.class new file mode 100644 index 0000000..1984081 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/GUIController$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/GUIController$2.class b/bin/org/jalgo/module/ebnf/gui/trans/GUIController$2.class new file mode 100644 index 0000000..5761836 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/GUIController$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/GUIController.class b/bin/org/jalgo/module/ebnf/gui/trans/GUIController.class new file mode 100644 index 0000000..29ef844 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/GUIController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.class b/bin/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.class new file mode 100644 index 0000000..fcf3010 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.class b/bin/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.class new file mode 100644 index 0000000..333f392 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAction.class b/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAction.class new file mode 100644 index 0000000..56570c3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.class b/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.class new file mode 100644 index 0000000..a7f473e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.class b/bin/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.class new file mode 100644 index 0000000..0af9e92 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/TransListener.class b/bin/org/jalgo/module/ebnf/gui/trans/event/TransListener.class new file mode 100644 index 0000000..1a747bf Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/TransListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAction.class b/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAction.class new file mode 100644 index 0000000..2457561 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.class b/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.class new file mode 100644 index 0000000..7c5a035 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.class new file mode 100644 index 0000000..5be39cf Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.class new file mode 100644 index 0000000..5d38f32 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.class new file mode 100644 index 0000000..c506a5b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.class new file mode 100644 index 0000000..6ec8a0e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.class new file mode 100644 index 0000000..3216d1b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.class new file mode 100644 index 0000000..7975f37 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.class new file mode 100644 index 0000000..5708b9e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.class new file mode 100644 index 0000000..e0e50cd Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.class b/bin/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.class new file mode 100644 index 0000000..321c194 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$1.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$1.class new file mode 100644 index 0000000..e6a7404 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$2.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$2.class new file mode 100644 index 0000000..f880516 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$3.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$3.class new file mode 100644 index 0000000..2011f4c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$4.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$4.class new file mode 100644 index 0000000..2b7a130 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$5.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$5.class new file mode 100644 index 0000000..66e60b3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$6.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$6.class new file mode 100644 index 0000000..68bd01a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$7.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$7.class new file mode 100644 index 0000000..11b8efc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$7.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$8.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$8.class new file mode 100644 index 0000000..c7e2f87 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel$8.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.class new file mode 100644 index 0000000..beba394 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel$1.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel$1.class new file mode 100644 index 0000000..e939520 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.class new file mode 100644 index 0000000..3816847 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.class new file mode 100644 index 0000000..89b33c0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$1.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$1.class new file mode 100644 index 0000000..ad01d8c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$1.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$2.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$2.class new file mode 100644 index 0000000..e13af50 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$2.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$3.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$3.class new file mode 100644 index 0000000..8b4f9b4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$3.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$4.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$4.class new file mode 100644 index 0000000..0a36c8d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$4.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$5.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$5.class new file mode 100644 index 0000000..75ceddf Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$5.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$6.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$6.class new file mode 100644 index 0000000..ef8a70d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$6.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$7.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$7.class new file mode 100644 index 0000000..67847c0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController$7.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.class new file mode 100644 index 0000000..72a041e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.class new file mode 100644 index 0000000..15ae9a3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.class new file mode 100644 index 0000000..e5489b1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.class new file mode 100644 index 0000000..350398c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.class new file mode 100644 index 0000000..cee0e39 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.class new file mode 100644 index 0000000..a4b27e6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.class new file mode 100644 index 0000000..4471bd9 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.class new file mode 100644 index 0000000..53b2539 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.class differ diff --git a/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.class b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.class new file mode 100644 index 0000000..be333b1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.class differ diff --git a/bin/org/jalgo/module/ebnf/jAlgoTabContrainerListener.class b/bin/org/jalgo/module/ebnf/jAlgoTabContrainerListener.class new file mode 100644 index 0000000..64c9b48 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/jAlgoTabContrainerListener.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/Definition.class b/bin/org/jalgo/module/ebnf/model/ebnf/Definition.class new file mode 100644 index 0000000..b2ff718 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/Definition.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.class b/bin/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.class new file mode 100644 index 0000000..06d2000 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/EAlternative.class b/bin/org/jalgo/module/ebnf/model/ebnf/EAlternative.class new file mode 100644 index 0000000..d05cb41 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/EAlternative.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/ECompoundTerm.class b/bin/org/jalgo/module/ebnf/model/ebnf/ECompoundTerm.class new file mode 100644 index 0000000..c880b4b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/ECompoundTerm.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/EConcatenation.class b/bin/org/jalgo/module/ebnf/model/ebnf/EConcatenation.class new file mode 100644 index 0000000..9010c8b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/EConcatenation.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/EOption.class b/bin/org/jalgo/module/ebnf/model/ebnf/EOption.class new file mode 100644 index 0000000..4805911 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/EOption.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/ERepetition.class b/bin/org/jalgo/module/ebnf/model/ebnf/ERepetition.class new file mode 100644 index 0000000..2a343bd Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/ERepetition.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/ESymbol.class b/bin/org/jalgo/module/ebnf/model/ebnf/ESymbol.class new file mode 100644 index 0000000..86fa777 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/ESymbol.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/ETermContainer.class b/bin/org/jalgo/module/ebnf/model/ebnf/ETermContainer.class new file mode 100644 index 0000000..6577a1d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/ETermContainer.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.class b/bin/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.class new file mode 100644 index 0000000..e6dd2e3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/EVariable.class b/bin/org/jalgo/module/ebnf/model/ebnf/EVariable.class new file mode 100644 index 0000000..ad9440f Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/EVariable.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/Rule.class b/bin/org/jalgo/module/ebnf/model/ebnf/Rule.class new file mode 100644 index 0000000..c254c41 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/Rule.class differ diff --git a/bin/org/jalgo/module/ebnf/model/ebnf/Term.class b/bin/org/jalgo/module/ebnf/model/ebnf/Term.class new file mode 100644 index 0000000..cb6f1ee Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/ebnf/Term.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/Branch.class b/bin/org/jalgo/module/ebnf/model/syndia/Branch.class new file mode 100644 index 0000000..7bbe075 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/Branch.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/Concatenation.class b/bin/org/jalgo/module/ebnf/model/syndia/Concatenation.class new file mode 100644 index 0000000..6d19a5e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/Concatenation.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.class b/bin/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.class new file mode 100644 index 0000000..be290c6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/NoNullElemException.class b/bin/org/jalgo/module/ebnf/model/syndia/NoNullElemException.class new file mode 100644 index 0000000..f542941 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/NoNullElemException.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/NullElem.class b/bin/org/jalgo/module/ebnf/model/syndia/NullElem.class new file mode 100644 index 0000000..6217027 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/NullElem.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/Repetition.class b/bin/org/jalgo/module/ebnf/model/syndia/Repetition.class new file mode 100644 index 0000000..04573f4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/Repetition.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/SynDiaElem.class b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaElem.class new file mode 100644 index 0000000..a070e3e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaElem.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.class b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.class new file mode 100644 index 0000000..0ee93ba Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.class b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.class new file mode 100644 index 0000000..ede5346 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.class b/bin/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.class new file mode 100644 index 0000000..03ebaa0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.class b/bin/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.class new file mode 100644 index 0000000..632725e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/Variable.class b/bin/org/jalgo/module/ebnf/model/syndia/Variable.class new file mode 100644 index 0000000..2d7dc85 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/Variable.class differ diff --git a/bin/org/jalgo/module/ebnf/model/syndia/WordWrap.class b/bin/org/jalgo/module/ebnf/model/syndia/WordWrap.class new file mode 100644 index 0000000..980c2d1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/syndia/WordWrap.class differ diff --git a/bin/org/jalgo/module/ebnf/model/trans/TransMap.class b/bin/org/jalgo/module/ebnf/model/trans/TransMap.class new file mode 100644 index 0000000..6df01e7 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/trans/TransMap.class differ diff --git a/bin/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.class b/bin/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.class new file mode 100644 index 0000000..414b9b3 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/EditorRenderer.class b/bin/org/jalgo/module/ebnf/renderer/EditorRenderer.class new file mode 100644 index 0000000..5d386f4 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/EditorRenderer.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/RenderElementFactory.class b/bin/org/jalgo/module/ebnf/renderer/RenderElementFactory.class new file mode 100644 index 0000000..9a33c18 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/RenderElementFactory.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/RenderValues.class b/bin/org/jalgo/module/ebnf/renderer/RenderValues.class new file mode 100644 index 0000000..33bc578 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/RenderValues.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/ReturnDiagram.class b/bin/org/jalgo/module/ebnf/renderer/ReturnDiagram.class new file mode 100644 index 0000000..2a5cf3e Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/ReturnDiagram.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/SynDiaRenderer.class b/bin/org/jalgo/module/ebnf/renderer/SynDiaRenderer.class new file mode 100644 index 0000000..785c59a Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/SynDiaRenderer.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/TransRenderer.class b/bin/org/jalgo/module/ebnf/renderer/TransRenderer.class new file mode 100644 index 0000000..c980027 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/TransRenderer.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/VirtualDim.class b/bin/org/jalgo/module/ebnf/renderer/VirtualDim.class new file mode 100644 index 0000000..12525a0 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/VirtualDim.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.class b/bin/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.class new file mode 100644 index 0000000..17c0a37 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderBase.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderBase.class new file mode 100644 index 0000000..313e35d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderBase.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderBranch.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderBranch.class new file mode 100644 index 0000000..b5f2cfd Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderBranch.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderElement.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderElement.class new file mode 100644 index 0000000..1b98c71 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderElement.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderName.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderName.class new file mode 100644 index 0000000..879879d Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderName.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.class new file mode 100644 index 0000000..34bd598 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.class new file mode 100644 index 0000000..fa3f324 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.class new file mode 100644 index 0000000..44e83fe Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderSplit.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderSplit.class new file mode 100644 index 0000000..2a0d3e6 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderSplit.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.class new file mode 100644 index 0000000..d872abc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.class new file mode 100644 index 0000000..7637ce2 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.class new file mode 100644 index 0000000..9093b1c Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderTrans.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTrans.class new file mode 100644 index 0000000..b7b07fc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderTrans.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/elements/RenderVariable.class b/bin/org/jalgo/module/ebnf/renderer/elements/RenderVariable.class new file mode 100644 index 0000000..67e2a85 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/elements/RenderVariable.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.class b/bin/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.class new file mode 100644 index 0000000..2249d66 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.class b/bin/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.class new file mode 100644 index 0000000..51acefc Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/event/SplitListener.class b/bin/org/jalgo/module/ebnf/renderer/event/SplitListener.class new file mode 100644 index 0000000..aa2d5f8 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/event/SplitListener.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.class b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.class new file mode 100644 index 0000000..fa5aa34 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.class b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.class new file mode 100644 index 0000000..6087c17 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.class b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.class new file mode 100644 index 0000000..b632911 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.class b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.class new file mode 100644 index 0000000..4717bce Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.class differ diff --git a/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.class b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.class new file mode 100644 index 0000000..d9e3d9b Binary files /dev/null and b/bin/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.class differ diff --git a/bin/org/jalgo/module/ebnf/res.properties b/bin/org/jalgo/module/ebnf/res.properties new file mode 100644 index 0000000..04552ed --- /dev/null +++ b/bin/org/jalgo/module/ebnf/res.properties @@ -0,0 +1,55 @@ +Module_logo=/ebnf_pix/logo.gif +HelpSet_Name=/help/jhelp/ebnf_help.hs + +Start_load=/ebnf_pix/start_load.gif +Start_load_rollover=/ebnf_pix/start_load_rollover.gif +Start_load_description_de=/ebnf_pix/start_load_desc_de.gif +Start_load_description_en=/ebnf_pix/start_load_desc_en.gif +Start_ebnf=/ebnf_pix/start_ebnf.gif +Start_ebnf_rollover=/ebnf_pix/start_ebnf_rollover.gif +Start_ebnf_description_de=/ebnf_pix/start_ebnf_desc_de.gif +Start_ebnf_description_en=/ebnf_pix/start_ebnf_desc_en.gif +Start_syndia=/ebnf_pix/start_syndia.gif +Start_syndia_rollover=/ebnf_pix/start_syndia_rollover.gif +Start_syndia_description_de=/ebnf_pix/start_syndia_desc_de.gif +Start_syndia_description_en=/ebnf_pix/start_syndia_desc_en.gif +Ebnf_Font=/font/EbnfSans.ttf + +ModeEdit_Image=/ebnf_pix/edit.gif +ModeAddTerminal_Image=/ebnf_pix/addTerminal.gif +ModeAddVariable_Image=/ebnf_pix/addVariable.gif +ModeAddBranch_Image=/ebnf_pix/addBranch.gif +ModeAddRepetition_Image=/ebnf_pix/addRepetition.gif +ModeDelete_Image=/ebnf_pix/rubber.gif + +Cursor_Branch=/ebnf_pix/cursor/branch.gif +Cursor_Repetition=/ebnf_pix/cursor/repetition.gif +Cursor_Variable=/ebnf_pix/cursor/variable.gif +Cursor_Terminal=/ebnf_pix/cursor/terminal.gif +Cursor_Delete=/ebnf_pix/cursor/rubber.gif +Cursor_Edit=/ebnf_pix/cursor/edit.gif +Cursor_BranchRight=/ebnf_pix/cursor/branch_right.gif +Cursor_RepetitionRight=/ebnf_pix/cursor/repetition_right.gif + +Icon.Edit=/ebnf_pix/button/edit.gif +Icon.AddTerminal=/ebnf_pix/button/addTerminal.gif +Icon.AddVariable=/ebnf_pix/button/addVariable.gif +Icon.AddBranch=/ebnf_pix/button/addBranch.gif +Icon.AddRepetition=/ebnf_pix/button/addRepetition.gif +Icon.Delete=/ebnf_pix/button/rubber.gif +Icon.AddDiagram=/ebnf_pix/button/addDiagram.gif +Icon.SelectedEdit=/ebnf_pix/button/selected_edit.gif +Icon.SelectedAddTerminal=/ebnf_pix/button/selected_addTerminal.gif +Icon.SelectedAddVariable=/ebnf_pix/button/selected_addVariable.gif +Icon.SelectedAddBranch=/ebnf_pix/button/selected_addBranch.gif +Icon.SelectedAddRepetition=/ebnf_pix/button/selected_addRepetition.gif +Icon.SelectedDelete=/ebnf_pix/button/selected_rubber.gif + +Icon.FitToSize=/ebnf_pix/button/fittosize.gif +Icon.FitToWidth=/ebnf_pix/button/fittowidth.gif +Icon.FitSelf=/ebnf_pix/button/zoomer.gif +Icon.NoStairs=/ebnf_pix/button/nostairs.gif +Icon.Stairs=/ebnf_pix/button/stairs.gif + +Light_Red=/ebnf_pix/light_red.png +Light_Green=/ebnf_pix/light_green.png \ No newline at end of file diff --git a/bin/org/jalgo/module/ebnf/rootPaneListener.class b/bin/org/jalgo/module/ebnf/rootPaneListener.class new file mode 100644 index 0000000..6529c13 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/rootPaneListener.class differ diff --git a/bin/org/jalgo/module/ebnf/util/ActionStack.class b/bin/org/jalgo/module/ebnf/util/ActionStack.class new file mode 100644 index 0000000..5994bc1 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/util/ActionStack.class differ diff --git a/bin/org/jalgo/module/ebnf/util/IAction.class b/bin/org/jalgo/module/ebnf/util/IAction.class new file mode 100644 index 0000000..79e6ed8 Binary files /dev/null and b/bin/org/jalgo/module/ebnf/util/IAction.class differ diff --git a/bin/org/jalgo/module/em/ModuleConnector.class b/bin/org/jalgo/module/em/ModuleConnector.class new file mode 100644 index 0000000..e2802f6 Binary files /dev/null and b/bin/org/jalgo/module/em/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/em/ModuleInfo.class b/bin/org/jalgo/module/em/ModuleInfo.class new file mode 100644 index 0000000..0ab69eb Binary files /dev/null and b/bin/org/jalgo/module/em/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$1.class b/bin/org/jalgo/module/em/control/Controller$1.class new file mode 100644 index 0000000..f6b6bc7 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$1.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$10.class b/bin/org/jalgo/module/em/control/Controller$10.class new file mode 100644 index 0000000..0940f4c Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$10.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$11.class b/bin/org/jalgo/module/em/control/Controller$11.class new file mode 100644 index 0000000..0d520a0 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$11.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$12.class b/bin/org/jalgo/module/em/control/Controller$12.class new file mode 100644 index 0000000..b9537d0 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$12.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$13.class b/bin/org/jalgo/module/em/control/Controller$13.class new file mode 100644 index 0000000..690d03b Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$13.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$2.class b/bin/org/jalgo/module/em/control/Controller$2.class new file mode 100644 index 0000000..4bb965f Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$2.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$3.class b/bin/org/jalgo/module/em/control/Controller$3.class new file mode 100644 index 0000000..35250fb Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$3.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$4.class b/bin/org/jalgo/module/em/control/Controller$4.class new file mode 100644 index 0000000..2900adb Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$4.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$5.class b/bin/org/jalgo/module/em/control/Controller$5.class new file mode 100644 index 0000000..dd41948 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$5.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$6.class b/bin/org/jalgo/module/em/control/Controller$6.class new file mode 100644 index 0000000..d861a21 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$6.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$7.class b/bin/org/jalgo/module/em/control/Controller$7.class new file mode 100644 index 0000000..ebe378f Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$7.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$8.class b/bin/org/jalgo/module/em/control/Controller$8.class new file mode 100644 index 0000000..1488ee1 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$8.class differ diff --git a/bin/org/jalgo/module/em/control/Controller$9.class b/bin/org/jalgo/module/em/control/Controller$9.class new file mode 100644 index 0000000..5577f18 Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller$9.class differ diff --git a/bin/org/jalgo/module/em/control/Controller.class b/bin/org/jalgo/module/em/control/Controller.class new file mode 100644 index 0000000..d7edaef Binary files /dev/null and b/bin/org/jalgo/module/em/control/Controller.class differ diff --git a/bin/org/jalgo/module/em/control/EMModule.class b/bin/org/jalgo/module/em/control/EMModule.class new file mode 100644 index 0000000..5f1e302 Binary files /dev/null and b/bin/org/jalgo/module/em/control/EMModule.class differ diff --git a/bin/org/jalgo/module/em/control/IOController.class b/bin/org/jalgo/module/em/control/IOController.class new file mode 100644 index 0000000..280c89c Binary files /dev/null and b/bin/org/jalgo/module/em/control/IOController.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$1.class b/bin/org/jalgo/module/em/control/InputController$1.class new file mode 100644 index 0000000..a307882 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$1.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$2.class b/bin/org/jalgo/module/em/control/InputController$2.class new file mode 100644 index 0000000..b22dd3f Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$2.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$3.class b/bin/org/jalgo/module/em/control/InputController$3.class new file mode 100644 index 0000000..12c3433 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$3.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$4.class b/bin/org/jalgo/module/em/control/InputController$4.class new file mode 100644 index 0000000..804daf9 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$4.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$5.class b/bin/org/jalgo/module/em/control/InputController$5.class new file mode 100644 index 0000000..709e9e0 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$5.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$6.class b/bin/org/jalgo/module/em/control/InputController$6.class new file mode 100644 index 0000000..23be7b1 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$6.class differ diff --git a/bin/org/jalgo/module/em/control/InputController$7.class b/bin/org/jalgo/module/em/control/InputController$7.class new file mode 100644 index 0000000..356ad22 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController$7.class differ diff --git a/bin/org/jalgo/module/em/control/InputController.class b/bin/org/jalgo/module/em/control/InputController.class new file mode 100644 index 0000000..9b93804 Binary files /dev/null and b/bin/org/jalgo/module/em/control/InputController.class differ diff --git a/bin/org/jalgo/module/em/control/LogState.class b/bin/org/jalgo/module/em/control/LogState.class new file mode 100644 index 0000000..d5c368c Binary files /dev/null and b/bin/org/jalgo/module/em/control/LogState.class differ diff --git a/bin/org/jalgo/module/em/control/MainController$1.class b/bin/org/jalgo/module/em/control/MainController$1.class new file mode 100644 index 0000000..948ef85 Binary files /dev/null and b/bin/org/jalgo/module/em/control/MainController$1.class differ diff --git a/bin/org/jalgo/module/em/control/MainController$2.class b/bin/org/jalgo/module/em/control/MainController$2.class new file mode 100644 index 0000000..9eccfc4 Binary files /dev/null and b/bin/org/jalgo/module/em/control/MainController$2.class differ diff --git a/bin/org/jalgo/module/em/control/MainController$3.class b/bin/org/jalgo/module/em/control/MainController$3.class new file mode 100644 index 0000000..5c430cf Binary files /dev/null and b/bin/org/jalgo/module/em/control/MainController$3.class differ diff --git a/bin/org/jalgo/module/em/control/MainController.class b/bin/org/jalgo/module/em/control/MainController.class new file mode 100644 index 0000000..cec57b9 Binary files /dev/null and b/bin/org/jalgo/module/em/control/MainController.class differ diff --git a/bin/org/jalgo/module/em/control/OptionPane$1.class b/bin/org/jalgo/module/em/control/OptionPane$1.class new file mode 100644 index 0000000..5ca765e Binary files /dev/null and b/bin/org/jalgo/module/em/control/OptionPane$1.class differ diff --git a/bin/org/jalgo/module/em/control/OptionPane$2.class b/bin/org/jalgo/module/em/control/OptionPane$2.class new file mode 100644 index 0000000..e29fa4a Binary files /dev/null and b/bin/org/jalgo/module/em/control/OptionPane$2.class differ diff --git a/bin/org/jalgo/module/em/control/OptionPane.class b/bin/org/jalgo/module/em/control/OptionPane.class new file mode 100644 index 0000000..f436ea8 Binary files /dev/null and b/bin/org/jalgo/module/em/control/OptionPane.class differ diff --git a/bin/org/jalgo/module/em/control/TestCalculation.class b/bin/org/jalgo/module/em/control/TestCalculation.class new file mode 100644 index 0000000..6ba6fe0 Binary files /dev/null and b/bin/org/jalgo/module/em/control/TestCalculation.class differ diff --git a/bin/org/jalgo/module/em/control/package-info.class b/bin/org/jalgo/module/em/control/package-info.class new file mode 100644 index 0000000..0683185 Binary files /dev/null and b/bin/org/jalgo/module/em/control/package-info.class differ diff --git a/bin/org/jalgo/module/em/data/EMData.class b/bin/org/jalgo/module/em/data/EMData.class new file mode 100644 index 0000000..9ff5661 Binary files /dev/null and b/bin/org/jalgo/module/em/data/EMData.class differ diff --git a/bin/org/jalgo/module/em/data/EMState.class b/bin/org/jalgo/module/em/data/EMState.class new file mode 100644 index 0000000..98f9032 Binary files /dev/null and b/bin/org/jalgo/module/em/data/EMState.class differ diff --git a/bin/org/jalgo/module/em/data/Event.class b/bin/org/jalgo/module/em/data/Event.class new file mode 100644 index 0000000..61dd34d Binary files /dev/null and b/bin/org/jalgo/module/em/data/Event.class differ diff --git a/bin/org/jalgo/module/em/data/Partition.class b/bin/org/jalgo/module/em/data/Partition.class new file mode 100644 index 0000000..52923c7 Binary files /dev/null and b/bin/org/jalgo/module/em/data/Partition.class differ diff --git a/bin/org/jalgo/module/em/data/StartParameters.class b/bin/org/jalgo/module/em/data/StartParameters.class new file mode 100644 index 0000000..2e422de Binary files /dev/null and b/bin/org/jalgo/module/em/data/StartParameters.class differ diff --git a/bin/org/jalgo/module/em/data/package-info.class b/bin/org/jalgo/module/em/data/package-info.class new file mode 100644 index 0000000..972d014 Binary files /dev/null and b/bin/org/jalgo/module/em/data/package-info.class differ diff --git a/bin/org/jalgo/module/em/de.properties b/bin/org/jalgo/module/em/de.properties new file mode 100644 index 0000000..59b460d --- /dev/null +++ b/bin/org/jalgo/module/em/de.properties @@ -0,0 +1,111 @@ +ObjectName=W +ObjectName.2=Münze +ObjectName.4=Tetraeder +ObjectName.6=Würfel +ObjectName.8=Oktaeder +Controller.togglePMode=Präsentationsmodus wechseln +ToolBar.save=Experiment speichern +ToolBar.load=Experiment laden +ToolBar.preferences=Einstellungen +ToolBar.wback=EM-Schritt zurück +ToolBar.back=Einzelschritt zurück +ToolBar.forw=Einzelschritt vorwärts +ToolBar.wforw=EM-Schritt vorwärts +ToolBar.home=Zurück in den Inputmodus +ToolBar.run=EM-Algorithmus bis Konvergenz ausführen +Menu.hybrid=Hybridansicht +Menu.table=Tabellenansicht +Menu.diagram=Diagrammansicht +Menu.log=logarithmische Likelihood +Menu.presentation=Präsentationsmodus +IOController.FileChooser=Datei wählen +InputPanel.bForward=Weiter +InputPanel.bBack=Zurück +StartScreen.start.description=Ein neues Experiment mit der Eingabe der Parameter beginnen +StartScreen.load.description=Ein gespeichertes Experiment laden und direkt visualisieren lassen +StartScreen.LoadErrorDescription=Die ausgewählte Datei ist fehlerhaft oder keine gültige em-Datei! +StartScreen.LoadErrorTitle=Ladefehler +XInputPanel.bAddCoin=Münze hinzufügen +XInputPanel.bAddDice=Würfel hinzufügen +XInputPanel.bAdd=n-seitiges Objekt hinzufügen +XInputPanel.bRemoveLast=Rückgängig +XInputPanel.lXInput=

Objekte hinzufügen

+XInputPanel.description=Fügen Sie durch klicken auf die Buttons mindestens ein neues Objekt zum Experiment hinzu. +XInputPanel.ErrorMessageDescriptionNegative=Ein Objekt kann keine negative Anzahl an Seiten haben. Geben Sie eine ganze Zahl &ge 1 ein. +XInputPanel.ErrorMessageTitle=Eingabefehler +XInputPanel.ErrorMessageDescription=Geben Sie eine ganze Zahl &ge 1 ein. +Partition.Name.Sum=Summe der Seiten: +Partition.Name.SideCount=-mal Seite +Partition.Name.Doublet=Pasch (gleiche Seiten) +Partition.Name.NoDoublet=kein Pasch +Partition.Name.Property= zeigt Seite +Partition.Name.PropertyNot=zeigt nicht Seite +PartitionPanel.lSelection=Auswahl +PartitionPanel.bSameSide=Gleiche Seite +PartitionPanel.bSideCount=Anzahl Seite +PartitionPanel.bObjectProperty=Ein Objekt hat
eine Eigenschaft +PartitionPanel.bSum=Summe der Seiten +PartitionPanel.bCustomize=Eigene Partitionierung +PartitionPanel.lList=Partitionen +PartitionPanel.bRemove=Partition löschen +PartitionPanel.lTable=Partitionierung anpassen +PartitionPanel.bNew=neue Partition erstellen +PartitionPanel.bFill=Partition aus Rest +PartitionPanel.coin.head=Kopf +PartitionPanel.coin.tail=Zahl +PartitionPanel.DefaultPartitionName=Partition +YFrequencyPanel.lHeading=Häufigkeit der Beobachtungen +YFrequencyPanel.lDescription=Tragen Sie in der Tabelle die Häufigkeit der jeweiligen Beobachtung (Partition) ein. +YFrequencyTableModel.PartitionName=Beobachtung (Partition) +YFrequencyTableModel.PartitionElements=Elemente +YFrequencyTableModel.Frequency=Häufigkeit +YFrequencyPanel.ErrorMessageDescription=Die Häufigkeit muss eine relle Zahl &ge 0 sein. Die Eingabe darf in der Form "1,5", "1.5" oder "3/2" sein. +YFrequencyPanel.ErrorMessageTitle=Eingabefehler +DiagramPanel.StandartZoom=zur\u00fcck zu Standardzoom +DiagramPanel.iterationToLiklihood=f(Iteration)=Likelihood +DiagramPanel.twoCoinsPlot=Likelihood 3D +DiagramPanel.iterationToD=f(Iteration)=Statistischer Analysator +DiagramPanel.iterationToH=f(Iteration)=X-Korpus +DiagramPanel.iterationToP=f(Iteration)=Wahrscheinlichkeit +DiagramPanel.iterationToPSingle=f(Iteration)=Wahrscheinlichkeit Einzelereignis +DiagramPanel.d=Statistischer Analysator +DiagramPanel.l=Likelihood +DiagramPanel.p=Wahrscheinlichkeit +DiagramPanel.psingle=Wahrscheinlichkeit Einzelereignis +DiagramPanel.h=X-Korpus +DiagramPanel.d.short=d +DiagramPanel.l.short=L +DiagramPanel.p.short=p +DiagramPanel.psingle.short=p +DiagramPanel.h.short=h +DiagramPanel.twoCoinsPlot.short=L 3D +DiagramPanel.3DAxisX=p1(K) +DiagramPanel.3DAxisY=p2(K) +P0InputPanel.bAddP0=p0 hinzufügen +P0InputPanel.bRemoveP0=p0 entfernen +P0InputPanel.bEquipartition=gleichverteilt auffüllen +P0InputPanel.bRandomFilling=zufällig auffüllen +P0InputPanel.lP0Input=

Startwahrscheinlichkeitsverteilung eingeben

+P0InputPanel.description=Geben Sie eine oder mehrere Startwahrscheinlichkeiten an. Dabei muss die Summe der Wahrscheinlichkeiten je Objekt 1 ergeben und jede Wahrscheinlichkeit > 0 sein. +StartParameters.side=Seite +StartParameters.Tail=Z +StartParameters.Head=K +P0InputPanel.ErrorMessageTitle=Eingabefehler +P0InputPanel.ErrorMessageDescriptionNoP0=Es wurde keine Startwahrscheinlichkeitsverteilung eingegeben. Geben Sie mindestens eine gültige Startwahrscheinlichkeitsverteilung ein! +P0InputPanel.ErrorMessageDescriptionNoDouble=Die Wahrscheinlichkeit muss eine reelle Zahl > 0 und &le 1 sein. Die Eingabe darf in der Form "0,5", "0.5" or "2/3" sein. +P0InputPanel.ErrorMessageDescriptionSumNot1=Die Summe der Startwahrscheinlichkeiten für ein Objekt ist ungleich 1! +P0InputPanel.ErrorMessageDescriptionNoSelection=Es wurde keine Spalte markiert! +P0InputPanel.bAddP0ToolTip=Eine neue Spalte für eine weitere Startwahrscheinlichkeitsverteilung hinzufügen. +P0InputPanel.bRemoveP0ToolTip=Die angewählte Spalte löschen. +P0InputPanel.bEquipartitionToolTip=Die unbelegten Zellen der angewählten Spalte gleichmäßig auffüllen, so dass die Summe in der Spalte 1 ergibt. +P0InputPanel.bRandomFillingToolTip=Die unbelegten Zellen der angewählten Spalte zufällig auffüllen, so dass die Summe in der Spalte 1 ergibt. +P0InputPanel.bForwardToolTip=Die Eingabe der Startwahrscheinlichkeitsverteilungen abschließen und zur Berechnung von EM-Schritten übergehen. +P0InputPanel.bBackToolTip=Zurück zur Eingabe für die Häufigkeiten der Beobachtungen. +Options.limitlabel=Bitte ein Berechnungslimit in Prozent eingeben. +Options.ex1=Bitte einen gültigen Prozentwert eingeben! +Options.ex2=Parserfehler. Bitte den Input prüfen +Options.c=Abbrechen +TableViewPanel.Event=Ereignis +ModuleInfo.info=Dieses Modul behandelt den EM-Algorithmus. +ModuleInfo.license=GPL. Grafiken von Onebit. +ModuleInfo.name=EM-Algorithmus \ No newline at end of file diff --git a/bin/org/jalgo/module/em/en.properties b/bin/org/jalgo/module/em/en.properties new file mode 100644 index 0000000..b3f8f9f --- /dev/null +++ b/bin/org/jalgo/module/em/en.properties @@ -0,0 +1,111 @@ +ObjectName=D +ObjectName.2=Coin +ObjectName.4=Tetrahedron +ObjectName.6=Dice +ObjectName.8=Octahedron +Controller.togglePMode=toggle presentation mode +ToolBar.save=save experiment +ToolBar.load=load experiment +ToolBar.preferences=preferences +ToolBar.wback=EM-step back +ToolBar.back=single step back +ToolBar.forw=single step forward +ToolBar.wforw=EM-step forward +ToolBar.home=Back to inputscreens +ToolBar.run=run EM-algorithm until convergence +Menu.hybrid=hybrid view +Menu.table=table view +Menu.diagram=diagram view +Menu.log=logarithmic Likelihood +Menu.presentation=presentation mode +IOController.FileChooser=Choose File +InputPanel.bForward=Next +InputPanel.bBack=Back +StartScreen.start.description=Start a new experiment with entering all needed parameters +StartScreen.load.description=Load a saved experiment and start the visualization immediately +StartScreen.LoadErrorDescription=The chosen file is invalid. +StartScreen.LoadErrorTitle=Load Error +XInputPanel.bAddCoin=Add coin +XInputPanel.bAddDice=Add dice +XInputPanel.bAdd=Add n-sided object +XInputPanel.bRemoveLast=undo +XInputPanel.lXInput=Add objects +XInputPanel.description=Add at least one object to the experiment by clicking on the buttons. +XInputPanel.ErrorMessageDescriptionNegative=The number of sides of an object has to be &ge 1. +XInputPanel.ErrorMessageDescription=Please enter a valid integer &ge 1. +XInputPanel.ErrorMessageTitle=Input Error +Partition.Name.Sum=Sum: +Partition.Name.SideCount=-times side +Partition.Name.Doublet=Doublet (same sides) +Partition.Name.NoDoublet=No doublet +Partition.Name.Property= shows side +Partition.Name.PropertyNot=does not show side +PartitionPanel.lSelection=Selection +PartitionPanel.bSameSide=Same side +PartitionPanel.bSideCount=Side frequency +PartitionPanel.bObjectProperty=A Object has a
specific property +PartitionPanel.bSum=Sum +PartitionPanel.bCustomize=Own partitioning +PartitionPanel.lList=Partitioning +PartitionPanel.bRemove=Delete partition +PartitionPanel.lTable=Customize Partitioning +PartitionPanel.bNew=Create new partition +PartitionPanel.bFill=Partition from rest +PartitionPanel.coin.head=Head +PartitionPanel.coin.tail=Tail +PartitionPanel.DefaultPartitionName=partition +YFrequencyPanel.lHeading=Observation's frequency +YFrequencyPanel.lDescription=Please enter the frequency of each observation into the table. +YFrequencyTableModel.PartitionName=Observation (partition) +YFrequencyTableModel.PartitionElements=Elements +YFrequencyTableModel.Frequency=Frequency +YFrequencyPanel.ErrorMessageDescription=The frequency must be a real number &ge 0. The entered value could be in the format "1,5", "1.5" or "3/2". +YFrequencyPanel.ErrorMessageTitle=Input Error +DiagramPanel.StandartZoom=restore standardzoom +DiagramPanel.iterationToLiklihood=f(Iteration)=Likelihood +DiagramPanel.twoCoinsPlot=Likelihood 3D +DiagramPanel.iterationToD=f(Iteration)=Statistical Analyzer +DiagramPanel.iterationToH=f(Iteration)=X-Corpus +DiagramPanel.iterationToP=f(Iteration)=Probability +DiagramPanel.iterationToP=f(Iteration)=Probability single events +DiagramPanel.d=Statistical Analyzer +DiagramPanel.l=Likelihood +DiagramPanel.p=Probability +DiagramPanel.psingle=Probability Single Event +DiagramPanel.h=X-Corpus +DiagramPanel.d.short=d +DiagramPanel.l.short=L +DiagramPanel.p.short=p +DiagramPanel.psingle.short=p +DiagramPanel.h.short=h +DiagramPanel.twoCoinsPlot.short=L 3D +DiagramPanel.3DAxisX=p1(H) +DiagramPanel.3DAxisY=p2(H) +P0InputPanel.bAddP0=add p0 +P0InputPanel.bRemoveP0=remove p0 +P0InputPanel.bEquipartition=fill uniform distributed +P0InputPanel.bRandomFilling=fill randomly +P0InputPanel.lP0Input=

Enter StartProbabilityDistribution

+StartParameters.side=Side +StartParameters.Tail=T +StartParameters.Head=H +P0InputPanel.description=Enter one or more start probability distributions. The sum of the start probabilities for each Object has to be 1. +P0InputPanel.ErrorMessageTitle=Input Error +P0InputPanel.ErrorMessageDescriptionNoP0=No Start Probability Distribution was entered. Enter at least one Start Probability Distribution! +P0InputPanel.ErrorMessageDescriptionNoDouble=The frequency must be a real number > 0 and &le 1. The entered value could be in the format "0,5", "0.5" or "2/3". +P0InputPanel.ErrorMessageDescriptionSumNot1=The Sum of the start probabilities for one object is not 1! +P0InputPanel.ErrorMessageDescriptionNoSelection=No Column has been selected! +P0InputPanel.bAddP0ToolTip=Adds a new column for a new start probability distribution. +P0InputPanel.bRemoveP0ToolTip=Deletes the selected column. +P0InputPanel.bEquipartitionToolTip=Fills the empty cells of the selected column equally, that the sum in the column is 1. +P0InputPanel.bRandomFillingToolTip=Fills the empty cells of the selected column randomly, that the sum in the column is 1. +P0InputPanel.bForwardToolTip=Completes the input of start probability distributions and starts the calculation of EM steps. +P0InputPanel.bBackToolTip=Steps back to the input for observation's frequency." +Options.limitlabel=Please enter a calculation limit in percentage. +Options.ex1=Please enter a valid percentage! +Options.ex2=Error while Parsing. Check input! +Options.c=Cancel +TableViewPanel.Event=Event +ModuleInfo.info=This module is about the EM-Algorithm. +ModuleInfo.license=GPL. Graphics from Onebit. +ModuleInfo.name=EM-Algorithm \ No newline at end of file diff --git a/bin/org/jalgo/module/em/gui/StartButton.class b/bin/org/jalgo/module/em/gui/StartButton.class new file mode 100644 index 0000000..2253e7d Binary files /dev/null and b/bin/org/jalgo/module/em/gui/StartButton.class differ diff --git a/bin/org/jalgo/module/em/gui/StartScreen$StartScreenActionHandler.class b/bin/org/jalgo/module/em/gui/StartScreen$StartScreenActionHandler.class new file mode 100644 index 0000000..df4b1ea Binary files /dev/null and b/bin/org/jalgo/module/em/gui/StartScreen$StartScreenActionHandler.class differ diff --git a/bin/org/jalgo/module/em/gui/StartScreen.class b/bin/org/jalgo/module/em/gui/StartScreen.class new file mode 100644 index 0000000..d8a08aa Binary files /dev/null and b/bin/org/jalgo/module/em/gui/StartScreen.class differ diff --git a/bin/org/jalgo/module/em/gui/UIConstants.class b/bin/org/jalgo/module/em/gui/UIConstants.class new file mode 100644 index 0000000..36d65ee Binary files /dev/null and b/bin/org/jalgo/module/em/gui/UIConstants.class differ diff --git a/bin/org/jalgo/module/em/gui/input/InputPanel.class b/bin/org/jalgo/module/em/gui/input/InputPanel.class new file mode 100644 index 0000000..bbf1521 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/InputPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/InputStringParser.class b/bin/org/jalgo/module/em/gui/input/InputStringParser.class new file mode 100644 index 0000000..f704d7e Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/InputStringParser.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$1.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$1.class new file mode 100644 index 0000000..f00db3f Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$1.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$2.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$2.class new file mode 100644 index 0000000..45328f2 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$2.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$3.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$3.class new file mode 100644 index 0000000..d147ba0 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$3.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$4.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$4.class new file mode 100644 index 0000000..7e20d43 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$4.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$5.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$5.class new file mode 100644 index 0000000..443f4e6 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$5.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$6.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$6.class new file mode 100644 index 0000000..ef1a3cd Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$6.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel$MyTableCellEditor.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel$MyTableCellEditor.class new file mode 100644 index 0000000..2bb5373 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel$MyTableCellEditor.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputPanel.class b/bin/org/jalgo/module/em/gui/input/P0InputPanel.class new file mode 100644 index 0000000..94235a5 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/P0InputTableModel.class b/bin/org/jalgo/module/em/gui/input/P0InputTableModel.class new file mode 100644 index 0000000..3fae638 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/P0InputTableModel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionListModel.class b/bin/org/jalgo/module/em/gui/input/PartitionListModel.class new file mode 100644 index 0000000..b359493 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionListModel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionPanel$1.class b/bin/org/jalgo/module/em/gui/input/PartitionPanel$1.class new file mode 100644 index 0000000..46209e7 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionPanel$1.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionPanel.class b/bin/org/jalgo/module/em/gui/input/PartitionPanel.class new file mode 100644 index 0000000..e3ae7d6 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionTable$1.class b/bin/org/jalgo/module/em/gui/input/PartitionTable$1.class new file mode 100644 index 0000000..054e345 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionTable$1.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionTable$TableMouseAdapter.class b/bin/org/jalgo/module/em/gui/input/PartitionTable$TableMouseAdapter.class new file mode 100644 index 0000000..7ea7a2a Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionTable$TableMouseAdapter.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionTable.class b/bin/org/jalgo/module/em/gui/input/PartitionTable.class new file mode 100644 index 0000000..b443357 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionTable.class differ diff --git a/bin/org/jalgo/module/em/gui/input/PartitionTableModel.class b/bin/org/jalgo/module/em/gui/input/PartitionTableModel.class new file mode 100644 index 0000000..5b57025 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/PartitionTableModel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/XInputPanel$SideVerifier.class b/bin/org/jalgo/module/em/gui/input/XInputPanel$SideVerifier.class new file mode 100644 index 0000000..eb1acca Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/XInputPanel$SideVerifier.class differ diff --git a/bin/org/jalgo/module/em/gui/input/XInputPanel.class b/bin/org/jalgo/module/em/gui/input/XInputPanel.class new file mode 100644 index 0000000..6708605 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/XInputPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor$FrequencyVerifier.class b/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor$FrequencyVerifier.class new file mode 100644 index 0000000..1d07dbe Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor$FrequencyVerifier.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor.class b/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor.class new file mode 100644 index 0000000..410b444 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyCellEditor.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1.class b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1.class new file mode 100644 index 0000000..080bdef Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable$1.class b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable$1.class new file mode 100644 index 0000000..30fc783 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable$1.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable.class b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable.class new file mode 100644 index 0000000..8dc3b7e Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$1MyTable.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$2.class b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$2.class new file mode 100644 index 0000000..2bc9d05 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel$2.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyPanel.class b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel.class new file mode 100644 index 0000000..60e650f Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/YFrequencyTableModel.class b/bin/org/jalgo/module/em/gui/input/YFrequencyTableModel.class new file mode 100644 index 0000000..ac83f20 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/YFrequencyTableModel.class differ diff --git a/bin/org/jalgo/module/em/gui/input/package-info.class b/bin/org/jalgo/module/em/gui/input/package-info.class new file mode 100644 index 0000000..67260b3 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/input/package-info.class differ diff --git a/bin/org/jalgo/module/em/gui/output/diagram/DiagramFactory.class b/bin/org/jalgo/module/em/gui/output/diagram/DiagramFactory.class new file mode 100644 index 0000000..40dd41d Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/diagram/DiagramFactory.class differ diff --git a/bin/org/jalgo/module/em/gui/output/diagram/DiagramPanel.class b/bin/org/jalgo/module/em/gui/output/diagram/DiagramPanel.class new file mode 100644 index 0000000..3aa4fba Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/diagram/DiagramPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/output/diagram/package-info.class b/bin/org/jalgo/module/em/gui/output/diagram/package-info.class new file mode 100644 index 0000000..5d6078e Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/diagram/package-info.class differ diff --git a/bin/org/jalgo/module/em/gui/output/table/TableModel.class b/bin/org/jalgo/module/em/gui/output/table/TableModel.class new file mode 100644 index 0000000..18780e0 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/table/TableModel.class differ diff --git a/bin/org/jalgo/module/em/gui/output/table/TableModelLike.class b/bin/org/jalgo/module/em/gui/output/table/TableModelLike.class new file mode 100644 index 0000000..9c11265 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/table/TableModelLike.class differ diff --git a/bin/org/jalgo/module/em/gui/output/table/TableModelSE.class b/bin/org/jalgo/module/em/gui/output/table/TableModelSE.class new file mode 100644 index 0000000..043b4be Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/table/TableModelSE.class differ diff --git a/bin/org/jalgo/module/em/gui/output/table/TableViewPanel$ColumnHeaderListener.class b/bin/org/jalgo/module/em/gui/output/table/TableViewPanel$ColumnHeaderListener.class new file mode 100644 index 0000000..909f6c5 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/table/TableViewPanel$ColumnHeaderListener.class differ diff --git a/bin/org/jalgo/module/em/gui/output/table/TableViewPanel.class b/bin/org/jalgo/module/em/gui/output/table/TableViewPanel.class new file mode 100644 index 0000000..250fd5d Binary files /dev/null and b/bin/org/jalgo/module/em/gui/output/table/TableViewPanel.class differ diff --git a/bin/org/jalgo/module/em/gui/package-info.class b/bin/org/jalgo/module/em/gui/package-info.class new file mode 100644 index 0000000..478abf1 Binary files /dev/null and b/bin/org/jalgo/module/em/gui/package-info.class differ diff --git a/bin/org/jalgo/module/em/res.properties b/bin/org/jalgo/module/em/res.properties new file mode 100644 index 0000000..94b31c1 --- /dev/null +++ b/bin/org/jalgo/module/em/res.properties @@ -0,0 +1,50 @@ +HelpSet_Name=/help/jhelp/em_help.hs + +StartScreen.load=/pics/start_load.png +StartScreen.load.rollover=/pics/start_load_rollover.png +StartScreen.start=/pics/start.png +StartScreen.start.rollover=/pics/start_rollover.png + +Objects=/pics/ +Object.2=/pics/2.png +Object.6=/pics/6.png + +ButtonIcon.bForward=/pics/nextFrame.png +ButtonIcon.bForward.small=/pics/small/nextFrame.png + +ButtonIcon.bBack=/pics/backFrame.png +ButtonIcon.bBack.small=/pics/small/backFrame.png + +ButtonIcon.bAddCoin=/pics/addCoin.png +ButtonIcon.bAddCoin.small=/pics/small/addCoin.png +ButtonIcon.bAddDice=/pics/addDice.png +ButtonIcon.bAddDice.small=/pics/small/addDice.png + +ButtonIcon.bAdd=/pics/addN.png +ButtonIcon.bAdd.small=/pics/small/addN.png + +ButtonIcon.bNew=/pics/new.png +ButtonIcon.bNew.small=/pics/small/new.png + +ButtonIcon.bRemove=/pics/remove.png +ButtonIcon.bRemove.small=/pics/small/remove.png + +ButtonIcon.bFill=/pics/fillUp.png +ButtonIcon.bFill.small=/pics/small/fillUp.png + +ButtonIcon.bRandomFilling=/pics/random.png +ButtonIcon.bRandomFilling.small=/pics/small/random.png + +ToolBarIcon.save=/pics/save.png +ToolBarIcon.load=/pics/load.png +ToolBarIcon.back=/previous.png +ToolBarIcon.forw=/next.png +ToolBarIcon.wback=/clear.png +ToolBarIcon.wforw=/last.png +ToolBarIcon.beamerOn=/pics/beamerOn.png +ToolBarIcon.beamerOff=/pics/beamerOff.png +ToolBarIcon.preferences=/pics/preferences.png +ToolBarIcon.run=/pics/run.png +ToolBarIcon.home=/pics/home.png + +EM.ICON=/pics/logo_small.png \ No newline at end of file diff --git a/bin/org/jalgo/module/em/test/EMDataTest.class b/bin/org/jalgo/module/em/test/EMDataTest.class new file mode 100644 index 0000000..5aa78c3 Binary files /dev/null and b/bin/org/jalgo/module/em/test/EMDataTest.class differ diff --git a/bin/org/jalgo/module/em/test/EMModuleTest.class b/bin/org/jalgo/module/em/test/EMModuleTest.class new file mode 100644 index 0000000..ae3718a Binary files /dev/null and b/bin/org/jalgo/module/em/test/EMModuleTest.class differ diff --git a/bin/org/jalgo/module/em/test/EMStateTest.class b/bin/org/jalgo/module/em/test/EMStateTest.class new file mode 100644 index 0000000..72d284e Binary files /dev/null and b/bin/org/jalgo/module/em/test/EMStateTest.class differ diff --git a/bin/org/jalgo/module/em/test/EventTest.class b/bin/org/jalgo/module/em/test/EventTest.class new file mode 100644 index 0000000..1666def Binary files /dev/null and b/bin/org/jalgo/module/em/test/EventTest.class differ diff --git a/bin/org/jalgo/module/em/test/LogStateTest.class b/bin/org/jalgo/module/em/test/LogStateTest.class new file mode 100644 index 0000000..3acce87 Binary files /dev/null and b/bin/org/jalgo/module/em/test/LogStateTest.class differ diff --git a/bin/org/jalgo/module/em/test/PartitionTest.class b/bin/org/jalgo/module/em/test/PartitionTest.class new file mode 100644 index 0000000..510e5ee Binary files /dev/null and b/bin/org/jalgo/module/em/test/PartitionTest.class differ diff --git a/bin/org/jalgo/module/em/test/StartParametersTest.class b/bin/org/jalgo/module/em/test/StartParametersTest.class new file mode 100644 index 0000000..01953e7 Binary files /dev/null and b/bin/org/jalgo/module/em/test/StartParametersTest.class differ diff --git a/bin/org/jalgo/module/em/test/TestSuite.class b/bin/org/jalgo/module/em/test/TestSuite.class new file mode 100644 index 0000000..158e7cb Binary files /dev/null and b/bin/org/jalgo/module/em/test/TestSuite.class differ diff --git a/bin/org/jalgo/module/em/test/package-info.class b/bin/org/jalgo/module/em/test/package-info.class new file mode 100644 index 0000000..6d9320e Binary files /dev/null and b/bin/org/jalgo/module/em/test/package-info.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$1.class b/bin/org/jalgo/module/heapsort/GuiController$1.class new file mode 100644 index 0000000..23d0526 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$1.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$1.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$1.class new file mode 100644 index 0000000..9af8673 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$1.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$2.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$2.class new file mode 100644 index 0000000..2285311 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$2.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$3.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$3.class new file mode 100644 index 0000000..7098b86 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$3.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$4.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$4.class new file mode 100644 index 0000000..36a3944 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$4.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$5.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$5.class new file mode 100644 index 0000000..55b2bcf Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$5.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$6.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$6.class new file mode 100644 index 0000000..fe7f30b Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$6.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState$7.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$7.class new file mode 100644 index 0000000..df41b9c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState$7.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$DerivationState.class b/bin/org/jalgo/module/heapsort/GuiController$DerivationState.class new file mode 100644 index 0000000..b110634 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$DerivationState.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$GState.class b/bin/org/jalgo/module/heapsort/GuiController$GState.class new file mode 100644 index 0000000..6d7a82c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$GState.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$InputState$1.class b/bin/org/jalgo/module/heapsort/GuiController$InputState$1.class new file mode 100644 index 0000000..ba67b36 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$InputState$1.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$InputState$2.class b/bin/org/jalgo/module/heapsort/GuiController$InputState$2.class new file mode 100644 index 0000000..066ad4b Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$InputState$2.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$InputState$3.class b/bin/org/jalgo/module/heapsort/GuiController$InputState$3.class new file mode 100644 index 0000000..85f897c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$InputState$3.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$InputState.class b/bin/org/jalgo/module/heapsort/GuiController$InputState.class new file mode 100644 index 0000000..6f563fb Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$InputState.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$ListItem.class b/bin/org/jalgo/module/heapsort/GuiController$ListItem.class new file mode 100644 index 0000000..f688675 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$ListItem.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController$UpdateThread.class b/bin/org/jalgo/module/heapsort/GuiController$UpdateThread.class new file mode 100644 index 0000000..2c85223 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController$UpdateThread.class differ diff --git a/bin/org/jalgo/module/heapsort/GuiController.class b/bin/org/jalgo/module/heapsort/GuiController.class new file mode 100644 index 0000000..b748445 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/GuiController.class differ diff --git a/bin/org/jalgo/module/heapsort/HeapsortApplet$1.class b/bin/org/jalgo/module/heapsort/HeapsortApplet$1.class new file mode 100644 index 0000000..2c64130 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/HeapsortApplet$1.class differ diff --git a/bin/org/jalgo/module/heapsort/HeapsortApplet$2.class b/bin/org/jalgo/module/heapsort/HeapsortApplet$2.class new file mode 100644 index 0000000..ba41d1b Binary files /dev/null and b/bin/org/jalgo/module/heapsort/HeapsortApplet$2.class differ diff --git a/bin/org/jalgo/module/heapsort/HeapsortApplet$UpdateThread.class b/bin/org/jalgo/module/heapsort/HeapsortApplet$UpdateThread.class new file mode 100644 index 0000000..5ce00bd Binary files /dev/null and b/bin/org/jalgo/module/heapsort/HeapsortApplet$UpdateThread.class differ diff --git a/bin/org/jalgo/module/heapsort/HeapsortApplet.class b/bin/org/jalgo/module/heapsort/HeapsortApplet.class new file mode 100644 index 0000000..92023f6 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/HeapsortApplet.class differ diff --git a/bin/org/jalgo/module/heapsort/ModuleConnector$1.class b/bin/org/jalgo/module/heapsort/ModuleConnector$1.class new file mode 100644 index 0000000..c6f9cc5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/ModuleConnector$1.class differ diff --git a/bin/org/jalgo/module/heapsort/ModuleConnector.class b/bin/org/jalgo/module/heapsort/ModuleConnector.class new file mode 100644 index 0000000..2248487 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/heapsort/ModuleInfo.class b/bin/org/jalgo/module/heapsort/ModuleInfo.class new file mode 100644 index 0000000..fe202df Binary files /dev/null and b/bin/org/jalgo/module/heapsort/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/heapsort/Subject$Notifier.class b/bin/org/jalgo/module/heapsort/Subject$Notifier.class new file mode 100644 index 0000000..e015a4a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/Subject$Notifier.class differ diff --git a/bin/org/jalgo/module/heapsort/Subject.class b/bin/org/jalgo/module/heapsort/Subject.class new file mode 100644 index 0000000..db441d1 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/Subject.class differ diff --git a/bin/org/jalgo/module/heapsort/Util.class b/bin/org/jalgo/module/heapsort/Util.class new file mode 100644 index 0000000..34e9f33 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/Util.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animation.class b/bin/org/jalgo/module/heapsort/anim/Animation.class new file mode 100644 index 0000000..9351df7 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animation.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationListener.class b/bin/org/jalgo/module/heapsort/anim/AnimationListener.class new file mode 100644 index 0000000..424ca79 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationListener.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State.class b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State.class new file mode 100644 index 0000000..5e06f83 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State1.class b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State1.class new file mode 100644 index 0000000..477f290 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State1.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State2.class b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State2.class new file mode 100644 index 0000000..238eddc Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State2.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State3.class b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State3.class new file mode 100644 index 0000000..b8c308a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity$State3.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity.class b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity.class new file mode 100644 index 0000000..82b7354 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/AnimationTimeEntity.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossfader.class b/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossfader.class new file mode 100644 index 0000000..2b093b8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossfader.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossmover.class b/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossmover.class new file mode 100644 index 0000000..d2bce0a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$AbstractCrossmover.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$CrossfaderFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$CrossfaderFactory.class new file mode 100644 index 0000000..b83a15d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$CrossfaderFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$CrossmoverFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$CrossmoverFactory.class new file mode 100644 index 0000000..ffca06e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$CrossmoverFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfader.class b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfader.class new file mode 100644 index 0000000..b567988 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfader.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfaderFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfaderFactory.class new file mode 100644 index 0000000..bf3a58a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossfaderFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmover.class b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmover.class new file mode 100644 index 0000000..adcaa9e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmover.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmoverFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmoverFactory.class new file mode 100644 index 0000000..253faf3 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$LinearCrossmoverFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$MarkingRectAdapter.class b/bin/org/jalgo/module/heapsort/anim/Animations$MarkingRectAdapter.class new file mode 100644 index 0000000..2a4bbe8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$MarkingRectAdapter.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$NodeAdapter.class b/bin/org/jalgo/module/heapsort/anim/Animations$NodeAdapter.class new file mode 100644 index 0000000..ccf7211 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$NodeAdapter.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SequenceElementAdapter.class b/bin/org/jalgo/module/heapsort/anim/Animations$SequenceElementAdapter.class new file mode 100644 index 0000000..ad63eda Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SequenceElementAdapter.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SmoothBlinker.class b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothBlinker.class new file mode 100644 index 0000000..3e171e5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothBlinker.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfader.class b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfader.class new file mode 100644 index 0000000..cbb1bc7 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfader.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfaderFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfaderFactory.class new file mode 100644 index 0000000..e2807a7 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossfaderFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmover.class b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmover.class new file mode 100644 index 0000000..8cbd2eb Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmover.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmoverFactory.class b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmoverFactory.class new file mode 100644 index 0000000..725de6c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$SmoothCrossmoverFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$TextAdapter.class b/bin/org/jalgo/module/heapsort/anim/Animations$TextAdapter.class new file mode 100644 index 0000000..507977d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$TextAdapter.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations$Zoomer.class b/bin/org/jalgo/module/heapsort/anim/Animations$Zoomer.class new file mode 100644 index 0000000..5a5ea04 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations$Zoomer.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Animations.class b/bin/org/jalgo/module/heapsort/anim/Animations.class new file mode 100644 index 0000000..8e10f31 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Animations.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/CompositeAnimation.class b/bin/org/jalgo/module/heapsort/anim/CompositeAnimation.class new file mode 100644 index 0000000..2a8cdfd Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/CompositeAnimation.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Fadeable.class b/bin/org/jalgo/module/heapsort/anim/Fadeable.class new file mode 100644 index 0000000..b2b6507 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Fadeable.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Moveable.class b/bin/org/jalgo/module/heapsort/anim/Moveable.class new file mode 100644 index 0000000..dd1b521 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Moveable.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/ParallelAnimation.class b/bin/org/jalgo/module/heapsort/anim/ParallelAnimation.class new file mode 100644 index 0000000..61ec13d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/ParallelAnimation.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/ProxyAnimation.class b/bin/org/jalgo/module/heapsort/anim/ProxyAnimation.class new file mode 100644 index 0000000..a93a7f5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/ProxyAnimation.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/Scalable.class b/bin/org/jalgo/module/heapsort/anim/Scalable.class new file mode 100644 index 0000000..de4cd43 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/Scalable.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/SequentialAnimation$AnimItem.class b/bin/org/jalgo/module/heapsort/anim/SequentialAnimation$AnimItem.class new file mode 100644 index 0000000..7b4d78a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/SequentialAnimation$AnimItem.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/SequentialAnimation.class b/bin/org/jalgo/module/heapsort/anim/SequentialAnimation.class new file mode 100644 index 0000000..459c190 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/SequentialAnimation.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/TimeEntity.class b/bin/org/jalgo/module/heapsort/anim/TimeEntity.class new file mode 100644 index 0000000..9ab86eb Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/TimeEntity.class differ diff --git a/bin/org/jalgo/module/heapsort/anim/TimeRoot.class b/bin/org/jalgo/module/heapsort/anim/TimeRoot.class new file mode 100644 index 0000000..6301899 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/anim/TimeRoot.class differ diff --git a/bin/org/jalgo/module/heapsort/de.properties b/bin/org/jalgo/module/heapsort/de.properties new file mode 100644 index 0000000..a968de0 --- /dev/null +++ b/bin/org/jalgo/module/heapsort/de.properties @@ -0,0 +1,28 @@ +Module_name=Heapsort +Module_version=1.0 +Module_authors=Matthias Büchse +Module_license=GNU General Public License +Module_description=Dieses Modul behandelt den Sortieralgorithmus Heapsort. + +Gui.Input_title=Eingabe der Folge +Gui.Input_label=Neue Zahl +Gui.Input_add=Hinzufügen +Gui.Input_start=Algorithmus starten + +Gui.Menu_lecture=Vorlesungsmodus + +Gui.reset=Zurück zum Anfang +Gui.back=Schritt zurückgehen +Gui.macroback=Makroschritt zurückgehen +Gui.step=Schritt vorwärtsgehen +Gui.macrostep=Makroschritt vorwärtsgehen +Gui.finish=Algorithmus zuendeführen +Gui.suspend=Makroschritt unterbrechen + +Gui.Hint_instructions=Geben Sie bis zu 31 paarweise verschiedene natürliche Zahlen zwischen 1 und 99 ein.\n\nEnter bestätigt die eingebene Zahl. Bei leerer Eingabe wird der Algorithmus gestartet. +Gui.Hint_double=Es sind keine doppelten Einträge erlaubt! +Gui.Hint_limit=Sie haben 31 Zahlen eingegeben. + +Gui.Log_title=Protokoll +Gui.Log_header=Sinkenlassen +Gui.Log_header2=von/nach diff --git a/bin/org/jalgo/module/heapsort/en.properties b/bin/org/jalgo/module/heapsort/en.properties new file mode 100644 index 0000000..0ad849d --- /dev/null +++ b/bin/org/jalgo/module/heapsort/en.properties @@ -0,0 +1,28 @@ +Module_name=Heapsort +Module_version=1.0 +Module_authors=Matthias Büchse +Module_license=GNU General Public License +Module_description=This module is all about the sorting algorithm Heapsort. + +Gui.Input_title=Input sequence +Gui.Input_label=New number +Gui.Input_add=Add +Gui.Input_start=Start algorithm + +Gui.Menu_lecture=Lecture mode + +Gui.reset=Go right to the beginning +Gui.back=Go back +Gui.macroback=Go back (macro step) +Gui.step=Make a step +Gui.macrostep=Make a macro step +Gui.finish=Finish algorithm +Gui.suspend=Suspend macro step animation + +Gui.Hint_instructions=Enter up to 31 unique natural numbers from 1 to 99.\n\nPress return to confirm your number. If the input field is empty, pressing return will start the algorithm. +Gui.Hint_double=Sequence items have to be distinct! +Gui.Hint_limit=You have entered 31 numbers. + +Gui.Log_title=Log +Gui.Log_header=Sinkenlassen +Gui.Log_header2=from/to diff --git a/bin/org/jalgo/module/heapsort/model/Action.class b/bin/org/jalgo/module/heapsort/model/Action.class new file mode 100644 index 0000000..3378e96 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Action.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$1.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$1.class new file mode 100644 index 0000000..5fba134 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$1.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$10.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$10.class new file mode 100644 index 0000000..341ad54 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$10.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$11.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$11.class new file mode 100644 index 0000000..7adf453 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$11.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$12.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$12.class new file mode 100644 index 0000000..0b50a16 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$12.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$2.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$2.class new file mode 100644 index 0000000..8fb6fcc Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$2.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$3.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$3.class new file mode 100644 index 0000000..df6ce9b Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$3.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$4.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$4.class new file mode 100644 index 0000000..346beff Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$4.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$5.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$5.class new file mode 100644 index 0000000..9c31d0c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$5.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$6.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$6.class new file mode 100644 index 0000000..f8890d8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$6.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$7.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$7.class new file mode 100644 index 0000000..cc1da1d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$7.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$8.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$8.class new file mode 100644 index 0000000..5c90919 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$8.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$9.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$9.class new file mode 100644 index 0000000..fbb8197 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions$9.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Actions.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions.class new file mode 100644 index 0000000..685fa35 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Actions.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Done.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Done.class new file mode 100644 index 0000000..15b5737 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Done.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$HeapsortState.class b/bin/org/jalgo/module/heapsort/model/Heapsort$HeapsortState.class new file mode 100644 index 0000000..9cb2df4 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$HeapsortState.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$InitialState.class b/bin/org/jalgo/module/heapsort/model/Heapsort$InitialState.class new file mode 100644 index 0000000..cd0b5e8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$InitialState.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$ModelChangedNotifier.class b/bin/org/jalgo/module/heapsort/model/Heapsort$ModelChangedNotifier.class new file mode 100644 index 0000000..eb76c11 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$ModelChangedNotifier.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase0.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase0.class new file mode 100644 index 0000000..2d939df Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase0.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1.class new file mode 100644 index 0000000..dbfafdb Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12.class new file mode 100644 index 0000000..24c1ae8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sl.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sl.class new file mode 100644 index 0000000..255ee3a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sl.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sla.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sla.class new file mode 100644 index 0000000..2732cd7 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12sla.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12slb.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12slb.class new file mode 100644 index 0000000..dac1732 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase12slb.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1a.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1a.class new file mode 100644 index 0000000..a258796 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1a.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1b.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1b.class new file mode 100644 index 0000000..8f6b03d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase1b.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2.class new file mode 100644 index 0000000..aa6f930 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2a.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2a.class new file mode 100644 index 0000000..1dd7ad5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2a.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2b.class b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2b.class new file mode 100644 index 0000000..da47112 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort$Phase2b.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Heapsort.class b/bin/org/jalgo/module/heapsort/model/Heapsort.class new file mode 100644 index 0000000..794da3e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Heapsort.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Model.class b/bin/org/jalgo/module/heapsort/model/Model.class new file mode 100644 index 0000000..05ceb65 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Model.class differ diff --git a/bin/org/jalgo/module/heapsort/model/ModelListener.class b/bin/org/jalgo/module/heapsort/model/ModelListener.class new file mode 100644 index 0000000..054f723 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/ModelListener.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer$Level.class b/bin/org/jalgo/module/heapsort/model/Sequencer$Level.class new file mode 100644 index 0000000..92b45f6 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer$Level.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer$MyEntry.class b/bin/org/jalgo/module/heapsort/model/Sequencer$MyEntry.class new file mode 100644 index 0000000..919c898 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer$MyEntry.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyBack.class b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyBack.class new file mode 100644 index 0000000..b2b30d8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyBack.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStep.class b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStep.class new file mode 100644 index 0000000..5313603 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStep.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStepAvail.class b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStepAvail.class new file mode 100644 index 0000000..a17c218 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer$NotifyStepAvail.class differ diff --git a/bin/org/jalgo/module/heapsort/model/Sequencer.class b/bin/org/jalgo/module/heapsort/model/Sequencer.class new file mode 100644 index 0000000..23410c8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/Sequencer.class differ diff --git a/bin/org/jalgo/module/heapsort/model/SequencerListener.class b/bin/org/jalgo/module/heapsort/model/SequencerListener.class new file mode 100644 index 0000000..171c34e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/SequencerListener.class differ diff --git a/bin/org/jalgo/module/heapsort/model/State.class b/bin/org/jalgo/module/heapsort/model/State.class new file mode 100644 index 0000000..0834140 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/model/State.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$CanvasEntityComparator.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$CanvasEntityComparator.class new file mode 100644 index 0000000..cf5a4d3 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$CanvasEntityComparator.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ClearDirtyVisitor.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ClearDirtyVisitor.class new file mode 100644 index 0000000..5568594 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ClearDirtyVisitor.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ComputeDirtyVisitor.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ComputeDirtyVisitor.class new file mode 100644 index 0000000..96cb5b5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity$ComputeDirtyVisitor.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntity.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity.class new file mode 100644 index 0000000..ba0d44a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntity.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.class new file mode 100644 index 0000000..8cce3f3 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.class b/bin/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.class new file mode 100644 index 0000000..9fa97e3 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/Edge.class b/bin/org/jalgo/module/heapsort/renderer/Edge.class new file mode 100644 index 0000000..9c8387f Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/Edge.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/MarkingRect.class b/bin/org/jalgo/module/heapsort/renderer/MarkingRect.class new file mode 100644 index 0000000..406163c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/MarkingRect.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/Node.class b/bin/org/jalgo/module/heapsort/renderer/Node.class new file mode 100644 index 0000000..f7f5614 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/Node.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$EdgeJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$EdgeJava2D.class new file mode 100644 index 0000000..100225a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$EdgeJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$MarkingRectJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$MarkingRectJava2D.class new file mode 100644 index 0000000..a6f348a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$MarkingRectJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$NodeJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$NodeJava2D.class new file mode 100644 index 0000000..8fc95e8 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$NodeJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderCanvas.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderCanvas.class new file mode 100644 index 0000000..795ba69 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderCanvas.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderVisitor.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderVisitor.class new file mode 100644 index 0000000..14d4b79 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RenderVisitor.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$Renderable.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$Renderable.class new file mode 100644 index 0000000..1427cca Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$Renderable.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RootJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RootJava2D.class new file mode 100644 index 0000000..1419f7a Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$RootJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$SequenceElementJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$SequenceElementJava2D.class new file mode 100644 index 0000000..c541474 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$SequenceElementJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$TextJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$TextJava2D.class new file mode 100644 index 0000000..98c3c7b Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D$TextJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/RenderJava2D.class b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D.class new file mode 100644 index 0000000..d70396c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/RenderJava2D.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/Renderer.class b/bin/org/jalgo/module/heapsort/renderer/Renderer.class new file mode 100644 index 0000000..ce13d10 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/Renderer.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/SequenceElement.class b/bin/org/jalgo/module/heapsort/renderer/SequenceElement.class new file mode 100644 index 0000000..106a0db Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/SequenceElement.class differ diff --git a/bin/org/jalgo/module/heapsort/renderer/Text.class b/bin/org/jalgo/module/heapsort/renderer/Text.class new file mode 100644 index 0000000..6bfe948 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/renderer/Text.class differ diff --git a/bin/org/jalgo/module/heapsort/res.properties b/bin/org/jalgo/module/heapsort/res.properties new file mode 100644 index 0000000..951ceb7 --- /dev/null +++ b/bin/org/jalgo/module/heapsort/res.properties @@ -0,0 +1,5 @@ +Module_logo=/heapsort_pix/logo.gif + +HelpSet_Name=/help/jhelp/heapsort_help.hs + +Icon.Suspend=/heapsort_pix/suspend.gif diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$AckWaitState.class b/bin/org/jalgo/module/heapsort/vis/Controller$AckWaitState.class new file mode 100644 index 0000000..fca19c7 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$AckWaitState.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Backwards.class b/bin/org/jalgo/module/heapsort/vis/Controller$Backwards.class new file mode 100644 index 0000000..df92d2d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Backwards.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$CState.class b/bin/org/jalgo/module/heapsort/vis/Controller$CState.class new file mode 100644 index 0000000..5f99f70 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$CState.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Direction.class b/bin/org/jalgo/module/heapsort/vis/Controller$Direction.class new file mode 100644 index 0000000..fab6841 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Direction.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Forward.class b/bin/org/jalgo/module/heapsort/vis/Controller$Forward.class new file mode 100644 index 0000000..0be559e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Forward.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Initial.class b/bin/org/jalgo/module/heapsort/vis/Controller$Initial.class new file mode 100644 index 0000000..a8a64b1 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Initial.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Listener.class b/bin/org/jalgo/module/heapsort/vis/Controller$Listener.class new file mode 100644 index 0000000..2dceb87 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Listener.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$LogListener.class b/bin/org/jalgo/module/heapsort/vis/Controller$LogListener.class new file mode 100644 index 0000000..d2c0320 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$LogListener.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$MacroState.class b/bin/org/jalgo/module/heapsort/vis/Controller$MacroState.class new file mode 100644 index 0000000..123c479 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$MacroState.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$PlayAnimState.class b/bin/org/jalgo/module/heapsort/vis/Controller$PlayAnimState.class new file mode 100644 index 0000000..54a6192 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$PlayAnimState.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$Ready.class b/bin/org/jalgo/module/heapsort/vis/Controller$Ready.class new file mode 100644 index 0000000..d89f5c9 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$Ready.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller$StateChangedNotifier.class b/bin/org/jalgo/module/heapsort/vis/Controller$StateChangedNotifier.class new file mode 100644 index 0000000..3c50a64 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller$StateChangedNotifier.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Controller.class b/bin/org/jalgo/module/heapsort/vis/Controller.class new file mode 100644 index 0000000..d013567 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Controller.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/ControllerListener.class b/bin/org/jalgo/module/heapsort/vis/ControllerListener.class new file mode 100644 index 0000000..d0de9ec Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/ControllerListener.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$1.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$1.class new file mode 100644 index 0000000..bf8e2b2 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$1.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$BackAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$BackAnim.class new file mode 100644 index 0000000..1653a00 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$BackAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$CompareAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$CompareAnim.class new file mode 100644 index 0000000..0e2c0bc Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$CompareAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$DecliAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$DecliAnim.class new file mode 100644 index 0000000..f2f2b86 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$DecliAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$DecreAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$DecreAnim.class new file mode 100644 index 0000000..8dd1b66 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$DecreAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$1.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$1.class new file mode 100644 index 0000000..1c716ee Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$1.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$2.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$2.class new file mode 100644 index 0000000..49fbd1e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$2.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$3.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$3.class new file mode 100644 index 0000000..c96f316 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$3.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$4.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$4.class new file mode 100644 index 0000000..23518fc Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim$4.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim.class new file mode 100644 index 0000000..a2ab991 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ExtendAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim$1.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim$1.class new file mode 100644 index 0000000..8d53700 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim$1.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim.class new file mode 100644 index 0000000..fd2c199 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$FinishAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$ReturnAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$ReturnAnim.class new file mode 100644 index 0000000..d5cd704 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$ReturnAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase0Anim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase0Anim.class new file mode 100644 index 0000000..61abe9f Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase0Anim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase1Anim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase1Anim.class new file mode 100644 index 0000000..6680a9e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase1Anim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase2Anim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase2Anim.class new file mode 100644 index 0000000..51fe209 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$Startphase2Anim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$StartslAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$StartslAnim.class new file mode 100644 index 0000000..993ac10 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$StartslAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapAnim.class new file mode 100644 index 0000000..6e23271 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapDecreAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapDecreAnim.class new file mode 100644 index 0000000..e8af4f5 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$SwapDecreAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim$1.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim$1.class new file mode 100644 index 0000000..17620e4 Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim$1.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim.class b/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim.class new file mode 100644 index 0000000..9327c7e Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort$TheSwapAnim.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Heapsort.class b/bin/org/jalgo/module/heapsort/vis/Heapsort.class new file mode 100644 index 0000000..eed7b2c Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Heapsort.class differ diff --git a/bin/org/jalgo/module/heapsort/vis/Visualisation.class b/bin/org/jalgo/module/heapsort/vis/Visualisation.class new file mode 100644 index 0000000..e1bd81d Binary files /dev/null and b/bin/org/jalgo/module/heapsort/vis/Visualisation.class differ diff --git a/bin/org/jalgo/module/hoare/ModuleConnector.class b/bin/org/jalgo/module/hoare/ModuleConnector.class new file mode 100644 index 0000000..4317b31 Binary files /dev/null and b/bin/org/jalgo/module/hoare/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/hoare/ModuleInfo.class b/bin/org/jalgo/module/hoare/ModuleInfo.class new file mode 100644 index 0000000..b766c87 Binary files /dev/null and b/bin/org/jalgo/module/hoare/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/hoare/constants/CodeDimension.class b/bin/org/jalgo/module/hoare/constants/CodeDimension.class new file mode 100644 index 0000000..68035d4 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/CodeDimension.class differ diff --git a/bin/org/jalgo/module/hoare/constants/Event.class b/bin/org/jalgo/module/hoare/constants/Event.class new file mode 100644 index 0000000..68be9a3 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/Event.class differ diff --git a/bin/org/jalgo/module/hoare/constants/ParserAccess.class b/bin/org/jalgo/module/hoare/constants/ParserAccess.class new file mode 100644 index 0000000..4cf03b9 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/ParserAccess.class differ diff --git a/bin/org/jalgo/module/hoare/constants/Rule.class b/bin/org/jalgo/module/hoare/constants/Rule.class new file mode 100644 index 0000000..152c607 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/Rule.class differ diff --git a/bin/org/jalgo/module/hoare/constants/Status.class b/bin/org/jalgo/module/hoare/constants/Status.class new file mode 100644 index 0000000..a768111 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/Status.class differ diff --git a/bin/org/jalgo/module/hoare/constants/TextStyle.class b/bin/org/jalgo/module/hoare/constants/TextStyle.class new file mode 100644 index 0000000..4cffbd2 Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/TextStyle.class differ diff --git a/bin/org/jalgo/module/hoare/constants/package-info.class b/bin/org/jalgo/module/hoare/constants/package-info.class new file mode 100644 index 0000000..1ef7f4e Binary files /dev/null and b/bin/org/jalgo/module/hoare/constants/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/control/Controller$1.class b/bin/org/jalgo/module/hoare/control/Controller$1.class new file mode 100644 index 0000000..d3b84dd Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/Controller$1.class differ diff --git a/bin/org/jalgo/module/hoare/control/Controller.class b/bin/org/jalgo/module/hoare/control/Controller.class new file mode 100644 index 0000000..4e1976b Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/Controller.class differ diff --git a/bin/org/jalgo/module/hoare/control/Evaluation.class b/bin/org/jalgo/module/hoare/control/Evaluation.class new file mode 100644 index 0000000..70359a4 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/Evaluation.class differ diff --git a/bin/org/jalgo/module/hoare/control/EvaluationThread.class b/bin/org/jalgo/module/hoare/control/EvaluationThread.class new file mode 100644 index 0000000..1b7f742 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/EvaluationThread.class differ diff --git a/bin/org/jalgo/module/hoare/control/JepEvaluator.class b/bin/org/jalgo/module/hoare/control/JepEvaluator.class new file mode 100644 index 0000000..283a883 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/JepEvaluator.class differ diff --git a/bin/org/jalgo/module/hoare/control/UndoableEdit.class b/bin/org/jalgo/module/hoare/control/UndoableEdit.class new file mode 100644 index 0000000..04ba6da Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/UndoableEdit.class differ diff --git a/bin/org/jalgo/module/hoare/control/edits/ApplyRule.class b/bin/org/jalgo/module/hoare/control/edits/ApplyRule.class new file mode 100644 index 0000000..009a461 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/edits/ApplyRule.class differ diff --git a/bin/org/jalgo/module/hoare/control/edits/AssertionEdit.class b/bin/org/jalgo/module/hoare/control/edits/AssertionEdit.class new file mode 100644 index 0000000..7304eb4 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/edits/AssertionEdit.class differ diff --git a/bin/org/jalgo/module/hoare/control/edits/DeleteNode.class b/bin/org/jalgo/module/hoare/control/edits/DeleteNode.class new file mode 100644 index 0000000..cb952ac Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/edits/DeleteNode.class differ diff --git a/bin/org/jalgo/module/hoare/control/edits/package-info.class b/bin/org/jalgo/module/hoare/control/edits/package-info.class new file mode 100644 index 0000000..a7f7a4d Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/edits/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/control/package-info.class b/bin/org/jalgo/module/hoare/control/package-info.class new file mode 100644 index 0000000..df0f439 Binary files /dev/null and b/bin/org/jalgo/module/hoare/control/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/de.properties b/bin/org/jalgo/module/hoare/de.properties new file mode 100644 index 0000000..544fc43 --- /dev/null +++ b/bin/org/jalgo/module/hoare/de.properties @@ -0,0 +1,102 @@ +Module_name=Hoare +Module_version=1.7 +Module_authors=Antje Lang, Johannes Kulik, Thomas Kühn, Tomas Karnagel, Uwe Pfeiffer +Module_description_1=Dieses Modul hilft beim Lernen und Verstehen von Beweisbäumen im Sinne des Hoare-Kalküls. +Module_description_2=Der Beweisbaum für ein Programm kann interaktiv entwickelt werden. +Module_license=GNU General Public License +Beamer_mode=Beamer-Modus + +ttt.openC0Program=C0-Program öffnen +ttt.redo=Einen Schritt wiederherstellen +ttt.undo=Einen Schritt rückgängig machen +ttt.reinit = Programm reinitialisieren +ttt.delNode=Teilbaum löschen +ttt.zoomIn=den Baum vergrößern +ttt.zoomOut=den Baum verkleinern +ttt.normalMouse=Auswahl von Zellen +ttt.toggleSplitter=Seitenleiste verstecken +ttt.resetZoom=Zoom zurücksetzen +ttt.applyFormulaChange=(Strg+Enter) + +out.evalError=Fehler bei der Auswertung: +out.noValidNode=Keinen zulässigen Knoten gewählt +out.ruleApplyError=Fehler bei Regelanwendung +out.IterationChangedToWrong=die Änderung hat eine Iterationsregel invalidiert +out.DeleteNodeFailed=Unterbaum konnte nicht gelöscht werden. +out.EditAssertionFailed=Die Bedingung konnte nicht editiert werden. +out.UndoImpossible=Undo nicht möglich +out.UndoError=Beim Undo ist ein Fehler aufgetreten. +out.RedoImpossible=Redo nicht möglich +out.RedoError=Beim Redo ist ein Fehler aufgetreten. +out.evaluationWrong=Auswertungs-Ergebnis: falsch +out.evaluationOK=Auswertungs-Ergebnis: richtig +out.loadError=Fehler beim Laden +out.saveError=Fehler beim Speichern +out.iterationCheckFailed=%s nicht von der Form %s \u2227 \u00AC \u03C0 + +allsuccessful=Herzlichen Glückwunsch. Der Beweis war erfolgreich. +wannaReinit=Eingaben löschen und Bildschrim neu laden? + +name.resetZoom=Zoom zurücksetzen +name.openC0Program=C0-Program öffnen +name.reparse=parst C0Program neu +name.toggleDesc=Details ein/aus +name.redo=Wiederherstellen +name.undo=Rückgängig +name.reinit=Programm neu starten +name.evalTree=Baum testen +name.delNode=Teilbaum löschen +name.eraseLog=Löschen +name.zoomIn=vergrößern +name.zoomOut=verkleinern +name.normalMouse=Auswahltool +name.toggleSplitter= +name.assign=Zuweisungsaxiom +name.comp=Block-Statement +name.sequence=Sequenz +name.alt1=If-Statement +name.alt2=If-Else +name.iter=Iteration +name.SV=Stärkere Vorbed. +name.SN=Schwächere Nachbed. +name.pre=Vorbedingung +name.post=Nachbedingung +name.source=C0-Quelltext +name.variables=Variablen +name.rules=Regeln + +rule.assign.desc=(ZA) +rule.comp.desc=(CR) +rule.sequence.desc=(SR) +rule.alt1.desc=(A1) +rule.alt2.desc=(A2) +rule.iter.desc=(IR) +rule.SV.desc=(SV) +rule.SN.desc=(SN) + +control.handleEvent.IdError=Diese Art Event brauch eine Id. +control.handleEvent.ParameterError=Nicht der richtige Parametertyp für dieses Event. +control.handleEvent.noSuchEvent=kein solches Event vorhanden +control.handleEvent.FileReadError=Fehler beim Lesen aus der Datei. +control.unknownRule=unbekannte Regel +control.ParseCodeError=Ein Fehler ist beim Parsen des Codes aufgetreten. + +view.zoomError=Zoom in diese Richtung nicht mehr möglich +view.cellSelectionError=keine Zelle ausgewählt +view.source.editButtonText=Bearbeiten +view.source.parseButtonText=Parsen +view.source.rereadButtonText=Wiederherstellen +view.source.editButtonTTT=anderes C0-Programm eingeben +view.source.parseButtonTTT=Parst das C0-Programm und erstellt die Wurzel des Beweisbaums. +view.source.rereadButtonTTT=Lädt wieder das zum aktuellen Baum zugehörige C0-Programm. Das eingegebene C0-Programm wird verworfen. +view.source.confirmParsingMessageTitle=Parsen bestätigen +view.source.confirmParsingMessage=Der aktuelle Beweisbaum geht beim Parsen verloren.\nWollen Sie den Quellcode trotzdem parsen? +view.parseError=Fehler beim Parsen +view.parseErrorFormulaSubstitution=(?) +view.changeFont=Schrift ändern +view.newFontName=neue Schriftart: +view.newFontSize=neue Schriftgröße: +view.editVariable=$Var bearbeiten +view.variables.selectedVariables=Variablen Vor- und Nachbedingung + +parserAccess.newParseException=Zusicherungen der Form a<b<c sind nicht gestattet. \ No newline at end of file diff --git a/bin/org/jalgo/module/hoare/en.properties b/bin/org/jalgo/module/hoare/en.properties new file mode 100644 index 0000000..90a5008 --- /dev/null +++ b/bin/org/jalgo/module/hoare/en.properties @@ -0,0 +1,103 @@ +Module_name=Hoare +Module_version=1.7 +Module_authors=Antje Lang, Johannes Kulik, Thomas Kühn, Tomas Karnagel, Uwe Pfeiffer +Module_description_1=A module for visualisation and training of the Hoare logic. +Module_description_2=The tree for a given programm can be interactivly developed. +Module_license=GNU General Public License +Beamer_mode=beamer-mode + +ttt.openC0Program=parse C0-program +ttt.redo=one step forward +ttt.undo=one step back +ttt.reinit = reinit program +ttt.delNode=delete the tree above the highlighted node +ttt.zoomIn=enlarge the tree +ttt.zoomOut=scaling down the tree +ttt.normalMouse=Mode for Selection of Cells +ttt.toggleSplitter=Hide sidebar +ttt.resetZoom=reset Zoom +ttt.applyFormulaChange=(Ctrl+Enter) + +out.evalError=evaluation error occured: +out.noValidNode=no valid node selected +out.ruleApplyError=error on ruleapply +out.IterationChangedToWrong=this edit invalidated an iteration rule +out.ApplyRuleFailed=Unable to apply that rule. +out.DeleteNodeFailed=Unable to delete the subtree. +out.EditAssertionFailed=Unable to edit assertion. +out.UndoImpossible=undo-operation impossible +out.UndoError=An error occured while trying to undo. +out.RedoImpossible=redo-operation impossible +out.RedoError=An error occured while trying to redo. +out.evaluationWrong=evaluation result: wrong +out.evaluationOK=evaluation result: ok +out.loadError=error on loading +out.saveError=error on saving +out.iterationCheckFailed=%s must have the form %s \u2227 \u00AC \u03C0 + +allsuccessful=You have been successful. +wannaReinit=Delete all inputs and reset the screen? + +name.resetZoom=reset Zoom +name.openC0Program=opens C0-Program +name.reparse=reparse C0Program +name.toggleDesc=toggle Description +name.redo=Redo +name.undo=Undo +name.reinit=reinit +name.evalTree=evaluate tree +name.delNode=delete the tree above the highlighted node +name.eraseLog=Clear +name.zoomIn=zoom in +name.zoomOut=zoom out +name.normalMouse=Selectiontool +name.toggleSplitter= +name.assign=assignment +name.comp=compound +name.sequence=sequence +name.alt1=if-statement +name.alt2=if-else +name.iter=iteration +name.SV=stronger precond. +name.SN=weaker postcond. +name.pre=precondition +name.post=postcondition +name.source=C0 source code +name.variables=Variables +name.rules=Rules + +rule.assign.desc=(AssR) +rule.comp.desc=(CR) +rule.sequence.desc=(SR) +rule.alt1.desc=(A1) +rule.alt2.desc=(A2) +rule.iter.desc=(IR) +rule.SV.desc=(SP) +rule.SN.desc=(WP) + +control.handleEvent.IdError=Need an Id for this type of Event +control.handleEvent.ParameterError=Not the correct parameter type for this Event +control.handleEvent.noSuchEvent=no such event +control.handleEvent.FileReadError=Error while reading from file. +control.unknownRule=unknown Rule +control.ParseCodeError=Unknown error occured while parsing the code. + +view.zoomError=cannot zoom anymore in this direction +view.cellSelectionError=no cell selected +view.source.editButtonText=Edit +view.source.parseButtonText=Parse +view.source.rereadButtonText=Reset +view.source.editButtonTTT=enter a different C0-program +view.source.parseButtonTTT=Parses the C0-program and creates the root of the proof tree. +view.source.rereadButtonTTT=Loads the C0-program belonging to the current tree. The entered C0-program will be lost. +view.source.confirmParsingMessageTitle=Confirm parsing +view.source.confirmParsingMessage=The current proof tree will be lost.\nDo you want to parse the source code anyway? +view.parseError=parse error +view.parseErrorFormulaSubstitution=(?) +view.changeFont=change font +view.newFontSize=new font size: +view.newFontName=new font: +view.editVariable=Edit $Var +view.variables.selectedVariables=Variables pre- and postcondition + +parserAccess.newParseException=Assertions like a<b<c aren't allowed. \ No newline at end of file diff --git a/bin/org/jalgo/module/hoare/model/AbstractAssertion.class b/bin/org/jalgo/module/hoare/model/AbstractAssertion.class new file mode 100644 index 0000000..2caeab5 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/AbstractAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/AndAssertion.class b/bin/org/jalgo/module/hoare/model/AndAssertion.class new file mode 100644 index 0000000..ca7231e Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/AndAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/AssignFormula.class b/bin/org/jalgo/module/hoare/model/AssignFormula.class new file mode 100644 index 0000000..193d6f2 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/AssignFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/CompoundFormula.class b/bin/org/jalgo/module/hoare/model/CompoundFormula.class new file mode 100644 index 0000000..2de2002 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/CompoundFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/ConcreteAssertion.class b/bin/org/jalgo/module/hoare/model/ConcreteAssertion.class new file mode 100644 index 0000000..0dcead3 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/ConcreteAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/IfElseFormula.class b/bin/org/jalgo/module/hoare/model/IfElseFormula.class new file mode 100644 index 0000000..f48858b Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/IfElseFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/IfFormula.class b/bin/org/jalgo/module/hoare/model/IfFormula.class new file mode 100644 index 0000000..ab0f5d5 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/IfFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/ImplicationFormula.class b/bin/org/jalgo/module/hoare/model/ImplicationFormula.class new file mode 100644 index 0000000..ca297e1 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/ImplicationFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/IterationFormula.class b/bin/org/jalgo/module/hoare/model/IterationFormula.class new file mode 100644 index 0000000..6a63dec Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/IterationFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/Model.class b/bin/org/jalgo/module/hoare/model/Model.class new file mode 100644 index 0000000..2e0646c Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/Model.class differ diff --git a/bin/org/jalgo/module/hoare/model/NotAssertion.class b/bin/org/jalgo/module/hoare/model/NotAssertion.class new file mode 100644 index 0000000..e220b02 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/NotAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/OrAssertion.class b/bin/org/jalgo/module/hoare/model/OrAssertion.class new file mode 100644 index 0000000..8b46b81 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/OrAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/StatSeqFormula.class b/bin/org/jalgo/module/hoare/model/StatSeqFormula.class new file mode 100644 index 0000000..67278b8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/StatSeqFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/StrongPreFormula.class b/bin/org/jalgo/module/hoare/model/StrongPreFormula.class new file mode 100644 index 0000000..aee63e6 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/StrongPreFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/VarAssertion.class b/bin/org/jalgo/module/hoare/model/VarAssertion.class new file mode 100644 index 0000000..623b735 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/VarAssertion.class differ diff --git a/bin/org/jalgo/module/hoare/model/Variable.class b/bin/org/jalgo/module/hoare/model/Variable.class new file mode 100644 index 0000000..fa4bc67 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/Variable.class differ diff --git a/bin/org/jalgo/module/hoare/model/VerificationFormula.class b/bin/org/jalgo/module/hoare/model/VerificationFormula.class new file mode 100644 index 0000000..389e5e6 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/VerificationFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/WeakPostFormula.class b/bin/org/jalgo/module/hoare/model/WeakPostFormula.class new file mode 100644 index 0000000..fcc0ab0 Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/WeakPostFormula.class differ diff --git a/bin/org/jalgo/module/hoare/model/package-info.class b/bin/org/jalgo/module/hoare/model/package-info.class new file mode 100644 index 0000000..3e2dddc Binary files /dev/null and b/bin/org/jalgo/module/hoare/model/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/res.properties b/bin/org/jalgo/module/hoare/res.properties new file mode 100644 index 0000000..f3e3f1a --- /dev/null +++ b/bin/org/jalgo/module/hoare/res.properties @@ -0,0 +1,42 @@ +Module_logo=/hoare_pix/logo.gif +HelpSet_Name=/help/jhelp/hoare_help.hs + +icon.openC0Program=/hoare_pix/CNull.gif +icon.reinit=/hoare_pix/reinit.gif +icon.redo=/hoare_pix/redo.gif +icon.redo.gray=/hoare_pix/grayredo.gif +icon.undo=/hoare_pix/undo.gif +icon.undo.gray=/hoare_pix/grayundo.gif +icon.delNode=/hoare_pix/delnode.gif +icon.duck=/hoare_pix/duck.png +icon.toggleSplitter=/hoare_pix/toggleSplitter.gif +icon.resetZoom=/hoare_pix/resetZoom.gif +icon.zoomIn=/hoare_pix/zoomIn.gif +icon.zoomOut=/hoare_pix/zoomOut.gif +icon.normalMouse=/hoare_pix/normalMouse.gif + +icon.openC0Welcome0=/hoare_pix/openc0_welcome_0.gif +icon.openC0Welcome1=/hoare_pix/openc0_welcome_1.gif +icon.openC0WelcomeDesc_de=/hoare_pix/openc0_welcome_Desc_de.gif +icon.openC0WelcomeDesc_en=/hoare_pix/openc0_welcome_Desc_en.gif + +icon.newWelcome0=/hoare_pix/new_welcome_0.gif +icon.newWelcome1=/hoare_pix/new_welcome_1.gif +icon.newWelcomeDesc_de=/hoare_pix/new_welcome_Desc_de.gif +icon.newWelcomeDesc_en=/hoare_pix/new_welcome_Desc_en.gif + +icon.openWelcome0=/hoare_pix/open_welcome_0.gif +icon.openWelcome1=/hoare_pix/open_welcome_1.gif +icon.openWelcomeDesc_de=/hoare_pix/open_welcome_Desc_de.gif +icon.openWelcomeDesc_en=/hoare_pix/open_welcome_Desc_en.gif + +rule.assign=/hoare_pix/assign.gif +rule.comp=/hoare_pix/Block.gif +rule.sequence=/hoare_pix/Sequenz.gif +rule.alt1=/hoare_pix/if.gif +rule.alt2=/hoare_pix/ifelse.gif +rule.iter=/hoare_pix/while.gif +rule.SV=/hoare_pix/SV.gif +rule.SN=/hoare_pix/SN.gif + +fontFolder=/hoare_font/ \ No newline at end of file diff --git a/bin/org/jalgo/module/hoare/view/JGraphRoundRectView$ActivityRenderer.class b/bin/org/jalgo/module/hoare/view/JGraphRoundRectView$ActivityRenderer.class new file mode 100644 index 0000000..ed4ccdc Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JGraphRoundRectView$ActivityRenderer.class differ diff --git a/bin/org/jalgo/module/hoare/view/JGraphRoundRectView.class b/bin/org/jalgo/module/hoare/view/JGraphRoundRectView.class new file mode 100644 index 0000000..42caf74 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JGraphRoundRectView.class differ diff --git a/bin/org/jalgo/module/hoare/view/JToolButton$1.class b/bin/org/jalgo/module/hoare/view/JToolButton$1.class new file mode 100644 index 0000000..c852a34 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JToolButton$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/JToolButton$2.class b/bin/org/jalgo/module/hoare/view/JToolButton$2.class new file mode 100644 index 0000000..4437093 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JToolButton$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/JToolButton$RolloverHandler.class b/bin/org/jalgo/module/hoare/view/JToolButton$RolloverHandler.class new file mode 100644 index 0000000..ae1e8aa Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JToolButton$RolloverHandler.class differ diff --git a/bin/org/jalgo/module/hoare/view/JToolButton.class b/bin/org/jalgo/module/hoare/view/JToolButton.class new file mode 100644 index 0000000..8c80dee Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/JToolButton.class differ diff --git a/bin/org/jalgo/module/hoare/view/MyCell.class b/bin/org/jalgo/module/hoare/view/MyCell.class new file mode 100644 index 0000000..f197747 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/MyCell.class differ diff --git a/bin/org/jalgo/module/hoare/view/MyCellViewFactory.class b/bin/org/jalgo/module/hoare/view/MyCellViewFactory.class new file mode 100644 index 0000000..681ef0b Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/MyCellViewFactory.class differ diff --git a/bin/org/jalgo/module/hoare/view/MyEdge.class b/bin/org/jalgo/module/hoare/view/MyEdge.class new file mode 100644 index 0000000..442432c Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/MyEdge.class differ diff --git a/bin/org/jalgo/module/hoare/view/PanelVertexRenderer.class b/bin/org/jalgo/module/hoare/view/PanelVertexRenderer.class new file mode 100644 index 0000000..b3d0330 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/PanelVertexRenderer.class differ diff --git a/bin/org/jalgo/module/hoare/view/VertexPanelFactory$VertexPanel.class b/bin/org/jalgo/module/hoare/view/VertexPanelFactory$VertexPanel.class new file mode 100644 index 0000000..e20bc52 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/VertexPanelFactory$VertexPanel.class differ diff --git a/bin/org/jalgo/module/hoare/view/VertexPanelFactory.class b/bin/org/jalgo/module/hoare/view/VertexPanelFactory.class new file mode 100644 index 0000000..ee9f71f Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/VertexPanelFactory.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$1$WarteThread.class b/bin/org/jalgo/module/hoare/view/View$1$WarteThread.class new file mode 100644 index 0000000..09c5472 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$1$WarteThread.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$1.class b/bin/org/jalgo/module/hoare/view/View$1.class new file mode 100644 index 0000000..51a0f52 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$1VariableLengthComparator.class b/bin/org/jalgo/module/hoare/view/View$1VariableLengthComparator.class new file mode 100644 index 0000000..309c315 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$1VariableLengthComparator.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$2.class b/bin/org/jalgo/module/hoare/view/View$2.class new file mode 100644 index 0000000..99c8f80 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$CellPopupMenu.class b/bin/org/jalgo/module/hoare/view/View$CellPopupMenu.class new file mode 100644 index 0000000..2ea041d Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$CellPopupMenu.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$EditVariableListener.class b/bin/org/jalgo/module/hoare/view/View$EditVariableListener.class new file mode 100644 index 0000000..fb91338 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$EditVariableListener.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$GraphListener.class b/bin/org/jalgo/module/hoare/view/View$GraphListener.class new file mode 100644 index 0000000..8fd9a47 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$GraphListener.class differ diff --git a/bin/org/jalgo/module/hoare/view/View$ZoomMode.class b/bin/org/jalgo/module/hoare/view/View$ZoomMode.class new file mode 100644 index 0000000..57f4170 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View$ZoomMode.class differ diff --git a/bin/org/jalgo/module/hoare/view/View.class b/bin/org/jalgo/module/hoare/view/View.class new file mode 100644 index 0000000..df09794 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/View.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSGraph.class b/bin/org/jalgo/module/hoare/view/WSGraph.class new file mode 100644 index 0000000..9682849 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSGraph.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSPart.class b/bin/org/jalgo/module/hoare/view/WSPart.class new file mode 100644 index 0000000..699a374 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSPart.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$1.class b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$1.class new file mode 100644 index 0000000..e7f3199 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$2.class b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$2.class new file mode 100644 index 0000000..c748649 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSRule$RuleButton.class b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton.class new file mode 100644 index 0000000..f52e647 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSRule$RuleButton.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSRule$RuleView.class b/bin/org/jalgo/module/hoare/view/WSRule$RuleView.class new file mode 100644 index 0000000..a7425a7 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSRule$RuleView.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSRule.class b/bin/org/jalgo/module/hoare/view/WSRule.class new file mode 100644 index 0000000..f193f9c Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSRule.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSSource$1.class b/bin/org/jalgo/module/hoare/view/WSSource$1.class new file mode 100644 index 0000000..23f9d74 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSSource$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSSource$2.class b/bin/org/jalgo/module/hoare/view/WSSource$2.class new file mode 100644 index 0000000..974db28 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSSource$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSSource$3.class b/bin/org/jalgo/module/hoare/view/WSSource$3.class new file mode 100644 index 0000000..011af82 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSSource$3.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSSource.class b/bin/org/jalgo/module/hoare/view/WSSource.class new file mode 100644 index 0000000..afd70fd Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSSource.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSVar$1SelectedVariablesPanel.class b/bin/org/jalgo/module/hoare/view/WSVar$1SelectedVariablesPanel.class new file mode 100644 index 0000000..6768654 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSVar$1SelectedVariablesPanel.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSVar$VariableView$FormulaEditorShower.class b/bin/org/jalgo/module/hoare/view/WSVar$VariableView$FormulaEditorShower.class new file mode 100644 index 0000000..6055ff2 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSVar$VariableView$FormulaEditorShower.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSVar$VariableView.class b/bin/org/jalgo/module/hoare/view/WSVar$VariableView.class new file mode 100644 index 0000000..a63ba7f Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSVar$VariableView.class differ diff --git a/bin/org/jalgo/module/hoare/view/WSVar.class b/bin/org/jalgo/module/hoare/view/WSVar.class new file mode 100644 index 0000000..0d3beec Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WSVar.class differ diff --git a/bin/org/jalgo/module/hoare/view/WelcomeScreen$1.class b/bin/org/jalgo/module/hoare/view/WelcomeScreen$1.class new file mode 100644 index 0000000..8eac0e7 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WelcomeScreen$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/WelcomeScreen.class b/bin/org/jalgo/module/hoare/view/WelcomeScreen.class new file mode 100644 index 0000000..84af3ca Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/hoare/view/WelcomeScreenButton.class b/bin/org/jalgo/module/hoare/view/WelcomeScreenButton.class new file mode 100644 index 0000000..9716f7e Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WelcomeScreenButton.class differ diff --git a/bin/org/jalgo/module/hoare/view/WorkScreen$1.class b/bin/org/jalgo/module/hoare/view/WorkScreen$1.class new file mode 100644 index 0000000..f18acf8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WorkScreen$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/WorkScreen$2.class b/bin/org/jalgo/module/hoare/view/WorkScreen$2.class new file mode 100644 index 0000000..e9afa2d Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WorkScreen$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/WorkScreen$3.class b/bin/org/jalgo/module/hoare/view/WorkScreen$3.class new file mode 100644 index 0000000..cbbfa66 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WorkScreen$3.class differ diff --git a/bin/org/jalgo/module/hoare/view/WorkScreen.class b/bin/org/jalgo/module/hoare/view/WorkScreen.class new file mode 100644 index 0000000..9f44492 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/WorkScreen.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$1.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$1.class new file mode 100644 index 0000000..14bac1f Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$2.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$2.class new file mode 100644 index 0000000..4cc1039 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$2.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$3.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$3.class new file mode 100644 index 0000000..86db522 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$3.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$4.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$4.class new file mode 100644 index 0000000..8e53e06 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$4.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$5.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$5.class new file mode 100644 index 0000000..0502e4e Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$5.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$6.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$6.class new file mode 100644 index 0000000..7c60e04 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$6.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$7.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$7.class new file mode 100644 index 0000000..1c3fc9c Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$7.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton$1.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton$1.class new file mode 100644 index 0000000..a9f02e7 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton.class new file mode 100644 index 0000000..7c03f31 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor$SymbolButton.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.class b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.class new file mode 100644 index 0000000..f6acf03 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/Enten.class b/bin/org/jalgo/module/hoare/view/formula/Enten.class new file mode 100644 index 0000000..e9416c8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/Enten.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/FormulaEditor.class b/bin/org/jalgo/module/hoare/view/formula/FormulaEditor.class new file mode 100644 index 0000000..78018dd Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/FormulaEditor.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.class b/bin/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.class new file mode 100644 index 0000000..95eeb90 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$1.class b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$1.class new file mode 100644 index 0000000..57a95e6 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$1.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$YPos.class b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$YPos.class new file mode 100644 index 0000000..8742fe0 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer$YPos.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/FormulaViewer.class b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer.class new file mode 100644 index 0000000..c44ada8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/FormulaViewer.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/Symbols.class b/bin/org/jalgo/module/hoare/view/formula/Symbols.class new file mode 100644 index 0000000..8fbb4b8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/Symbols.class differ diff --git a/bin/org/jalgo/module/hoare/view/formula/package-info.class b/bin/org/jalgo/module/hoare/view/formula/package-info.class new file mode 100644 index 0000000..eece0dd Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/formula/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/view/package-info.class b/bin/org/jalgo/module/hoare/view/package-info.class new file mode 100644 index 0000000..5d4898a Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/BeamerMode.class b/bin/org/jalgo/module/hoare/view/toolbar/BeamerMode.class new file mode 100644 index 0000000..25bcc85 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/BeamerMode.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/DelPart.class b/bin/org/jalgo/module/hoare/view/toolbar/DelPart.class new file mode 100644 index 0000000..653bdf4 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/DelPart.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.class b/bin/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.class new file mode 100644 index 0000000..f120563 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/NormalMouse.class b/bin/org/jalgo/module/hoare/view/toolbar/NormalMouse.class new file mode 100644 index 0000000..df2c5aa Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/NormalMouse.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/ReInit.class b/bin/org/jalgo/module/hoare/view/toolbar/ReInit.class new file mode 100644 index 0000000..65397a4 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/ReInit.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/Redo.class b/bin/org/jalgo/module/hoare/view/toolbar/Redo.class new file mode 100644 index 0000000..aa11f51 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/Redo.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/ResetZoom.class b/bin/org/jalgo/module/hoare/view/toolbar/ResetZoom.class new file mode 100644 index 0000000..d46b959 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/ResetZoom.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.class b/bin/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.class new file mode 100644 index 0000000..d4d766b Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/Undo.class b/bin/org/jalgo/module/hoare/view/toolbar/Undo.class new file mode 100644 index 0000000..b1e3473 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/Undo.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/ZoomIn.class b/bin/org/jalgo/module/hoare/view/toolbar/ZoomIn.class new file mode 100644 index 0000000..b2a9a56 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/ZoomIn.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/ZoomOut.class b/bin/org/jalgo/module/hoare/view/toolbar/ZoomOut.class new file mode 100644 index 0000000..c8bfe45 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/ZoomOut.class differ diff --git a/bin/org/jalgo/module/hoare/view/toolbar/package-info.class b/bin/org/jalgo/module/hoare/view/toolbar/package-info.class new file mode 100644 index 0000000..c831e91 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/toolbar/package-info.class differ diff --git a/bin/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.class b/bin/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.class new file mode 100644 index 0000000..d058e40 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.class differ diff --git a/bin/org/jalgo/module/hoare/view/util/VariableSizeButton.class b/bin/org/jalgo/module/hoare/view/util/VariableSizeButton.class new file mode 100644 index 0000000..f8fada8 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/util/VariableSizeButton.class differ diff --git a/bin/org/jalgo/module/hoare/view/util/package-info.class b/bin/org/jalgo/module/hoare/view/util/package-info.class new file mode 100644 index 0000000..09efd46 Binary files /dev/null and b/bin/org/jalgo/module/hoare/view/util/package-info.class differ diff --git a/bin/org/jalgo/module/kmp/.emptyDir b/bin/org/jalgo/module/kmp/.emptyDir new file mode 100644 index 0000000..96d2928 --- /dev/null +++ b/bin/org/jalgo/module/kmp/.emptyDir @@ -0,0 +1 @@ +This file was generated by Together to prevent this folder from being deleted during synchronization with the CVS repositiory. Please do not delete this file. \ No newline at end of file diff --git a/bin/org/jalgo/module/kmp/Constants.class b/bin/org/jalgo/module/kmp/Constants.class new file mode 100644 index 0000000..5e88d0d Binary files /dev/null and b/bin/org/jalgo/module/kmp/Constants.class differ diff --git a/bin/org/jalgo/module/kmp/Controller.class b/bin/org/jalgo/module/kmp/Controller.class new file mode 100644 index 0000000..e0b5ec7 Binary files /dev/null and b/bin/org/jalgo/module/kmp/Controller.class differ diff --git a/bin/org/jalgo/module/kmp/ModuleConnector.class b/bin/org/jalgo/module/kmp/ModuleConnector.class new file mode 100644 index 0000000..d904128 Binary files /dev/null and b/bin/org/jalgo/module/kmp/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/kmp/ModuleInfo.class b/bin/org/jalgo/module/kmp/ModuleInfo.class new file mode 100644 index 0000000..51a75ac Binary files /dev/null and b/bin/org/jalgo/module/kmp/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/ExampleFileFilter.class b/bin/org/jalgo/module/kmp/algorithm/ExampleFileFilter.class new file mode 100644 index 0000000..74f4992 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/ExampleFileFilter.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/History.class b/bin/org/jalgo/module/kmp/algorithm/History.class new file mode 100644 index 0000000..dfc68ee Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/History.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/KMPHighlighter.class b/bin/org/jalgo/module/kmp/algorithm/KMPHighlighter.class new file mode 100644 index 0000000..82b732d Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/KMPHighlighter.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/Pattern.class b/bin/org/jalgo/module/kmp/algorithm/Pattern.class new file mode 100644 index 0000000..7d43d45 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/Pattern.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/Step.class b/bin/org/jalgo/module/kmp/algorithm/Step.class new file mode 100644 index 0000000..e452d40 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/Step.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/StepFactory.class b/bin/org/jalgo/module/kmp/algorithm/StepFactory.class new file mode 100644 index 0000000..2414c97 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/StepFactory.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.class new file mode 100644 index 0000000..e256c52 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.class new file mode 100644 index 0000000..6aec1be Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.class new file mode 100644 index 0000000..1262351 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.class new file mode 100644 index 0000000..2947efd Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.class new file mode 100644 index 0000000..d6d4a08 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.class new file mode 100644 index 0000000..e4e93fa Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.class new file mode 100644 index 0000000..922a346 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1Step.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1Step.class new file mode 100644 index 0000000..f21fcb2 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1Step.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.class b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.class new file mode 100644 index 0000000..f405870 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.class new file mode 100644 index 0000000..a8b6b0b Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.class new file mode 100644 index 0000000..f67e250 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.class new file mode 100644 index 0000000..8d4df56 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.class new file mode 100644 index 0000000..4355838 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.class new file mode 100644 index 0000000..da8d7e4 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.class new file mode 100644 index 0000000..55cd8f5 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.class new file mode 100644 index 0000000..e8f4f94 Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.class differ diff --git a/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.class b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.class new file mode 100644 index 0000000..6c0be7e Binary files /dev/null and b/bin/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.class differ diff --git a/bin/org/jalgo/module/kmp/de.properties b/bin/org/jalgo/module/kmp/de.properties new file mode 100644 index 0000000..853de0c --- /dev/null +++ b/bin/org/jalgo/module/kmp/de.properties @@ -0,0 +1,120 @@ +Module_name=KMP - Knuth Morris Pratt +Module_version=1.0 +Module_authors=Danilo Lißke, Sebastian Patschorke, Elisa Böhl, Nadine Grabow, Matthias Neubert +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt den Suchalgorithmus von Knuth Morris Pratt. +Module_description_2=Es werden die Algorithmen Verschiebetabelle generieren und Anwendung auf den Suchtext visualisiert. Dabei können die Algorithmen interaktiv gesteuert werden. + +ModuleConnector.No_valid_KMP_file=Keine gültige KMP-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. + +Screen.Slider_ttt=Veränderung der Anzeigegrössen. + +ShowPanel.Head_textposition=TextIndex +ShowPanel.Head_text=Text +ShowPanel.Head_pattern=Pattern +ShowPanel.Head_table=Tabelle +ShowPanel.Head_index=Index +ShowPanel.Head_cycles=Zyklen + +InputPanel.Label_extension=Erweiterung +InputPanel.Label_pattern=Pattern +InputPanel.Label_searchtext=Suchtext +InputPanel.Label_result_true=Pattern gefunden! +InputPanel.Label_result_false=Pattern nicht gefunden! +InputPanel.Label_result_ttt=Das Ergebnis der Suche. +InputPanel.TextField_pattern_ttt=Geben Sie hier Ihr Pattern ein. +InputPanel.TextField_addpattern_ttt=Geben Sie hier Ihre Erweiterung zum Pattern ein. +InputPanel.CheckBox_cycle=Zyklen +InputPanel.CheckBox_cycle_ttt=Sollen die Zyklen des Patterns angezeigt werden? +InputPanel.Button_goon=Weiter in Phase 2 +InputPanel.Button_goon_ttt=Das aktuelle Pattern in Phase 2 anwenden. +InputPanel.Button_set=Setzen +InputPanel.Button_set_ttt=Setzt das eingegebene Pattern. +InputPanel.Button_random=Zufall +InputPanel.Button_random_ttt=Generieren Sie sich ein Zufallspattern. +InputPanel.Button_addpattern=Hinzufügen +InputPanel.Button_addpattern_ttt=Fügt die Erweiterung an das bestehende Pattern an. +InputPanel.Button_loadst=Eingeben +InputPanel.Button_loadst_ttt=Laden, eingeben oder bearbeiten Sie den Suchtext. +InputPanel.Button_generst=Generieren +InputPanel.Button_generst_ttt=Generiert einen Suchtext anhand des Patterns. + +Abort=Algorithmus abbrechen +Abort_tooltip=Bricht den laufenden Algorithmus ab +Back=Schritt zurück +Back_tooltip=Macht den letzten Schritt im aktuellen Algorithmus rückgängig +FastBack=Blockschritt zurück +FastBack_tooltip=Macht den letzen grösseren Schritt im aktuellen Algorithmus rückgängig +Forward=Nächster Schritt +Forward_tooltip=Führt den nächsten Schritt im aktuellen Algorithmus aus +FastForward=Nächster Blockschritt +FastForward_tooltip=Führt den nächsten grösseren Schritt im aktuellen Algorithmus aus +Finish=Algorithmus beenden +Finish_tooltip=Durchläuft den Algorithmus bis zum Ende + +Show_welcome_screen=Willkommensbildschirm anzeigen +Show_welcome_screen_tooltip=Öffnet den Willkommensbildschirm +Beamer_mode=Beamer-Modus +Wish_to_discard=Möchten Sie Ihre Änderungen verwerfen? + +LED.Title=Lernbeispiele Laden +LED.RB_Title=Pattern +LED.LB_Title=Suchtext +LED.Button_apply=Laden +LED.Button_cancel=Abbrechen +LED.Example_pattern_0=sinn +LED.Example_searchtext_0=dasisteinsinnlosertext +LED.Example_description_0=Dieses Beispiel zeigt die simpelste Form des Patterns: Es existieren keine Zyklen. +LED.Example_pattern_1=essen +LED.Example_searchtext_1=esHatNurDagesessenUndZugeschaut. +LED.Example_description_1=In diesem Beispiel existiert genau ein Zyklus im Pattern. +LED.Example_pattern_2=gigant +LED.Example_searchtext_2=grgigigalaginggigantisch +LED.Example_description_2=In dieser Vorlage gibt es mehrere Zyklen. +LED.Example_pattern_3=abacaabcab +LED.Example_searchtext_3=abacaabacababacaabcabacaabcac +LED.Example_description_3=Auch hier gibt es mehrere Zyklen. Versuchen Sie einmal, selbst alle zu finden. +LED.Example_pattern_4=bbabbac +LED.Example_searchtext_4=bbbabcabbcaabbabbbabbacbbacbacb +LED.Example_description_4=Das Beispielpattern enthält recht viele Zyklen. Das besondere an diesen ist, dass Zyklen in Zyklen vokommen. +LED.Example_pattern_5=erereerr +LED.Example_searchtext_5=erererereererrerereerrerrreer +LED.Example_description_5=Das Pattern enthält mehrere Zyklen. Das besondere an diesen ist, dass Zyklen in Zyklen entstehen und gemeinsam enden. +LED.Example_pattern_6=nennen +LED.Example_searchtext_6=enenneenenenenneenenennenenneenene +LED.Example_description_6=Auch im Wort nennen gibt es mehrere Zyklen, die zum Teil ineinander verschachtelt sind. +LED.Example_pattern_7=babcababc +LED.Example_searchtext_7=bacbaababcabcbabcababcababcabababac +LED.Example_description_7=In diesem Beispielpattern existieren auch wieder Zyklen in Zyklen nur diesmal sind sie ineinander geschachtelt. +LED.Example_pattern_8=xxfxxfxxd +LED.Example_searchtext_8=xxfxxfxxfxxffxxfxxxxfxxfxffxfxxxffxx +LED.Example_description_8=Dieses Beispiel enthält viele Zyklen, ist jedoch im Suchtext nicht vorhanden. +LED.Example_pattern_9=abaababaab +LED.Example_searchtext_9=abaabababaabaabbaababaababaab +LED.Example_description_9=Umso weniger Zeichen in Text und Pattern verwendet werden, desto mehr "passiert" + +RPD.Title=Zufallsgenerierung +RPD.Label_alphabet=Kardinalität des Alphabets +RPD.Label_pattern=Länge des Patterns +RPD.Button_apply=Anwenden +RPD.Button_cancel=Abbrechen + +STLD.Title=Suchtext erstellen +STLD.Label_searchtext=Suchtext +STLD.Button_load=Laden +STLD.Button_apply=Anwenden +STLD.Button_cancel=Abbrechen + +ITP.Tab_codeanddesc=Code und Protokoll +ITP.Tab_codeonly=Code +ITP.Tab_desconly=Protokoll +ITP.Tab_codeandst=Code und Suchtext +ITP.Tab_descandst=Protokoll und Suchtext +ITP.Label_code=Code +ITP.Label_desc=Protokoll +ITP.Label_searchtext=Suchtext +ITP.TextPane_code_ttt=Zeigt den aktuell abzuarbeitenden Code an. +ITP.TextPane_desc_ttt=Zeigt das Protokoll der Algorithmenschritte an. +ITP.TextPane_st_ttt=Zeigt den Suchtext an. \ No newline at end of file diff --git a/bin/org/jalgo/module/kmp/en.properties b/bin/org/jalgo/module/kmp/en.properties new file mode 100644 index 0000000..2e6c46e --- /dev/null +++ b/bin/org/jalgo/module/kmp/en.properties @@ -0,0 +1,120 @@ +Module_name=KMP - Knuth Morris Pratt +Module_version=1.0 +Module_authors=Danilo Lißke, Sebastian Patschorke, Elisa Böhl, Nadine Grabow, Matthias Neubert +Module_license=GNU General Public License +Module_description_1=This module is about the search-algorithm from Knuth Morris Pratt. +Module_description_2=The algorithms to be visualized are: generating the shifting table and use to the search text. The algorithms can be controlled interactively. + +ModuleConnector.No_valid_KMP_file=No valid KMP - file. +ModuleConnector.Loading_error=Error while loading the file. +ModuleConnector.File_damaged=Maybe the file is damaged. + +Screen.Slider_ttt=Change the view size. + +ShowPanel.Head_textposition=TextIndex +ShowPanel.Head_text=Text +ShowPanel.Head_pattern=Pattern +ShowPanel.Head_table=Table +ShowPanel.Head_index=Index +ShowPanel.Head_cycles=Cycles + +InputPanel.Label_extension=Extension +InputPanel.Label_pattern=Pattern +InputPanel.Label_searchtext=Searchtext +InputPanel.Label_result_true=Pattern was found! +InputPanel.Label_result_false=Pattern was not found! +InputPanel.Label_result_ttt=The result of the search. +InputPanel.TextField_pattern_ttt=Enter your pattern here. +InputPanel.TextField_addpattern_ttt=Enter your extension to the pattern here. +InputPanel.CheckBox_cycle=Cycles +InputPanel.CheckBox_cycle_ttt=Should the cycles been shown? +InputPanel.Button_goon=Go on in phase 2 +InputPanel.Button_goon_ttt=Use the actual pattern in phase 2. +InputPanel.Button_set=Set +InputPanel.Button_set_ttt=Sets the given pattern. +InputPanel.Button_random=Random +InputPanel.Button_random_ttt=Generates a random pattern. +InputPanel.Button_addpattern=Add +InputPanel.Button_addpattern_ttt=Adds the extension to the given pattern. +InputPanel.Button_loadst=Enter +InputPanel.Button_loadst_ttt=Load, edit or type in a searchtext. +InputPanel.Button_generst=Generate +InputPanel.Button_generst_ttt=Generates a searchtext from the given pattern. + +Abort=Abort algorithm +Abort_tooltip=Aborts the currently running algorithm +Back=Undo +Back_tooltip=Undoes the last step in current algorithm +FastBack=Undo block step +FastBack_tooltip=Undoes the last block step in current algorithm +Forward=Next step +Forward_tooltip=Performs the next step in current algorithm +FastForward=Next block step +FastForward_tooltip=Performs the next block step in current algorithm +Finish=Finish algorithm +Finish_tooltip=Runs the algorithm until it ends + +Show_welcome_screen=Show welcome screen +Show_welcome_screen_tooltip=Shows the welcome screen +Beamer_mode=Beamer-Mode +Wish_to_discard=Do you wish to discard your changes? + +LED.Title=Load learnexamples +LED.RB_Title=Pattern +LED.LB_Title=Searchtext +LED.Button_apply=Load +LED.Button_cancel=Cancel +LED.Example_pattern_0=tasen +LED.Example_searchtext_0=thisisnotasensefulltext +LED.Example_description_0=This example shows the simplest of all Pattern: there is no cycle inside. +LED.Example_pattern_1=eye +LED.Example_searchtext_1=eneyyeeepopeye +LED.Example_description_1=In this Example exist exactly one cycle. +LED.Example_pattern_2=gigant +LED.Example_searchtext_2=grgigigalaginggigantgiaga +LED.Example_description_2=In this Pattern exists some cycles. +LED.Example_pattern_3=abacaabcab +LED.Example_searchtext_3=abacaabacababacaabcabacaabcac +LED.Example_description_3=In this example exists more cycles. +LED.Example_pattern_4=bbabbac +LED.Example_searchtext_4=bbbabcabbcaabbabbbabbacbbacbacb +LED.Example_description_4=This Pattern has got many cycles. The distinction is, that cycles are in cycles. +LED.Example_pattern_5=erereerr +LED.Example_searchtext_5=erererereererrerereerrerrreer +LED.Example_description_5=The Examplepattern has got some Cycles. The distinction here is, that cycles begin in cycles, they end together. +LED.Example_pattern_6=nennen +LED.Example_searchtext_6=enenneenenenenneenenennenenneenene +LED.Example_description_6=Also real words can have some cycles (nennen is a german word and means denominate) +LED.Example_pattern_7=babcababc +LED.Example_searchtext_7=bacbaababcabcbabcababcababcabababac +LED.Example_description_7=In this example are some cycles again, but these are in a structire like a box in a box. +LED.Example_pattern_8=xxfxxfxxd +LED.Example_searchtext_8=xxfxxfxxfxxffxxfxxxxfxxfxffxfxxxffxx +LED.Example_description_8=This Pattern has got many Cycles but it doesn't exist in the searchtext. +LED.Example_pattern_9=abaababaab +LED.Example_searchtext_9=abaabababaabaabbaababaababaab +LED.Example_description_9=If you use few signs, you got more actions. + +RPD.Title=Random Generation +RPD.Label_alphabet=Size of the alphabet +RPD.Label_pattern=Length of the patterns +RPD.Button_apply=Apply +RPD.Button_cancel=Cancel + +STLD.Title=Create Searchtext +STLD.Label_searchtext=Searchtext +STLD.Button_load=Load +STLD.Button_apply=Apply +STLD.Button_cancel=Cancel + +ITP.Tab_codeanddesc=Code and description +ITP.Tab_codeonly=Code +ITP.Tab_desconly=Description +ITP.Tab_codeandst=Code and searchtext +ITP.Tab_descandst=Description und searchtext +ITP.Label_code=Code +ITP.Label_desc=Description +ITP.Label_searchtext=Searchtext +ITP.TextPane_code_ttt=Shows the actual code. +ITP.TextPane_desc_ttt=Shows the protocol of the algorithm steps. +ITP.TextPane_st_ttt=Shows the searchtext. \ No newline at end of file diff --git a/bin/org/jalgo/module/kmp/gui/GUIConstants.class b/bin/org/jalgo/module/kmp/gui/GUIConstants.class new file mode 100644 index 0000000..e8b9ee1 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/GUIConstants.class differ diff --git a/bin/org/jalgo/module/kmp/gui/GUIController.class b/bin/org/jalgo/module/kmp/gui/GUIController.class new file mode 100644 index 0000000..6df861c Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/GUIController.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.class b/bin/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.class new file mode 100644 index 0000000..2eefaca Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.class b/bin/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.class new file mode 100644 index 0000000..b07fcbb Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.class b/bin/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.class new file mode 100644 index 0000000..1fb62fa Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseOneScreen.class b/bin/org/jalgo/module/kmp/gui/component/PhaseOneScreen.class new file mode 100644 index 0000000..b0a97cd Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseOneScreen.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.class b/bin/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.class new file mode 100644 index 0000000..6283ee2 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.class b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.class new file mode 100644 index 0000000..8c94ef4 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.class b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.class new file mode 100644 index 0000000..d1f5a85 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel$AniThread.class b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel$AniThread.class new file mode 100644 index 0000000..59da705 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel$AniThread.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.class b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.class new file mode 100644 index 0000000..7a69336 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/RandomPatternDialog.class b/bin/org/jalgo/module/kmp/gui/component/RandomPatternDialog.class new file mode 100644 index 0000000..11216cf Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/RandomPatternDialog.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.class b/bin/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.class new file mode 100644 index 0000000..414160e Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/WelcomeButton.class b/bin/org/jalgo/module/kmp/gui/component/WelcomeButton.class new file mode 100644 index 0000000..f1ce423 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/WelcomeButton.class differ diff --git a/bin/org/jalgo/module/kmp/gui/component/WelcomeScreen.class b/bin/org/jalgo/module/kmp/gui/component/WelcomeScreen.class new file mode 100644 index 0000000..5af4e92 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/component/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/AbortAction.class b/bin/org/jalgo/module/kmp/gui/event/AbortAction.class new file mode 100644 index 0000000..4815408 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/AbortAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/BackwardAction.class b/bin/org/jalgo/module/kmp/gui/event/BackwardAction.class new file mode 100644 index 0000000..f0c5eb1 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/BackwardAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/BeamerModeAction.class b/bin/org/jalgo/module/kmp/gui/event/BeamerModeAction.class new file mode 100644 index 0000000..4cba6b5 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/BeamerModeAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/FastBackwardAction.class b/bin/org/jalgo/module/kmp/gui/event/FastBackwardAction.class new file mode 100644 index 0000000..a94e603 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/FastBackwardAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/FastForwardAction.class b/bin/org/jalgo/module/kmp/gui/event/FastForwardAction.class new file mode 100644 index 0000000..ad48278 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/FastForwardAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/FinishAction.class b/bin/org/jalgo/module/kmp/gui/event/FinishAction.class new file mode 100644 index 0000000..0327474 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/FinishAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/ForwardAction.class b/bin/org/jalgo/module/kmp/gui/event/ForwardAction.class new file mode 100644 index 0000000..96c5871 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/ForwardAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.class b/bin/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.class new file mode 100644 index 0000000..ba662c6 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.class b/bin/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.class new file mode 100644 index 0000000..ee8e108 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/WelcomeAction.class b/bin/org/jalgo/module/kmp/gui/event/WelcomeAction.class new file mode 100644 index 0000000..ce14065 Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/WelcomeAction.class differ diff --git a/bin/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.class b/bin/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.class new file mode 100644 index 0000000..6fd503e Binary files /dev/null and b/bin/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.class differ diff --git a/bin/org/jalgo/module/kmp/res.properties b/bin/org/jalgo/module/kmp/res.properties new file mode 100644 index 0000000..8b0ee2c --- /dev/null +++ b/bin/org/jalgo/module/kmp/res.properties @@ -0,0 +1,20 @@ +Module_logo=/kmp_pix/logo.gif + +HelpSet_Name=/help/jhelp/kmp_help.hs + +Welcome_phaseone=/kmp_pix/welcome_phaseone.gif +Welcome_phaseone_rollover=/kmp_pix/welcome_phaseone_rollover.gif +Welcome_phaseone_description_de=/kmp_pix/welcome_phaseone_desc_de.gif +Welcome_phaseone_description_en=/kmp_pix/welcome_phaseone_desc_en.gif +Welcome_phasetwo=/kmp_pix/welcome_phasetwo.gif +Welcome_phasetwo_rollover=/kmp_pix/welcome_phasetwo_rollover.gif +Welcome_phasetwo_description_de=/kmp_pix/welcome_phasetwo_desc_de.gif +Welcome_phasetwo_description_en=/kmp_pix/welcome_phasetwo_desc_en.gif +Welcome_open=/kmp_pix/welcome_open.gif +Welcome_open_rollover=/kmp_pix/welcome_open_rollover.gif +Welcome_open_description_de=/kmp_pix/welcome_open_desc_de.gif +Welcome_open_description_en=/kmp_pix/welcome_open_desc_en.gif +Welcome_example=/kmp_pix/welcome_example.gif +Welcome_example_rollover=/kmp_pix/welcome_example_rollover.gif +Welcome_example_description_de=/kmp_pix/welcome_example_desc_de.gif +Welcome_example_description_en=/kmp_pix/welcome_example_desc_en.gif \ No newline at end of file diff --git a/bin/org/jalgo/module/lambda/Constants.class b/bin/org/jalgo/module/lambda/Constants.class new file mode 100644 index 0000000..675df91 Binary files /dev/null and b/bin/org/jalgo/module/lambda/Constants.class differ diff --git a/bin/org/jalgo/module/lambda/LambdaCalculus.g b/bin/org/jalgo/module/lambda/LambdaCalculus.g new file mode 100644 index 0000000..731839f --- /dev/null +++ b/bin/org/jalgo/module/lambda/LambdaCalculus.g @@ -0,0 +1,112 @@ +grammar LambdaCalculus; + + +options { + output = AST; + } + +tokens { + LAMBDA = '\u03BB'; + POINT = '.'; + POPEN = '('; + PCLOSE = ')'; + SPOPEN = '<'; + SPCLOSE = '>'; + ABSTRACTION; + APPLICATION; + ATOM; + SHORTCUT; + } + +@header { + package parser; + import model.*; + +} + +@lexer::header { + + package parser; + import model.*; + +} + +@members { + + + Term t; +protected void mismatch(IntStream input, int ttype, BitSet follow) + throws RecognitionException +{ + System.out.println("aki1"); + throw new MismatchedTokenException(ttype, input); + +} +protected Object recoverFromMismatchedToken(IntStream input, + int ttype, + BitSet follow) + throws RecognitionException +{ + System.out.println("aki2"); + throw new MismatchedTokenException(ttype, input); +} + + +} + + + +// Alter code generation so catch-clauses get replace with +// this action. +@rulecatch { +catch (RecognitionException e) { + throw e; +} +} +// END:override LAMBDA = '\u03BB'; + + +/*------------------------------------------------------------------ + * PARSER RULES + *------------------------------------------------------------------*/ + +start : term EOF; +term : atom + | abstraction + | application + | shortcut + /*| (POPEN term PCLOSE)=> term /* FIXME: this should go */ + | (POPEN atom PCLOSE)=> atom /*FIXME: this should go */ + ; + + +atom : variable + | constant + ; +variable: v=VAR -> ^(ATOM $v); +constant: c=CONS -> ^(ATOM $c); + +abstraction + : POPEN LAMBDA aa=variable POINT at=term PCLOSE -> ^(ABSTRACTION $aa $at) ; +application + : POPEN t1=term t2=term PCLOSE -> ^(APPLICATION $t1 $t2); +shortcut: s=SHORTCUTID -> ^(SHORTCUT $s); +/*------------------------------------------------------------------ + * LEXER RULES + *------------------------------------------------------------------*/ + +VAR : ('k'..'z'); +CONS : ('a'..'j' | '+' | '-' | '*' | '/' | '%' ); + +SHORTCUTID + : SPOPEN(LETTER)+SPCLOSE; +fragment LETTER + : ('a'..'z'|'A'..'Z'|'0'..'9'); +WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ; + +COMMENT + : '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;} + ; +LINE_COMMENT + : '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;} + ; diff --git a/bin/org/jalgo/module/lambda/ModuleConnector.class b/bin/org/jalgo/module/lambda/ModuleConnector.class new file mode 100644 index 0000000..009c776 Binary files /dev/null and b/bin/org/jalgo/module/lambda/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/lambda/ModuleInfo.class b/bin/org/jalgo/module/lambda/ModuleInfo.class new file mode 100644 index 0000000..1f6b010 Binary files /dev/null and b/bin/org/jalgo/module/lambda/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/lambda/ShortcutHandler.class b/bin/org/jalgo/module/lambda/ShortcutHandler.class new file mode 100644 index 0000000..a9f5724 Binary files /dev/null and b/bin/org/jalgo/module/lambda/ShortcutHandler.class differ diff --git a/bin/org/jalgo/module/lambda/controller/Controller.class b/bin/org/jalgo/module/lambda/controller/Controller.class new file mode 100644 index 0000000..64014a1 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/Controller.class differ diff --git a/bin/org/jalgo/module/lambda/controller/EToken.class b/bin/org/jalgo/module/lambda/controller/EToken.class new file mode 100644 index 0000000..808e959 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/EToken.class differ diff --git a/bin/org/jalgo/module/lambda/controller/HistoryStep.class b/bin/org/jalgo/module/lambda/controller/HistoryStep.class new file mode 100644 index 0000000..1afa085 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/HistoryStep.class differ diff --git a/bin/org/jalgo/module/lambda/controller/HistoryTerm.class b/bin/org/jalgo/module/lambda/controller/HistoryTerm.class new file mode 100644 index 0000000..2cae056 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/HistoryTerm.class differ diff --git a/bin/org/jalgo/module/lambda/controller/IController.class b/bin/org/jalgo/module/lambda/controller/IController.class new file mode 100644 index 0000000..e811ed4 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/IController.class differ diff --git a/bin/org/jalgo/module/lambda/controller/IParseUnit.class b/bin/org/jalgo/module/lambda/controller/IParseUnit.class new file mode 100644 index 0000000..11ab459 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/IParseUnit.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculus.tokens b/bin/org/jalgo/module/lambda/controller/LambdaCalculus.tokens new file mode 100644 index 0000000..03d70d1 --- /dev/null +++ b/bin/org/jalgo/module/lambda/controller/LambdaCalculus.tokens @@ -0,0 +1,23 @@ +SPOPEN=8 +ABSTRACTION=10 +LINE_COMMENT=20 +POPEN=6 +POINT=5 +APPLICATION=11 +LETTER=17 +SHORTCUTID=16 +WHITESPACE=18 +ATOM=12 +SHORTCUT=13 +PCLOSE=7 +CONS=15 +VAR=14 +LAMBDA=4 +COMMENT=19 +SPCLOSE=9 +'<'=8 +'('=6 +')'=7 +'.'=5 +'>'=9 +'\u03BB'=4 diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer$DFA6.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer$DFA6.class new file mode 100644 index 0000000..372706f Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer$DFA6.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer.class new file mode 100644 index 0000000..c7059ac Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusLexer.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$abstraction_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$abstraction_return.class new file mode 100644 index 0000000..efa7736 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$abstraction_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$application_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$application_return.class new file mode 100644 index 0000000..d6fc7b6 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$application_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$atom_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$atom_return.class new file mode 100644 index 0000000..c41a05a Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$atom_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$constant_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$constant_return.class new file mode 100644 index 0000000..d28e08a Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$constant_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$shortcut_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$shortcut_return.class new file mode 100644 index 0000000..b1da536 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$shortcut_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$start_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$start_return.class new file mode 100644 index 0000000..8c44e2f Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$start_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$term_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$term_return.class new file mode 100644 index 0000000..3610780 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$term_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$variable_return.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$variable_return.class new file mode 100644 index 0000000..2430ca0 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser$variable_return.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser.class b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser.class new file mode 100644 index 0000000..46152af Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaCalculusParser.class differ diff --git a/bin/org/jalgo/module/lambda/controller/LambdaException.class b/bin/org/jalgo/module/lambda/controller/LambdaException.class new file mode 100644 index 0000000..2b79fad Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/LambdaException.class differ diff --git a/bin/org/jalgo/module/lambda/controller/ParseUnit.class b/bin/org/jalgo/module/lambda/controller/ParseUnit.class new file mode 100644 index 0000000..4656ad8 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/ParseUnit.class differ diff --git a/bin/org/jalgo/module/lambda/controller/TermHistory.class b/bin/org/jalgo/module/lambda/controller/TermHistory.class new file mode 100644 index 0000000..266a7c4 Binary files /dev/null and b/bin/org/jalgo/module/lambda/controller/TermHistory.class differ diff --git a/bin/org/jalgo/module/lambda/de.properties b/bin/org/jalgo/module/lambda/de.properties new file mode 100644 index 0000000..991a81f --- /dev/null +++ b/bin/org/jalgo/module/lambda/de.properties @@ -0,0 +1,88 @@ +Module_name=Lambda Kalkül +Module_version=1.0 +Module_authors=Frank Dietze, Tobias Reiher, Benjamin Schneider, Nico Braunisch, Joshua Peschke, Francisco Rojas +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt das Lambda Kalkül. +Module_description_2=... + +btxt.done=OK +btxt.clear=Löschen +btxt.toList=zur Liste + +bts.done=Eingabe beenden. +bts.clear=Löscht das Eingabefeld. +bts.insertSC=Fügt die Abkürzung an der Cursorposition ein. +bts.deleteSC=Löscht die markierte Abkürzung. +bts.newSC=Erstellt aus dem Term im Eingabefeld eine neue Abkürzung. +bts.toList=Fügt den Term der Liste hinzu. +bts.doStep=Führt den nächsten Schritt aus. +bts.doShortcutStep=Führt einen Rechenschritt auf Abkürzungen aus. +bts.undoStep=Nimmt den aktuellen Schritt zurück. +bts.doAllSteps=Führt alle Schritte aus. +bts.undoAllSteps=Nimmt alle Schritte zurück. +bts.alpha=Führt eine Alpha-Konversion durch. +bts.beta=Führt eine Beta-Reduktion durch. +bts.markFreeVars=Zeigt alle freien Variablen. +bts.markBoundVars=Zeigt alle gebundenen Variablen. +bts.showhideBrackets=Zeigt oder verbirgt Klammern. +bts.shortcutDialog=Zeigt/Verbirgt die Auswahlliste der Abkürzungen. +bts.shortcutEliminate=Löst einen Shortcut auf. +bts.shortcutMatch=Ersetzt den selektierten Term durch eine definierte Abkürzung. +bts.doAutoStep=Führt einen automatischen Rechenschritt aus. +bts.doAllAutoSteps=Führt so viele Rechenschritte wie möglich automatisch aus. + +ltxt.input=Bitte Lambda-Term eingeben (mit Variablen k..z, allen Klammern und \u03bb = backslash). +ltxt.toList=Term wurde in die Liste eingetragen. +ltxt.termCorrect=Lambda-Term korrekt. +ltxt.termIncorrect=Lambda-Term nicht korrekt. +ltxt.alphaFailed=Alpha-Conversion fehlgeschlagen. Markieren Sie eine Abstraktion! +ltxt.alphaNoVars=Alpha-Conversion nicht möglich, alle Variablen verbraucht. +ltxt.betaFailed=Beta-Reduktion fehlgeschlagen. Markieren Sie eine Applikation! +ltxt.alphaNeeded=Zunächst ist eine Alpha-Conversion erforderlich! + +ltxt.recognitionEx=Syntaxfehler bei Zeichen Nummer X gefunden. +ltxt.recognitionEx2= An Position X wurde Y erwartet aber Z gefunden. +ltxt.errorApplication= Die Applikation hatte weniger als 2 Kinder. +ltxt.errorAbstraction=Die Abstraktion hatte weniger als 2 Kinder. +ltxt.errorForbidden=Es sind verbotene Zeichen enthalten. Erlaubt sind a..z,(,),+,-,*,/ und % sowie definierte Abkürzungen. +ltxt.errorAbstraction =eine Abstraktion +ltxt.errorApplication =eine Applikation +ltxt.errorAtom =eine Variable oder eine Konstante +ltxt.errorLetter =eine Variable +ltxt.errorCons =eine Konstante +ltxt.errorShortcut1 =eine Abkürzung +ltxt.errorPoint =ein Punkt +ltxt.errorEof =nichts +ltxt.errorShortcut=Die Abkürzung X wurde nicht gefunden. +ltxt.inputSCTerm=Bitte geben Sie den Term der Abkürzung ein (mit Variablen k..z, allen Klammern und \u03bb = backslash). +ltxt.scNameFault=Abkürzungen müssen mit < beginnen und mit > enden! +ltxt.scNameExists=Dieser Name existiert bereits für eine Abkürzung! Bitte anderen Namen eingeben. +ltxt.scTermExists=Dieser Term ist bereits als Abkürzung vorhanden! + +dia.alphaTitle=Auswahldialog der Variablen-Ersetzung +dia.alphaMessage=Bitte wählen Sie aus den verfügbaren Variablen eine aus. +dia.clearMessage=Soll dieser Term aus der Liste entfernt werden? +dia.newclearMessageTitel=Auswahl-Liste bearbeiten +dia.newTermMessage=Soll dieser Term in die Liste aufgenommen werden? + +scDlg.title=Shortcut auswählen oder erstellen +scDlg.clsBtn=Schließen +scDlg.insBtn=Einf +scDlg.delBtn=Entf +scDlg.newBtn=Neu +scDlg.crtBtn=Erstellen +scDlg.lblTxt=Shortcut Text +scDlg.lblTrm=Shortcut Term +scDlg.ShortcutEmpty=Das Shortcutfeld ist leer +scDlg.TermEmpty=Das Termfeld ist leer. +scDlg.ShortcutExist=Dieser Shortcut ist schon vorhanden. +scDlg.ListLabel=Liste der Abkürzungen +scDlg.ListLabel2=Neue Abkürzungen definieren +scDlg.inputSCLabel=Name der Abkürzung + +wlc.new=Lambdaterm eingeben +wlc.load=Lambdaterm laden + +ModuleConnector.Load_Error=Fehler beim Laden der Datei. +ModuleConnector.Save_Error=Fehler beim Speichern der Datei. +ModuleConnector.File_damaged=Datei beschädigt. \ No newline at end of file diff --git a/bin/org/jalgo/module/lambda/en.properties b/bin/org/jalgo/module/lambda/en.properties new file mode 100644 index 0000000..255cc24 --- /dev/null +++ b/bin/org/jalgo/module/lambda/en.properties @@ -0,0 +1,88 @@ +Module_name=Lambda Calculus +Module_version=1.0 +Module_authors=Frank Dietze, Tobias Reiher, Benjamin Schneider, Nico Braunisch, Joshua Peschke, Francisco Rojas +Module_license=GNU General Public License +Module_description_1=This module handels the lambda calculus. +Module_description_2=... + +btxt.done=OK +btxt.clear=Clear +btxt.toList=add to List + +bts.done=Finish the input. +bts.clear=Clears the inputfield. +bts.insertSC=Inserts the selected shortcut at cursor position. +bts.deleteSC=Deletes the selected shortcut. +bts.newSC=Creates a new shortcut from the term of the inputfield. +bts.toList=Adds the term to the list. +bts.doStep=Do the next step. +bts.doShortcutStep=Performs a step on shortcuts. +bts.undoStep=Undo the last step. +bts.doAllSteps=Do all steps. +bts.undoAllSteps=Undo all steps. +bts.alpha=Do alpha-conversion. +bts.beta=Do beta-reduction. +bts.markFreeVars=Mark free variables. +bts.markBoundVars=Mark bound variables. +bts.showhideBrackets=Show or hide brackets. +bts.shortcutDialog=Show/Hide list of shortcuts. +bts.shortcutEliminate=Break shortcut(s) down. +bts.shortcutMatch=Makes a defined shortcut out of the selected term. +bts.doAutoStep=Performs an automatic step. +bts.doAllAutoSteps=Performs as many automatic steps as possible. + +ltxt.input=Please input Lambda-Term (with k..z as variables, all brackets and \u03bb = backslash) +ltxt.toList=Term was added to the list. +ltxt.termCorrect=Lambda-Term correct. +ltxt.termIncorrect=Lambda-Term incorrect. +ltxt.alphaFailed=Alpha-Conversion failed. Mark an Abstraction! +ltxt.alphaNoVars=Alpha-Conversion impossible, no unused variables left. +ltxt.betaFailed=Beta-Reduction failed. Mark an Application. +ltxt.alphaNeeded=Alpha-Conversion needed. + +ltxt.recognitionEx=An error occured while parsing at letter number X. +ltxt.recognitionEx2=Expected X at position Y but found Z. +ltxt.errorApplication=Application had less than 2 children. +ltxt.errorAbstraction=Abstraction had less than 2 children. +ltxt.errorForbidden=There are forbidden characters. Allowed are a..z,(,),+,-,*,/ and % as well as defined shortcuts. +ltxt.errorAbstraction =an abstraction +ltxt.errorApplication =an application +ltxt.errorAtom =a variable or constant +ltxt.errorLetter =a variable +ltxt.errorCons =a constant +ltxt.errorShortcut1 =a shortcut +ltxt.errorPoint =a point +ltxt.errorEof=no character +ltxt.errorShortcut = The shortcut X was not found. +ltxt.inputSCTerm=Please input the term of the shortcut (with k..z as variables, all brackets and \u03bb = backslash) +ltxt.scNameFault=Shortcut-names have to start with < and end with > ! +ltxt.scNameExists=This shortcut-name already exists! Please input another name. +ltxt.scTermExists=This term already exists as a shortcut! + +dia.alphaTitle=Select variable +dia.alphaMessage=Please choose one of the available variables. +dia.clearMessage=Should this term be removed from the list? +dia.newclearMessageTitel=Change dropdown-list +dia.newTermMessage=Should this term be added to the list? + +scDlg.title=Choose or Create Shortcut +scDlg.clsBtn=Close +scDlg.insBtn=Ins +scDlg.delBtn=Del +scDlg.newBtn=New +scDlg.crtBtn=Create +scDlg.lblTxt=Shortcut Text +scDlg.lblTrm=Shortcut Term +scDlg.ShortcutEmpty=The shortcut field is empty. +scDlg.TermEmpty=The term field is empty. +scDlg.ShortcutExist=This Shortcut already exists. +scDlg.ListLabel=List of shortcuts +scDlg.ListLabel2=Define new shortcuts +scDlg.inputSCLabel=Name of the shortcut + +wlc.new=Enter Lambdaterm +wlc.load=Load Lambdaterm + +ModuleConnector.Load_Error=Error while loading file. +ModuleConnector.Save_Error=Error while saving file. +ModuleConnector.File_damaged=File damaged. \ No newline at end of file diff --git a/bin/org/jalgo/module/lambda/model/Abstraction.class b/bin/org/jalgo/module/lambda/model/Abstraction.class new file mode 100644 index 0000000..9779b26 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Abstraction.class differ diff --git a/bin/org/jalgo/module/lambda/model/Application.class b/bin/org/jalgo/module/lambda/model/Application.class new file mode 100644 index 0000000..4f1415e Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Application.class differ diff --git a/bin/org/jalgo/module/lambda/model/Atom.class b/bin/org/jalgo/module/lambda/model/Atom.class new file mode 100644 index 0000000..18f089f Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Atom.class differ diff --git a/bin/org/jalgo/module/lambda/model/EAvailability.class b/bin/org/jalgo/module/lambda/model/EAvailability.class new file mode 100644 index 0000000..e48a0da Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/EAvailability.class differ diff --git a/bin/org/jalgo/module/lambda/model/EStepKind.class b/bin/org/jalgo/module/lambda/model/EStepKind.class new file mode 100644 index 0000000..dd48517 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/EStepKind.class differ diff --git a/bin/org/jalgo/module/lambda/model/ETermType.class b/bin/org/jalgo/module/lambda/model/ETermType.class new file mode 100644 index 0000000..22d5979 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/ETermType.class differ diff --git a/bin/org/jalgo/module/lambda/model/Format.class b/bin/org/jalgo/module/lambda/model/Format.class new file mode 100644 index 0000000..8a77d1b Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Format.class differ diff --git a/bin/org/jalgo/module/lambda/model/FormatString.class b/bin/org/jalgo/module/lambda/model/FormatString.class new file mode 100644 index 0000000..3dc7ea4 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/FormatString.class differ diff --git a/bin/org/jalgo/module/lambda/model/ITermHandler.class b/bin/org/jalgo/module/lambda/model/ITermHandler.class new file mode 100644 index 0000000..77b9de3 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/ITermHandler.class differ diff --git a/bin/org/jalgo/module/lambda/model/Shortcut.class b/bin/org/jalgo/module/lambda/model/Shortcut.class new file mode 100644 index 0000000..fa60d0c Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Shortcut.class differ diff --git a/bin/org/jalgo/module/lambda/model/Term.class b/bin/org/jalgo/module/lambda/model/Term.class new file mode 100644 index 0000000..c818319 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/Term.class differ diff --git a/bin/org/jalgo/module/lambda/model/TermHandler.class b/bin/org/jalgo/module/lambda/model/TermHandler.class new file mode 100644 index 0000000..74cfd75 Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/TermHandler.class differ diff --git a/bin/org/jalgo/module/lambda/model/TermIterator.class b/bin/org/jalgo/module/lambda/model/TermIterator.class new file mode 100644 index 0000000..44e120b Binary files /dev/null and b/bin/org/jalgo/module/lambda/model/TermIterator.class differ diff --git a/bin/org/jalgo/module/lambda/res.properties b/bin/org/jalgo/module/lambda/res.properties new file mode 100644 index 0000000..97a9eba --- /dev/null +++ b/bin/org/jalgo/module/lambda/res.properties @@ -0,0 +1,22 @@ +Module_logo=/lambda_pix/logo.jpg +Icon.alpha=/lambda_pix/alpha.png +Icon.beta=/lambda_pix/beta.png +Icon.freeVar=/lambda_pix/freeVar.png +Icon.boundVar=/lambda_pix/boundVar.png +Icon.brackets=/lambda_pix/brackets.png +Icon.sc_brackets=/lambda_pix/sc_brackets.png +Icon.sc_brackets_x=/lambda_pix/sc_brackets_x.png +Icon.welcomeNew=/lambda_pix/WelcomeNew.png +Icon.welcomeLoad=/lambda_pix/WelcomeOpen.png +Icon.welcomeNewOver=/lambda_pix/WelcomeNewOver.png +Icon.welcomeLoadOver=/lambda_pix/WelcomeOpenOver.png + +file.terms=/lambda/terms.txt +file.shortcuts=/lambda/shortcuts.txt + +Icon.Clear=/main_pix/clear.gif +Icon.Add=/images/plus_button.gif +Icon.autoStep=/lambda_pix/autoStep.png +Icon.shortcutStep=/lambda_pix/shortcutStep.png + +HelpSet_Name=/help/jhelp/lambda_help.hs \ No newline at end of file diff --git a/bin/org/jalgo/module/lambda/view/.merge.tmp b/bin/org/jalgo/module/lambda/view/.merge.tmp new file mode 100644 index 0000000..e69de29 diff --git a/bin/org/jalgo/module/lambda/view/EMessageType.class b/bin/org/jalgo/module/lambda/view/EMessageType.class new file mode 100644 index 0000000..b32e79f Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/EMessageType.class differ diff --git a/bin/org/jalgo/module/lambda/view/ExchangeTextField$ExchangeDocument.class b/bin/org/jalgo/module/lambda/view/ExchangeTextField$ExchangeDocument.class new file mode 100644 index 0000000..2b4062c Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/ExchangeTextField$ExchangeDocument.class differ diff --git a/bin/org/jalgo/module/lambda/view/ExchangeTextField.class b/bin/org/jalgo/module/lambda/view/ExchangeTextField.class new file mode 100644 index 0000000..53ce8fc Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/ExchangeTextField.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$1.class b/bin/org/jalgo/module/lambda/view/GUIController$1.class new file mode 100644 index 0000000..a630240 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$1.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$10.class b/bin/org/jalgo/module/lambda/view/GUIController$10.class new file mode 100644 index 0000000..42d4fe2 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$10.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$11.class b/bin/org/jalgo/module/lambda/view/GUIController$11.class new file mode 100644 index 0000000..9382b21 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$11.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$12.class b/bin/org/jalgo/module/lambda/view/GUIController$12.class new file mode 100644 index 0000000..3e1f521 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$12.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$13.class b/bin/org/jalgo/module/lambda/view/GUIController$13.class new file mode 100644 index 0000000..2c1cf9a Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$13.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$14.class b/bin/org/jalgo/module/lambda/view/GUIController$14.class new file mode 100644 index 0000000..6c4f345 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$14.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$15.class b/bin/org/jalgo/module/lambda/view/GUIController$15.class new file mode 100644 index 0000000..61d5246 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$15.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$16.class b/bin/org/jalgo/module/lambda/view/GUIController$16.class new file mode 100644 index 0000000..f003845 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$16.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$17.class b/bin/org/jalgo/module/lambda/view/GUIController$17.class new file mode 100644 index 0000000..1ad7980 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$17.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$18.class b/bin/org/jalgo/module/lambda/view/GUIController$18.class new file mode 100644 index 0000000..29c9fa8 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$18.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$19.class b/bin/org/jalgo/module/lambda/view/GUIController$19.class new file mode 100644 index 0000000..52e5974 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$19.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$2.class b/bin/org/jalgo/module/lambda/view/GUIController$2.class new file mode 100644 index 0000000..584230a Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$2.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$20.class b/bin/org/jalgo/module/lambda/view/GUIController$20.class new file mode 100644 index 0000000..e07bfd3 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$20.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$21.class b/bin/org/jalgo/module/lambda/view/GUIController$21.class new file mode 100644 index 0000000..b0692ba Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$21.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$22.class b/bin/org/jalgo/module/lambda/view/GUIController$22.class new file mode 100644 index 0000000..2f6c2bf Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$22.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$23.class b/bin/org/jalgo/module/lambda/view/GUIController$23.class new file mode 100644 index 0000000..9f53054 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$23.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$24.class b/bin/org/jalgo/module/lambda/view/GUIController$24.class new file mode 100644 index 0000000..92968db Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$24.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$25.class b/bin/org/jalgo/module/lambda/view/GUIController$25.class new file mode 100644 index 0000000..4a92488 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$25.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$26.class b/bin/org/jalgo/module/lambda/view/GUIController$26.class new file mode 100644 index 0000000..ad632ac Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$26.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$3.class b/bin/org/jalgo/module/lambda/view/GUIController$3.class new file mode 100644 index 0000000..7555433 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$3.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$4.class b/bin/org/jalgo/module/lambda/view/GUIController$4.class new file mode 100644 index 0000000..3c56a0a Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$4.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$5.class b/bin/org/jalgo/module/lambda/view/GUIController$5.class new file mode 100644 index 0000000..dd90e7d Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$5.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$6.class b/bin/org/jalgo/module/lambda/view/GUIController$6.class new file mode 100644 index 0000000..8cbbfed Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$6.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$7.class b/bin/org/jalgo/module/lambda/view/GUIController$7.class new file mode 100644 index 0000000..4b8d079 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$7.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$8.class b/bin/org/jalgo/module/lambda/view/GUIController$8.class new file mode 100644 index 0000000..0a82d15 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$8.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController$9.class b/bin/org/jalgo/module/lambda/view/GUIController$9.class new file mode 100644 index 0000000..4094b3d Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController$9.class differ diff --git a/bin/org/jalgo/module/lambda/view/GUIController.class b/bin/org/jalgo/module/lambda/view/GUIController.class new file mode 100644 index 0000000..680120a Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/GUIController.class differ diff --git a/bin/org/jalgo/module/lambda/view/RenderElement.class b/bin/org/jalgo/module/lambda/view/RenderElement.class new file mode 100644 index 0000000..27700aa Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/RenderElement.class differ diff --git a/bin/org/jalgo/module/lambda/view/RenderLabel.class b/bin/org/jalgo/module/lambda/view/RenderLabel.class new file mode 100644 index 0000000..718af6d Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/RenderLabel.class differ diff --git a/bin/org/jalgo/module/lambda/view/Renderer.class b/bin/org/jalgo/module/lambda/view/Renderer.class new file mode 100644 index 0000000..604b73e Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/Renderer.class differ diff --git a/bin/org/jalgo/module/lambda/view/WelcomeScreen.class b/bin/org/jalgo/module/lambda/view/WelcomeScreen.class new file mode 100644 index 0000000..0798495 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/lambda/view/WelcomeScreenButton.class b/bin/org/jalgo/module/lambda/view/WelcomeScreenButton.class new file mode 100644 index 0000000..331d871 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/WelcomeScreenButton.class differ diff --git a/bin/org/jalgo/module/lambda/view/WorkScreen.class b/bin/org/jalgo/module/lambda/view/WorkScreen.class new file mode 100644 index 0000000..5799d23 Binary files /dev/null and b/bin/org/jalgo/module/lambda/view/WorkScreen.class differ diff --git a/bin/org/jalgo/module/pulsemem/Admin.class b/bin/org/jalgo/module/pulsemem/Admin.class new file mode 100644 index 0000000..ccfca9f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/Admin.class differ diff --git a/bin/org/jalgo/module/pulsemem/Controller.class b/bin/org/jalgo/module/pulsemem/Controller.class new file mode 100644 index 0000000..f215835 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/Controller.class differ diff --git a/bin/org/jalgo/module/pulsemem/ModuleConnector.class b/bin/org/jalgo/module/pulsemem/ModuleConnector.class new file mode 100644 index 0000000..71bde4c Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/pulsemem/ModuleInfo.class b/bin/org/jalgo/module/pulsemem/ModuleInfo.class new file mode 100644 index 0000000..2d82126 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/pulsemem/Parsertest.class b/bin/org/jalgo/module/pulsemem/Parsertest.class new file mode 100644 index 0000000..25b992a Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/Parsertest.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/CliIOSimulation.class b/bin/org/jalgo/module/pulsemem/core/CliIOSimulation.class new file mode 100644 index 0000000..99f0542 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/CliIOSimulation.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/CodeGenerator.class b/bin/org/jalgo/module/pulsemem/core/CodeGenerator.class new file mode 100644 index 0000000..46e7ee9 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/CodeGenerator.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/FunctionHandler.class b/bin/org/jalgo/module/pulsemem/core/FunctionHandler.class new file mode 100644 index 0000000..b27a050 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/FunctionHandler.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/IOSimulation.class b/bin/org/jalgo/module/pulsemem/core/IOSimulation.class new file mode 100644 index 0000000..097e79c Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/IOSimulation.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/PulsMemLine.class b/bin/org/jalgo/module/pulsemem/core/PulsMemLine.class new file mode 100644 index 0000000..b313717 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/PulsMemLine.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/Stack.class b/bin/org/jalgo/module/pulsemem/core/Stack.class new file mode 100644 index 0000000..94b562b Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/Stack.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/SwitchHandler.class b/bin/org/jalgo/module/pulsemem/core/SwitchHandler.class new file mode 100644 index 0000000..60a44fc Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/SwitchHandler.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/VarInfo.class b/bin/org/jalgo/module/pulsemem/core/VarInfo.class new file mode 100644 index 0000000..6b60c23 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/VarInfo.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/Variable.class b/bin/org/jalgo/module/pulsemem/core/Variable.class new file mode 100644 index 0000000..71283c6 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/Variable.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/Zeiger.class b/bin/org/jalgo/module/pulsemem/core/Zeiger.class new file mode 100644 index 0000000..7fb3ee7 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/Zeiger.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/bufferedIOSimulation.class b/bin/org/jalgo/module/pulsemem/core/bufferedIOSimulation.class new file mode 100644 index 0000000..0257257 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/bufferedIOSimulation.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.class b/bin/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.class new file mode 100644 index 0000000..729be0c Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.class new file mode 100644 index 0000000..7577518 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.class new file mode 100644 index 0000000..9403cd0 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.class new file mode 100644 index 0000000..aaf8eff Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.class new file mode 100644 index 0000000..d4194fb Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.class new file mode 100644 index 0000000..8cdec9b Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.class new file mode 100644 index 0000000..659316f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.class new file mode 100644 index 0000000..1f9a9e4 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.class new file mode 100644 index 0000000..1e1533f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.class b/bin/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.class new file mode 100644 index 0000000..6c2be52 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EPMLException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EPMLException.class new file mode 100644 index 0000000..94bc0a5 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EPMLException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.class new file mode 100644 index 0000000..56f1407 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.class new file mode 100644 index 0000000..c872c1c Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EReturnException.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EReturnException.class new file mode 100644 index 0000000..a7ce52d Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EReturnException.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.class b/bin/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.class new file mode 100644 index 0000000..fc836aa Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.class new file mode 100644 index 0000000..9d7fcb7 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.class new file mode 100644 index 0000000..b6ea5e8 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.class new file mode 100644 index 0000000..a9eea72 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.class b/bin/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.class new file mode 100644 index 0000000..9df7ef4 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.class differ diff --git a/bin/org/jalgo/module/pulsemem/core/myInterpreter.class b/bin/org/jalgo/module/pulsemem/core/myInterpreter.class new file mode 100644 index 0000000..4e1a600 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/core/myInterpreter.class differ diff --git a/bin/org/jalgo/module/pulsemem/de.properties b/bin/org/jalgo/module/pulsemem/de.properties new file mode 100644 index 0000000..f4cf0c4 --- /dev/null +++ b/bin/org/jalgo/module/pulsemem/de.properties @@ -0,0 +1,90 @@ +#Created by JInto - www.guh-software.de +#Thu Jun 28 22:32:41 CEST 2007 +Exception.ECycleLimitReached.Message_End=) \u00FCberschritten. Fehler im C00-Code? +Exception.ECycleLimitReached.Message_Start=Maximale Rekursionstiefe ( +Exception.EFunctionNotImplemented.Message_End=) wurde aufgerufen. +Exception.EFunctionNotImplemented.Message_Start=Nicht implementierte Funktion (Zeile\: +Exception.EIncompatibleFunctionHeaders.Message_End=). Funktion wurde bereits mit einem anderen Header definiert\! +Exception.EIncompatibleFunctionHeaders.Message_Start=Fehler bei Funktionsimplementierung (Zeile\: +Exception.EIncompatibleParameterCount.Message_Between=\ Parameter aber es wurden +Exception.EIncompatibleParameterCount.Message_End=\ gefunden. +Exception.EIncompatibleParameterCount.Message_Start=Funktion erwartet +Exception.EIncompatibleParameterTypes.Message_Between=. Parameter sollte +Exception.EIncompatibleParameterTypes.Message_End=\ sein. Vorgefunden wurde\: +Exception.EIncompatibleParameterTypes.Message_Start=Fehler beim Aufruf der Funktion +Exception.EIncompatibleTypes.Message_Between=\ wurde ein +Exception.EIncompatibleTypes.Message_End=zugewiesen. Erwartet wurde +Exception.EIncompatibleTypes.Message_Start=Der Variable +Exception.EMemoryError.Message_Start=Speicherzugriffsfehler. Zugriff auf nicht initialisierte oder nicht sichtbare Variable\: +Exception.ENotAPointerException.Message_End=\ kann nicht dereferenziert werden. +Exception.ENotAPointerException.Message_Start=Nicht-Pointer Variable +Exception.ENullPointer.Message_End=\ wurde nicht initialisiert. +Exception.ENullPointer.Message_Start=Der Pointer +Exception.EPMLException.Message=PML wurde ver\u00E4ndert. Fehler in im Interpreter\! +Exception.EPointerTargetException.Message_End=\ wurde ein int-Wert zugewiesen. (Pointer m\u00FCssen auf Variablen zeigen) +Exception.EPointerTargetException.Message_Start=Dem Pointer +Exception.EPrintfException.Message_Start=Anzahl von Platzhaltern und Argumenten bei Printf-Anweisung stimmt nicht \u00FCberein. Zeile\: +Exception.EReturnException.Message_Between=. Erwarteter Typ\: +Exception.EReturnException.Message_End=\ Zeile\: +Exception.EReturnException.Message_Start=Fehler bei R\u00FCcksprung aus der Funktion\! Typ des R\u00FCckgabewerts\: +Exception.ETypeExpected.Message_Between=\ wurde erwartet, aber Typ +Exception.ETypeExpected.Message_End=wurde gefunden. Zeile\: +Exception.ETypeExpected.Message_Start=Typ +Exception.EVarNotFound.Message_End=\ wurde nicht deklariert. +Exception.EVarNotFound.Message_Start=Gesuchte Variable +Exception.EWriteConstant.Message_End=\ darf nicht schreibend zugegriffen werden\! +Exception.EWriteConstant.Message_Start=Auf die Konstante +ExportCFileAction.exportCLong=Exportiere Quellcode als C00-Datei +ExportCFileAction.exportCShort=Exportiere als C-Datei +FirstStepAction.firstStepLong=Springt zum ersten Schritt. +FirstStepAction.firstStepShort=Erster Schritt +GUIController.consoleText=Konsole +GUIController.editorText=C-Editor +GUIController.printf_End=)\: +GUIController.printf_Start=printf (Zeile\: +GUIController.pulsememetableText=Speicherabbild +GoBeamerAction.BeamerMode=Pr\u00E4sentationsmodus +ImportCFileAction.importCLong=Importiere eine C00-Datei +ImportCFileAction.importCShort=Importiere C-Datei +LastStepAction.lastStepLong=Springe zum letzten Schritt +LastStepAction.lastStepShort=Letzter Schritt +Module.Description=J-Algo Modul zur Visualisierung des pulsierenden Speichers +ModuleInfo.LicenceType=GPL +ModuleInfo.ModuleName=Pulsierender Speicher +ModuleInfo.ModuleVersion=0.5 +ModuleInfo.Programmers=Martin Brylski, Karsten Diepelt, Julian Eberius, Frank Herrlich, Joachim Protze +NextBreakpointAction.nextBreakpointLong=Springe zum n\u00E4chsten Haltepunkt. +NextBreakpointAction.nextBreakpointShort=N\u00E4chster Haltpunkt +ParseAction.startParsingLong=L\u00E4sst das Programm ablaufen und stellt den Pulsierenden Speicher dar +ParseAction.startParsingShort=Pulsierenden Speicher darstellen +PrevBreakpointAction.prevBreakpointLong=Springe zum vorigen Haltepunkt. +PrevBreakpointAction.prevBreakpointShort=Voriger Haltpunkt +PulseMemTable.Label=Label +PulseMemTable.Line=Zeile +PulseMemTable.Stack=RM-Keller +PulseMemTablePanel.LabelLine=Label-Zeile +PulseMemTablePanel.Stack=RM-Keller +StopAction.stopParsingLong=Zur\u00FCck in den Editor-Modus +StopAction.stopParsingShort=Zur\u00FCck zum Editor-Modus +WelcomeAction.welcomeLong=Zeigt den Wilkommensbildschirm +WelcomeAction.welcomeShort=Zeigt Willkommensbildschirm +gui.ExportCFileDialogText=Datei existiert bereits. \u00DCberschreiben? +gui.ExportCFileDialogTitle=\u00DCberschreiben? +gui.ExportCFileToolTip=Exportiert den aktuellen Quelltext als C00-Datei +gui.FileFilterDescription=C-Dateien ( *.c ) +gui.FirstStepToolTip=Zur\u00FCck zum ersten Haltepunkt +gui.ImportCFileToolTip=Importiert eine C00-Datei in das Quelltextfeld +gui.ImportError=Fehler beim Importieren der Datei. (Keine g\u00FCltige C00-Datei?) +gui.InputExpected_End=) erwartet eine Eingabe\! +gui.InputExpected_Start=Eine scanf-Anweisung (Zeile\: +gui.IntegerParseError_End=" ist kein g\u00FCltiger Integerwert. +gui.IntegerParseError_Start=Die Zeichenfolge " +gui.InterpretationError=Es ist ein Fehler bei der Interpretation des Quellcodes aufgetreten\! +gui.LastStepToolTip=Zeigt den kompletten pulsierenden Speicher (zum letzten Haltepunkt gehen) +gui.NextBreakpointToolTip=Geht zum n\u00E4chsten Haltepunkt +gui.OutOfMemory=Tabelle konnte nicht erstellt werden\: zu wenig Speicher\! (Versuchen sie kleine Eingabewerte\!) +gui.ParsingError=Es ist ein Fehler beim Parsen des Quellcodes aufgetreten\! +gui.PrevBreakpointToolTip=Geht zum vorherigen Haltepunkt +gui.StartParsingToolTip=L\u00E4sst das Programm ablaufen und stellt den Pulsierenden Speicher dar. +gui.StopParsingToolTip=Beendet die Visualisierung und kehrt in den Editor-Modus zur\u00FCck. +gui.UnknownInterpretationError=Es ist ein unbekannter Fehler w\u00E4hrend der Programminterpretation aufgetreten diff --git a/bin/org/jalgo/module/pulsemem/en.properties b/bin/org/jalgo/module/pulsemem/en.properties new file mode 100644 index 0000000..c926e08 --- /dev/null +++ b/bin/org/jalgo/module/pulsemem/en.properties @@ -0,0 +1,90 @@ +#Created by JInto - www.guh-software.de +#Thu Jun 28 22:33:20 CEST 2007 +Exception.ECycleLimitReached.Message_End=) is reached. Error in C00-Code? +Exception.ECycleLimitReached.Message_Start=Maximal recursion depth ( +Exception.EFunctionNotImplemented.Message_End=) was called. +Exception.EFunctionNotImplemented.Message_Start=Unimplemented method (line\: +Exception.EIncompatibleFunctionHeaders.Message_End=). Method is already declared with a different header\! +Exception.EIncompatibleFunctionHeaders.Message_Start=Error on method implementation +Exception.EIncompatibleParameterCount.Message_Between=\ parameters, but +Exception.EIncompatibleParameterCount.Message_End=\ were found. +Exception.EIncompatibleParameterCount.Message_Start=Method expected +Exception.EIncompatibleParameterTypes.Message_Between=. parameter should have been of type +Exception.EIncompatibleParameterTypes.Message_End=. Found was +Exception.EIncompatibleParameterTypes.Message_Start=Error on call of function +Exception.EIncompatibleTypes.Message_Between=\ was assigned to a +Exception.EIncompatibleTypes.Message_End=. Expected was +Exception.EIncompatibleTypes.Message_Start=The variable +Exception.EMemoryError.Message_Start=Memory access fault. Access on not initialized or not visible variable\: +Exception.ENotAPointerException.Message_End=\ could not be dereferenced. +Exception.ENotAPointerException.Message_Start=The non-pointer variable +Exception.ENullPointer.Message_End=\ is not initialized. +Exception.ENullPointer.Message_Start=The pointer +Exception.EPMLException.Message=PML was changed. Error in interpreter\! +Exception.EPointerTargetException.Message_End=\ (Pointer should point to variables\!) +Exception.EPointerTargetException.Message_Start=An int-value was assigned to the pointer +Exception.EPrintfException.Message_Start=Number of dummies and argument at printf-statement are not equal. line\: +Exception.EReturnException.Message_Between=. expected type\: +Exception.EReturnException.Message_End=. Line\: +Exception.EReturnException.Message_Start=Error while returning from method\! Type of return value\: +Exception.ETypeExpected.Message_Between=\ expected, but type +Exception.ETypeExpected.Message_End=found. Line\: +Exception.ETypeExpected.Message_Start=Type +Exception.EVarNotFound.Message_End=\ not declared. +Exception.EVarNotFound.Message_Start=Searched variable +Exception.EWriteConstant.Message_End=\ cannot be written\! +Exception.EWriteConstant.Message_Start=The constant +ExportCFileAction.exportCLong=Exports sourcecode as a C00-File +ExportCFileAction.exportCShort=Export C-File +FirstStepAction.firstStepLong=Goes to first step +FirstStepAction.firstStepShort=First Step +GUIController.consoleText=Console +GUIController.editorText=C-Editor +GUIController.printf_End=)\: +GUIController.printf_Start=printf (line\: +GUIController.pulsememetableText=Core Image +GoBeamerAction.BeamerMode=Beamer Mode +ImportCFileAction.importCLong=Imports a C00-File +ImportCFileAction.importCShort=Import C-File +LastStepAction.lastStepLong=Goes to last step +LastStepAction.lastStepShort=Last Step +Module.Description=J-Algo Modul visualising the concept pulsing memory +ModuleInfo.LicenceType=GPL +ModuleInfo.ModuleName=Pulsing Memory +ModuleInfo.ModuleVersion=0.5 +ModuleInfo.Programmers=Martin Brylski, Karsten Diepelt, Julian Eberius, Frank Herrlich, Joachim Protze +NextBreakpointAction.nextBreakpointLong=Goes to next breakpoint +NextBreakpointAction.nextBreakpointShort=Next Breakpoint +ParseAction.startParsingLong=Runs the programm and shows the pulsing memory +ParseAction.startParsingShort=Shows the pulsing memory +PrevBreakpointAction.prevBreakpointLong=Goes to previous breakpoint +PrevBreakpointAction.prevBreakpointShort=Previous Breakpoint +PulseMemTable.Label=Label +PulseMemTable.Line=Line +PulseMemTable.Stack=RM-Stack +PulseMemTablePanel.LabelLine=label-line +PulseMemTablePanel.Stack=RM-Stack +StopAction.stopParsingLong=Stops visualization and returns to editor mode +StopAction.stopParsingShort=Back to editor mode +WelcomeAction.welcomeLong=Shows the Welcome Screen +WelcomeAction.welcomeShort=Show Welcome Screen +gui.ExportCFileDialogText=File already exists. Override? +gui.ExportCFileDialogTitle=Override? +gui.ExportCFileToolTip=Exports current sourecode as a C00-file +gui.FileFilterDescription=C-Files ( *.c ) +gui.FirstStepToolTip=Back to the first breakpoints +gui.ImportCFileToolTip=Imports a C00-file into the sourcecode field +gui.ImportError=Error while loading file. (Not a valid C00-File?) +gui.InputExpected_End=) expects an Input. +gui.InputExpected_Start=A scanf-statement (line\: +gui.IntegerParseError_End=" is not a valid integer value. +gui.IntegerParseError_Start=The character sequence " +gui.InterpretationError=An error occured while interpreting the C-Code\! +gui.LastStepToolTip=Shows the complete pulsing memory (goes forward to the last breakpoint) +gui.NextBreakpointToolTip=Forward to the next breakpoint +gui.OutOfMemory=Could not create the table\: out of memory\! (Try smaller input values\!) +gui.ParsingError=An error occured while parsing the C-Code +gui.PrevBreakpointToolTip=Backward to the previous breakpoint +gui.StartParsingToolTip=Runs the programm and shows the pulsing memory +gui.StopParsingToolTip=stops the visualization and returns to editor mode +gui.UnknownInterpretationError=An unexpected error occured while interpreting the program diff --git a/bin/org/jalgo/module/pulsemem/gui/GUIConstants.class b/bin/org/jalgo/module/pulsemem/gui/GUIConstants.class new file mode 100644 index 0000000..c944753 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/GUIConstants.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/GUIController$1.class b/bin/org/jalgo/module/pulsemem/gui/GUIController$1.class new file mode 100644 index 0000000..5184d61 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/GUIController$1.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/GUIController$2.class b/bin/org/jalgo/module/pulsemem/gui/GUIController$2.class new file mode 100644 index 0000000..cbd1fad Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/GUIController$2.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/GUIController$3.class b/bin/org/jalgo/module/pulsemem/gui/GUIController$3.class new file mode 100644 index 0000000..e207133 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/GUIController$3.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/GUIController.class b/bin/org/jalgo/module/pulsemem/gui/GUIController.class new file mode 100644 index 0000000..9979702 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/GUIController.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/CellObject.class b/bin/org/jalgo/module/pulsemem/gui/components/CellObject.class new file mode 100644 index 0000000..0208c54 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/CellObject.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.class b/bin/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.class new file mode 100644 index 0000000..e7f97b5 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.class b/bin/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.class new file mode 100644 index 0000000..7ccd53f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel$1.class b/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel$1.class new file mode 100644 index 0000000..60c84f0 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel$1.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel.class b/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel.class new file mode 100644 index 0000000..5515f44 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/NOLPanel.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$1.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$1.class new file mode 100644 index 0000000..9f67f92 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$1.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$2.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$2.class new file mode 100644 index 0000000..6ddc92f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$2.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$3.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$3.class new file mode 100644 index 0000000..eee7942 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$3.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$CenterRenderer.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$CenterRenderer.class new file mode 100644 index 0000000..68f3958 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable$CenterRenderer.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable.class new file mode 100644 index 0000000..eae5e02 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTable.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.class b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.class new file mode 100644 index 0000000..d9626c7 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction$1.class b/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction$1.class new file mode 100644 index 0000000..e88cbd6 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction$1.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.class b/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.class new file mode 100644 index 0000000..012ce0d Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/FirstStepAction.class b/bin/org/jalgo/module/pulsemem/gui/events/FirstStepAction.class new file mode 100644 index 0000000..6b0678f Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/FirstStepAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.class b/bin/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.class new file mode 100644 index 0000000..75e4aba Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction$1.class b/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction$1.class new file mode 100644 index 0000000..32732ad Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction$1.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.class b/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.class new file mode 100644 index 0000000..bf5f60c Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/LastStepAction.class b/bin/org/jalgo/module/pulsemem/gui/events/LastStepAction.class new file mode 100644 index 0000000..9ecc615 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/LastStepAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.class b/bin/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.class new file mode 100644 index 0000000..af70e4b Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/ParseAction.class b/bin/org/jalgo/module/pulsemem/gui/events/ParseAction.class new file mode 100644 index 0000000..945525d Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/ParseAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.class b/bin/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.class new file mode 100644 index 0000000..9575ebb Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/StopAction.class b/bin/org/jalgo/module/pulsemem/gui/events/StopAction.class new file mode 100644 index 0000000..8832b64 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/StopAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/gui/events/WelcomeAction.class b/bin/org/jalgo/module/pulsemem/gui/events/WelcomeAction.class new file mode 100644 index 0000000..3547598 Binary files /dev/null and b/bin/org/jalgo/module/pulsemem/gui/events/WelcomeAction.class differ diff --git a/bin/org/jalgo/module/pulsemem/res.properties b/bin/org/jalgo/module/pulsemem/res.properties new file mode 100644 index 0000000..e1642b7 --- /dev/null +++ b/bin/org/jalgo/module/pulsemem/res.properties @@ -0,0 +1,19 @@ +#Created by JInto - www.guh-software.de +#Tue Jun 19 12:32:56 CEST 2007 +BreakBack=/pulsemem_pix/backward_nav.gif +BreakForw=/pulsemem_pix/forward_nav.gif +Breakpoint=/pulsemem_pix/generic_element.gif +CFile=/pulsemem_pix/workset_wiz.png +Example=/pulsemem_pix/quick_fix.png +ExportCFile=/pulsemem_pix/exportCFile.gif +HelpSet_Name=/help/jhelp/pulsemem_help.hs +ImportCFile=/pulsemem_pix/importCFile.gif +Main_Icon=/pulsemem_pix/icon.gif +NewFile=/pulsemem_pix/newfile_wiz.png +PRestart=/pulsemem_pix/restart_task.gif +PStart=/pulsemem_pix/start_task.gif +PStop=/pulsemem_pix/progress_stop.gif +Session=/pulsemem_pix/importzip_wiz.png +StepBack=/pulsemem_pix/shift_l_edit.gif +StepForw=/pulsemem_pix/shift_r_edit.gif +Welcome=/pulsemem_pix/trash.gif diff --git a/bin/org/jalgo/module/testModule/ModuleConnector.class b/bin/org/jalgo/module/testModule/ModuleConnector.class new file mode 100644 index 0000000..222f3e3 Binary files /dev/null and b/bin/org/jalgo/module/testModule/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/testModule/ModuleInfo.class b/bin/org/jalgo/module/testModule/ModuleInfo.class new file mode 100644 index 0000000..23536d2 Binary files /dev/null and b/bin/org/jalgo/module/testModule/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/testModule/res.properties b/bin/org/jalgo/module/testModule/res.properties new file mode 100644 index 0000000..d5607b6 --- /dev/null +++ b/bin/org/jalgo/module/testModule/res.properties @@ -0,0 +1 @@ +HelpSet_Name=/help/jhelp/test_help.hs \ No newline at end of file diff --git a/bin/org/jalgo/module/unifikation/Application$1.class b/bin/org/jalgo/module/unifikation/Application$1.class new file mode 100644 index 0000000..ccf762d Binary files /dev/null and b/bin/org/jalgo/module/unifikation/Application$1.class differ diff --git a/bin/org/jalgo/module/unifikation/Application.class b/bin/org/jalgo/module/unifikation/Application.class new file mode 100644 index 0000000..c1272c7 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/Application.class differ diff --git a/bin/org/jalgo/module/unifikation/ApplicationState.class b/bin/org/jalgo/module/unifikation/ApplicationState.class new file mode 100644 index 0000000..20565a3 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/ApplicationState.class differ diff --git a/bin/org/jalgo/module/unifikation/Constants.class b/bin/org/jalgo/module/unifikation/Constants.class new file mode 100644 index 0000000..3378bba Binary files /dev/null and b/bin/org/jalgo/module/unifikation/Constants.class differ diff --git a/bin/org/jalgo/module/unifikation/IAppView.class b/bin/org/jalgo/module/unifikation/IAppView.class new file mode 100644 index 0000000..38a2377 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/IAppView.class differ diff --git a/bin/org/jalgo/module/unifikation/ModuleConnector.class b/bin/org/jalgo/module/unifikation/ModuleConnector.class new file mode 100644 index 0000000..67de481 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/ModuleConnector.class differ diff --git a/bin/org/jalgo/module/unifikation/ModuleInfo.class b/bin/org/jalgo/module/unifikation/ModuleInfo.class new file mode 100644 index 0000000..450b587 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/ModuleInfo.class differ diff --git a/bin/org/jalgo/module/unifikation/WelcomeScreen.class b/bin/org/jalgo/module/unifikation/WelcomeScreen.class new file mode 100644 index 0000000..f53d92c Binary files /dev/null and b/bin/org/jalgo/module/unifikation/WelcomeScreen.class differ diff --git a/bin/org/jalgo/module/unifikation/WelcomeScreenButton.class b/bin/org/jalgo/module/unifikation/WelcomeScreenButton.class new file mode 100644 index 0000000..c57c70f Binary files /dev/null and b/bin/org/jalgo/module/unifikation/WelcomeScreenButton.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/FixSizeInlineView.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/FixSizeInlineView.class new file mode 100644 index 0000000..848e045 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/FixSizeInlineView.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/MyLinkController.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/MyLinkController.class new file mode 100644 index 0000000..796a1b1 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/MyLinkController.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument$MyHTMLReader.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument$MyHTMLReader.class new file mode 100644 index 0000000..2b4c65f Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument$MyHTMLReader.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.class new file mode 100644 index 0000000..3d1cfdc Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit$VerboseViewFactory.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit$VerboseViewFactory.class new file mode 100644 index 0000000..6923593 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit$VerboseViewFactory.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.class new file mode 100644 index 0000000..54c0ce1 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/XParserDelegator.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/XParserDelegator.class new file mode 100644 index 0000000..11c575d Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/XParserDelegator.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/HTMLParser/package-info.class b/bin/org/jalgo/module/unifikation/algo/HTMLParser/package-info.class new file mode 100644 index 0000000..d22a2ab Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/HTMLParser/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory$HoverListener.class b/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory$HoverListener.class new file mode 100644 index 0000000..786e4a7 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory$HoverListener.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory.class b/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory.class new file mode 100644 index 0000000..d7e5753 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/ButtonListenerFactory.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/ClickListener.class b/bin/org/jalgo/module/unifikation/algo/controller/ClickListener.class new file mode 100644 index 0000000..13a957e Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/ClickListener.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.class new file mode 100644 index 0000000..3e96088 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.class new file mode 100644 index 0000000..8df03fe Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.class new file mode 100644 index 0000000..3ba4150 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.class new file mode 100644 index 0000000..92f7f39 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.class new file mode 100644 index 0000000..f82a669 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/HLLPairs.class b/bin/org/jalgo/module/unifikation/algo/controller/HLLPairs.class new file mode 100644 index 0000000..5dcafd3 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/HLLPairs.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/HelpMode.class b/bin/org/jalgo/module/unifikation/algo/controller/HelpMode.class new file mode 100644 index 0000000..4cb9f2e Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/HelpMode.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/IButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/IButtonAction.class new file mode 100644 index 0000000..9adfde9 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/IButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.class b/bin/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.class new file mode 100644 index 0000000..f89249e Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.class new file mode 100644 index 0000000..341c6ce Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.class new file mode 100644 index 0000000..a2abff6 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.class new file mode 100644 index 0000000..90b8dcf Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/SelectPairResult.class b/bin/org/jalgo/module/unifikation/algo/controller/SelectPairResult.class new file mode 100644 index 0000000..ca03f32 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/SelectPairResult.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/SubButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/SubButtonAction.class new file mode 100644 index 0000000..b7b6959 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/SubButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.class new file mode 100644 index 0000000..62b3336 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.class new file mode 100644 index 0000000..551703b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.class new file mode 100644 index 0000000..21d6b3c Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.class new file mode 100644 index 0000000..f17a05d Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.class b/bin/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.class new file mode 100644 index 0000000..1f37836 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/controller/package-info.class b/bin/org/jalgo/module/unifikation/algo/controller/package-info.class new file mode 100644 index 0000000..44e9725 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/controller/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ATerm.class b/bin/org/jalgo/module/unifikation/algo/model/ATerm.class new file mode 100644 index 0000000..d702364 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ATerm.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.class b/bin/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.class new file mode 100644 index 0000000..7eff98c Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ColorVariable.class b/bin/org/jalgo/module/unifikation/algo/model/ColorVariable.class new file mode 100644 index 0000000..f54d1a7 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ColorVariable.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.class b/bin/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.class new file mode 100644 index 0000000..43e0d01 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/Formating.class b/bin/org/jalgo/module/unifikation/algo/model/Formating.class new file mode 100644 index 0000000..5f25380 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/Formating.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.class b/bin/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.class new file mode 100644 index 0000000..a4a36d9 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/HTMLVariable.class b/bin/org/jalgo/module/unifikation/algo/model/HTMLVariable.class new file mode 100644 index 0000000..6fc5aef Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/HTMLVariable.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/History.class b/bin/org/jalgo/module/unifikation/algo/model/History.class new file mode 100644 index 0000000..1ac481a Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/History.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/IModelFormat.class b/bin/org/jalgo/module/unifikation/algo/model/IModelFormat.class new file mode 100644 index 0000000..a07e685 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/IModelFormat.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ITerm.class b/bin/org/jalgo/module/unifikation/algo/model/ITerm.class new file mode 100644 index 0000000..8599fdb Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ITerm.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/Pair.class b/bin/org/jalgo/module/unifikation/algo/model/Pair.class new file mode 100644 index 0000000..ac6a982 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/Pair.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/ProblemSet.class b/bin/org/jalgo/module/unifikation/algo/model/ProblemSet.class new file mode 100644 index 0000000..e93ef5b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/ProblemSet.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/Rule.class b/bin/org/jalgo/module/unifikation/algo/model/Rule.class new file mode 100644 index 0000000..2e5242b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/Rule.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/Variable.class b/bin/org/jalgo/module/unifikation/algo/model/Variable.class new file mode 100644 index 0000000..30ae317 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/Variable.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/model/package-info.class b/bin/org/jalgo/module/unifikation/algo/model/package-info.class new file mode 100644 index 0000000..dda10e6 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/model/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoFinished.class b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoFinished.class new file mode 100644 index 0000000..49b993e Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoFinished.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoRunning.class b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoRunning.class new file mode 100644 index 0000000..59b9abb Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateAlgoRunning.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/Algo$StateNoRuleUsable.class b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateNoRuleUsable.class new file mode 100644 index 0000000..84d1be3 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/Algo$StateNoRuleUsable.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/Algo.class b/bin/org/jalgo/module/unifikation/algo/view/Algo.class new file mode 100644 index 0000000..574a1f7 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/Algo.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/EditorFormat.class b/bin/org/jalgo/module/unifikation/algo/view/EditorFormat.class new file mode 100644 index 0000000..f2a3290 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/EditorFormat.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/IAlgoState.class b/bin/org/jalgo/module/unifikation/algo/view/IAlgoState.class new file mode 100644 index 0000000..69c1ce4 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/IAlgoState.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/JFadeButton$fadeTask.class b/bin/org/jalgo/module/unifikation/algo/view/JFadeButton$fadeTask.class new file mode 100644 index 0000000..a9d5205 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/JFadeButton$fadeTask.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/JFadeButton.class b/bin/org/jalgo/module/unifikation/algo/view/JFadeButton.class new file mode 100644 index 0000000..1933105 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/JFadeButton.class differ diff --git a/bin/org/jalgo/module/unifikation/algo/view/package-info.class b/bin/org/jalgo/module/unifikation/algo/view/package-info.class new file mode 100644 index 0000000..8ff4387 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/algo/view/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/de.properties b/bin/org/jalgo/module/unifikation/de.properties new file mode 100644 index 0000000..29a3ed3 --- /dev/null +++ b/bin/org/jalgo/module/unifikation/de.properties @@ -0,0 +1 @@ +Parser.CommonError=Fehlerhafte Menge eingegeben. diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$1.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$1.class new file mode 100644 index 0000000..c86c41b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$1.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$10.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$10.class new file mode 100644 index 0000000..4b2ffbe Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$10.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$11.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$11.class new file mode 100644 index 0000000..ba63f20 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$11.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$12.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$12.class new file mode 100644 index 0000000..4ad9a0b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$12.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$13.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$13.class new file mode 100644 index 0000000..dc27071 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$13.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$2.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$2.class new file mode 100644 index 0000000..0f699a2 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$2.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$3.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$3.class new file mode 100644 index 0000000..6c1cafa Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$3.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$4.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$4.class new file mode 100644 index 0000000..384c559 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$4.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$5.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$5.class new file mode 100644 index 0000000..039760b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$5.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$6.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$6.class new file mode 100644 index 0000000..d888748 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$6.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$7.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$7.class new file mode 100644 index 0000000..6a19360 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$7.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$8.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$8.class new file mode 100644 index 0000000..7afa619 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$8.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners$9.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners$9.class new file mode 100644 index 0000000..0c9770e Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners$9.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/ActionListeners.class b/bin/org/jalgo/module/unifikation/editor/ActionListeners.class new file mode 100644 index 0000000..875b91b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/ActionListeners.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/Editor.class b/bin/org/jalgo/module/unifikation/editor/Editor.class new file mode 100644 index 0000000..e5a93f0 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/Editor.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/VKeyboard.class b/bin/org/jalgo/module/unifikation/editor/VKeyboard.class new file mode 100644 index 0000000..aca2f1b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/VKeyboard.class differ diff --git a/bin/org/jalgo/module/unifikation/editor/package-info.class b/bin/org/jalgo/module/unifikation/editor/package-info.class new file mode 100644 index 0000000..3be5995 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/editor/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/junit/TestRules.class b/bin/org/jalgo/module/unifikation/junit/TestRules.class new file mode 100644 index 0000000..324c30d Binary files /dev/null and b/bin/org/jalgo/module/unifikation/junit/TestRules.class differ diff --git a/bin/org/jalgo/module/unifikation/junit/TestSetParser.class b/bin/org/jalgo/module/unifikation/junit/TestSetParser.class new file mode 100644 index 0000000..82efe65 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/junit/TestSetParser.class differ diff --git a/bin/org/jalgo/module/unifikation/junit/package-info.class b/bin/org/jalgo/module/unifikation/junit/package-info.class new file mode 100644 index 0000000..b8059fd Binary files /dev/null and b/bin/org/jalgo/module/unifikation/junit/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/package-info.class b/bin/org/jalgo/module/unifikation/package-info.class new file mode 100644 index 0000000..1af5813 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/FormatConstraints.class b/bin/org/jalgo/module/unifikation/parser/FormatConstraints.class new file mode 100644 index 0000000..7b613d3 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/FormatConstraints.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/ISetParser.class b/bin/org/jalgo/module/unifikation/parser/ISetParser.class new file mode 100644 index 0000000..f29fa4b Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/ISetParser.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/ParserError.class b/bin/org/jalgo/module/unifikation/parser/ParserError.class new file mode 100644 index 0000000..5eff1f9 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/ParserError.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/ParserErrorType.class b/bin/org/jalgo/module/unifikation/parser/ParserErrorType.class new file mode 100644 index 0000000..a358cc8 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/ParserErrorType.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/SetParser.class b/bin/org/jalgo/module/unifikation/parser/SetParser.class new file mode 100644 index 0000000..d985c7a Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/SetParser.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetLexer.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetLexer.class new file mode 100644 index 0000000..445bbee Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetLexer.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.class new file mode 100644 index 0000000..50b1cab Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructor_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructor_return.class new file mode 100644 index 0000000..eac0a51 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructor_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructorsymbol_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructorsymbol_return.class new file mode 100644 index 0000000..06dbe9c Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$constructorsymbol_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$pair_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$pair_return.class new file mode 100644 index 0000000..830ff07 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$pair_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$set_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$set_return.class new file mode 100644 index 0000000..2745e4f Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$set_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$term_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$term_return.class new file mode 100644 index 0000000..5967e7a Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$term_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$unificationset_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$unificationset_return.class new file mode 100644 index 0000000..c48ca97 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$unificationset_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$variable_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$variable_return.class new file mode 100644 index 0000000..836dfb0 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$variable_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$varid_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$varid_return.class new file mode 100644 index 0000000..a23a62f Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$varid_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$ws_return.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$ws_return.class new file mode 100644 index 0000000..599b998 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser$ws_return.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParser.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser.class new file mode 100644 index 0000000..af94e15 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParser.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.class b/bin/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.class new file mode 100644 index 0000000..6cbd119 Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.class differ diff --git a/bin/org/jalgo/module/unifikation/parser/package-info.class b/bin/org/jalgo/module/unifikation/parser/package-info.class new file mode 100644 index 0000000..d19242c Binary files /dev/null and b/bin/org/jalgo/module/unifikation/parser/package-info.class differ diff --git a/bin/org/jalgo/module/unifikation/res.properties b/bin/org/jalgo/module/unifikation/res.properties new file mode 100644 index 0000000..8d14804 --- /dev/null +++ b/bin/org/jalgo/module/unifikation/res.properties @@ -0,0 +1,8 @@ +HelpSet_Name=/help/jhelp/test_help.hs +Icon=/unifikation_pix/icon.jpg + +Icon.welcomeNew=/unifikation_pix/WelcomeNew.jpg +Icon.welcomeNewOver=/unifikation_pix/WelcomeNewHover.jpg +Icon.welcomeLoad=/unifikation_pix/WelcomeLoad.jpg +Icon.welcomeLoadOver=/unifikation_pix/WelcomeLoadHover.jpg +Icon.Editor=/unifikation_pix/pencilbutton.png diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..187ac65 --- /dev/null +++ b/build.xml @@ -0,0 +1,316 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/CVS/Entries b/doc/CVS/Entries new file mode 100644 index 0000000..25e2a21 --- /dev/null +++ b/doc/CVS/Entries @@ -0,0 +1,9 @@ +/Swing-SWT-Probleme/1.1/Thu Jun 23 09:30:56 2005// +/ToDo/1.5/Mon Oct 16 14:31:32 2006/-kb/ +D/avl_user_manual//// +/character-problem/1.1/Sat Dec 18 18:54:18 2004/-kb/ +D/developers_manual_german//// +/message-board/1.4/Fri Apr 7 09:40:24 2006/-kb/ +D/module_programmers_guide//// +D/users_manual_english//// +D/users_manual_german//// diff --git a/doc/CVS/Repository b/doc/CVS/Repository new file mode 100644 index 0000000..e8912fb --- /dev/null +++ b/doc/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc diff --git a/doc/CVS/Root b/doc/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/Swing-SWT-Probleme b/doc/Swing-SWT-Probleme new file mode 100644 index 0000000..08786e3 --- /dev/null +++ b/doc/Swing-SWT-Probleme @@ -0,0 +1,29 @@ +Probleme bei der Integration von Swing-Komponenten in SWT-Umgebung: + +reine SWT-Probleme: + - bei SWT v3.106 wird neu hinzugekommener Fensterinhalt erst nach Grössenänderung + des Fensters sichtbar + -> Abhilfe: SWT v3.064 verwenden, da funktionierte noch alles + - Implementation verschiedener Teile des Frameworks (z.B. die SWT-AWT-Bridge) gehen + auf vielen Plattformen nur schleppend voran + -> Abhilfe: keine, arbeite selbst an SWT mit... + +SWT-Swing-Probleme: + - Zugriff aus Swing-Event-Thread auf bestimmte Routinen von SWT endet in einer + Invalid Thread Access Exception, so z.B.: + Setzen des Textes der Statuszeile, + Auslesen von Komponentenkoordinaten, + Öffnen eines FileDialoges + -> Abhilfe: an Instanz des ApplicationWindow wenden, über das Shell-Objekt und + darüber über das Display-Objekt kann man mittels syncExec(Runnable) oder + asyncExec(Runnable) einen separaten, jedoch von SWT kontrollierten Thread starten, + der dieses Problem umgeht, + Beispielaufruf: appWin.getShell().getDisplay().syncExec(new Runnable() {...}); + + - Mauszeigergestalt verändert sich nicht direkt über den entsprechenden Komponenten, + Verschiebung um Hauptfensterposition + -> Abhilfe: beim ApplicationWindow über das Shell-Objekt einen ControlListener + registrieren, bei controlMoved() und controlResized() jeweils die Koordinaten des + SWT-AWT-Bridge-Frames anpassen durch Auslesen der Fensterkoordinaten + Offset + -> bessere Abhilfe: statt eine Lightweight-Komponente wie JPanel auf die Bridge zu + setzen, eine Heavyweight-Komponente nehmen, z.B. java.awt.Panel \ No newline at end of file diff --git a/doc/ToDo b/doc/ToDo new file mode 100644 index 0000000..93b0fee --- /dev/null +++ b/doc/ToDo @@ -0,0 +1,16 @@ +Sachen, die man noch machen k�nnte +----------------------------------- + + +-- halb transparente Folie �ueber gesamtem Programm, die es erm�oeglicht mit einem (roten) + Stift auf laufende Algorithmen zu zeichnen. Fue�r Erklae�rungen in der Vorlesung besonders n�uetzlich. +-- Nachrichtenfenster für nicht installierte Module ueberarbeiten. +-- ModuleChooseDialog für leere Moduleliste überarbeiten +-- Dateiarbeit einbauen, die andere (modulspezif.) Dateiendungen als ".jalgo" zulaesst. + +-- statisches Mergen der Modulhilfen. Persistieren der Modulliste, abfragen dieser + und Test ob sie sich geae�ndert hat. Wenn ja: Neuschreiben des main-HelpSets +-- Modul-kontextspezifische Hilfe + +-- Erweiterung des Entwicklerhandbuches um einen Abschnitt mit dem Thema: "Erzeugung des Modul-.jar-File". +-- Ändern des Entwicklerhandbuches auf Seite: 5 --> der SF-Hostname hat sich geändert \ No newline at end of file diff --git a/doc/character-problem b/doc/character-problem new file mode 100644 index 0000000..78f360d --- /dev/null +++ b/doc/character-problem @@ -0,0 +1,9 @@ +Stand der Dinge beim Problem der Sonderzeichen auf Solaris +---------------------------------------------------------- + +(falls sich mal jemand damit beschaeftigen will, und fuer mich zum erinnern) + +* (nochmal) kleine Test-Programme geschrieben: org.jalgo.tests.CharTest1.java (SWT) und CharTest2.java (Konsole) +* http://developers.sun.com/dev/gadc/unicode/solaris/ ueberflogen, Auswaehlen von en_US.UTF8 als locale beim Login hilft nicht +* die hier: http://www.bolthole.com/java/unicode/solaris.html beschriebene Methode, die Datei fnt.properties in der Java-Lib zu ersetzen geht scheinbar auch nicht (waere aber eh ein doofer Weg, weil man im Java-VM-Pfad rumfuschen muss) + diff --git a/doc/developers_manual_german/CVS/Entries b/doc/developers_manual_german/CVS/Entries new file mode 100644 index 0000000..2cfa2b9 --- /dev/null +++ b/doc/developers_manual_german/CVS/Entries @@ -0,0 +1,7 @@ +/developers_manual_german.pdf/1.7/Mon Apr 10 16:18:48 2006/-kb/ +/developers_manual_german.tex/1.4/Mon Apr 10 16:18:49 2006/-kk/ +/getting_started.tex/1.4/Fri Apr 7 07:52:41 2006/-kk/ +/misc.tex/1.2/Thu Apr 6 17:23:36 2006/-kk/ +/module_development.tex/1.7/Mon Apr 10 16:18:48 2006/-kk/ +/overview.tex/1.1/Sun Mar 26 12:07:09 2006/-kk/ +D/pics//// diff --git a/doc/developers_manual_german/CVS/Repository b/doc/developers_manual_german/CVS/Repository new file mode 100644 index 0000000..34357ac --- /dev/null +++ b/doc/developers_manual_german/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/developers_manual_german diff --git a/doc/developers_manual_german/CVS/Root b/doc/developers_manual_german/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/developers_manual_german/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/developers_manual_german/developers_manual_german.pdf b/doc/developers_manual_german/developers_manual_german.pdf new file mode 100644 index 0000000..e063fba Binary files /dev/null and b/doc/developers_manual_german/developers_manual_german.pdf differ diff --git a/doc/developers_manual_german/developers_manual_german.tex b/doc/developers_manual_german/developers_manual_german.tex new file mode 100644 index 0000000..3c421df --- /dev/null +++ b/doc/developers_manual_german/developers_manual_german.tex @@ -0,0 +1,96 @@ +\documentclass{scrartcl} +\usepackage[ngerman]{babel} +\usepackage[T1]{fontenc} +\usepackage[ansinew]{inputenc} +\usepackage{a4wide} + +%verwenden von grafiken +\usepackage[dvipdf, final]{graphicx} + +%verwenden von hyperlinks, stil derselben +\usepackage{color} +\definecolor{darkblue}{rgb}{0,0,0.5} + +\usepackage{hyperref} +\hypersetup{ +% draft, %hyperlinks ausschalten + colorlinks, %hyperlinks farbig darstellen + linkcolor = darkblue, + filecolor = darkblue, + urlcolor = darkblue, + citecolor = darkblue, + pdftitle = {Entwicklerhandbuch}, %titel + pdfsubject = {j-Algo}, %thema + pdfauthor = {Alexander Claus, Matthias Schmidt}, + pdfkeywords = {Algorithmen, Visualisierung}, + pdfcreator = {Distiller}, + pdfproducer = {LaTeX mit Hyperref-Package}} + +%verwenden von code-ausschnitten +%\usepackage{listings} + +%spezielle kommandos +%schreibweise des software-titels +\newcommand{\jalgo}{\mbox{\bfseries {\color{red}j}-Algo} } +%pfad zu den bildern +\newcommand{\pfad}{pics/} +%f�gt ein bild an einer bestimmten stelle, relativ zur position des befehls, ein. +%usage: \icon{dateiname}{y-offset}{x-offset}{bildvergr��erung} +\newcommand{\icon}[4]{ + \vspace{#2 ex} + \hspace{#3 ex} + \includegraphics[scale=#4]{\pfad #1} +} +%f�gt ein bild mittig mit bildunterschrift ein. +%usage: \centerpic{dateiname}{bildvergr��erung}{untertitel} +\newcommand{\centerpic}[3]{ + \begin{center} + \includegraphics[scale=#2]{\pfad #1}\\ + {\small #3} + \end{center} +} +%f�gt eine \subsection mit einem f�hrenden icon ein +%usage: \subsectionicon{text}{icon} +\newcommand{\subsectionicon}[2]{ + \subsection[#1]{\qquad #1} + \icon{#2}{-5}{7}{1} + \\ +} +%f�gt eine \subsection mit 2 f�hrenden icons ein +%usage: \subsectiondoubleicon{text}{icon1}{icon2} +\newcommand{\subsectiondoubleicon}[3]{ + \subsection[#1]{\qquad \quad #1} + \icon{#2}{-5}{7}{1} + \icon{#3}{0}{-2}{1} + \\ +} +%f�gt eine \subsubsection* mit 2 f�hrenden icons ein +%usage: \subsubsectiondoubleicon{text}{icon1}{icon2} +\newcommand{\subsubsectiondoubleicon}[3]{ + \subsubsection*{\qquad \qquad #1} + \icon{#2}{-4}{1}{1} + \icon{#3}{0}{-2}{1} + \\ +} + +\begin{document} + +\begin{titlepage} +\centerpic{title}{1}{} +\vfill +\begin{flushright} +{\Huge \textbf{Entwicklerhandbuch}} +\end{flushright} +\end{titlepage} + +\newpage + +\tableofcontents +\newpage + +\input{overview} +\input{getting_started} +\input{module_development} +\input{misc} + +\end{document} \ No newline at end of file diff --git a/doc/developers_manual_german/getting_started.tex b/doc/developers_manual_german/getting_started.tex new file mode 100644 index 0000000..6e85761 --- /dev/null +++ b/doc/developers_manual_german/getting_started.tex @@ -0,0 +1,63 @@ +\section{CVS-Zugang} +\jalgo ist als Projekt bei \href{https://sourceforge.net/projects/j-algo/}{SourceForge} registriert und gehostet. Es gibt 2 Arten, auf das CVS-Repository des Projektes zuzugreifen. +\begin{enumerate} + \item Lesezugriff. Als Beobachter des Projektes kann jeder auf das Projekt lesend zugreifen. Die Zugangsdaten sind:\\ + Verbindungsmethode: \verb|pserver|\\ + Host: \verb|cvs.sourceforge.net|\\ + Repository-Pfad: \verb|/cvsroot/j-algo|\\ + Login: \verb|anonymous| + \item Vollzugriff. Als registrierter Entwickler bei SourceForge und als eingetragenes Projektmitglied bei \jalgo kann das CVS unter folgenden Zugangsdaten im Vollzugriff erreicht werden:\\ + Verbindungsmethode: \verb|extssh|\\ + Host: \verb|cvs.sourceforge.net|\\ + Repository-Pfad: \verb|/cvsroot/j-algo|\\ + Login: <\textsc{SourceForge-Login}>\\ + Passwort: <\textsc{SourceForge-Passwort}>\\ + Um als Projektmitglied eingetragen zu werden, wenden Sie sich bitte an den Projekt-Administrator. Dessen Kontaktdaten sind auf der SourceForge-Seite zugänglich. +\end{enumerate} +\textbf{Achtung:} Wird das Projekt im Rahmen des Software-Praktikums an der TUD weiterentwickelt, gelten andere Bedingungen für den CVS-Zugang. Diese sind beim zuständigen Betreuer des Praktikums zu erfragen. + +\newpage + +\section{Entwickeln unter Eclipse} +Natürlich steht es jedem Entwickler frei, eine Programmierumgebung seiner Wahl zu benutzen. Da jedoch der Großteil der \jalgo-Entwickler unter \href{http://eclipse.org}{Eclipse} programmiert, und diese Plattform einige komfortable Features besitzt, sollen hier die wichtigsten Einstellungen für diese Umgebung erläutert werden. Für andere Programmierumgebungen gelten sie sinngemäß.\\ +Da \jalgo die Java-Version 1.5 verwendet, ist eine Eclipse-Version 3.1 oder höher erforderlich.\footnote{Achtung, auf der Seite des Eclipse-Projektes wird noch auf die Version 1.4.2 des JDK verlinkt} + +Das Projekt kann in der CVS-Ansicht von Eclipse ausgecheckt werden. Ab jetzt sind zwar alle nötigen Daten (Quellcodes, etc.) auf dem Rechner. Allerdings müssen noch einige Einstellungen vorgenommen werden, damit das Projekt kompiliert und gestartet werden kann: +\begin{itemize} + \item Unter den Projekteinstellungen->"'Java Compiler"'->"`Compiler Compliance Level"' ist "`5.0"' einzustellen. Es ist sicherzustellen, dass unter Projekteinstellungen->Libraries als "`JRE System Library"' die Version 1.5 eingestellt ist. Ist dies nicht der Fall, so ist diese mittels "`Add Library..."'->"`JRE System Library"' einzustellen. + \item Unter Projekteinstellungen->Info->Text file encoding muss UTF-8 eingestellt werden. Dies garantiert reibungslose Unterstützung von Umlauten auf verschiedenen Betriebssystemen. + \item Unter Projekteinstellungen->Java Build Path müssen jetzt einige Einstellungen für den ClassPath des Projektes vorgenommen werden:\\ +Unter Source darf nur der Ordner \textsc{}\verb|/src| stehen. Ist dies nicht der Fall, ist dieser mittels "`Add Folder..."' aus der Ordnerliste auszuwählen. Andere Ordner sind zu entfernen. + \item Als "`Default Output Folder"' ist \textsc{}\verb|/bin| anzugeben. + \item Unter "`Libraries"'->"`Add JARs..."' ist \textsc{}\verb|/extlibs/jh.jar| hinzuzufügen. Dies ist die nötige Bibliothek für das Hilfe-System. + \item Unter "`Libraries"'->"`Add Class Folder..."' sind folgende Ordner hinzuzufügen:\\ + \textsc{}\verb|/runtime| (für die Erkennung der installierten Module)\\ + \textsc{}\verb|/res/main| (für die Ressourcen zum Hauptprogramm)\\ + sowie alle verfügbaren Modulordner unter + \textsc{}\verb|/res/module/|, also z.B. + \textsc{}\verb|/res/module/testModule| (für die Ressourcen der einzelnen Module) + \item Als nächstes werden die jUnit-Bibliotheken benötigt. Weil Eclipse diese bereits eingebaut hat, ist die einfachste Variante, diese hinzuzufügen, folgendermaßen:\\ +Projekteinstellungen übernehmen, Workspace neu kompilieren lassen, und dann im View "`Problems"' einen der vielen Fehler auswählen, die im Zusammenhang mit jUnit gebracht werden. Beim Öffnen des gewählten Source-Files zeigt Eclipse im Editor bei den entsprechenden Imports Fehler an. Drücken Sie genau dort auf das rote Kreuz, und Ihnen wird die Option angeboten "`Add jUnit libraries"'. Wählen Sie diese aus, schließen das Source-File, und fertig.\\ +Jetzt sollte im View "`Problems"' kein Fehler mehr angezeigt werden. + \item Nun muss noch eine Startkonfiguration erstellt werden, und dann sind wir fertig:\\ +Unter dem Menüpunkt Run->Run... erstellen Sie eine neue Konfiguration vom Typ "`Java Application"', vergeben einen sinnvollen Namen und wählen vom \jalgo-Projekt als "`Main-Class"' \verb|org.jalgo.main.JAlgoMain| aus. +\end{itemize} + +Jetzt ist das Projekt kompilierbar und das Programm kann gestartet werden. + +\section{Projektstruktur} +Es folgt ein kurzer Überblick über die bestehende Struktur des Projektes, so dass der Entwickler weiß, welche Teile er verändern darf, und welche besser unangetastet bleiben sollten\dots\\ +Das Projekt fasst mehrere Ordner und einige "`lose"' Dateien. Der Reihe nach: +\begin{itemize} + \item Der Ordner \verb|bin| fasst die kompilierten Klassen. Sein Inhalt kann gelöscht werden, er wird bei jedem kompilieren neu erstellt. (Hinweis: Dieser Ordner gehört nicht unter die Versionskontrolle!) + \item Der Ordner \verb|doc| fasst die Projektdokumentation. Dies sind die Dateien zum Entwicklerhandbuch, zum Benutzerhandbuch, sowie einige Dateien, die gewisse aufgetretene Probleme und evtl. Abhilfen schildern. + \item Im Ordner \verb|examples| sind Beispieldateien für jedes Modul enthalten. Der komplette Ordner wird später in der Distribution enthalten sein. + \item Im Ordner \verb|extlibs| liegen Bibliotheken, die Fremdcode enthalten. Dies ist derzeit nur die Laufzeitbibliothek des Hilfesystems. Der komplette Ordner wird später in der Distribution enthalten sein. + \item Der Ordner \verb|relicts| fasst Codeteile und Ressourcendateien, welche derzeit nicht mehr verwendet werden. Sie wurden trotzdem aufgehoben, weil sie teilweise Funktionalität enthalten, die zu implementieren mal begonnen wurde, die jedoch nie ausgereift waren und daher derzeit nicht verwendet werden. Vielleicht bringen Sie einen Nutzen, wenn der Entwickler Ideen sucht. + \item Im Ordner \verb|res| liegen alle Ressourcendateien geordnet nach Programmteilen. + \item Der Ordner \verb|runtime| enthält leere, aber notwendige Dateien für die Laufzeit. Sie sind Teil der Pluginstruktur, und ermöglichen das Erkennen der installierten Module. + \item Im Ordner \verb|src| schließlich ist der Quellcode enthalten. Die Paketstruktur ist intuitiv gehalten. Unter \verb|org.jalgo.main| findet sich alles, was zum Hauptprogramm gehört, und unter \verb|org.jalgo.module| liegen alle Modulpakete. + \item Die "`losen"' Dateien sind diverse Build-Skripte, Manifest- und Start-Dateien für verschiedene Betriebssysteme sowie einige projektspezifische Dateien. +\end{itemize} +Teilweise wird in diesem Entwicklerhandbuch auf die API-Dokumentation von \jalgo verwiesen. Da an der Software permanent gearbeitet wird, ist diese nicht unter der Versionskontrolle verfügbar, sondern sollte vom Entwickler selbst in regelmäßigen Abständen generiert werden. Arbeitet der Entwickler unter Eclipse, so kann dies unter dem Menüpunkt Project->"`Generate Javadoc..."' ganz einfach durchgeführt werden. +\newpage \ No newline at end of file diff --git a/doc/developers_manual_german/misc.tex b/doc/developers_manual_german/misc.tex new file mode 100644 index 0000000..035a2e3 --- /dev/null +++ b/doc/developers_manual_german/misc.tex @@ -0,0 +1,10 @@ +\section{Bekannte Fehler und Schwachstellen} +Derzeit wird vom Hauptprogramm kein Drucken unterstützt. Daher ist die Methode\\ +\verb|AbstractModuleConnector.print()| derzeit nutzlos. Sie wird trotzdem aus Kompatibilitätsgründen mitgeführt, um für zukünftige Implementationen gerüstet zu sein. + +\section{Weiterführende Links} +Die Software nutzt für die graphische Oberfläche die \textbf{Swing}-Technologie. Informationen hierzu findet man unter\\ +\url{http://java.sun.com/docs/books/tutorial/},\\ +\url{http://java.sun.com/products/jfc/}\\ +\url{http://java.sun.com/products/javahelp/}\\ +oder in der API-Dokumentation von Java. \ No newline at end of file diff --git a/doc/developers_manual_german/module_development.tex b/doc/developers_manual_german/module_development.tex new file mode 100644 index 0000000..1dc8bb7 --- /dev/null +++ b/doc/developers_manual_german/module_development.tex @@ -0,0 +1,165 @@ +\newcommand{\code}[1]{\lstinline$#1$} + +\section{Implementieren eines neuen Moduls} +Hier sollen nur die technischen Schritte angegeben sein, die nötig sind, ein neues Modul für \jalgo korrekt und vollständig aufzusetzen und in das Hauptprogramm zu integrieren. Es wird vorausgesetzt, dass der Entwickler selbst ein Konzept seines Moduls entwickelt, insbesondere, was Details der Visualisierung betrifft. + +Es folgen fünf Abschnitte. Im ersten wird der Teil erklärt, der für das Implementieren eines neuen Moduls minimal notwendig ist. Der zweite Abschnitt enthält Erklärungen zur Funktionsweise der Pluginstruktur von \jalgo, und was der Entwickler für korrekte Erkennung des Moduls zu beachten hat. Der dritte Abschnitt zeigt, wie die Ressourcen des zu implementierenden Moduls organisiert sein sollten. Der vierte Abschnitt erklärt, wie die Dateien der Online-Hilfe für das Modul zu organisieren sind und der fünfte Abschnitt schließlich zeigt die hauptprogrammseitige Schnittstelle zwischen Modul und Hauptprogramm. Im folgenden wird abkürzend für "`Das zu implementierende Modul"' nur "`Das Modul"' geschrieben. + +\subsection{Grundimplementierung} +Der Code für das Modul wird im Paket \verb|org.jalgo.module.|\textsc{} abgelegt. Das Modulkürzel sollte aussagekräftig, jedoch relativ kurz gehalten sein. Es wird später im Code oft benötigt, wenn es um Ressourcen-Zugriffe geht.\\ +Eine schlechte Wahl wären also zum Beispiel \verb|dijkstrasShortestPathAlgorithm| oder vielleicht \verb|syntaxDiagramsAndEBNF|. + +Es gibt zwei Schnittstellen, um das Hauptprogramm mit einem Modul zu vernetzen. Die erste, modulseitige, Schnittstelle besteht aus zwei Klassen. Jedes Modul muss eine Verbindungseinheit und eine Informationseinheit anbieten. Die Verbindungseinheit muss abgeleitet sein von \verb|org.jalgo.main.AbstractModuleConnector|. Hier sind Methoden zu implementieren, die die Interaktion des Moduls mit dem Hauptprogramm spezifizieren. Für Details dazu sollte die API-Dokumentation von \jalgo konsultiert werden. Nachfolgend ist die Schnittstelle von \verb|AbstractModuleConnector| abgebildet.\\[0.25cm] +\textbf{Achtung!} Die Verbindungseinheit muss sich an eine Namenskonvention halten: Paket und Name der Klasse muss \verb|org.jalgo.module.|\textsc{}\verb|.ModuleConnector| lauten. Dies ist ein notwendiger Teil der Pluginstruktur von \jalgo. Für Details dazu lesen Sie bitte den nächsten Abschnitt. +\newpage +\begin{verbatim} +public abstract class AbstractModuleConnector { + public abstract void init(); + public abstract void run(); + public abstract void setDataFromFile(ByteArrayInputStream data); + public abstract ByteArrayOutputStream getDataForFile(); + public abstract void print(); + + public boolean close(); + + public final IModuleInfo getModuleInfo(); + public enum SaveStatus { + NOTHING_TO_SAVE, + NO_CHANGES, + CHANGES_TO_SAVE + } + public final SaveStatus getSaveStatus(); + public final void setSaveStatus(SaveStatus status); + public final void setSavingBlocked(boolean blocked); + public final boolean isSavingBlocked(); + public final String getOpenFileName(); + public final void setOpenFileName(String filename); +} +\end{verbatim} + +Die Informationseinheit ist dazu da, Informationen über das Modul bereitzustellen, die dem Benutzer entsprechend aufbereitet dargeboten werden, wenn er ein Modul zur Benutzung auswählen will. Sie muss das Interface \verb|org.jalgo.main.IModuleInfo| implementieren. Für Details dazu sei hier wieder auf die API-Dokumentation von \jalgo verwiesen. Nachfolgend ist die Schnittstelle von \verb|IModuleInfo| abgebildet. +\begin{verbatim} +public interface IModuleInfo { + public String getName(); + public String getVersion(); + public String getAuthor(); + public String getDescription(); + public URL getLogoURL(); + public String getLicense(); + public URL getHelpSetURL(); +} +\end{verbatim} +\textbf{Achtung!} Die Informationseinheit muss sich an eine Namenskonvention halten: Name und Paket der Klasse muss \verb|org.jalgo.module.|\textsc{}\verb|.ModuleInfo| lauten. Dies ist notwendiger Teil der Pluginstruktur von \jalgo.\\ +Weiterhin hat die Informationseinheit das \textbf{Singleton}-Entwurfsmuster zu implementieren mit der Zugriffsmethode +\verb|public static IModuleInfo getInstance();|\\ +Als Klassenmethode kann diese nicht in das Interface \verb|IModuleInfo| aufgenommen werden. Es sei jedoch ausdrücklich darauf hingewiesen, dass das Fehlen dieser Methode dazu führt, dass das Modul nicht korrekt erkannt wird und dass Laufzeitfehler beim Starten des Programmes auftreten. + +Als Beispielcode ist ein minimalistisches Modul implementiert namens \verb|testModule|. Es ist ein korrekt implementiertes Modul, jedoch hat es keinerlei Funktionalität. Der Entwickler kann den Code bei Bedarf als Skelett zum Aufsetzen eines neuen Moduls nehmen. Zum aktuellen Zeitpunkt existieren für \jalgo 2 Module: \textbf{AVL-Bäume} und \textbf{Dijkstra}. Es sei dem Entwickler freigestellt, diese als Anleihe zu nehmen.\\[0.5cm] +Mit diesen beiden Klassen ist die modulseitige Schnittstelle fertiggestellt. Damit das Modul als solches auch vom Hauptprogramm erkannt wird, ist noch ein Schritt notwendig. + +\subsection{Pluginstruktur von \jalgo} +An dieser Stelle scheint es angebracht, kurz die Pluginstruktur von \jalgo zu erläutern. In der Distribution wird das Hauptprogramm in ein JAR-Archiv verpackt. Es muss unabhängig von den Modulen sein. Daher wird auch jedes Modul in ein eigenes JAR-Archiv verpackt mit allem, was zu diesem Modul gehört: Code und Ressourcendateien. Dies garantiert, dass bei Erscheinen eines neuen Modules nur das entsprechende JAR-Archiv vom Benutzer heruntergeladen werden muss.\\[0.25cm] +\textbf{Achtung!} Die JAR-Archive für die Module müssen als Namen das Modulkürzel tragen und im Ordner \verb|runtime/modules| liegen. Nur so kann das Modul vom Hauptprogramm erkannt werden.\\[0.25cm] +Während der Laufzeit wird zum Start des Hauptprogramms der Ordner \verb|runtime/modules| nach JAR-Archiven durchsucht. Dabei wird der Name des Archives als Paketname angenommen, und es wird in jedem Archiv nach den beiden Verbindungsklassen (siehe oben) gesucht:\\ +\verb|org.jalgo.module.|\textsc{}\verb|.ModuleConnector| und\\ +\verb|org.jalgo.module.|\textsc{}\verb|.ModuleInfo|\\ +Sind diese korrekt implementiert, wird das Modul in die Liste der installierten Module aufgenommen und kann vom Benutzer ausgewählt werden. + +Der Entwickler hat also nun noch eine leere Datei mit dem Namen \textsc{}\verb|.jar| im Ordner \verb|runtime/modules| zu erstellen. Wird \jalgo aus der Entwicklungsumgebung ge\-startet, kann das Modul nun aufgerufen werden. +\newpage + +\subsection{Organisation der Ressourcen} +Sicher soll das Modul irgendwelche Ressourcendateien halten, wie zum Beispiel Icons oder ausgelagerte Algorithmentexte. + +Da, wie erwähnt, zur Laufzeit das Modul in einem JAR-Archiv vorliegt, kann auf die Ressourcen nur über den Klassenlader zugegriffen werden, indem die Methoden\\ \verb|getClass().getResource(String)| (liefert eine URL) oder\\ \verb|getClass().getResourceAsStream(String)| (liefert einen InputStream)\\ +verwendet werden. Es erweist sich als vorteilhaft, wenn die Pfade zu den Ressourcendateien nicht direkt im Code verankert werden, sondern in einer externen Textdatei abgelegt werden. Um einen einfachen Ressourcenzugriff zu ermöglichen, bietet das Hauptprogramm mit der Klasse \verb|org.jalgo.main.util.Messages| die Methode\\ +\verb|getResourceURL(String bundleKey, String key)|\\ +an, welche direkt die URL einer Ressource zurückgibt. Der erste Parameter ist der Schlüssel, mit welchem das Ressourcenpaket ausgewählt wird, aus dem der Pfad zu entnehmen ist. Dies ist wieder das Modulkürzel, also der Hauptpaketname, wenn moduleigene Ressourcen geladen werden sollen, und \verb|main|, wenn Ressourcen des Hauptprogramms, z.B. Standard-Icons verwendet werden sollen. Der zweite Parameter ist der Schlüssel der Ressource. Dafür ist im Hauptpaket des Moduls eine Textdatei zu erstellen, in welcher Ressourcenpfade zu Schlüsseln zugeordnet werden. Es sei als Beispiel auf die existierenden Dateien von Hauptprogramm und den bestehenden Modulen verwiesen.\\[0.25cm] +\textbf{Achtung!} Die Textdatei mit den Ressourcenpfaden muss einer Namenskonvention folgen: Sie hat den Titel \verb|res.properties| zu tragen und muss im Hauptpaket des Moduls liegen. Anderenfalls wird sie von der Klasse \verb|Messages| nicht gefunden.\\[0.25cm] +Die Ressourcendateien selbst werden im Ordner \verb|res/module/|\textsc{Modulkürzel} abgelegt. Wird unter Eclipse programmiert, ist dieser Ordner unter "`Projekteinstellungen"'->"`Libraries"'-> \mbox{"`Add Class Folder..."'} hinzuzufügen, damit die Ressourcen in der Entwicklungsumgebung freigegeben sind.\\ +Um Namenskonflikten unter den Ressourcendateien vorzubeugen (letzlich liegen alle Ressourcenpfade hinter \verb|res/main/| und \verb|res/module/|\textsc{}\verb|/| auf dem Klassenpfad), empfiehlt es sich, im angelegten Ressourcenordner eine angemessene Struktur zu entwickeln, so zum Beispiel einen Unterordner \textsc{}\verb|_pix| für Bilddateien. Jetzt kann auch ein Dateiname wie \verb|icon.gif| ohne Probleme verwendet werden.\vspace{0.5cm} + +\jalgo ist ein Programm, welches mehrere Sprachen unterstützt. Zum aktuellen Zeitpunkt sind sämtliche Programmteile in Deutsch und Englisch verfügbar. Dem Entwickler wird nahegelegt, auch das neue Modul in diesen Sprachen zu veröffentlichen. Dazu ist es notwendig, alle Zeichenketten, die dem Benutzer dargeboten werden sollen, in externen Textdateien zu speichern. Auch für den einfachen Zugriff auf diese Zeichenketten bietet die Klasse \verb|org.jalgo.main.util.Messages| eine Methode an:\\ +\verb|getString(String bundleKey, String messageKey)|\\ +Die Verwendung dieser Methode erfolgt analog zu der oben erwähnten Methode für die Ressourcen.\newpage +\textbf{Achtung!} Die Textdatei mit den ausgelagerten Zeichenketten muss einer Namenskonvention folgen: Auch sie hat die Endung \verb|.properties| zu tragen. Der Name der Datei ist einfach das Kürzel der Sprache, für welche sie Zeichenketten enthält. Für deutsch also \verb|de.properties|, für englisch \verb|en.properties|. Auch diese Textdateien haben im Hauptpaket des Moduls zu liegen.\\[0.25cm] +Liegen die Textdateien korrekt vor, so wird vom Hauptprogramm automatisch auf die eingestellte Sprache umgestellt. Der Modulentwickler muss hierzu nichts mehr beachten.\\ +Auch hier wieder sei als Beispiel auf die existierenden Dateien von Hauptprogramm und Modulen verwiesen.\vspace{0.5cm} + +Letzlich sei noch erwähnt, dass jedes Modul die Möglichkeit hat, persistente Benutzereinstellungen anzubieten. Will der Modulentwickler solche Einstellungen einbauen, so muss eine Textdatei mit Zuordnungen zwischen Schlüsseln und Werten angelegt werden. Es sind hier alle Einstellmöglichkeiten als Schlüssel zu erwähnen; die zugeordneten Werte sind jeweils die Default-Werte für die entsprechenden Einstellungen.\\[0.25cm] +\textbf{Achtung!} Die Textdatei mit den Default-Einstellungen muss einer Namenskonvention folgen: Sie muss den Namen \textsc{}\verb|.prefs| tragen und im Ressourcenverzeichnis des Moduls (\verb|res/|\textsc{}\verb|/|) liegen. Außerdem muss ein Schlüssel namens "`Version"' in der Datei stehen, dessen Wert die Version der Einstellungsdatei angibt. Wird in einer späteren Version etwas am Bestand der Schlüssel geändert, gewährleistet der geänderte Wert von "`Version"', dass beim Benutzer die Einstellungsdatei neu erstellt wird und an die neuen Einstellungen angepasst wird.\\[0.25cm] +Es wird als Beispiel auf die Dateien \verb|main.prefs| des Hauptprogramms und \verb|avl.prefs| des Moduls AVL-Bäume verwiesen.\\ +Zugegriffen wird auf die persistenten Einstellungen über die Klasse\\ \verb|org.jalgo.main.util.Settings|\\ +Für Details ist die API-Dokumentation von \jalgo zu konsultieren. Nachfolgend ist der relevante Teil von \verb|Settings| abgebildet: +\begin{verbatim} +public class Settings { + + public static boolean getBoolean(String resourceKey, String settingKey); + public static void setBoolean(String resourceKey, String key, + boolean value); + public static String getString(String resourceKey, String key); + public static void setString(String resourceKey, String key, + String value); +} +\end{verbatim} +Wie schon beim Zugriff auf Ressourcenpfade und ausgelagerte Zeichenketten gibt der erste Parameter jeder Methode hier an, in welcher Einstellungsdatei die Einstellmöglichkeit gesucht werden soll. Dies ist für modulspezifische Einstellungen wieder das Modulkürzel. Es ist aber auch möglich, an die Einstellungen des Hauptprogramms zu gelangen mittels des \verb|resourceKey|s \verb|main|. +\newpage + +\subsection{Organisation der Hilfe-Dateien} +Dem Entwickler wird angeraten, ebenfalls eine Online-Hilfe zu seinem Modul zu erstellen. Die Online-Hilfe von \jalgo nutzt die Technologie von JavaHelp 2.0. An dieser Stelle kann lediglich ein kleiner Einblick in den Umfang dieses System ermöglicht werden, und es wird vor allem auf die \href{http://java.sun.com/products/javahelp/}{Support-Seiten von Sun} und \href{http://www.knopf.com/resources/help/javahelp.html}{Tutorials} verwiesen.\\ +Es folgen 5 Abschnitte. Der erste gibt einen groben Überblick über die für JavaHelp notwendigen Ressourcen. Die Teile 2 bis 4 befassen sich dagegen mit einzelnen Ansichten, mit denen der Zugriff auf die Hilfetexte angenehmer gestaltet werden kann. Zum Schluss wird im letzten Abschnitt noch auf die Einbettung der Hilfe in \jalgo eingegangen.\\ +\textbf{Hinweis!} Beispieldateien zur Hilfe sind in den Ressourcen des Hauptprogrammes im Ordner \verb|res/main/help| zu finden. Hier finden sich auch CSS Stylesheets und die config-Datei für die Volltextsuche. + +\subsubsection{Überblick} +Bei JavaHelp handelt es sich um eine Betriebssystem-unabhängige Technologie, die in einem Java-basierten Browser HTML-Dateien anzeigen kann. Sie bietet die Möglichkeit, über Ansichten wie Inhaltsverzeichnis, Indexübersicht, Favoriten und Volltextsuche den Zugriff auf die Hilfe zu beschleunigen. Grundlegend für eine mit JavaHelp konstruierte Hilfe sind zwei Dateien. +\begin{itemize} + \item Die erste ist das sogenannte \textbf{HelpSet}. Diese Datei vereinigt alle für die Hilfe wichtigen Daten und dient der Applikation als eine Art Kontaktdatei. Hier wird unter anderem festgelegt, welche Ansichten die Hilfe unterstützen soll und welche Dateien dafür benutzt werden. Außerdem wird hier die Map-Datei festgelegt. + \item Die \textbf{Map-Datei} ist ein Liste von Schlüssel-URL-Zuordungen. Alle von der Hilfe benötigten Resourcendateien, wie HTML- oder Bilddateien, werden hier aufgelistet und einem Schlüssel zugeordnet. In den Dateien für die einzelnen Ansichten werden anschließend nur noch Schlüssel als Verweis auf bestimmte Ressourcen verwendet. +\end{itemize} +Neben diesen beiden wichtigen Metadateien besitzt jede Ansicht eine oder mehrere beschreibende Dateien. Dazu jetzt mehr. + +\subsubsection{Inhaltsverzeichnis} +Das Inhaltsverzeichnis (Table Of Contents) ermöglicht einen schnellen inhaltsbezogenen Zugriff auf spezielle Hilfethemen und ist daher ungemein praktisch. Aus diesem Grund ist es für eine Hilfe unersetzlich. Die Struktur des Verzeichnisbaumes wird in einer XML-Datei beschrieben, die traditionell den Namen \textsc{}\verb|TOC.xml| trägt. Die genaue Struktur einer solchen Datei lässt sich am besten am Beispiel der Hilfedateien des Hauptprogramms und der bestehenden Module ergründen und wird hier nicht weiter beleuchtet. + +\subsubsection{Indexübersicht} +Die Indexübersicht gewährt ähnlich dem Inhaltsverzeichnis einen Überblick über die verschiedenen Hilfethemen. Doch ist sie im allgemeinen alphabetisch geordnet. Auch die Indexübersicht wird durch eine XML-Datei beschrieben. Traditionell ist diese mit dem Namen \mbox{\textsc{}}\verb|Index.xml| betitelt. Auch hier sei bezüglich der Struktur dieser Datei ein Blick in die bestehenden Dateien der Module und des Hauptprogramms ans Herz gelegt. + +\subsubsection{Volltextsuche} +Die Volltextsuche ist ein sehr hilfreiches Feature, welches es erlaubt, den gesamten Text der Hilfe nach bestimmten Wörtern zu durchsuchen. Das Erstellen einer solchen Suchoption gestaltet sich nicht so einfach wie bisher und es werden mehrere Dateien dafür verwendet, die im allgemeinen in einem Ordner namens \verb|JavaHelpSearch| des JavaHelp-Ordners abgelegt werden. Im HelpSet wird zu dem auch nur auf diesen Ordner verwiesen und nicht auf eine bestimmte Datei.\\ +JavaHelp bietet für die Erzeugung einer Suchengine einen Konsolenbefehl, der alle notwendigen Dateien erzeugt. Der sogenannte \textbf{jhindexer}-Befehl wird im Ordner ausgeführt, in dem das HelpSet zu finden ist. Er durchläuft die HTML-Dateien und vergibt für jedes Wort einen Index. Später wird mit Hilfe dieser das Wort wieder gefunden. Nun ist es ratsam bestimmte Wörter, wie "`eine"', "`keine"', "`mit"' oder "`oder"', aus der Indexierung auszuklammern. Diese sogenannten \textbf{Stopwords} werden in einem config-File aufgelistet und \textbf{jhindexer} übergeben.\\[0.25cm] +Der Befehl hat dann die folgende Form:\\ +\verb|jhindexer -c|\textsc{ }\\[0.25cm] +ein Beispiel: \\ +\verb|jhindexer -c|\textsc{ /JavaHelpSearch/config.ini ../html/data}\\[0.25cm] +\textbf{Hinweis!} Der jhindexer-Befehl ist weitaus umfangreicher und es wird empfohlen, alles weitere im JavaHelpUserGuide (jhug.pdf) nachzuschlagen. + +\subsubsection{Einbettung von JavaHelp in \jalgo} +Nachdem nun ein wesentlicher Überblick über die Dateien und Ressourcen von JavaHelp entstanden sein sollte, wird im kommenden Abschnitt auf die Einbettung dieser in die Umgebung von \jalgo eingegangen.\\ +Grundlegend besteht keine Namenskonvention, die unbedingt eingehalten werden muss. Nur empfiehlt es sich, ausdrucksstarke Namen sowohl für die Datei des HelpSets als auch für Map- und Ansichtsdateien zu verwenden. Das HelpSet sammelt alle wichtigen Dateinamen, und es ist nur ausschlaggebend, wie diese Datei benannt wird. Die bestehenden Module und das Hauptprogramm folgen hier der folgenden Namenskonvention: \textsc{}\verb|_help.hs|.\\ +Um die Hilfe schließlich aus dem \jalgo - Hauptprogramm aufrufbar zu machen, wird die Methode \verb|org.jalgo.module.|\textsc{}\verb|.ModuleInfo.getHelpSetURL()| genutzt. Diese liefert den Pfad der HelpSet-Datei. Da es sich bei dem HelpSet um eine Ressource von \jalgo handelt, wird empfohlen, die Methode \verb|getResourceURL(String bundleKey, String key)| der Klasse \verb|org.jalgo.main.util.Messages| wie beschrieben zu nutzen. + +\newpage +\subsection{Schnittstelle zum Hauptprogramm} +Die zweite erwähnte Schnittstelle ist die auf Seiten des Hauptprogramms, namentlich die Klasse \verb|org.jalgo.main.gui.JAlgoGUIConnector|. Der Entwickler hat hier nichts zu implementieren, jedoch hat er Kenntnis von dieser Schnittstelle zu haben. Hierüber laufen alle Anfragen, die das Modul an die graphische Oberfläche des Hauptprogramms richtet. Für Details dazu sei auf die API-Dokumentation von \jalgo verwiesen. Nachfolgend ist die Schnittstelle von \verb|JAlgoGUIConnector| abgebildet. Gerade die letzten 3 Methoden sind interessant, um an die moduleigenen GUI-Komponenten zu gelangen. +\begin{verbatim} +public class JAlgoGUIConnector { + + public static JAlgoGUIConnector getInstance(); + + public void saveStatusChanged(AbstractModuleConnector moduleInstance); + public void showErrorMessage(String msg); + public void showWarningMessage(String msg); + public void showInfoMessage(String msg); + public int showConfirmDialog(String question, int optionType); + public void setStatusMessage(String msg); + public String showOpenDialog(boolean openAsJAlgoFile, + boolean useCurrentModuleInstance); + public AbstractModuleConnector newModuleInstanceByName(String moduleName); + + public JComponent getModuleComponent(AbstractModuleConnector module); + public JMenu getModuleMenu(AbstractModuleConnector module); + public JToolBar getModuleToolbar(AbstractModuleConnector module); +} +\end{verbatim} +Diese Klasse implementiert das \textbf{Singleton}-Entwurfsmuster. Somit kommt man über die Zugriffsmethode \verb|getInstance()| an die Instanz. +\newpage \ No newline at end of file diff --git a/doc/developers_manual_german/overview.tex b/doc/developers_manual_german/overview.tex new file mode 100644 index 0000000..543b6e4 --- /dev/null +++ b/doc/developers_manual_german/overview.tex @@ -0,0 +1,36 @@ +\section{Einleitung} +Dieses Handbuch soll künftigen Entwicklern von \jalgo helfen, sich schnell mit der Struktur der Software auseinanderzusetzen. \jalgo ist eine Software, die sich mit der Visualisierung von Algorithmen beschäftigt. Sie soll dazu dienen, verschiedene Algorithmen zu veranschaulichen um sie so Studenten und anderen Interessierten verständlicher zu machen. Die Anwendung basiert auf einer Plugin-Struktur, die es ermöglicht, einzelne Module, die jeweils einen Algorithmus oder ein Themengebiet abdecken können, in das Programm zu integrieren und zu laden. + +Sowohl \jalgo als auch die einzelnen Module entstanden im Rahmen des externen Softwarepraktikums im Studiengang Informatik der TU Dresden in Zusammenarbeit mit dem Lehrstuhl Programmierung. Die implementierten Module orientieren sich daher an den Lehrveranstaltungen "`Algorithmen und Datenstrukturen"' sowie "`Programmierung"' im Grundstudium Informatik an der TU Dresden. Das Einsatzgebiet soll vor allem die Vorlesung und das studentische Lernen zu Hause umfassen.\\ +\jalgo ist eine freie Software, die beliebig oft kopiert werden darf. + +\bigskip +\section{Technische Hinweise} +\subsection{Systemvoraussetzungen} +Folgende minimale Systemanforderungen werden für den reibungslosen Einsatz von \jalgo benötigt: +\begin{itemize} + \item IBM-kompatibler PC + \item Mindestens 64 MB RAM + \item {\sc Windows} 98(SE)/ME/2000/XP , {\sc Linux} SuSE/Red Had + \item Java 2 Platform Standard Edition 5.0 {\small (siehe: \href{http://java.sun.com/}{http://java.sun.com/})} + \item Maus und Tastatur + \item Monitor mit einer Auflösung von mindestens 800x600 +\end{itemize} + +\medskip +\subsection{Installation} +\subsubsection*{Windows} +Entpacken Sie nach dem Herunterladen das ZIP-komprimierte Archiv in einen Ordner Ihrer Wahl. +In diesem Ordner finden Sie eine Datei namens "`j-algo.bat"'. +Öffnen Sie diese Datei mit einem Doppelklick, und das Programm wird gestartet. + +\subsubsection*{Unix} +Entpacken Sie nach dem Herunterladen das TGZ-komprimierte Archiv in einen Ordner Ihrer Wahl. +In diesem Ordner finden Sie eine Datei namens "`j-algo.sh"'. +Öffnen Sie die Konsole und starten sie mittles \verb|sh j-algo.sh| das Programm. + +\medskip +\subsection{Deinstallation} +Der komplette Programmordner kann jederzeit gefahrlos von der Festplatte gelöscht werden. + +\newpage \ No newline at end of file diff --git a/doc/developers_manual_german/pics/CVS/Entries b/doc/developers_manual_german/pics/CVS/Entries new file mode 100644 index 0000000..ebb49b9 --- /dev/null +++ b/doc/developers_manual_german/pics/CVS/Entries @@ -0,0 +1 @@ +/title.png/1.1/Sun Mar 26 12:07:09 2006/-kb/ diff --git a/doc/developers_manual_german/pics/CVS/Repository b/doc/developers_manual_german/pics/CVS/Repository new file mode 100644 index 0000000..f1e5fbb --- /dev/null +++ b/doc/developers_manual_german/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/developers_manual_german/pics diff --git a/doc/developers_manual_german/pics/CVS/Root b/doc/developers_manual_german/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/developers_manual_german/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/developers_manual_german/pics/title.png b/doc/developers_manual_german/pics/title.png new file mode 100644 index 0000000..f7be70a Binary files /dev/null and b/doc/developers_manual_german/pics/title.png differ diff --git a/doc/message-board b/doc/message-board new file mode 100644 index 0000000..85c7a3e --- /dev/null +++ b/doc/message-board @@ -0,0 +1,2 @@ +Nachrichten, die unter den Entwicklern ausgetauscht werden sollen +------------------------------------------------------------------ \ No newline at end of file diff --git a/doc/users_manual_german/CVS/Entries b/doc/users_manual_german/CVS/Entries new file mode 100644 index 0000000..2214389 --- /dev/null +++ b/doc/users_manual_german/CVS/Entries @@ -0,0 +1,5 @@ +D/main//// +D/modules//// +D/pics//// +/users_manual_german.pdf/1.14/Wed Oct 18 11:57:20 2006/-kb/ +/users_manual_german.tex/1.7/Sat Aug 12 21:04:12 2006// diff --git a/doc/users_manual_german/CVS/Repository b/doc/users_manual_german/CVS/Repository new file mode 100644 index 0000000..17d7a54 --- /dev/null +++ b/doc/users_manual_german/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german diff --git a/doc/users_manual_german/CVS/Root b/doc/users_manual_german/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/main/CVS/Entries b/doc/users_manual_german/main/CVS/Entries new file mode 100644 index 0000000..31004e2 --- /dev/null +++ b/doc/users_manual_german/main/CVS/Entries @@ -0,0 +1,3 @@ +/basics.tex/1.3/Tue Mar 28 14:21:12 2006// +/imprint.tex/1.3/Tue Mar 28 14:21:12 2006// +/overview.tex/1.3/Mon Dec 19 19:13:37 2005// diff --git a/doc/users_manual_german/main/CVS/Repository b/doc/users_manual_german/main/CVS/Repository new file mode 100644 index 0000000..10d99c9 --- /dev/null +++ b/doc/users_manual_german/main/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/main diff --git a/doc/users_manual_german/main/CVS/Root b/doc/users_manual_german/main/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/main/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/main/basics.tex b/doc/users_manual_german/main/basics.tex new file mode 100644 index 0000000..a33c2d0 --- /dev/null +++ b/doc/users_manual_german/main/basics.tex @@ -0,0 +1,44 @@ +\section{Grundfunktionen} +\jalgo bietet eine Reihe von Grundfunktionen, die unabhängig von den Modulen zur Verfügung stehen, bzw. für jedes Modul die gleiche Bedeutung haben. Im Einzelnen sind das das Öffnen von Modulen sowie das Laden und Speichern von Sitzungsdaten. Die Grundfunktionen sind über die Werkzeugleiste oder den Menüpunkt <\textsc{Datei}> erreichbar. + +\subsectionicon{Neues Modul öffnen}{main/icon_new} +Ein Klick auf den Button <\textsc{Neu}> in der Werkzeugleiste gibt Ihnen die Möglichkeit, ein beliebiges neues Modul zu öffnen. Dabei wird ein Auswahldialog geöffnet, in welchem die installierten Module aufgelistet sind. Hier werden Ihnen außerdem kurze Informationen zu diesen Modulen angezeigt. Sie können wählen, ob dieser Auswahldialog bei jedem Start des Programmes angezeigt werden soll oder nicht.\\ +Alternativ dazu kann über das Menü \textsc{$\rightarrow$} das gewünschte Modul geladen werden. Dies ist der schnellere Weg und zu empfehlen, wenn man bereits einen Überblick über die installierten Module hat. + +\subsectionicon{Gespeicherte Sitzungsdaten laden}{main/icon_open} +Mit einem Klick auf den Button <\textsc{Öffnen}> erscheint ein Dialog zur Dateiauswahl. Hier haben Sie die Möglichkeit, eine Datei auszuwählen, in welcher modulspezifische Sitzungsdaten gespeichert wurden. Die Dateien, die von \jalgo gespeichert werden, tragen die Dateiendung \emph{"`.jalgo"'}.\\ +Achtung: Da jedes Modul von \jalgo seine Daten in einer solchen Datei ablegt, kann man beim Blick auf die ungeöffnete Datei nicht erkennen, mit welchem Modul diese assoziiert wurde. Es wird jeweils das assoziierte Modul zu der geladenen Datei geöffnet. Achten Sie daher bei der Vergabe der Dateinamen auf möglichst eindeutige Bezeichner.\\ +Anmerkung: In einer späteren Version wird direkt bei der Dateiauswahl das zugehörige Modul mit angezeigt. +\centerpic{main/loaddialog}{0.45}{Das Dialogfenster zum Öffnen} + +\medskip +\subsectiondoubleicon{Sitzungsdaten speichern}{main/icon_save}{main/icon_save_as} +Per Klick auf die Buttons <\textsc{Speichern}> und <\textsc{Speichern unter}> können Sie die Sitzungsdaten des gerade aktiven Moduls in einer Datei speichern. Wie beim Laden öffnet sich auch hier ein Dialog zur Dateiauswahl, in welchem Sie Zielpfad und Name der neuen Datei eintragen können. Die Angabe der Dateiendung ist nicht nötig, das Programm +ergänzt diese automatisch.\\ +Je nach Implementierung des aktiven Moduls steht die Speicherfunktion nur zur Verfügung, wenn gerade kein Algorithmus läuft. Sollte noch ein Algorithmus aktiv sein, so beenden Sie diesen bitte vorher oder brechen ihn ab. + +\subsection{Modul schließen} +Sie haben die Möglichkeit, jede Modulinstanz durch Klick auf das Kreuz der dazugehörigen Registerkarte zu schließen. Dabei werden Sie gegebenenfalls gefragt, ob Sie Ihre Arbeit speichern wollen. Um das gesamte Programm zu schließen, ist es nicht nötig, die Module einzeln zu schliessen, das erledigt das Programm für Sie. + +\bigskip +\begin{center} + \raisebox{-7ex}{\includegraphics[scale=0.8]{\pfad main/closebutton}} \hfill + \includegraphics[scale=0.55]{\pfad main/closemessage} \\ + {\small Der Knopf zum Schließen eines Moduls.} \hfill + {\small Die Abfrage, ob die Daten gespeichert werden sollen.} +\end{center} + +\subsectionicon{Einstellungen}{main/icon_prefs} +\jalgo bietet ein paar Möglichkeiten an, das Programm den Bedürfnissen des Benutzers anzupassen. Den Dialog für die Grundeinstellungen erreichen Sie unter dem Menüpunkt\\ \textsc{$\rightarrow$} +\centerpic{main/prefsdialog}{0.8}{Der Dialog für die Grundeinstellungen} +Unter anderem kann hier die Sprache eingestellt werden. Außerdem bietet sich die Möglichkeit, die Art der graphischen Oberfläche zu ändern, da unter manchen Betriebssystemen diverse Oberflächenelemente nicht immer vorteilhaft aussehen. + +\subsectionicon{Hilfe}{main/icon_help} +Die Hilfe stellt ein wichtiges Nachschlagewerk für all diejenigen dar, die nicht auf Anhieb mit allen Funktionen von \jalgo und seinen Modulen klar kommen. Hier können Sie noch einmal eine genaue Beschreibung zu den einzelnen Programmelementen nachlesen.\\ +Die Hilfe ist kontextspezifisch aufgebaut, d.h. ist ein Modul geöffnet, so wird in der Hilfe automatisch an die entsprechende Stelle gesprungen.\\ +Sie erreichen die Hilfe über den Menüpunkt \textsc{$\rightarrow$} oder indem Sie einfach auf die Taste <\textsc{F1}> Ihrer Tastatur drücken. + +\subsection{Hinweis-Tipps} +Zusätzlich wird zu den meisten Kontrollelementen, also Buttons, Menüeinträge, etc., ein kurzer Hinweistext neben dem Mauszeiger bzw. in der Statuszeile des Programmes angezeigt. Dies sollte als schnelle Hilfestellung den meisten Anforderungen genügen. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/main/imprint.tex b/doc/users_manual_german/main/imprint.tex new file mode 100644 index 0000000..d0e2b54 --- /dev/null +++ b/doc/users_manual_german/main/imprint.tex @@ -0,0 +1,17 @@ +\section{Impressum} +Die \jalgo Software wurde im Sommersemester 2004 von der Praktikumsgruppe SWT04-PROG1 im Rahmen des externen Softwarepraktikums entwickelt. Mitwirkende waren die +\paragraph{Teammitglieder} +\begin{itemize} + \item Michael Pradel --- Chief of Algorithms + \item Cornelius Hald --- Chief of Framework + \item Malte Blumberg + \item Stephan Creutz + \item Christopher Friedrich + \item Anne Kersten + \item Hauke Menges + \item Babett Schalitz + \item Benjamin Scholz + \item Marco Zimmerling +\end{itemize} +Die Webseite des Praktikums finden Sie unter \url{http://web.inf.tu-dresden.de/~swt04-p1/}.\\ +Komplette Überarbeitung erfuhr die Software und die Dokumentation unter anderem durch Alexander Claus und Matthias Schmidt. Weitergehende Informationen über \jalgo erhalten Sie unter \url{http://j-algo.binaervarianz.de/}. \ No newline at end of file diff --git a/doc/users_manual_german/main/overview.tex b/doc/users_manual_german/main/overview.tex new file mode 100644 index 0000000..d965983 --- /dev/null +++ b/doc/users_manual_german/main/overview.tex @@ -0,0 +1,37 @@ +\chapter{Das Hauptprogramm} +\section{Einleitung} +Dieses Handbuch stellt eine Einführung und Hilfe für die Arbeit mit \jalgo dar. \jalgo ist eine Software, die sich mit der Visualisierung von Algorithmen beschäftigt. Sie soll dazu dienen, verschiedene Algorithmen zu veranschaulichen um sie so Studenten und anderen Interessierten verständlicher zu machen. Die Anwendung basiert auf einer Plugin-Struktur, die es ermöglicht, einzelne Module, die jeweils einen Algorithmus oder ein Themengebiet abdecken können, in das Programm zu integrieren und zu laden. + +Sowohl \jalgo als auch die einzelnen Module entstanden im Rahmen des externen Softwarepraktikums im Studiengang Informatik der TU Dresden in Zusammenarbeit mit dem Lehrstuhl Programmierung. Die implementierten Module orientieren sich daher an den Lehrveranstaltungen "`Algorithmen und Datenstrukturen"' sowie "`Programmierung"' im Grundstudium Informatik an der TU Dresden. Das Einsatzgebiet soll vor allem die Vorlesung und das studentische Lernen zu Hause umfassen.\\ +\jalgo ist eine freie Software, die beliebig oft kopiert werden darf. + +\bigskip +\section{Technische Hinweise} +\subsection{Systemvoraussetzungen} +Folgende minimale Systemanforderungen werden für den reibungslosen Einsatz von \jalgo benötigt: +\begin{itemize} + \item IBM-kompatibler PC + \item Mindestens 64 MB RAM + \item {\sc Windows} 98(SE)/ME/2000/XP , {\sc Linux} SuSE/Red Had + \item Java 2 Platform Standard Edition 5.0 {\small (siehe: \href{http://java.sun.com/}{http://java.sun.com/})} + \item Maus und Tastatur + \item Monitor mit einer Auflösung von mindestens 800x600 +\end{itemize} + +\medskip +\subsection{Installation} +\subsubsection*{Windows} +Entpacken Sie nach dem Herunterladen das ZIP-komprimierte Archiv in einen Ordner Ihrer Wahl. +In diesem Ordner finden Sie eine Datei namens "`j-algo.bat"'. +Öffnen Sie diese Datei mit einem Doppelklick, und das Programm wird gestartet. + +\subsubsection*{Unix} +Entpacken Sie nach dem Herunterladen das TGZ-komprimierte Archiv in einen Ordner Ihrer Wahl. +In diesem Ordner finden Sie eine Datei namens "`j-algo.sh"'. +Öffnen Sie die Konsole und starten sie mittles \verb|sh j-algo.sh| das Programm. + +\medskip +\subsection{Deinstallation} +Der komplette Programmordner kann jederzeit gefahrlos von der Festplatte gelöscht werden. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/CVS/Entries b/doc/users_manual_german/modules/CVS/Entries new file mode 100644 index 0000000..a5a3c7e --- /dev/null +++ b/doc/users_manual_german/modules/CVS/Entries @@ -0,0 +1,4 @@ +D/avl//// +D/dijkstra//// +D/ebnf//// +D/kmp//// diff --git a/doc/users_manual_german/modules/CVS/Repository b/doc/users_manual_german/modules/CVS/Repository new file mode 100644 index 0000000..8c12cc5 --- /dev/null +++ b/doc/users_manual_german/modules/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/modules diff --git a/doc/users_manual_german/modules/CVS/Root b/doc/users_manual_german/modules/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/modules/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/modules/avl/CVS/Entries b/doc/users_manual_german/modules/avl/CVS/Entries new file mode 100644 index 0000000..162c6bb --- /dev/null +++ b/doc/users_manual_german/modules/avl/CVS/Entries @@ -0,0 +1,10 @@ +/additionals.tex/1.1/Tue Oct 11 09:08:15 2005// +/appendix.tex/1.4/Thu Oct 27 20:08:23 2005// +/contents.tex/1.1/Tue Oct 11 09:08:15 2005// +/documentation.tex/1.1/Tue Oct 11 09:08:15 2005// +/flowcontrol.tex/1.1/Tue Oct 11 09:08:15 2005// +/functions.tex/1.2/Fri Oct 14 09:49:19 2005// +/imprint.tex/1.2/Tue Mar 28 14:21:12 2006// +/overview.tex/1.2/Fri Nov 18 13:42:42 2005// +/screen.tex/1.1/Tue Oct 11 09:08:15 2005// +/start.tex/1.2/Fri Oct 14 09:49:19 2005// diff --git a/doc/users_manual_german/modules/avl/CVS/Repository b/doc/users_manual_german/modules/avl/CVS/Repository new file mode 100644 index 0000000..213690e --- /dev/null +++ b/doc/users_manual_german/modules/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/modules/avl diff --git a/doc/users_manual_german/modules/avl/CVS/Root b/doc/users_manual_german/modules/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/modules/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/modules/avl/additionals.tex b/doc/users_manual_german/modules/avl/additionals.tex new file mode 100644 index 0000000..9039182 --- /dev/null +++ b/doc/users_manual_german/modules/avl/additionals.tex @@ -0,0 +1,26 @@ +\section{Zusatzfunktionen} +Dieses Kapitel widmet sich den Eastereggs des Moduls \avl.\\ +Sollten Sie sich lieber selber gerne auf die Suche nach diesen Zusatzfunktionen machen wollen, so überspringen Sie besser dieses Kapitel.\\ +Für alle Anderen folgt nun eine Übersicht zum Baumnavigator und dem Beamermodus. + +\subsection{Navigator} +Der Navigator ist eine kleine, versteckte Zusatzfunktion, die die Arbeit mit großen Bäumen erheblich vereinfachen kann. Er stellt eine willkommene Hilfe für das Scrollen der Zeichenfläche dar, ist aber nicht so einfach zu finden. +\begin{itemize} + \item Wenn der Baum, der auf der Zeichenfläche angezeigt wird, zu groß für diese wird, so erscheinen Schiebebalken, mit denen Sie den Bildausschnitt verschieben können. + \item Klicken Sie nun auf das kleine Quadrat in der rechten unteren Ecke der Zeichenfläche, genau zwischen den beiden Schiebebalken. Halten Sie dabei die linke Maustaste gedrückt. + \item Eine kleine Übersichtskarte des Baumes mit einem Ausschnittfenster erscheint. Bewegen Sie die Maus (mit gedrückter Taste) und das Ausschnittfenster, das den Bildschirminhalt der Zeichenfläche repräsentiert, folgt Ihren Bewegungen. +\end{itemize} +\bigskip +\begin{center} + \includegraphics[scale=0.7]{\pfad avl/navigator1} \hfill + \includegraphics[scale=0.7]{\pfad avl/navigator2} \\ + Ein Klick auf das kleine Kästchen... \hfill ...öffnet den Navigator! +\end{center} + +\subsectionicon{Beamermodus}{avl/icon_beamer} +Der Beamermodus ist in erster Linie für die Präsentation in Vorlesungen oder ähnlichen Veranstaltungen gedacht. Ist dieser Modus aktiv, so werden die Knoten des Baumes und die Einträge des Logbuches vergrößert dargestellt. Der Algorithmustext aus dem Skript von Prof. Vogler bleibt dabei unverändert, weil davon ausgegangen wird, dass die interessierten Studenten der Vorlesung über ein (eventuell aktuelleres) Skript verfügen.\\ +Sie erreichen den Beamermodus über den Menüpunkt \textsc{<\avl>} $\rightarrow$ \textsc{}. Ist der Modus aktiv, so erscheint neben diesem Menüeintrag ein Häkchen. Um den Modus wieder auszuschalten, entfernen Sie einfach den Haken per Klick. +\bigskip +\centerpic{avl/beamermenu}{0.5}{Das Menü \textsc{<\avl>} mit dem Eintrag \textsc{}} + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/appendix.tex b/doc/users_manual_german/modules/avl/appendix.tex new file mode 100644 index 0000000..fc44dbe --- /dev/null +++ b/doc/users_manual_german/modules/avl/appendix.tex @@ -0,0 +1,151 @@ +\newtheorem{alg}{Algorithmus} + +\chapter{\label{appendix_avl_A}Einleitung zu Datenstrukturen} +\begin{tabbing} +\textbf{Anmerkung:} \=Der Autor der folgenden Seiten (Kapitel \ref{appendix_avl_A}, \ref{appendix_avl_B} und \ref{appendix_avl_C} dieses Anhangs) ist\\ +\> Jean Christoph Jung (Teammitglied AVL-Modul) +\end{tabbing} + +Eine häufige Anwendung auf großen Datenmengen ist das Suchen: Das Wiederfinden eines bestimmten Elements oder bestimmter Informationen aus einer großen Menge früher abgelegter Daten. Um die Suche zu vereinfachen, werden den (möglicherweise sehr komplexen) großen Datensätzen eineindeutige Suchschlüssel (Keys) zugeordnet. Der Vergleich zweier solcher Schlüssel ist in der Regel viel schneller als der Vergleich zweier Datensätze. Wegen der Schlüsselzuordnung reicht es aus, alle vorkommenden Algorithmen nur auf den Schlüsseln zu betrachten; in Wirklichkeit verweisen erst die Schlüssel auf die Datensätze.\\ +Eine grundlegende Idee ist nun, die Daten in Form einer Liste oder eines Feldes abzulegen. Diese Datenstruktur ist höchst einfach. Jedoch ist der Aufwand für das Suchen relativ hoch, nämlich $O(n)$. Genauer gesagt benötigt man für eine erfolglose Suche $n$ Vergleiche (bei $n$ Elementen in der Datenstruktur), denn man muss jedes Element überprüfen, und für eine erfolgreiche Suche durchschnittlich $(n+1)/2$ Vergleiche durchführen, da nach jedem Element mit der gleichen Wahrscheinlichkeit gesucht wird.\\ +Eine Verbesserung dieses Verfahrens wäre, die Daten sortiert abzulegen, was zu einer binären Suche führt. Die Suche hat jetzt nur noch Komplexität $O(\log_2{n})$, da bei jedem Suchschritt das Feld halbiert wird. Der Nachteil ist, dass durch die Sortierung das Einfügen erschwert wird, da unter Umständen viele Datensätze bewegt werden müssen. Das Verfahren sollte also nur angewandt werden, wenn sehr wenige oder gar keine Einfügeoperationen ausgeführt werden müssen. Dann können die Daten anfangs mit einem schnellen Verfahren sortiert werden und müssen danach nicht mehr verändert werden.\\ +Eine weitere Datenstruktur, die der Suchbäume, wollen wir hier vorstellen. + +\chapter{\label{appendix_avl_B}Suchbäume} +Suchbäume sind binäre Bäume (jeder Knoten hat höchstens 2 Kinder) mit der Eigenschaft:\\ +Für jeden Knoten gilt: alle Schlüssel im rechten Teilbaum sind größer als der eigene Schlüssel und alle Schlüssel im linken Teilbaum sind kleiner. Diese Eigenschaft wird hier immer Suchbaumeigenschaft genannt. + +\centerpic{avl/bsp_suchbaum}{4.5}{Ein Beispiel für einen Suchbaum} + +An dieser Stelle noch eine Bemerkung zu den Schlüsseln: Die Schlüssel können Elemente einer beliebigen Menge sein, unter der Bedingung, dass auf dieser Menge eine Ordnungsrelation definiert ist. Die Ordnungsrelation wird offensichtlich für die Suchbaumeigenschaft benötigt, da dort die Begriffe "`kleiner"' und "`größer"' vorkommen. Eine häufig verwendete Menge sind die natürlichen Zahlen mit ihrer normalen Ordnungsrelation $\leq$. Alle Operationen auf Suchbäumen kann man sich also anhand der natürlichen Zahlen vorstellen.\\ +Aus der Suchbaumeigenschaft kann man sich leicht rekursive Algorithmen für das Einfügen und Suchen in einem Suchbaum herleiten: + +\begin{alg} \label{search} + (Suchen eines Schlüssels $s$ in einem Suchbaum) + \begin{enumerate} + \item Falls Teilbaum leer, dann Schlüssel nicht im Baum vorhanden + \item Falls $s$ gleich dem Schlüssel des aktuellen Knoten, dann Suche erfolgreich. + \item Falls $s$ größer als Schlüssel des aktuellen Knotens, dann suche (rekursiv) $s$ im rechten Teilbaum. + \item Falls $s$ kleiner als Schlüssel des aktuellen Knotens, dann suche (rekursiv) $s$ im linken Teilbaum. + \end {enumerate} +\end{alg} + +\newpage +\begin{alg} \label{insert} + (Einfügen eines Schlüssels $s$ in einen Suchbaum) + \begin {enumerate} + \item Falls Teilbaum leer, dann neuen Schlüssel hier einfügen. + \item Falls $s$ gleich dem Schlüssel des aktuellen Knotens, dann Schlüssel bereits vorhanden, Einfügen nicht nötig. + \item Falls $s$ größer als Schlüssel des aktuellen Knotens, dann füge (rekursiv) $s$ in den rechten Teilbaum ein. + \item Falls $s$ kleiner als Schlüssel des aktuellen Knotens, dann füge (rekursiv) $s$ in den linken Teilbaum ein. + \end {enumerate} +\end{alg} + +Mit Algorithmus \ref{insert} ergibt sich folgende Eigenschaft der Struktur von Suchbäumen: im Gegensatz zur sortierten Liste hängt die Struktur eines Baumes davon ab, in welcher Reihenfolge die Elemente eingefügt werden. So erhält man verschiedene Bäume, wenn man $1, 2, 3, 4$ in dieser Reihenfolge und in der Reihenfolge $3, 2, 4, 1$ einfügt. + +\centerpic{avl/12345}{4}{Unterschiedliche Suchbäume bei unterschiedlicher Einfügereihenfolge} + +Im ersten Fall erhält man einen Suchbaum, der zur linearen Liste entartet ist. Das ist nicht nur in dieser speziellen Reihenfolge so, es gibt viele Möglichkeiten einen entarteten Baum zu erzeugen. Der Algorithmus hat also zwei Nachteile: zum einen kann der Suchaufwand linear zur Anzahl der Knoten im Baum sein, was keine Verbesserung zur linearen Liste darstellt; zum anderen hängt die Güte des Verfahrens von der Eingabefolge ab. Der Vorteil von Suchbäumen wird klar, wenn man einen "`vollen"' Baum betrachtet, d.h. alle Pfade zu Blättern haben dieselbe Länge. Dann hat sowohl das Suchen (unabhängig davon, ob der Schlüssel im Baum vorhanden ist) als auch das Einfügen eine Komplexität von $O(\log{n})$. + +\centerpic{avl/vollerbaum}{5}{Ein Beispiel für einen vollen Baum} +\medskip +Es gibt einige Algorithmen, bei denen der Einfügealgorithmus so modifiziert ist, dass die entarteten Fälle vermieden werden und immer nahezu volle Bäume entstehen. Einen davon, den Algorithmus nach Adelson-Velskij und Landis (AVL), werden wir später betrachten. + +Doch zunächst wollen wir noch eine weitere wichtige Operation auf Suchbäumen untersuchen: das Löschen. Leider ist es nicht ganz so einfach wie Suche und Einfügen.\\ +Zuerst muss der zu löschende Schlüssel gesucht werden. Ist der betreffende Knoten ein Blatt, kann er einfach entfernt werden. Hat der zu löschende Knoten nur ein Kind, kann er durch dieses ersetzt werden. Der schwierige Fall ist, wenn er zwei Kinder hat. Damit die Suchbaum\-eigenschaft erhalten bleibt, muss man ihn durch den nächst größeren Schlüssel ersetzen. Der nächst größere Schlüssel befindet sich offensichtlich im rechten Teilbaum. + +\centerpic{avl/remove}{5}{Löschen eines Knoten im Suchbaum} +\medskip +Nach dem Ersetzen bleibt die Suchbaumeigenschaft erhalten, weil alle Schlüssel aus dem linken Teilbaum ohnehin kleiner sind als die aus dem rechten. Außerdem sind auch alle Schlüssel aus dem rechten Teilbaum größer, sonst wäre es nicht der nächst größere Schlüssel gewesen. Aus diesen Überlegungen erhält man folgende verbale Beschreibung des Löschen-Algorithmus: + +\newpage +\begin{alg} \label{delete} + (Löschen eines Schlüssels $s$ aus einem Suchbaum) + \begin{enumerate} + \item Suche s nach Algorithmus \ref{search}. Falls s nicht im Baum enthalten, terminiert der Algorithmus. + \item \begin{enumerate} + \item Ist der zu löschende Knoten ein Blatt, dann entferne ihn einfach aus dem Baum. + \item Hat der zu löschende Knoten nur ein Kind, dann ersetze ihn durch dieses. + \item Sonst suche den kleinsten Schlüssel im rechten Teilbaum: Gehe zum rechten Kind und dann immer zum linken Teilbaum, solange dieser nicht leer ist. Ersetze den zu löschenden Schlüssel durch den des so gefundenen Knotens. Ersetze den gefundenen Knoten durch sein rechtes Kind. + \end{enumerate} + \end{enumerate} +\end{alg} + +Man kann anstelle des nächst größeren Schlüssels genausogut den nächstkleineren nehmen, der Algorithmus funktioniert trotzdem. Zur Komplexität ist zu sagen, dass der Algorithmus maximal $h$ Vergleiche macht, wobei $h$ die Höhe des Baumes ist. Auch hier ist also die Komplexität abhängig von der Struktur des Baumes. + +\chapter{\label{appendix_avl_C}AVL-Bäume} +AVL-Bäume (benannt nach Adelson-Velskij und Landis) sind spezielle Suchbäume: In jedem Knoten unterscheiden sich die Höhen des linken Teilbaums und des rechten Teilbaums um höchstens 1. Um diese Eigenschaft (AVL-Eigenschaft) abzusichern, wird für jeden Knoten ein Balancefaktor eingeführt. Der Balancefaktor ist die Differenz der Höhen des rechten Teilbaums und des linken Teilbaums. Also gilt für jeden AVL-Baum, dass alle Balancefaktoren aus $\{-1,0,1\}$ sind. Bäume mit AVL-Eigenschaft sind niemals als lineare Liste entartet (sofern sie denn mehr als 2 Knoten haben), sondern sind immer fast vollständig. Zwischen der Höhe $h$ eines Baumes und der Anzahl $n$ seiner Knoten besteht folgender Zusammenhang: $h\leq 2 \cdot \log_2{n}$. Das bedeutet, dass für das Suchen logarithmische Komplexität garantiert werden kann (das Suchen erfolgt gemäß Algorithmus \ref{search}). + +\centerpic{avl/avlbsp}{5}{Ein Beispiel für einen AVL-Baum mit Balancen} +\medskip +Jetzt muss noch untersucht werden, wie groß der zusätzliche Aufwand beim Einfügen ist, um die AVL-Eigenschaft zu wahren. In jedem Fall wird der neue Knoten als Blatt eingefügt (nach demselben Algorithmus wie bei Suchbäumen). Dabei kann sich der Balancefaktor ändern. Allerdings kann man sich leicht klarmachen, dass das nur entlang des Suchpfades passieren kann. Die Aktualisierung von Balancefaktoren erfolgt von der Einfügestelle zur Wurzel. Hier der Algorithmus: + +\newpage +\begin{alg} \label{avlinsert} + (Algorithmus zum Einfügen eines Elements x in einen AVL-Baum) + \begin{enumerate} + \item Füge das neue Element x als direkten Nachfolger des Knotens n als Blatt ein, sodass die Suchbaumeigenschaft erfüllt bleibt. Aktualisiere n.balance. + \item Setze n auf den Vorgängerknoten von n. + \begin{enumerate} + \item Falls x im linken Unterbaum von n eingefügt wurde + \begin{enumerate} + \item wenn n.balance==1 dann n.balance=0 und gehe nach 3. + \item wenn n.balance==0, dann n.balance=-1 und gehe nach 2. + \item wenn n.balance==-1 und + \begin{itemize} + \item wenn n.left.balance==-1, dann Rechts(n)-Rotation. + \item wenn n.left.balance==1 dann Links(n.left)-Rechts(n)-Rotation. + \end{itemize} + Gehe zu 3. + \end{enumerate} + \item Falls x im rechten Unterbaum von n eingefügt wurde + \begin{enumerate} + \item wenn n.balance==-1 dann n.balance=0 und gehe nach 3. + \item wenn n.balance==0, dann n.balance=1 und gehe nach 2. + \item wenn n.balance==1 und + \begin{itemize} + \item wenn n.left.balance==1, dann Links(n)-Rotation. + \item wenn n.left.balance==-1 dann Rechts(n.left)-Links(n)-Rotation. + \end{itemize} + Gehe zu 3. + \end{enumerate} + \end{enumerate} + \item Gehe zurück zur Wurzel. + \end{enumerate} +\end{alg} + +Zur Analyse dieses Algorithmus: Das reine Einfügen erfolgt gemäß Einfügen im Suchbaum (Algorithmus \ref{insert}), allerdings ist hier sichergestellt, dass sich die Höhe logarithmisch zur Anzahl der Knoten verhält, d.h. auch der Aufwand für das Einfügen ist garantiert logarithmisch. Wie gesagt können sich jedoch Balancefaktoren geändert haben, sodass die AVL-Eigenschaft nicht mehr erfüllt ist. Das wird durch sogenannte Rotationen behoben. Es gibt zwei Typen von Rotationen -- Linksrotation und Rechtsrotation, jeweils um einen Knoten n. + +\centerpic{avl/rotateleft}{5}{Linksrotation um den Knoten 65} \medskip +\centerpic{avl/rotateright}{5}{Rechtsrotation um den Knoten 58} \medskip + +Falls durch das Einfügen irgendwo ein Balancefaktor $2$($-2$) entsteht (größere Änderungen können beim Einfügen eines Knotens offensichtlich nicht auftreten), heißt das, dass sich im rechten (linken) Teilbaum die Höhe um 1 erhöht hat. Durch Rotation(en) wie im Algorithmus angegeben, wird aber genau diese Höhe wieder reduziert. Somit ist klar, dass man maximal zweimal rotieren muss, der Aufwand ist also noch erträglich, im Gegensatz zum Löschen, wie man gleich sehen wird. + +Genauso wie Einfügen verändert auch Löschen eines Knotens aus einem AVL-Baum die Balancefaktoren, also müssen auch hier Rotationen ausgeführt werden. Hier der Algorithmus: + +\begin{alg} \label{avldelete} + Löschen eines Knotens aus einem AVL-Baum) + \begin{enumerate} + \item Lösche den Knoten analog zum Löschen im Suchbaum (Algorithmus \ref{delete}). Falls der Knoten ein Blatt war oder nur einen linken Nachbarn hatte, setze aktuellen Knoten auf den Vater. Sonst setze aktuellen Knoten auf den Vater des Knotens mit dem nächst größeren Schlüssel. + \item Berechne den Balancefaktor des aktuellen Knotens neu. Falls + \begin{enumerate} + \item Balance 2 und rechte Balance -1, dann Rechts(n.right)-Links(n)-Rotation. + \item Balance 2 und rechte Balance nicht -1, dann Links(n)-Rotation. + \item Balance -2 und linke Balance 1, dann Links(n.left)-Rechts(n)-Rotation. + \item Balance -2 und linke Balance nicht 1, dann Rechts(n)-Rotation. + \item sonst keine Rotation. + \end{enumerate} + Wiederhole diesen Schritt solange, bis die Wurzel erreicht ist. + \end{enumerate} +\end{alg} + +Auch hier wollen wir den Aufwand des Algorithmus etwas genauer untersuchen. Schritt 1 entspricht dem Löschen aus dem Suchbaum, nur garantiert mit logarithmischen Aufwand. Die Frage ist nun, ob, wie beim Einfügen, der Algorithmus mit maximal zwei Rotationen auskommt. Leider ist das nicht der Fall. Das liegt an der erwähnten Eigenschaft der Rotationen, sie verringern die Höhe eines Teilbaums. Beim Einfügen war das gut, da durch das Anhängen eines Knotens gerade die Höhe vergrößert wurde. Hier jedoch ist das unvorteilhaft, es kann passieren, dass man mehrere Rotationen auf dem Weg zur Wurzel durchführen muss. Die Anzahl der Rotationen ist nur durch die Höhe des Baums beschränkt. Das ist in Anwendungsfällen nicht wünschenswert. + +Bei zeitkritischen Anwendungen muss man also entweder auf einen anderen Algorithmus ausweichen, oder Varianten wie etwa Lazy-Delete implementieren, d.h. der Knoten wird nur als gelöscht markiert und wird später (wenn Zeit ist) aus dem Baum entfernt. + +\begin{thebibliography}{99} + \bibitem {sedgewick} R. Sedgewick, "`Algorithmen in C++"', Addison-Wesley, 5. Auflage, 1999 + \bibitem {vogler} Prof. Vogler, "`Vorlesungsskript Algorithmen, Datenstrukturen und Programmierung"', TU Dresden, 2003 + \bibitem {wiki} http://de.wikipedia.org/wiki/AVL-Baum + \bibitem {uni-leipzig} http://dbs.uni-leipzig.de/de/skripte/ADS1/HTML/kap6-11.html +\end{thebibliography} \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/contents.tex b/doc/users_manual_german/modules/avl/contents.tex new file mode 100644 index 0000000..b19a1d5 --- /dev/null +++ b/doc/users_manual_german/modules/avl/contents.tex @@ -0,0 +1,10 @@ +\newcommand{\avl}{\mbox{\bfseries AVL-Bäume} } + +\input{modules/avl/overview} +\input{modules/avl/start} +\input{modules/avl/screen} +\input{modules/avl/functions} +\input{modules/avl/flowcontrol} +\input{modules/avl/documentation} +\input{modules/avl/additionals} +\input{modules/avl/imprint} \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/documentation.tex b/doc/users_manual_german/modules/avl/documentation.tex new file mode 100644 index 0000000..90f9e52 --- /dev/null +++ b/doc/users_manual_german/modules/avl/documentation.tex @@ -0,0 +1,24 @@ +\section{Dokumentation} +Da das Modul \avl vor allem zu Lehr- und Lernzwecken eingesetzt werden soll, ist eine detaillierte Dokumentation der Algorithmen unumgänglich. Für die Einzelheiten des Algorithmustextes steht ein Auszug aus dem Vorlesungsskript von Prof. Vogler zur Verfügung. Ein Logbuch in der rechten unteren Ecke des Bildschirmes führt Protokoll über den Stand und die Beschaffenheit des einzelnen Algorithmusteilschrittes.\\ +Zu guter Letzt wird ein Infobereich angeboten, in dem wichtige Baumdaten zusammengefasst sind. + +\subsection{Skript} +Der Dokumentationsbereich, der das Skript enthält, befindet sich am unteren Bildschirmrand. Es handelt sich hierbei um einen Auszug des Skripts zur Vorlesung "`Algorithmen und Datenstrukturen"' von Prof. Vogler (TU Dresden), Version vom 2. Oktober 2003. Im Rahmen dieser Vorlesung soll das Modul vorwiegend eingesetzt werden.\\ +Bei dem jeweils aktuellen Algorithmustext handelt es sich um die Aktion, die als nächstes im Ablauf des Algorithmus erfolgen wird. Sie wird rot markiert angezeigt. + +\subsection{Logbuch} +Das Logbuch ist eine weitere Möglichkeit, den Ablauf des Algorithmus zu verfolgen. Es bezieht sich in erster Linie auf baumspezifische Daten und verwendet zum Beispiel konkrete Schlüsselwerte, anhand deren die Aktionen des Algorithmus besser verstanden werden sollen.\\ +Auch hier wird der aktuelle Eintrag rot markiert dargestellt. Dieser bezieht sich aber auf die zuletzt ausgeführte Aktion. + +\subsection{Infobereich} +Der Infobereich ist hauptsächlich dafür gedacht, Ihnen schnell wichtige Daten des Baumes bereit zu stellen. Hier finden Sie folgende Punkte: +\begin{itemize} + \item \textsc{Anzahl der Knoten}\\ + Dieser Punkt fasst für Sie die Anzahl der Knoten im Baum zusammen. + \item \textsc{Baumhöhe}\\ + Hier finden Sie die Anzahl der Level des Baumes. + \item \textsc{Durchschnittliche Suchtiefe}\\ + Dieser Wert berechnet sich durch die Summe der Level aller Knoten geteilt durch die Anzahl dieser. Der Wert ist ein Indiz dafür, wie gut der Baum ausbalanciert ist bzw. wie groß der Suchaufwand im Durchschnitt ist. +\end{itemize} + +\bigskip \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/flowcontrol.tex b/doc/users_manual_german/modules/avl/flowcontrol.tex new file mode 100644 index 0000000..31257d8 --- /dev/null +++ b/doc/users_manual_german/modules/avl/flowcontrol.tex @@ -0,0 +1,29 @@ +\section{Algorithmussteuerung} +Aufgabe des Moduls \avl ist es, Baumalgorithmen, wie das Einfügen und Löschen von Knoten, zu visualisieren. Jeder Algorithmus ist in verschiedene Teilschritte unterteilt, die nacheinander angezeigt werden. Das Visualisieren erfolgt dabei durch das Zeichnen des Baumes, durch die Erklärung der Schritte im Dokumentationsbereich und im Logbuch und durch die Neuberechnung der baumspezifischen Daten, die im Infobereich präsentiert werden.\\ +Nachdem Sie einen Algorithmus gestartet haben, verweilt er in einem Initialzustand und wartet auf Ihre Eingabe. Nun haben Sie die Möglichkeit, den Algorithmus in kleinen oder großen Schritten zu durchlaufen; Sie können ihn sofort beenden oder direkt abbrechen. Dafür bietet die Algorithmussteuerung die entsprechenden Werkzeuge. + +\subsection{Schritt-Pfeile} +Mittels der Schritt-Pfeile steuern Sie die Abfolge der Einzelschritte und bekommen so eine detaillierte Sicht auf die Arbeitsweise des Algorithmus. Das Programm bietet Ihnen die Möglichkeit, einen Teilschritt rückgängig zu machen und damit gewisse Abläufe zu wiederholen. Die Schritt-Pfeile, welche die Rückgängigfunktion anbieten, weisen in ihrer Richtung nach links und sind dadurch intuitiv von den Vorwärts-Pfeilen zu unterscheiden.\\ +Zusätzlich gibt es für jede Richtung einen großen und einen kleinen Schritt, der per Knopfdruck ausgeführt wird. + +Kleine Schritte beim Einfügen eines Knotens stellen Schlüsselvergleiche, Balancenberechnungen und Rotationen dar. Große Schritte hingegen sind zum Beispiel das Suchen der Einfügestelle, das Einfügen an dieser und die gesamte Balancenaktualisierung. + +\subsubsectiondoubleicon{Einzel-Schritt-Pfeile}{avl/icon_undo}{avl/icon_perform} +Ein Klick auf diese Buttons realisiert einen kleinen Algorithmusschritt zurück bzw. nach vorn. +\subsubsectiondoubleicon{Block-Schritt-Pfeile}{avl/icon_undo_blockstep}{avl/icon_perform_blockstep} +Ein Klick auf diese Buttons realisiert einen großen Schritt zurück bzw. nach vorn. Sollte der Algorithmusablauf an eine Stelle geraten, an der es nur noch einen kleinen Schritt nach vorn bzw. zurück gibt, so hat der Block-Schritt die selbe Funktionalität wie ein Einzel-Schritt. + +\subsectiondoubleicon{Abbruch und Beenden-Buttons}{avl/icon_abort}{avl/icon_finish} +Klicken Sie auf den Beenden-Button \raisebox{-1ex}{\includegraphics[scale=0.8]{\pfad avl/icon_finish}} um den laufenden Algorithmus bis zum Ende auszuführen.\\ +Klicken Sie auf den Abbruch-Button \raisebox{-1ex}{\includegraphics[scale=0.8]{\pfad avl/icon_abort}} um den laufenden Algorithmus abzubrechen. Der Baum hat danach den gleichen Status wie vor Beginn des Algorithmus.\\ +Ist ein Algorithmus beendet, so steht Ihnen diese Option nicht mehr zur Verfügung, weil nur der +\textit{laufende} Algorithmus abgebrochen werden kann. + +\subsection{Animationsgeschwindigkeit} +Beim Generieren eines Zufallsbaumes haben Sie die Option, den Ablauf der Baumerzeugung als Animation ablaufen zu lassen. Starten Sie in diesem Modus, so beginnt die Animation sofort und kann mit dem Geschwindigkeitsregler schneller oder langsamer abgespielt werden. Zu Beginn steht dieser auf der mittleren Position. Verschieben Sie den Regler nach links, um die Animation zu verlangsamen bzw. nach rechts, um sie zu beschleunigen.\\ +Eine Animation der anderen Algorithmenabläufe ist in dieser Version von \avl nicht integriert. + +\bigskip +\centerpic{avl/animregler}{1}{Der Regler für die Animationsgeschwindigkeit} + +\bigskip \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/functions.tex b/doc/users_manual_german/modules/avl/functions.tex new file mode 100644 index 0000000..9043822 --- /dev/null +++ b/doc/users_manual_german/modules/avl/functions.tex @@ -0,0 +1,39 @@ +\section{Modulfunktionen} +Alle Funktionen des Moduls \avl lassen sich über den Kontroll-Bereich der Arbeitsfläche bedienen. Sie stellen die verschiedenen Baumalgorithmen dar, deren Visualisierung Aufgabe dieses Moduls ist. Grundlegend läuft die Arbeit mit den Algorithmen immer nach dem gleichen Schema ab: +\begin{enumerate} + \item Schlüsseleingabe + \item Starten des Algorithmus per Klick auf den entsprechenden Button +\end{enumerate} +Es gibt natürlich auch Algorithmen, wie der AVL-Test, die keinen Schlüssel benötigen und ohne Schritt 1 auskommen.\\ +Es folgen nun die einzelnen Funktionen im Detail. + +\subsection{Schlüsseleingabe} +Für die Eingabe der Schlüsselwerte steht ein Textfeld und ein Button für zufällige Werte zur Verfügung. Es sind nur ganzzahlige Schlüsselwerte von 1 bis 99 erlaubt.\\ +Über dem Textfeld befindet sich eine Nachrichtenzeile, in welcher Sie auf eventuelle Fehleingaben aufmerksam gemacht werden. Hier werden später ebenfalls kurze Ergebnismeldungen zu den Algorithmen eingeblendet. + +\subsection{Algorithmusfunktionen} +\subsubsection*{Knoten einfügen} +Der eingegebene Wert wird als Schlüssel für einen neuen Knoten verwendet, der in den Baum eingefügt werden soll. Ist bereits ein Knoten mit dem gleichen Schlüssel im Baum enthalten, so bricht der Algorithmus erfolglos ab. +\subsubsection*{Knoten suchen} +Nach dem Starten dieses Algorithmus beginnt die Suche nach dem eingegebenen Schlüssel im Baum. +\subsubsection*{Knoten löschen} +Nach dem eingegebenen Schlüssel wird gesucht, und wenn ein entsprechender Knoten gefunden wurde, wird dieser aus der Baumstruktur entfernt. + +\subsection{AVL-Modus} +Ist dieses Kästchen aktiviert, werden die entsprechenden Algorithmen so ausgeführt, dass die AVL-Eigenschaft gewahrt bleibt.\\ +Achtung: Es ist keine Funktion implementiert, die an einem beliebigen Suchbaum die AVL-Eigenschaft herstellt!\\ +Ist das Kästchen deaktiviert, ist es daher nicht immer ohne weiteres wieder zu aktivieren. Dazu muss zuerst getestet werden, ob der Baum die AVL-Eigenschaft hat. Es ist jedoch jederzeit möglich, das Kästchen zu deaktivieren und einen unbalancierten Baum zu erzeugen. + +\subsection{Baum auf AVL-Eigenschaft testen} +\medskip +\centerpic{avl/avltest}{1}{Hinweisfenster des AVL-Tests} +Wenn der AVL-Modus einmal deaktiviert sein sollte, so ermöglicht das Programm einen Test des Baumes auf die AVL-Eigenschaft. Dabei erfolgt eine Berechnung und Anzeige der Balancen aller Knoten und das eventuelle Markieren von Knoten, deren Balance sich nicht mehr im Rahmen der AVL-Eigenschaft bewegt.\\ +Es wird ein Hinweis-Dialog geöffnet, der Ihnen das Ergebnis des Tests präsentiert. Sollte der Baum tatsächlich die AVL-Eigenschaft besitzen, so wird Ihnen angeboten, direkt in den AVL-Modus zu wechseln. + +\newpage +\subsection{Baum löschen} +Mit einem Klick auf den Button \raisebox{-1.5ex}{\includegraphics[scale=1]{\pfad avl/icon_clear}} in der Werkzeugleiste können Sie nach einer Sicherheitsabfrage die gesamte Baumstruktur löschen und mit einer leeren Arbeitsfläche neu beginnen. +\medskip +\centerpic{avl/cleartreemessage}{1}{Sicherheitsabfrage beim Löschen des Baumes} + +\vfill \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/imprint.tex b/doc/users_manual_german/modules/avl/imprint.tex new file mode 100644 index 0000000..538434c --- /dev/null +++ b/doc/users_manual_german/modules/avl/imprint.tex @@ -0,0 +1,14 @@ +\section{Impressum} +Das Modul \avl wurde im Sommersemester 2005 von der Praktikumsgruppe SWT05-PROG1 im Rahmen des externen Softwarepraktikums entwickelt. Mitwirkende waren die +\paragraph{Teammitglieder} +\begin{itemize} + \item Alexander Claus --- Chefprogrammierer + \item Ulrike Fischer --- Assistent + \item Sebastian Pape --- Administrator + \item Jean Christoph Jung --- Testverantwortlicher + \item Matthias Schmidt --- Sekretär +\end{itemize} +sowie der betreuende Tutor Marco Zimmerling.\\ +Die Webseite des Projektes finden Sie unter \href{http://web.inf.tu-dresden.de/~swt05-p1/}{http://web.inf.tu-dresden.de/\~{}swt05-p1/}. + +Das Handbuch zu diesem Modul wurde erstellt von Matthias Schmidt und Jean Christoph Jung. \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/overview.tex b/doc/users_manual_german/modules/avl/overview.tex new file mode 100644 index 0000000..a2bca7e --- /dev/null +++ b/doc/users_manual_german/modules/avl/overview.tex @@ -0,0 +1,19 @@ +\chapter{Das Modul AVL-Bäume} +\section{Einleitung} +Das Modul \avl realisiert die Darstellung von binären Such- und AVL-Bäumen. Für eine detaillierte Beschreibung dieser Baumtypen lesen Sie bitte nach im Vorlesungsskript von Prof. Vogler "`Algorithmen, Datenstrukturen und Programmierung"'. Eine mehr oder weniger kurze Einführung in diese Thematik ist auch zu finden im Anhang \ref{appendix_avl_A}. +\medskip\\ +\textbf{Anmerkung:} In dieser Version von \jalgo ist das Modul \avl unter Linux aus +Kompatibilitätsgründen nicht installiert. + +\section{Funktionsübersicht} +Das Modul \avl realisiert folgende Funktionen: +\begin{itemize} + \item Visualisieren von binären Suchbäumen mit und ohne AVL-Eigenschaft + \item Einfügen, Suchen und Löschen von Baumknoten + \item Testen eines Baumes auf die AVL-Eigenschaft + \item Generieren von zufälligen Suchbäumen + \item Speichern und Laden von Bäumen + \item Informationen zum Baum und zu den laufenden Algorithmen +\end{itemize} + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/screen.tex b/doc/users_manual_german/modules/avl/screen.tex new file mode 100644 index 0000000..d32e62d --- /dev/null +++ b/doc/users_manual_german/modules/avl/screen.tex @@ -0,0 +1,19 @@ +\section{Die Arbeitsfläche} +Die Arbeit mit \avl spielt sich auf der Arbeitsfläche ab. Sie bietet alle Funktionalitäten +des Moduls und ist in fünf wichtige Bereiche unterteilt: +\begin{itemize} + \item \textsc{Zeichenfläche}\\ + Der Baum und alle Algorithmen werden hier visualisiert. + \item \textsc{Infobereich}\\ + Wichtige Baumdaten wie Anzahl der Knoten, Baumhöhe und Suchtiefe sind hier zu finden. + \item \textsc{Kontroll-Bereich}\\ + In diesem Bereich erfolgt der Start und die Steuerung der Algorithmen. + \item \textsc{Dokumentationsbereich}\\ + Hier läuft der Text zum jeweiligen Algorithmus mit. Der aktuelle Schritt wird dabei farbig hervorgehoben. Der Text ist dem Skript "`Algorithmen, Datenstrukturen und Programmierung"' von Prof. Vogler, Version vom 2. Oktober 2003, entnommen. + \item \textsc{Logbuch}\\ + Hier werden erfolgte Einzelaktionen protokolliert und dabei der jeweils aktuelle Schritt farbig hervorgehoben. +\end{itemize} + +Die Aufteilung zwischen dem unteren und dem oberen Bereich kann mit dem Schiebebalken verändert werden. Per Klick auf die schwarzen Pfeile können Sie den Textbereich wahlweise maximieren, um einen Überblick über den Algorithmustext zu gewinnen, oder minimieren, um die Zeichenfläche zu vergrößern. +\newpage +\centerpic{avl/prgmscreen}{1}{Die Arbeitsfläche des Moduls \avl} \ No newline at end of file diff --git a/doc/users_manual_german/modules/avl/start.tex b/doc/users_manual_german/modules/avl/start.tex new file mode 100644 index 0000000..66766ec --- /dev/null +++ b/doc/users_manual_german/modules/avl/start.tex @@ -0,0 +1,39 @@ +\section{Programmstart - Der Willkommensbildschirm} +Nach Starten des Hauptprogramms \jalgo können Sie über den Button <\textsc{Neu}> oder mit dem Menüpunkt \textsc{$\rightarrow$$\rightarrow$<\avl>} eine neue Instanz des Moduls \avl öffnen. Anschließend öffnet sich der Willkommensbildschirm des Moduls, der Ihnen verschiedene Möglichkeiten eröffnet.\\ +\bigskip +\centerpic{avl/welcomscreen}{0.5}{Der Willkommensbildschirm des Moduls \avl} +\bigskip + +\subsectionicon{Baum laden}{avl/welcome_load} +Mit Klick auf das Ordner-Symbol öffnet sich ein Dialogfenster, in dem Ihnen die Möglichkeit +gegeben wird, eine \emph{"`*.jalgo"'} - Datei auszuwählen, in welcher ein Baum gespeichert wurde.\\ +Im Prinzip ist die Bedeutung dieses Buttons die gleiche wie des <\textsc{Öffnen}>-Buttons in der Werkzeugleiste. Der Unterschied besteht darin, dass der Button in der Werkzeugleiste eine neue Modulinstanz öffnet, in welcher die Datei geladen wird, der Button im Startbildschirm von \avl jedoch die Datei in die aktuell geöffnete Modulinstanz lädt. + +\subsectionicon{Baum von Hand erstellen}{avl/welcome_manual} +Mit Klick auf das Hand-Symbol gelangen Sie sofort zur leeren Arbeitsfläche des Moduls \avl. +Sie können jetzt mit der knotenweisen Generierung eines neuen Suchbaumes beginnen. + +\subsectionicon{Zufallsbaum erstellen lassen}{avl/welcome_random} +Mit Klick auf das Würfel-Symbol beginnen Sie die Generierung eines zufällig erzeugten Suchbaumes. In dem folgenden Dialogfenster können Sie verschiedene Daten zum Baum und die Art der Visualisierung festlegen. +\centerpic{avl/rgd}{1}{Eingabe der Zufallsbaumdaten} +\begin{itemize} + \item {\bf Anzahl der Knoten}\\ + Geben Sie hier die Anzahl der Knoten ein. Der entstehende Baum muss mindestens einen Knoten enthalten, höchstens aber 99. + \item {\bf AVL-Eigenschaft}\\ + Aktivieren Sie dieses Kästchen, wenn der zu erstellende Baum die AVL-Eigenschaft besitzen soll. + \item {\bf Visualisierung}\\ + Wählen Sie hier die Art der Visualisierung der Erstellung aus. + \begin{itemize} + \item {\sc keine}\\ Der Baum wird sofort erstellt. + \item {\sc schrittweise}\\ Jeder Algorithmusschritt kann von Ihnen per Hand bestätigt werden. + \item {\sc automatisch}\\ Lassen Sie die Erstellung des Baumes als Animation ablaufen, die Geschwindigkeit ist dabei einstellbar. + \end{itemize} + Haben Sie schrittweise oder automatische Visualisierung gewählt, können Sie den Ablauf jederzeit abbrechen. + Dabei wird das gerade aktive Knoteneinfügen abgebrochen, und der Baum steht mit entsprechend weniger Knoten zur Verfügung. +\end{itemize} + +\subsectionicon{Willkommensbildschirm anzeigen}{avl/logo} +Mit Klick auf diesen Button in der Werkzeugleiste des Modulbildschirms kann der Willkommensbildschirm später jederzeit wieder angezeigt werden. Dabei werden Sie eventuell gefragt, wie Sie mit Ihren Änderungen verfahren wollen. Sollten Sie Ihre Änderungen nicht verwerfen wollen, so wird eine neue Instanz des Moduls geöffnet. +\centerpic{avl/clearmessage}{1}{Dialog mit der Frage, ob der ganze Baum gelöscht werden soll.} + +\bigskip \ No newline at end of file diff --git a/doc/users_manual_german/modules/dijkstra/CVS/Entries b/doc/users_manual_german/modules/dijkstra/CVS/Entries new file mode 100644 index 0000000..655c9fa --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/CVS/Entries @@ -0,0 +1,5 @@ +/contents.tex/1.1/Tue Oct 11 09:08:15 2005// +/edit.tex/1.1/Tue Oct 11 09:08:15 2005// +/imprint.tex/1.2/Tue Mar 28 14:21:12 2006// +/overview.tex/1.1/Tue Oct 11 09:08:15 2005// +/run.tex/1.2/Fri Oct 14 09:49:19 2005// diff --git a/doc/users_manual_german/modules/dijkstra/CVS/Repository b/doc/users_manual_german/modules/dijkstra/CVS/Repository new file mode 100644 index 0000000..f585f7b --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/modules/dijkstra diff --git a/doc/users_manual_german/modules/dijkstra/CVS/Root b/doc/users_manual_german/modules/dijkstra/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/modules/dijkstra/contents.tex b/doc/users_manual_german/modules/dijkstra/contents.tex new file mode 100644 index 0000000..4821db2 --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/contents.tex @@ -0,0 +1,6 @@ +\newcommand{\dijkstra}{\mbox{\bfseries Dijkstra} } + +\input{modules/dijkstra/overview} +\input{modules/dijkstra/edit} +\input{modules/dijkstra/run} +\input{modules/dijkstra/imprint} \ No newline at end of file diff --git a/doc/users_manual_german/modules/dijkstra/edit.tex b/doc/users_manual_german/modules/dijkstra/edit.tex new file mode 100644 index 0000000..0727a8d --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/edit.tex @@ -0,0 +1,40 @@ +\section{Graph erstellen} +Nach dem Start des Moduls wird die Oberfläche für das Erstellen eines Graphen angezeigt. Sie ist +in die Bereiche +\begin{enumerate} + \item "`Werkzeuge"' + \item "`Graph"' + \item "`Knotenliste"' + \item "`Kantenliste"' + \item "`Distanzmatrix"' +\end{enumerate} +aufgeteilt. + +\subsection{Graphische Eingabe/Erstellen eines Graphen per Maus} +Das Erstellen eines Graphen per Maus wird durch die Werkzeuge +\begin{enumerate} + \item "`Knoten hinzufügen/verschieben"' --- Durch Klicken auf die Zeichenfläche wird ein neuer Knoten erzeugt. Ein bestehender Knoten kann durch Ziehen mit der Maus bewegt werden. + \item "`Kante hinzufügen/bewerten"' --- Indem man die Maus von einem Knoten zu einem anderen zieht, entsteht zwischen ihnen eine neue Kante. Die Kantenbewertung wird geändert, wenn man sie herauf- bzw. hinunterzieht. + \item "`Knoten löschen"' --- Ein angeklickter Knoten wird gelöscht. + \item "`Kante löschen"' --- Eine angeklickte Kante wird gelöscht. +\end{enumerate} +unterstützt. +Dabei geht man wie folgt vor: Nach der Auswahl des Werkzeugs "`Knoten hinzufügen / verschieben"' kann man durch einfaches Klicken auf die weiße Zeichenfläche Knoten erstellen. Vorhandene Knoten können mit Drag\&Drop verschoben werden.\\ +Nachdem man alle Knoten angelegt hat, kann man nach Auswahl des Werkzeugs "`Kante hinzufügen/bewerten"' den Graphen vervollständigen. Um eine Kante zu erstellen, klickt man erst den "`Startknoten"' und dann den "`Endknoten"' der Kante an. Es erscheint eine Kante zwischen den Knoten mit der Bewertung fünf. Diese Bewertung (auch Kantengewicht) kann verändert werden, indem man das Kantengewicht mit der Maus "`festhält"' und nach oben (das Gewicht wird größer) oder unten (das Gewicht wird kleiner) zieht. +\newpage +\centerpic{dijkstra/edit}{0.5}{Graphisches Erstellen eines Graphen} + +\subsection{Die Knotenliste} +Die Knotenliste zeigt die Indizes aller Knoten durch Kommata getrennt. Durch Hinzufügen von +Indizes werden auch neue Knoten erzeugt. Änderungen in der Knotenliste werden nach Betätigen der Schaltfläche "`Anwenden"' übernommen. + +\subsection{Die Kantenliste} +Die Kantenliste zeigt alle Kanten des Graphen im Format ( VON, WEG, ZU ). Durch Editieren +dieser Liste können bestehende Kanten geändert und neue hinzufügt werden. Auch hier ist zu +beachten, dass Änderungen erst durch Klicken von "`Anwenden"' übernommen werden. + +\subsection{Die Adjazenzmatrix} +Die Adjazenzrelation des Graphen ist in dieser Matrix dargestellt. Kanten und Knoten können in jener durch einfaches Eingeben einer Kantenbewertung erzeugt werden. Dabei muss nicht beachtet werden, daß die Matrix symmetrisch bleibt, da dies automatisch gewährleistet wird.\\ +Nach dem Bearbeiten der Matrix darf nicht vergessen werden, den "`Anwenden"' - Button zu betätigen, damit die Änderungen übernommen werden. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/dijkstra/imprint.tex b/doc/users_manual_german/modules/dijkstra/imprint.tex new file mode 100644 index 0000000..fb1bda2 --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/imprint.tex @@ -0,0 +1,14 @@ +\section{Impressum} +Das Modul \dijkstra wurde im Sommersemester 2005 von der Praktikumsgruppe SWT05-PROG2 im Rahmen des externen Softwarepraktikums entwickelt. Mitwirkende waren die +\paragraph{Teammitglieder} +\begin{itemize} + \item Frank Staudinger --- Chefprogrammierer + \item Julian Stecklina --- Assistent + \item Hannes Straß --- Administrator + \item Martin Winter --- Testverantwortlicher + \item Steven Voigt --- Sekretär +\end{itemize} +sowie der betreuende Tutor Marco Zimmerling.\\ +Die Webseite des Projektes finden Sie unter \href{http://web.inf.tu-dresden.de/~swt05-p2/}{http://web.inf.tu-dresden.de/\~{}swt05-p2/}. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/dijkstra/overview.tex b/doc/users_manual_german/modules/dijkstra/overview.tex new file mode 100644 index 0000000..998750a --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/overview.tex @@ -0,0 +1,22 @@ +\chapter{Das Modul Dijkstra} +\section{Einleitung} +Das Modul \dijkstra visualisiert den bekannten Algorithmus von E. W. Dijkstra zum Finden der kürzesten Wege von einem Startknoten in einem Distanzgraphen. Der Algorithmus selbst ist unter anderem im Vorlesungsskript von Prof. Vogler "`Algorithmen, Datenstrukturen und Programmierung"' zu finden. Aber auch im Internet existieren zahlreiche Quellen dazu. + +Soweit es möglich gewesen ist, wurde beim Design des Moduls darauf geachtet, es weitgehend intuitiv und selbst-dokumentierend zu gestalten. Nichtsdestotrotz findet sich hier eine kurze +Einführung in das \dijkstra - Modul. + +\section{Funktionsübersicht} +Das Modul \dijkstra realisiert folgende Funktionen: +\begin{itemize} + \item graphisches Erstellen / Bearbeiten eines Distanzgraphen + \item Erstellen / Bearbeiten eines Graphen mittels Kanten- / Knotenliste oder Adjazenzmatrix + \item Speichern und Laden von Graphen + \item Visualisierung des Dijkstra-Algorithmus +\end{itemize} + +\section{Modul starten} +Um das Modul zu starten, wählt man im Menü \textsc{} das Submenü \textsc{} und dann den Menübefehl \textsc{\dijkstra}. Im Hauptfenster erscheint nun die Oberfläche des \dijkstra - Moduls im Eingabe-Modus. + +\section{Symbolleiste} +Die Symbolleiste stellt die Funktionen \textsc{Speichern, Speichern unter, Rückgängig} und \textsc{Wiederherstellen} bereit. +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/dijkstra/run.tex b/doc/users_manual_german/modules/dijkstra/run.tex new file mode 100644 index 0000000..d529503 --- /dev/null +++ b/doc/users_manual_german/modules/dijkstra/run.tex @@ -0,0 +1,12 @@ +\section{Ablauf des Algorithmus} +\centerpic{dijkstra/run}{0.5}{Der Algorithmus läuft} +\bigskip +Ist man mit dem Aussehen seines Graphen zufrieden, wird durch Auswählen des "`Algorithmus starten"'-Buttons in den Algorithmus-Modus des Moduls gewechselt. Der Graph erscheint nun zuerst grau und ändert sich farblich im weiteren Verlauf, um die verschiedenen Zustände des \dijkstra-Algorithmus darzustellen. + +Um die einzelnen Schritte des Algorithmus abzuarbeiten, kann man man mit den "`<"'- und "`>"'-Buttons zum vorherigen bzw. nächsten Schritt springen. "`<<"' und "`>>"' überspringen +gleich mehrere Schritte. + +Falls man sich entschließt, einen anderen Graphen untersuchen zu wollen, kann mit "`Graph +bearbeiten"' in den Editiermodus zurückgekehrt werden. "`Algorithmus neu starten"' springt zurück an den Anfang des Algorithmus. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/CVS/Entries b/doc/users_manual_german/modules/ebnf/CVS/Entries new file mode 100644 index 0000000..c23aad5 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/CVS/Entries @@ -0,0 +1,12 @@ +/contents.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/defeditor.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/defsave.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/defview.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ +/diaeditor.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ +/diasave.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ +/diaview.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/imprint.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ +/overview.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/start.tex/1.1/Sat Aug 12 20:12:32 2006/-kb/ +/trans.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ +/word.tex/1.2/Wed Oct 18 11:57:20 2006/-kb/ diff --git a/doc/users_manual_german/modules/ebnf/CVS/Repository b/doc/users_manual_german/modules/ebnf/CVS/Repository new file mode 100644 index 0000000..2c3019e --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/modules/ebnf diff --git a/doc/users_manual_german/modules/ebnf/CVS/Root b/doc/users_manual_german/modules/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/modules/ebnf/contents.tex b/doc/users_manual_german/modules/ebnf/contents.tex new file mode 100644 index 0000000..59369b2 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/contents.tex @@ -0,0 +1,13 @@ +\newcommand{\ebnf}{\mbox{\bfseries EBNF und Syntaxdiagramme} } + +\input{modules/ebnf/overview} +\input{modules/ebnf/start} +\input{modules/ebnf/defeditor} +\input{modules/ebnf/defview} +\input{modules/ebnf/defsave} +\input{modules/ebnf/trans} +\input{modules/ebnf/diaeditor} +\input{modules/ebnf/diaview} +\input{modules/ebnf/diasave} +\input{modules/ebnf/word} +\input{modules/ebnf/imprint} \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/defeditor.tex b/doc/users_manual_german/modules/ebnf/defeditor.tex new file mode 100644 index 0000000..eb84958 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/defeditor.tex @@ -0,0 +1,199 @@ +\section{EBNF-Definitionen} + +\subsection{Der EBNF-Editor} + +\subsubsection{Die Arbeitsfläche} + +Die Arbeitsfläche der EBNF-Eingabe teilt sich in eine obere und eine untere Hälfte. Die obere Hälfte dient der Eingabe der Definition, die untere der Ansicht. \\ + +Ein nachträgliches Bearbeiten der Definition wird durch die Interaktivität der Definition im unteren Bereich ermöglicht. + +\centerpic{ebnf/ebnfinput_full.png}{.7}{Die Arbeitsfläche des Moduls \ebnf} +\bigskip + +\subsubsection{Eingabe einer Definition} + +Die Definition wird im oberen Bilschirmbereich eingegeben. Es stehen Steuerelemente für die Eingabe von Variablen, Terminalsymbolen sowie Regeln zur Verfügung. + +\begin{itemize} + \item Eingabe von Variablen und Terminalsymbolen + + \begin{itemize} + \item Zugelassene Symbole \\ + Grundsätzlich sind alle Symbole zugelassen, die die folgenden Bedingungen + erfüllen: + + \begin{itemize} + \item Ein Symbol darf nicht der Anfang eines anderen Terminalsymbols oder + einer anderen Variable sein + \item Ein Symbol darf nicht mit Leerzeichen beginnen oder enden + \item Ein Symbol darf nicht leer sein + \item Ein Symbol darf keine Metasymbole enthalten + \end{itemize} + + \item Hinzufügen von Terminalsymbolen und Variablen zur EBNF-Definition \\ + Das hinzuzufügende Symbol muss in das entsprechende Textfeld geschrieben werden + und kann dann mit der Eingabetaste oder Klick auf Hinzufügen zur Definition + hinzugefügt werden. Falls das Symbol nicht hinzugefügt werden kann, wird eine + entsprechende Fehlermeldung angezeigt. + + \begin{center} + \includegraphics[scale=0.5]{\pfad ebnf/ebnfinput_addterminal.png} \hfill + \includegraphics[scale=0.5]{\pfad ebnf/ebnfinput_addvariable.png} \\ + Eingabemaske für Terminalsymbole \hfill ...und für Variablen + \end{center} + + \end{itemize} + + \item Eingabe von Regeln \\ + + Mit einer EBNF-Regel wird einer Variablen ein EBNF-Term zugeordnet. Die Variable kann + aus der Drop-Down-Liste ausgewählt werden. Da es zu jeder Variablen nur eine Regel + geben darf, werden nur diejenigen Variablen angezeigt, zu denen es noch keine Regel gibt. + + \begin{itemize} + \item Für einen korrekten EBNF-Term gelten folgende Regeln: + + \begin{itemize} + \item Ein EBNF-Term besteht aus Variablen, Terminalsymbolen und Metasymbolen + \item Die Metasymbole müssen korrekt geklammert sein + \item Der EBNF-Term darf nicht leer sein (genauso darf der in einer Klammerung + enthaltene Sub-Term nicht leer sein) + \end{itemize} + + \item Eine neue Regel kann mit der Eingabetaste oder Klick auf Hinzufügen zur + Definition hinzugefügt werden. Falls die Regel nicht hinzugefügt werden kann, + wird eine entsprechende Fehlermeldung angezeigt. + + \centerpic{ebnf/ebnfinput_addrule.png}{.5}{Eingabemaske für Regeln} + + \item Kommt in der Regel ein unbekanntes Symbol vor, so wird ein Dialogfenster + angezeigt, welches die Möglichkeit bietet, das neue Symbol der Menge der + Variablen oder Terminalsymbole hinzuzufügen. Man kann auch Teile des nicht + erkannten Textes als Symbol hinzufügen, indem man den Text im Dialog + bearbeitet. In diesem Fall ist es möglich, dass weitere unbekannte Symbole + gefunden werden. Wählt man in diesem Dialog “Abbrechen”, so schlägt das + Hinzufügen der Regel fehl. + + \centerpic{ebnf/ebnfinput_unknownsymbol.png}{.5}{Dialog für unbekannte Symbole} + + \end{itemize} + + \item Setzen der Startvariable + + \begin{itemize} + + \item Eine Definition besitzt genau dann eine Startvariable, wenn sie mindestens eine + Variable enthält. Beim Hinzufügen der ersten Variablen wird diese automatisch zur + Startvariable. + + \centerpic{ebnf/ebnfinput_setstartvar.png}{.8}{Setzen der Startvariable} + + + \item Die Startvariable kann geändert werden, indem man eine Variable aus der + entsprechenden Drop-Down-Liste auswählt. Außerdem kann man eine Variable über ihr + Kontextmenü in der Anzeige der Variablenmenge als Startvariable setzen. + + \centerpic{ebnf/ebnfinput_popup_startvar.png}{.8}{Setzen der Startvariable in der Ansicht} + \end{itemize} + +\end{itemize} + +\subsubsection{Bearbeiten einer Definition} + +Möchte man an einer bereits eingegebenen Definition Änderungen vornehmen, zum Beispiel eine Regel löschen oder ein Terminalsymbol umbenennen, so kann dies über das Kontextmenü in der Ansicht geschehen. + +\begin{itemize} + + \item Löschen + + \begin{itemize} + + \item Löschen von Variablen und Terminalsymbolen + + \begin{itemize} + \item Ein Symbol kann nur dann gelöscht werden, wenn es in keiner Regel mehr + vorkommt. + \item Wenn dies der Fall ist, kann man im Kontextmenü des Symbols in der Variablen- + oder Terminalsymbolmenge die Funktion "`Löschen"' auswählen. + + \centerpic{ebnf/ebnfinput_delvariable.png}{.8}{Löschen einer Variable} + + + \end{itemize} + + \item Löschen von Regeln \\ + Regeln können über das Kontextmenü in der Regel-Ansicht gelöscht werden. + + \centerpic{ebnf/ebnfinput_delrule.png}{.8}{Löschen einer Regel} + \end{itemize} + + \item Bearbeiten + + \begin{itemize} + \item Bearbeiten von Variablen und Terminalsymbolen. + + \begin{itemize} + \item Symbole können über ihr Kontextmenü umbenannt werden. Dabei gelten für die + Namensänderung die gleichen Regeln wie für die Eingabe. + \item Wählt man im Kontextmenü eines Symbols “Bearbeiten” aus, so erscheint in der + entsprechenden Eingabemaske das Symbol, der Hinzufügen-Button ändert sich in + einen “Ändern”-Button und es erscheint zusätzlich ein “Abbrechen”-Button. Im + Textfeld kann man den Symbolnamen ändern und anschließend durch die Auswahl + von “Ändern” übernehmen. Möchte man die Änderung abbrechen, so kann man dies + über den entsprechenden Button vornehmen. + \item Grundsätzlich kann man immer nur eine Variable und ein Terminalsymbol + gleichzeitig bearbeiten; im Moment bearbeitete Symbole werden in der Ansicht + gelb hervorgehoben. + + \bigskip + + \centerpic{ebnf/ebnfinput_editvar.png}{.6}{Umbenennen einer Variable} + + \bigskip + + \centerpic{ebnf/ebnfinput_editterminal.png}{.6}{Umbenennnen eines Terminalsymbols} + + \end{itemize} + \bigskip + \item Bearbeiten von Regeln + + \begin{itemize} + \item Regeln können über ihr Kontextmenü bearbeitet werden. + \item Wählt man im Kontextmenü einer Regel “Bearbeiten” aus, so erscheint in der + Regel-Eingabemaske die Regel, der Hinzufügen-Button ändert sich in einen + “Ändern”-Button und es erscheint zusätzlich ein “Abbrechen”-Button. Im + Textfeld kann man den Term bearbeiten und anschließend durch die Auswahl von + “Ändern” übernehmen. Das Ändern der Variablen der Regel ist nicht möglich. + Möchte man die Änderung abbrechen, so kann man dies über den entsprechenden + Button vornehmen. + + \bigskip + + \centerpic{ebnf/ebnfinput_editrule.png}{.6}{Bearbeiten einer Regel} + + \bigskip + + \item Grundsätzlich kann man immer nur eine Regel bearbeiten; die im Moment + bearbeitete Regel wird in der Ansicht gelb hervorgehoben. + \end{itemize} + \end{itemize} +\end{itemize} + +\bigskip + +\subsubsection{Überprüfen einer Definition und Beenden der Eingabe} + +Um eine Definition zu überprüfen kann der Button “Definition überprüfen” genutzt werden. Die Definition wird dann auf folgende Fehler und mögliche Probleme überprüft: + +\begin{itemize} + \item Das Vorhandensein einer Startvariable (--> Fehlermeldung) + \item Das Vorhandensein einer Regel für jede Variable (--> Fehlermeldung) + \item Die Nutzung aller Variablen der Variablenmenge (--> Warnung) + \item Die Nutzung aller Terminalsymbole der Terminalsymbolmenge (--> Warnung) + \item Die Erreichbarkeit aller Regeln von der Startvariablen aus (--> Warnung) +\end{itemize} + +Wird mind. ein Fehler gefunden, so werden Warnungen ignoriert und nicht angezeigt, um die Übersicht zu wahren. \\ + +Durch das Aktivieren des \textsc{Eingabe beenden}-Buttons wird die Definition überprüft. Wird dabei mind. ein Fehler gefunden, so kann der Wechsel zur EBNF-Anzeige nicht stattfinden. Wenn kein Fehler auftritt (Warnungen können vorkommen, werden aber nicht angezeigt) geschieht ein Wechsel zur EBNF-Anzeige, in welcher die Eingabemaske nicht mehr zu sehen ist. \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/defsave.tex b/doc/users_manual_german/modules/ebnf/defsave.tex new file mode 100644 index 0000000..0c6d12c --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/defsave.tex @@ -0,0 +1,9 @@ +\subsection{Speichern und Laden von EBNF-Defintionen} + +Man kann grundsätzlich Definitionen zu jedem Zeitpunkt in der EBNF-Eingabe speichern. \\ + +Dies geschieht entweder über das Menü \textsc{Datei} oder die ensprechenden Symbole in der Werkzeugleiste. Außerdem wird gefragt, ob die Definition gespeichert werden soll, sobald man das Modul verlassen möchte und nicht gesicherte Veränderungen vorgenommen hat. \\ + +Falls in der EBNF-Anzeige nachträglich eine binäre Klammerung vorgenommen wurde, so wird beim Speichern aus der EBNF-Anzeige heraus nachgefragt, ob diese in der Definition beibehalten werden soll. \\ + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/defview.tex b/doc/users_manual_german/modules/ebnf/defview.tex new file mode 100644 index 0000000..a7a8df3 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/defview.tex @@ -0,0 +1,33 @@ +\subsection{Anzeige von EBNF-Defintionen} + +Die EBNF-Anzeige kann nur erreicht werden, wenn die Definition korrekt und vollständig ist. Eine Überprüfung dessen findet durch die vorausgegangene Nutzung des \textsc{Eingabe beenden}-Buttons bzw. Beim Laden einer Datei statt. \\ + +Hintergrund der EBNF-Anzeige ist die übersichtliche Anzeige einer EBNF-Definition, ohne die Eingabemaske. Außerdem besteht hier die Möglichkeit, zum trans()-Algorithmus zu wechseln, um die EBNF-Definition in ein Syntaxdiagramm umzuwandeln. + +\subsubsection{Definition binär klammern} + +Um in den trans()-Algorithmus wechseln zu können, muss die Definition binär geklammert sein. Nach strenger Auslegung der Definition existieren nur binäre Alternativen in der EBNF: +\begin{itemize} + \item nicht binär geklammert: (a|b|c) + \item korrekt geklammert: (a|(b|c)) +\end{itemize} + +\centerpic{ebnf/ebnfdisplay_makebinary.png}{.6}{Definition binär klammern} + +\bigskip + +Der Lesbarkeit halber ermöglicht das Programm eine Eingabe von nicht binär geklammerten Alternativen. Ob die Definition noch nicht korrekt geklammerte Terme enthält, wird durch eine entsprechende Meldung angezeigt: BILD \\ + +Um eine Definition binär zu klammern, muss der \textsc{Definition binär klammern}-Button genutzt werden. Dadurch werden die noch fehlenden Klammern hinzugefügt und rot hervorgehoben. Damit ist der Wechsel zum trans()-Algorithmus ermöglicht. + +\subsubsection{Wechsel zum trans()-Algorithmus} + +Wenn die Definition binär geklammert ist, kann man in den trans()-Algorithmus durch Anklicken des \textsc{trans()-Algorithmus anwenden}-Buttons wechseln. + +\subsubsection{Beibehalten der binären Klammerung} + +Falls in der EBNF-Anzeige nachträglich eine binäre Klammerung vorgenommen wurde, so wird beim Wechsel zur EBNF-Eingabe (mittels \textsc{Definition überarbeiten}-Button) und beim Speichern aus der EBNF-Anzeige heraus nachgefragt, ob diese in der Definition beibehalten werden soll. + +\bigskip +\centerpic{ebnf/ebnfdisplay_keepbinary.png}{.8}{Beibehalten der Klammerung} +\bigskip \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/diaeditor.tex b/doc/users_manual_german/modules/ebnf/diaeditor.tex new file mode 100644 index 0000000..930face --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/diaeditor.tex @@ -0,0 +1,132 @@ +\section{Syntaxdiagramme} + +\subsection{Der Syntaxdiagramm-Editor} + +\subsubsection{Die Arbeitsfläche} + +Die Arbeitsfläche des Syntaxdiagramm-Editors ist zweigeteilt: Im oberen Abschnitt befindet sich der Kontrollbereich, über den alle Aktionen, die für das Erstellen und Editieren von Syntaxdiagrammen nötig sind, anwählbar sind. Darunter befindet sich die Anzeige für Syntaxdiagramme - die Arbeitsfläche, auf der an den Diagrammen gearbeitet wird. + +\bigskip +\centerpic{ebnf/syndia_aufteilung.png}{.4}{} +\bigskip + +\subsubsection{Hinzufügen von Elementen} + +Um einem Syntaxdiagrammsystem Elemente hinzufügen zu können, muss man sich in einem entsprechenden Modus befinden. Einzig das Hinzufügen neuer Syntaxdiagramme geschieht ohne Moduswechsel. + +\begin{itemize} + \item Syntaxdiagramme \\ + Um ein neues Syntaxdiagramm einzufügen genügt ein einfacher Klick auf das Symbol + \icon{ebnf/syndia_Leiste_NeuesDiagramm.png}{0}{0}{.4} im Kontrollbereich. In der Syntaxdiagramm-Anzeige erscheint ein + Popupfenster, in dem sich u.a. ein Texteingabefeld befindet. In diesem bereits + fokusierten Eingabefeld können Sie nun den gewünschten Namen ihres neuen + Syntaxdiagramms angeben. Ihre Eingabe beenden Sie entweder mit dem OK-Button \icon{ebnf/syndia_Button_OK.png}{0}{0}{.4} + rechts des Eingabefeldes oder über \textsc{Enter}. \\ + + Falls der von Ihnen gewählte Name schon für ein anderes Diagramm vergeben ist, + werden Sie im Rahmentext des Popupfensters darauf hingewiesen. Sie müssen einen + anderen Namen wählen. \\ + + Unterhalb des Eingabefeldes befindet sich eine weitere Zeile: + +\centerpic{ebnf/syndia_startdiagramm.png}{.8}{} + + + Indem Sie die + Checkbox auswählen, können Sie ihr neues Diagramm als Startdiagramm einfügen. Es + ist immer nur ein Startdiagramm zulässig, d.h. das alte Startdiagramm verliert + dieses "`Privileg"' an das neue Syntaxdiagramm. \\ + + Sie können die Eingabe jederzeit mit \textsc{Esc} abbrechen. Die Eingabe eines leeren + Diagrammnamens bewirkt ebenfalls einen Abbruch. Es wird kein Syntaxdiagramm + hinzugefügt. + + \item Über die Einfüge-Modi \\ + Um Elemente einfügen zu können, müssen Sie in den Modus "` einfügen"' + wechseln. Dieses Beispiel demonstriert dies für Terminalsymbole. Den Moduswechsel + erreichen Sie auf zwei verschiedenen Wegen: entweder wählen Sie im Kontrollbereich + den Button \icon{ebnf/syndia_Leiste_Terminal.png}{0}{0}{.4} aus oder Sie bewegen Ihre Maus in die Syntaxdiagramm-Anzeige. + Dort können Sie jederzeit mit einem Rechtsklick ein Kontextmenü öffnen, in dem Sie + ebenfalls den Modus "`Terminalsymbole einfügen"' anwählen können. \icon{ebnf/syndia_Popup_Terminal.png}{0}{0}{.4} \\ + + Ist dieser Modus gewählt, wird der zugehörige Button im Kontrollbereich ausgegraut. + Auch ändert sich der Mauszeiger, wenn Sie über den Arbeitsbereich fahren. \\ + + Somit wissen Sie immer, in welchem Modus Sie sich gerade befinden. + + \item Über die Rhomben \\ + Im Editiermodus bekommen die Syntaxdiagramme neue Elemente - die Rhomben. Sie sind + Pseudoelemente, die das Einfügen von Elementen erleichtern bzw. erst ermöglichen. + In ihrem Grundzustand sind die Rhomben grau. Befindet man sich in einem + Einfügemodus, so leuchten sie grün auf, falls an dieser Stelle ein Hinzufügen + möglich ist. Leuchten sie dagegen rot auf, kann das Element an dieser + Stelle nicht eingefügt werden. \\ + + Hat man etwas eingefügt, erscheinen vor und hinter diesem Element neue Rhomben, an + denen erneut hinzugefügt werden kann. In Wiederholungen und Verzweigungen + erscheinen zudem in den Elementen neue Rhomben - schließlich soll man auch hier + Einfügen können. + + \item Terminalsymbole und Variablen \\ + Wechseln Sie als erstes in den Modus \textsc{Terminalsymbole einfügen} oder \textsc{Variablen einfügen}. \icon{ebnf/syndia_Leiste_Terminal.png}{0}{0}{.4}\icon{ebnf/syndia_Leiste_Variable.png}{0}{0}{.4} In der Arbeitsfläche können Sie nun mit der Maus über + jeden beliebigen Rhombus fahren - er leuchtet grün auf. Mit einem Linksklick fügen + Sie das Terminalsymbol / die Variable an dem aktuell grün leuchtenden Rhobus ein. \\ + + Es erscheint ein Textfeld, in dem Sie einen Namen für das Element eingeben müssen. + Als Standard erscheint ausgewählt "`a"' / "`A"'. \\ + + Zum Bestätigen einer Eingabe drücken Sie entweder auf den OK-Button \icon{ebnf/syndia_Button_OK.png}{0}{0}{.4} oder + ENTER. Falls Sie das Erstellen abbrechen möchten, drücken Sie ESACAPE oder geben + einen leeren Namen ein. + + \item Verzweigungen und Wiederholungen \newline + Wechseln Sie als erstes in den Modus "`Verzweigungen einfügen"' / "`Wiederholungen + einfügen"' \icon{ebnf/syndia_Leiste_Verzweigung.png}{0}{0}{.4}\icon{ebnf/syndia_Leiste_Wiederholung.png}{0}{0}{.4}. In der Arbeitsfläche können Sie nun mit der Maus über + jeden beliebigen Rhombus fahren - er leuchtet grün auf. Mit einem Linksklick fügen + Sie den Anfang der Verzweigung / Wiederholung ein. Daraufhin erscheint grau + gepunktet eine neue Verzweigung / Wiederholung. Diese zeigt, von wo bis wo + eingefügt werden kann. Anfangs ist sie auf den angeklickten Rhombus beschränkt. \\ + + Sie können diese "`unfertige"' Verzweigung / Wiederholung nun sowohl nach links als + auch nach rechts in die Breite ziehen. Fahren Sie dazu mit der Maus über andere + Rhomben. Leuchtet ein Rhombus grün auf, so kann bis zu dieser Stelle eingefügt + werden. Dies wird durch die veränderte grau gepunktete Verzweigunng / Wiederholung + angezeigt. Dabei können auch schon vorhandene Elemente eingeschlossen werden. \\ + + Leuchtet ein Rhombus dagegen rot auf, so darf an dieser Stelle nicht eingefügt + werden. Dies ist der Fall, wenn das Ende nicht auf der gleichen Linie liegt wie der + Startpunkt. Auch dürfen sich Linien nicht kreuzen, so dass das Einfügen eines Endes + in das Innere einer anderen Verzweigung / Wiederholung ebenfalls nicht erlaubt ist. \\ + + Haben Sie den Mauszeiger über ein grün leuchtendes Ende gefahren, so können Sie nun + mit einem weiteren Linksklick Einfügen. Die grau gepunktete Verzweigung / + Wiederholung verschwindet und ein vollständig neues Element erscheint. +\end{itemize} + +\subsubsection{Bearbeiten und Löschen von Elementen} + +\begin{itemize} + \item Editieren \\ + Im Editiermodus ist es möglich, Terminalsymbol-, Variablen- und Syntaxdiagrammnamen + zu ändern. \\ + + Wechseln Sie dazu zuerst in diesen Modus. \icon{ebnf/syndia_Leiste_Edit.png}{0}{0}{.5} \\ + +Fahren Sie nun mit der Maus über Terminalsymbole oder Variablen, so leuchten diese blau auf. Mit einem Linksklick auf diese Elemente erscheint ein Textfeld mit dessen Namen. Sie können den Namen nun beliebig ändern. Mit dem OK-Button oder \textsc{Enter} schließen Sie die Änderung ab. Mit \textsc{Escape} oder der Eingabe eines leeren Namens brechen Sie den Editiervorgang ab. \\ + +Fahren Sie mit der Maus über den Namen eines Syntaxdiagramms, so erscheint dieser fett. Mit einem Linksklick können Sie nun den Namen des Diagramms ändern. Dazu erscheint der Dialog, der auch zum Einfügen neuer Elemente angezeigt wird. Einziger Unterschied ist, dass, falls Sie das Startdiagramm editieren, Sie diesem Diagramm diesen Status nicht nehmen können - die entsprechende Checkbox ist ausgegraut. + + \item Löschen \\ + +Im Löschmodus ist es möglich, sowohl alle Syntaxdiagrammelemente als auch leere Diagramme zu löschen. + +Wechseln Sie dazu zuerst in diesen Modus. \icon{ebnf/syndia_Leiste_Radiergummi.png}{0}{0}{.5} \\ + +Fahren Sie nun mit der Maus über Terminalsymbole oder Variablen, so leuchten diese rot auf. Mit einem Linksklick werden diese gelöscht. Nachfolgende Elemente rücken nach links. + +Verzweigungen und Wiederholungen können ebenfalls gelöscht werden. Bewegen Sie dazu den Mauszeiger auf die obere oder untere Linie eines dieser Elemente. Die Linie und alle darauf liegenden Elemente leuchten rot auf. Mit einem Linksklick bestätigen Sie den Löschvorgang. +War die untere Linie markiert, so werden Elemente der oberen Linie beibehalten. Löschen Sie die obere Linie einer Verzweigung, so werden die Elemente der unteren Linie - sofern vorhanden - auf die obere Linie eingefügt. Die untere Linie verschwindet. Dies geschieht auch beim Löschen des unteren Teils einer Wiederholung; nur werden hier die Elemente in umgekehrter Reihenfolge oben eingefügt (d.h. ihre "`Leserichtung"' bleibt erhalten). \\ + +Befinden Sie sich mit dem Mauszeiger über einem leeren Syntaxdiagramm (d.h. nur ein Rhombus befindet sich in diesem Diagramm), so erscheint um dieses ein roter Rahmen. Bestätigen Sie mit einem Linksklick, wird das Diagramm gelöscht. Handelt es sich dabei um das Startdiagramm, so erscheint ein Hinweis, dass das Löschen des Startdiagramms nicht möglich ist. + +\end{itemize} \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/diasave.tex b/doc/users_manual_german/modules/ebnf/diasave.tex new file mode 100644 index 0000000..4573815 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/diasave.tex @@ -0,0 +1,15 @@ +\subsection{Speichern und Laden von Syntaxdiagrammen} + +\subsubsection{Speichern} + +Natürlich haben Sie auch die Möglichkeit, Syntaxdiagramme zu speichern. \\ + +Dies ist möglich in der Syntaxdiagramm-Anzeige sowie im Syntaxdiagramm-Editor. Das Speichern ist nur mit der Endung \emph{"`*.jalgo"'} möglich. Das Programm erkennt jedoch automatisch, dass es sich um ein Syntaxdiagramm handelt. \\ + +Hinweis! Speichern sie die Diagramme in einem eindeutigen Ordner oder geben Sie dem Diagramm einen geeigneten Namen, da die Speicherendungen im gesamten \jalgo \emph{"`*.jalgo"'} sind. + +\subsubsection{Laden von Syntaxdiagrammen} + +Beim Laden von Syntaxdiagrammen unterscheidet das Modul, ob sie vollständig sind oder nicht. Vollständig bedeutet, dass zu jeder Variable im Diagramm ein Diagramm mit diesem Namen existiert. Ist es vollständig, befinden Sie sich nach dem Laden in der Syntaxdiagramm\-anzeige. Ist es nicht vollständig wird der Editor geöffnet und das Diagramm kann bearbeitet werden. + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/diaview.tex b/doc/users_manual_german/modules/ebnf/diaview.tex new file mode 100644 index 0000000..6ae4546 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/diaview.tex @@ -0,0 +1,25 @@ +\subsection{Die Syntaxdiagramm-Anzeige} + +\bigskip +\centerpic{ebnf/syndia_view.png}{.4}{} +\bigskip + +\subsubsection{Anzeigebereich} + +Hier werden die Syntaxdiagramme visualisiert. + +\subsubsection{Kontrollbereich} + +Im Kontrollbereich hat man die Möglichkeit, die Syntaxdiagramme grafisch zu verändern. Die Möglichkeiten beschränken sich auf das Skalieren der Diagramme, das automatische Anpassen der Größe an das Fenster, sowie das Entfernen von Treppenstrukturen. Auf der rechten Seite befinden sich zudem noch Navigationsbuttons. + + \begin{itemize} + \item \icon{ebnf/trans_resize.png}{0}{0}{.6} Hier haben Sie die Möglichkeit, das Diagramm selbst zu + vergrößern und zu verkleinern + + \item \icon{ebnf/trans_fit.png}{0}{0}{.6} Hier kann man einstellen, ob sich die Größe der Diagramme + automatisch dem Fensterrahmen anpassen soll oder nicht. + + \item \icon{ebnf/trans_stairs.png}{0}{0}{.6} Bei Aktivierung dieses Knopfes, während Treppenstrukturen in + den Diagrammen entfernt. + + \end{itemize} \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/imprint.tex b/doc/users_manual_german/modules/ebnf/imprint.tex new file mode 100644 index 0000000..4a164e1 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/imprint.tex @@ -0,0 +1,16 @@ +\section{Impressum} +Das Modul \ebnf wurde im Sommersemester 2006 von der Praktikumsgruppe 12 im Rahmen des externen Softwarepraktikums entwickelt. Mitwirkende waren die +\paragraph{Teammitglieder} +\begin{itemize} +\item Tom Kazimiers --- Administrator +\item Johannes Mey --- Testverantwortlicher +\item Michael Thiele --- Chefprogrammierer +\item André Viergutz --- Assistent +\item Claas Wilke --- Sekretär + +\end{itemize} +sowie der betreuende Tutor Matthias Schmidt.\\ +Die Webseite des Projektes finden Sie unter \href{http://web.inf.tu-dresden.de/~swt06-12/}{http://web.inf.tu-dresden.de/\~{}swt06-12/}. + +\newpage +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/overview.tex b/doc/users_manual_german/modules/ebnf/overview.tex new file mode 100644 index 0000000..d3c4d19 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/overview.tex @@ -0,0 +1,12 @@ +\chapter{Das Modul Ebnf und Syntaxdiagramme} + +\section{Einleitung und Funktionsübersicht} + +Das \jalgo Modul \ebnf erweitert \jalgo um die Möglichkeit, EBNF Definitionen und Syntaxdiagramme zu erzeugen und bearbeiten. \\ + +Darüberhinaus stellt das Modul die Möglichkeit bereit, EBNF-Definitionen in Syntaxdiagramme zu überführen; dies geschieht mit dem trans()-Algorithmus, der im Modul schrittweise nachvollzogen werden kann. \\ + +Außerdem wird eine graphische Darstellung des Rücksprungalgorithmus zur Verfügung gestellt, mit deren Hilfe der Benutzer Worte der von einem Syntaxdiagramm definierten Sprache erzeugen kann. + + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/start.tex b/doc/users_manual_german/modules/ebnf/start.tex new file mode 100644 index 0000000..788a7b1 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/start.tex @@ -0,0 +1,22 @@ +\section{Der Willkommensbildschirm} + +\bigskip +\centerpic{ebnf/welcome.png}{.4}{Der Willkommensbischirm} +\bigskip + +Der Willkommensbilschirm des \ebnf -Moduls bietet eine Auswahl der verschiedenen Möglichkeiten des Moduls: + +\begin{itemize} + +\item \icon{ebnf/load.png}{0}{0}{.6}Laden einer EBNF-Definition oder eines Syntaxdiagramms \\ +Wenn die Definition bzw. das Diagramm vollständig und korrekt ist, gelangt man in die jeweilige Anzeige, ansonsten in den Editor. + +\item \icon{ebnf/editebnf.png} {0}{0}{.6} Erstellen einer neuen EBNF-Definition \\ +Hier gelangt man zum Editor für EBNF-Definitionen + +\item \icon{ebnf/editsyndia.png}{0}{0}{.6}Erstellen eines neuen Syntaxdiagramms \\ +Diese Schaltfläche führt zum Editor für Syntaxdiagramme + +\end{itemize} + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/trans.tex b/doc/users_manual_german/modules/ebnf/trans.tex new file mode 100644 index 0000000..69420cf --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/trans.tex @@ -0,0 +1,87 @@ +\section{Der trans()-Algorithmus} + +\subsection{\label{transArbeitsFlaeche}Die Arbeitsfläche} + + +\bigskip +\centerpic{ebnf/trans_gui.png}{.4}{Die Arbeitsfläche des trans()-Algorithmus} +\bigskip + +\begin{itemize} + \item Anzeigebereich \\ + Hier werden die Syntaxdiagramme visualisiert, vollständig, sowie auch während des + Algorithmus. Neben den Syntaxdiagrammelementen existieren hier zusätzlich noch die + hinterlegten trans()-Elemente. Fährt man mit der Maus darüber, werden die zu + trennenden Elemente farblich hervorgehoben und im Erklärungsbereich wird der + dazugehörige Schritt angezeigt. Bei Klick, wird dieser Schritt ausgeführt. + + \item Kontrollbereich \\ + Im Kontrollbereich hat man die Möglichkeit, die Syntaxdiagramme grafisch zu + verändern. Die Möglichkeiten beschränken sich auf das Skalieren der Diagramme, das + automatische Anpassen der Größe an das Fenster, sowie die Entfernung von + Treppenstrukturen. Auf der rechten Seite befinden sich zudem noch + Navigationsbuttons. + + + \begin{itemize} + \item \icon{ebnf/trans_resize.png}{0}{0}{.6} Hier haben Sie die Möglichkeit, das Diagramm selbst zu + vergrößern und zu verkleinern + + \item \icon{ebnf/trans_fit.png}{0}{0}{.6} Hier kann man einstellen, ob sich die Größe der Diagramme + automatisch dem Fensterrahmen anpassen soll oder nicht. + + \item \icon{ebnf/trans_stairs.png}{0}{0}{.6} Bei Aktivierung dieses Knopfes, werden Treppenstrukturen in + den Diagrammen entfernt. + + \item Wechsel zur Syntaxdiagramm-Anzeige \\ + ACHTUNG! Ein Wechsel in die Syntaxdiagramm-Anzeige ist nur nach Beendigen des + Algorithmus möglich und man kommt zudem nicht wieder zurück! + + \item Wechsel zur EBNF-Definition \\ + Wechselt man in die + Ebnf-Ansicht und lässt die Ebnf-Definition unverändert, fährt man bei Rückkehr in + den trans()-Algorithmus fort, ändert man die Ebnf-Defintion, wird der Algorithmus + neu gestartet. + + \end{itemize} + + \item Steuerbereich \\ + Hier kann man neben dem direkten Arbeiten in der Anzeige noch über Buttons den + Algorithmus steuern. + + \begin{itemize} + \item \icon{ebnf/trans_reset.png}{0}{0}{.6} Macht alle bisher ausgeführten Schritte rückgängig + + \item \icon{ebnf/trans_last.png}{0}{0}{.6} Macht den letzten ausgeführten Schritt rückgängig + + \item \icon{ebnf/trans_info.png}{0}{0}{.6} Bei Aktivierung dieses Buttons wird permanent der nächste Schritt + hervorgehoben + + \item \icon{ebnf/trans_next.png}{0}{0}{.6} Führt den nächsten automatisch gewählten Schritt aus + + \item \icon{ebnf/trans_finish.png}{0}{0}{.6} Führt den Algorithmus bis zum Ende aus + + \end{itemize} + + \item Erklärungsbereich \\ + Hier werden die Erklärungen zu den einzelnen Schritten angezeigt oder es werden dem + Nutzer Hinweise angezeigt +\end{itemize} + +\subsection{Steuerung des Algorithmus} + +Es existieren zwei Möglichkeiten, den Algorithmus zu steuern. Zum einen + +\begin{itemize} + \item Im Anzeigebereich \\ + Hier kann man direkt mit den farblich hinterlegten trans()-Elementen arbeiten. + Befindet sich die Maus darüber, werden die zu trennenden Teilstücke hervorgehoben + sowie der zugehörige Algorithmusschritt im Erklärungsbereich angezeigt. Klickt man + darauf, wird dieser Schritt ausgeführt und das Element umgeformt. + + \item Über die Steuerbuttons \\ + Die Erklärung zu den Steuerbuttons befindet sich im Abschnitt + \ref{transArbeitsFlaeche} in der Erklärung zur Arbeitsfläche. +\end{itemize} + +\newpage \ No newline at end of file diff --git a/doc/users_manual_german/modules/ebnf/word.tex b/doc/users_manual_german/modules/ebnf/word.tex new file mode 100644 index 0000000..c8fc290 --- /dev/null +++ b/doc/users_manual_german/modules/ebnf/word.tex @@ -0,0 +1,144 @@ +\section{Der Rücksprung-Algorithmus} + +\subsection{Die Arbeitsfläche} + +Die Arbeitsfläche des Rücksprungalgorithmus ist in vier Bereiche aufgeteilt. + + +\bigskip +\centerpic{ebnf/rs_full.png}{.8}{Der Rücksprungalgorithmus} +\bigskip + +\begin{itemize} + \item Syntaxdiagramm-Ansicht \\ + die Syntaxdiagramme werden hier grafisch dargestellt. Darüber hinaus erfolgt die + Steuerung während des Algorithmus’ durch Anklicken der Diagramme in dieser Ansicht. + + \item Keller \\ + Hier werden alle Rücksprungadressen dargestellt, die während des Algorithmus’ auf + den Keller gelegt werden. + + \item Kontrollbereich \\ + Hier wird das Wort ausgegeben, das während des Algorithmus’ erzeugt wurde. Darüber + hinaus kann hier ein Wort eingegeben werden, das erzeugt werden soll, der + Algorithmus wird von hier gestartet. Zusätzlich bietet der Kontrollbereich die + Möglichkeit, die Darstellung der Syntaxdiagramme in der Syntaxdiagramm-Ansicht + anzupassen. + + \item Erklärungsbereich \\ + Hier werden während des Ablaufes des Algorithmus’ Erklärungen zu den einzelnen + Algorithmusschritten ausgegeben. +\end{itemize} + +\subsection{Steuerung des Algorithmus} + +Aufgabe des Bereichs ‚Rücksprungalgorithmus’ ist es, den Algorithmus der Worterzeugung zu visualisieren. Er repräsentiert den Ablauf eines Weges durch ein Syntaxdiagramm-System und erzeugt während des Ablaufes ein Wort, das sich aus den passierten Terminalsymbolen zusammensetzt. Das Modul ist dabei nicht in der Lage, Entscheidungen über die Wegewahl bezüglich der Erzeugung eines Wortes selbst zu treffen. Vielmehr soll er dem Nutzer helfen, eigene Durchläufe und Sprünge zwischen den einzelnen Diagrammen zu überprüfen. + +Im Folgenden wird die Steuerung des Algorithmus’ erläutert: + +\subsubsection{Eingabe eines Wortes} + +Bevor der Algorithmus gestartet wird, besteht die Möglichkeit, im Kontrollbereich ein Wort einzugeben, welches während des Algorithmus erzeugt werden soll. Dieses kann einfach in das Textfeld eingegeben werden, welches mit ‚Zu erzeugendes Wort’ bezeichnet ist. Die Eingabe eines Wortes, welches erzeugt werden soll, ist optional. Es ist genauso möglich, kein Wort einzugeben und die Generierung von Wörtern so zu testen, oder den Button 'Wort erzeugen' im Kontrollbereich zu klicken, der automatisch ein Wort - welches auch mit dem Algorithmus erzeugt werden kann - generiert (Dabei kann es sich aber auch um das leere Wort handeln, falls das Syntax-Diagramm-System dieses ermöglicht). + +\subsubsection{Start des Algorithmus} + +Nach der (optionalen) Eingabe eines Wortes kann der Algorithmus gestartet werden. Dies ist über einen Klick auf den Button ‚Algorithmus starten’ im Kontrollbereich, oder über das Menü Rücksprung-Algorithmus-> Algorithmus starten möglich. + +Anmerkung: Besteht das im Schritt 1 eingegebene Wort nicht ausschließlich aus in den Syntax-Diagrammen vorhandenen Terminalsymbolen, so ist die Erzeugung eines solchen Wortes prinzipiell nicht möglich. Das Programm wird ein solches Wort zurückweisen und den Algorithmus nicht starten. + +Ist der Algorithmus gestartet, so wird die aktuelle Position in einem der gegebenen Programme durch einen roten Punkt gekennzeichnet. + + +\bigskip +\centerpic{ebnf/rs_dot.png}{.8}{} +\bigskip + +Zu Beginn des Algorithmus wird dieser Punkt am Anfang des Startdiagrammes stehen. + +\subsubsection{Wählen eines Weges durch ein Syntax-Diagramm} + +Um einen Weg durch ein Syntax-Diagramm zu wählen, können einzelne Elemente des Diagrammes in der Syntax-Diagramm-Anzeige direkt angeklickt werden. Folgende Elemente können angeklickt werden: Erreichbare Terminalsymbole und Variable, erreichbare und leere Verzweigungen sowie erreichbare Ausgänge von Syntax-Diagrammen. + +\subsubsection{Passieren eines Terminalsymboles} + +Um ein Terminalsymbol zu passieren, kann dieses einfach angeklickt werden. Dies ist nur möglich, wenn das entsprechende Terminalsymbol von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist ein Terminalsymbol zu erreichen, so wird es blau hervorgehoben, sobald man mit der Maus über das Symbol fährt. Passierte Terminalsymbole werden an das Ende des erzeugten Wortes im Kontrollbereich angehängt. + +\bigskip +\centerpic{ebnf/rs_terminal.png}{.8}{} +\bigskip + +\subsubsection{Passieren einer Variable} + +Um eine Variable zu passieren, kann diese einfach angeklickt werden. Dies ist nur möglich, wenn die entsprechende Variable von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist eine Variable zu erreichen, so wird sie blau hervorgehoben, sobald man mit der Maus über die Variable fährt. Wird eine Variable passiert, so wird ihre Rücksprungadresse auf den Keller gelegt. Dem Passieren einer Variable folgt stets ein Sprung in ein Syntax-Diagramm. + +\bigskip +\centerpic{ebnf/rs_variable.png}{.8}{} +\bigskip + +\subsubsection{Sprung in ein Syntax-Diagramm} + +Dem Sprung in ein Syntax-Diagramm geht stets das Passieren einer Variable voraus. Um in ein Syntax-Diagramm zu springen, muss einfach mit der Maus über das entsprechende Syntax-Diagramm in der Syntaxdiagramm-Ansicht gefahren werden, dieses wird dann mit einem blauen Rahmen umrandet. Durch den Klick auf das Diagramm wird der Sprung ins Diagramm durchgeführt. Ein Sprung ist nur möglich, wenn der Name des Diagrammes, mit dem Inhalt der zuvor passierten Variable übereinstimmt. Andernfalls wird der Algorithmus den Sprung zurückweisen. + +\bigskip +\centerpic{ebnf/rs_frame.png}{.8}{} +\bigskip + +\subsubsection{Passieren einer leeren Verzweigung} + +Um eine leere Verzweigung zu passieren, kann diese einfach angeklickt werden. Dies ist nur möglich, wenn die entsprechende Verzweigung von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist eine leere Verzweigung zu erreichen, so wird sie blau hervorgehoben, sobald man mit der Maus über die Variable fährt. Beim Klick auf eine leere Verzweigung wird das erzeugte Wort nicht verändert. Es ändert sich lediglich die Position im Syntax-Diagramm. + +\bigskip +\centerpic{ebnf/rs_mouseoverline.png}{.8}{} +\bigskip + +\subsubsection{Verlassen eines Syntax-Diagrammes} + +Ist nach dem Passieren eines Terminalsymboles, einer Variable oder leeren Verzweigung, sowie dem Rücksprung in ein Syntax-Diagramm nur noch der Ausgang des Diagrammes zu erreichen, so wird der Algorithmus das Diagramm automatisch verlassen. Doch nicht immer ist der Weg zum Ausgang die einzige Möglichkeit. In solchen Situationen muss man selbst entscheiden, ob das Diagramm verlassen werden soll. \\ + +Um das Diagramm zu verlassen, muss einfach in der Syntaxdiagramm-Anzeige auf den Ausgang des Diagrammes geklickt werden. Das Verlassen des Diagrammes wird nur durchgeführt, wenn der Ausgang des Diagrammes von der aktuellen Position im Diagramm erreicht werden kann. Der Ausgang des Diagrammes wird dann beim Fahren mit der Maus über den Ausgang blau hervorgehoben. \\ + +\bigskip +\centerpic{ebnf/rs_mouseoverexit.png}{.8}{} +\bigskip + +Dem Verlassen des Diagrammes folgt entweder der Rücksprung in ein Diagramm, oder das Ende des Algorithmus. \\ + +\subsubsection{Rücksprung in ein Syntax-Diagramm} + +Wurde ein Syntax-Diagramm verlassen, so kann ein Rücksprung in ein Diagramm folgen. Der Rücksprung folgt immer dann, wenn noch Rücksprungadressen auf dem Keller liegen. Um einen Rücksprung durchzuführen, muss einfach in der Syntaxdiagramm-Anzeige die Rücksprungmarke einer Variable in einem Diagramm angeklickt werden. Diese werden, falls ein Rücksprung möglich ist, beim Fahren mit der Maus über die Marke blau hervorgehoben. + +\bigskip +\centerpic{ebnf/rs_keller.png}{.8}{} +\bigskip + +Ein Rücksprung wird nur durchgeführt, wenn die Nummer der angeklickten Rücksprungmarke mit der obersten Adresse auf dem Keller übereinstimmt. Die oberste Adresse wird dann vom Keller gelöscht, der Weg kann hinter der Variable fortgesetzt werden, zu der zurückgesprungen wurde. Stimmen Rücksprungmarke und oberste Adresse auf dem Keller nicht überein, so wird der Rücksprung vom Algorithmus zurückgewiesen. + +\bigskip +\centerpic{ebnf/rs_variable_keller.png}{.8}{} +\bigskip + +\subsubsection{Ende des Rücksprungalgorithmus} + +Wird ein Syntax-Diagramm verlassen und es befindet sich keine Rücksprung-Adresse mehr auf dem Keller, so endet der Algorithmus. Er endet jedoch nur dann erfolgreich, wenn das Ende des Startdiagrammes erreicht wurde, und das vor Beginn des Algorithmus eingegebene Wort erzeugt wurde. Andernfalls wird der Algorithmus mit einer Fehlermeldung enden. + +\subsubsection{Fehler während des Algorithmusdurchlaufes} + +Nicht immer werden Fehler während des Laufens durch ein Syntax-Diagramm sofort erkannt und vom Algorithmus zurückgewiesen. So kann es z.B. passieren, dass das eingegebene Wort komplett erzeugt, der Ausgang des Startdiagrammes aber noch nicht erreicht wurde. Genauso kann ein anderes Wort als die Eingabe erzeugt worden sein. In einem solchen Fall wird der Algorithmus die Weiterarbeit verweigern. Es bestehen die Möglichkeiten, einzelne, falsche Schritte rückgängig zu machen, oder den Algorithmus komplett zurück zu setzen. + +\subsubsection{Schritte rückgängig machen} + +Um einen Schritt im Algorithmus rückgängig zu machen, gibt es zwei Möglichkeiten. Zum einen den Klick auf das entsprechende Symbol in der Toolbar am oberen Fensterrand \icon{ebnf/undo.png}{0}{0}{.5}, oder die Auswahl über das Menü Rücksprung-Algorithmus -> Schritt rückgängig. + +\subsubsection{Schritte wiederherstellen} + +Um einen Schritt im Algorithmus wiederherzustellen, gibt es zwei Möglichkeiten. Zum einen den Klick auf das entsprechende Symbol in der Toolbar am oberen Fensterrand \icon{ebnf/redo.png}{0}{0}{.5}, oder die Auswahl über das Menü Rücksprung-Algorithms -> Schritt wiederherstellen. + +\subsubsection{Den Rücksprungalgorithmus zurücksetzen} + +Der Klick auf den Button \textsc{Algorithmus zurücksetzen} im Kontrollbereich ermöglicht das Zurücksetzen des Algorithmus in die Ausgangsposition. Einzelne Schritte können von hier aus wieder hergestellt werden. Es kann aber auch ein neues Wort eingegeben und der Algorithmus neu gestartet werden. + +\subsubsection{Verlassen des Rücksprungalgorithmus-Bereiches} + +Der Rücksprungalgorithmus-Bereich kann über den Button \textsc{Zur Syntaxdiagrammanzeige wechseln} im Kontrollbereich verlassen werden. Das Programm kehrt dann in die Syntaxdiagramm-Anzeige zurück. Die gleiche Funktionalität bietet die Auswahl im Menü Rücksprung-Algorithmus -> Algorithmus verlassen. + +\newpage diff --git a/doc/users_manual_german/modules/kmp/CVS/Entries b/doc/users_manual_german/modules/kmp/CVS/Entries new file mode 100644 index 0000000..bc1de0e --- /dev/null +++ b/doc/users_manual_german/modules/kmp/CVS/Entries @@ -0,0 +1,8 @@ +/contents.tex/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/flowcontrol.tex/1.1/Fri Jun 30 14:39:09 2006/-kb/ +/functions.tex/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/imprint.tex/1.1/Fri Jun 30 14:39:09 2006/-kb/ +/info.tex/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/overview.tex/1.1/Fri Jun 30 14:39:09 2006/-kb/ +/screen.tex/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/start.tex/1.1/Fri Jun 30 14:39:08 2006/-kb/ diff --git a/doc/users_manual_german/modules/kmp/CVS/Repository b/doc/users_manual_german/modules/kmp/CVS/Repository new file mode 100644 index 0000000..d07bb66 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/modules/kmp diff --git a/doc/users_manual_german/modules/kmp/CVS/Root b/doc/users_manual_german/modules/kmp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/modules/kmp/contents.tex b/doc/users_manual_german/modules/kmp/contents.tex new file mode 100644 index 0000000..7e069b6 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/contents.tex @@ -0,0 +1,9 @@ +\newcommand{\kmp}{\mbox{\bfseries KMP} } + + +\input{modules/kmp/overview} +\input{modules/kmp/start} +\input{modules/kmp/screen} +\input{modules/kmp/functions} +\input{modules/kmp/flowcontrol} +\input{modules/kmp/info} \ No newline at end of file diff --git a/doc/users_manual_german/modules/kmp/flowcontrol.tex b/doc/users_manual_german/modules/kmp/flowcontrol.tex new file mode 100644 index 0000000..9e4c382 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/flowcontrol.tex @@ -0,0 +1,32 @@ +\section{Algorithmussteuerung} +\label{sec:Algorithmussteuerung} + + +\centerpic{kmp/control}{0.5}{Der Willkommensbildschirm des Moduls} + +\textbf{Startbildschirm} +Hierbei wird der aktuelle Arbeitsbereich verlassen und der Benutzer kehrt zum Startbildschirm zurück. +\bigskip + +\textbf{Abbruch} +Hierbei wird zum Anfang des Algorithmus gesprungen. + +\bigskip +\textbf{'Schnelles' Zurück} +Hierbei wird ein Schritt vollzogen, der mehreren vorherigen Statements im Quelltext entspricht. + +\bigskip +\textbf{Zurück} +Hierbei wird einer Schritt vollzogen, der dem vorherigen Statement im Quelltext entspricht. + +\bigskip +\textbf{Weiter} +Hierbei wird ein Schritt vollzogen, der dem nächsten Statement im Quelltext entspricht. + +\bigskip +\textbf{'Schnelles' Weiter} +Hierbei wird ein Schritt vollzogen, der mehreren nächsten Statements im Quelltext entspricht. Beim Erstellen der Verschiebetabelle entspricht dieser Schritt der Berechnung der Verschiebeinformation je eines Zeichens. Beim Anwenden der Verschiebetabelle an einem Text entspricht dieser Schritt dem Verschieben des Patterns unter Berücksichtigung der Verschiebetabelle. + +\bigskip +\textbf{Ende} +Hierbei werden alle Schritte, die bis zum Ende des Algorithmus durchgeführt werden, vollzogen. \ No newline at end of file diff --git a/doc/users_manual_german/modules/kmp/functions.tex b/doc/users_manual_german/modules/kmp/functions.tex new file mode 100644 index 0000000..de84821 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/functions.tex @@ -0,0 +1,91 @@ +\section{Modulfunktionen} +\label{sec:Modulfunktionen} + +\subsection{Eingabe von Pattern und Text} +\label{sec:EingabeVonPatternUndText} + +\subsubsection{Pattern eingeben} +\label{sec:PatternEingeben} + + +\centerpic{kmp/pattern1}{0.5}{Pattern manuell eingeben} +\bigskip +Das Pattern kann manuell eingegeben werden, hierbei ist die maximale Länge von 10 Zeichen zu beachten. Das Alphabet kann aus beliebigen Zeichen bestehen. Die Eingabe erfolgt im Steuerungsbereich in die Eingabezeile 'Pattern'. Um das Pattern zu übernehmen klicken Sie auf 'Setzen'. + +\subsubsection{Suchtext eingeben} + + +Der Text unterliegt keinen Beschränkungen und kann manuell eingegeben oder aus einer vorhandenen *.txt-Datei importiert werden. +Die Eingabe erfolgt im Steuerungsbereich, klicken Sie hierfür auf 'Eingeben'. + +\centerpic{kmp/text1}{0.5}{Text manuell eingeben} +\bigskip +Es öffnet sich ein Fenster, in dem Sie den Text manuell eingeben (oder auch per Copy und Paste einfügen) oder eine *.txt-Datei laden können. Um den Text zu übernehmen klicken Sie auf 'Anwenden'. + +\centerpic{kmp/text1}{0.5}{Text laden oder eingeben} +\bigskip +\subsection{Generieren von Pattern und passenden Texten} +\label{sec:GenerierenVonPatternUndPassendenTexten} + +\subsubsection{Pattern eingeben} + +\centerpic{kmp/pattern2}{0.5}{Pattern generieren lassen} +\bigskip +Neben der manuellen Eingabe des Patterns gibt es die Möglichkeit, ein Pattern generieren zu lassen. Klicken Sie dafür auf den Knopf 'Zufall' (im Steuerungsbereich neben der Eingabezeile 'Pattern') und wählen Sie im folgenden Fenster die Kardinalität des zu nutzenden Alphabets und die gewünschte Länge des Patterns aus. Das Pattern wird mit Klick auf 'Anwenden' geniert und Sie kehren zum Arbeitsbereich zurück. + +\centerpic{kmp/pattern3}{0.5}{Pattern generieren lassen} +\bigskip +\subsubsection{Suchtext eingeben} + +\centerpic{kmp/text3}{0.5}{Suchtext generieren lassen} +\bigskip +Um einen zum Pattern passenden Text generieren zu lassen, klicken Sie auf 'Generieren' (im Steuerungsbereich neben 'Text'). Dadurch wird eine Text erstellt, der das Pattern enthält und nur aus den im Pattern genutzten Zeichen besteht. Dieser Text wird sofort übernommen, Sie haben aber die Möglichkeit, ihn zu bearbeiten, indem Sie auf 'Eingeben' klicken. + + +\subsection{Generierung der Verschiebetabelle} +\label{sec:GenerierungDerVerschiebetabelle} + + +Wenn ein Pattern gesetzt wurde, kann die Verschiebetabelle erstellt werden. Um den Algorithmus zu starten und zu steuern, benutzen Sie die Pfeile im Steuerungsbereich. + +\centerpic{kmp/control}{0.5}{Algorithmussteuerung} +\bigskip +Das Pattern kann nun noch erweitert werden ohne den aktuellen Algorithmus zu unterbrechen, geben Sie hierfür das gewünschte Zeichen in das Eingabefeld "Erweiterung" im Steuerungsbereich ein. Sollte das Pattern bereits die maximale Länge haben, ist eine Erweiterung nicht möglich. + +\centerpic{kmp/expand}{0.5}{Pattern erweitern} +\bigskip +Nachdem die Verschiebetabelle erstellt wurde, können Pattern und Verschiebetabelle für eine Suche im Text genutzt werden. Klicken Sie hierfür auf das Feld 'Weiter zu Phase 2', welches erst am Ende des Algorithmus im Steuerungsbereich erscheint. + +\centerpic{kmp/go_p2}{0.5}{Von Phase 1 in Phase 2 wechseln} +\bigskip +\subsection{Suchen im Suchtext} +Erst wenn Pattern und Text gesetzt sind, kann das Anwenden der Verschiebetabelle an einem Text durchgeführt werden. Um Pattern und Text zu setzen, haben Sie verschiedene Möglichkeiten, siehe: Eingabe von Pattern und Text , Generieren von Pattern und passenden Texten. +Um den Algorithmus zu starten und zu steuern, benutzen Sie die Pfeile im Steuerungsbereich. + +\centerpic{kmp/control}{0.5}{Algorithmussteuerung} +\bigskip +Sollten Sie während der Durchführung des Algorithmus das Pattern und/oder den Text ändern, wird die aktuelle Durchführung des Algorithmus unterbrochen. +\bigskip +Der Suchvorgang wird beendet, wenn das Pattern gefunden wurde oder das Textende erreicht wurde, es erscheint eine Meldung dazu im Steuerungsbereich. + +\centerpic{kmp/endnegativ}{0.5}{Nachricht, dass Pattern nicht gefunden wurde} +\bigskip +\centerpic{kmp/endpositiv}{0.5}{Nachricht, dass Pattern gefunden wurde} +\bigskip +\subsection{Öffnen einer KMP-Sitzung} +\label{sec:ÖffnenEinerKMPSitzung} + + +Mit Klick auf das Ordner-Symbol öffnet sich ein Dialogfenster, in dem Ihnen die Möglichkeit gegeben wird, eine '*.jalgo' - Datei auszuwählen, in welcher eine KMP-Sitzung gespeichert wurde. + +\centerpic{kmp/load}{0.5}{Dialogfenster zum Laden einer Sitzung} +\bigskip + +\subsection{Präsentation von Lernbeispielen} +Es stehen Ihnen zehn Beispiele zur Auswahl, die jeweils eine besondere Eigenschaft des KMP-Algorithmus repräsentieren. Wenn Sie mit dem Mauszeiger über die Beispiele fahren, werden diese Eigenschaften kurz beschrieben. Wählen Sie das gewünschte Lernbeispiel aus und klicken Sie auf 'Laden' um das Beispiel zu starten.\newline +Die Beispiele bestehen aus Pattern- und passendem Text. + +\centerpic{kmp/learning}{0.5}{Präsentation von Lernbeispielen} +\bigskip +Die Steuerung der Lernbeispiele erfolgt durch die Pfeile im Steuerungsbereich. + diff --git a/doc/users_manual_german/modules/kmp/imprint.tex b/doc/users_manual_german/modules/kmp/imprint.tex new file mode 100644 index 0000000..7dd0961 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/imprint.tex @@ -0,0 +1,14 @@ +\section{Impressum} +Das Modul KMP wurde im Sommersemester 2006 von der Praktikumsgruppe SWT06-13 im Rahmen des externen Softwarepraktikums entwickelt. Mitwirkende waren die +\paragraph{Teammitglieder} +\begin{itemize} + \item Danilo Lisske --- Chefprogrammierer + \item Sebastian Patschorke --- Assistent + \item Matthias Neubert --- Testverantwortlicher + \item Elisa Böhl --- Sekretär + \item Nadine Grabow --- Administrator +\end{itemize} +sowie der betreuende Tutor Matthias Schmidt.\\ +Die Webseite des Projektes finden Sie unter \href{http://web.inf.tu-dresden.de/~swt06-13/}{http://web.inf.tu-dresden.de/\~{}swt06-13/}. + +Das Handbuch zu diesem Modul wurde erstellt von Nadine Grabow. \ No newline at end of file diff --git a/doc/users_manual_german/modules/kmp/info.tex b/doc/users_manual_german/modules/kmp/info.tex new file mode 100644 index 0000000..7ae364a --- /dev/null +++ b/doc/users_manual_german/modules/kmp/info.tex @@ -0,0 +1,16 @@ +\section{Dokumentation} +\label{sec:Dokumentation} + +Im Dokumentationsbereich stehen verschiedene Perspektiven und ihre Kombinationen zur Auswahl, die Aktivierung der Perspektive erfolgt über Reiter. + + +\begin{itemize} + \item \textbf{Code} - der Quellcode des Algorithmus, entnommen dem Vorlesungsskript von Prof. Vogler 'Algorithmen, Datenstrukturen und Programmierung'. + \item \textbf{Protokoll} - jeder vom Benutzer durchgeführte Schritt wird aufgelistet, egal ob es sich um Vorwärts- oder Rückwärts-Schritte handelt. + \item \textbf{Suchtext} - der zu durchsuchende Text. +\end{itemize} +\bigskip +\centerpic{kmp/phase2screen_ex2}{0.5}{Der Dokumentationsbereich} +\bigskip +Die Größe sowie die Aufteilung des Dokumentationsbereichs lassen sich vom Benutzer einstellen, siehe Anzeigeoptionen.\newline +Die Bedeutung der verwendeten Farben wird in der Legende erklärt. \ No newline at end of file diff --git a/doc/users_manual_german/modules/kmp/overview.tex b/doc/users_manual_german/modules/kmp/overview.tex new file mode 100644 index 0000000..6653047 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/overview.tex @@ -0,0 +1,27 @@ +\chapter{Das Modul KMP} +\label{sec:DasModulKMP} + +\subsection{Einleitung} +\label{sec:Einleitung} + + +Dieses Modul behandelt den Suchalgorithmus \textit{'Knuth Morris Pratt'} (KMP) und zeigt Arbeitsweise am Pattern und Text. Für eine detaillierte Beschreibung des Algorithmus sei auf das Vorlesungsskript von Prof. Vogler 'Algorithmen, Datenstrukturen und Programmierung' verwiesen. + +\subsection{Funktionsübersicht} +\label{sec:Funktionsübersicht} + + +Das Modul KMP realisiert folgende Funktionen: + + +\begin{itemize} + \item Visualisierung und Erläuterung des Algorithmus + \item Manuelle Eingabe von Pattern und Text + \item Generieren von Pattern und passenden Texten + \item Erstellen der Verschiebetabelle + \item Suchen im Suchtext + \item Präsentation von Lernbeispielen + \item Speichern und Laden von KMP-Beispielen + +\end{itemize} + diff --git a/doc/users_manual_german/modules/kmp/screen.tex b/doc/users_manual_german/modules/kmp/screen.tex new file mode 100644 index 0000000..239216c --- /dev/null +++ b/doc/users_manual_german/modules/kmp/screen.tex @@ -0,0 +1,104 @@ +\section{Der Arbeitsbereich} +\label{sec:DerArbeitsbereich} + +Der Arbeitsbereich ist untergliedert in drei Bereiche, die Ihnen Zugriff auf alle wesentlichen Funktionen in den Algorithmus-Phasen ermöglicht: + +\bigskip +\centerpic{kmp/phase1screen}{0.5}{Phase 1 Bildschirm} +\bigskip + + +\begin{enumerate} + \item \textbf{Steuerung}\newline + Hier wird der Algorithmus gestartet und gesteuert. + \item \textbf{Visualisierung}\newline + Hier werden die Verschiebetabelle bzw. der Text dargestellt. + \item \textbf{Dokumentation}\newline + Hier gibt es verschiedene Perspektiven, die miteinander kombiniert werden können: Quellcode, Text, Protokoll. +\end{enumerate} + +\section{Anzeigeoptionen} +\label{sec:Anzeigeoptionen} + +\subsection{Skalierung} +\label{sec:Skalierung} + +Die Größe der Elemente des Visualisierungs- und Dokumentationsbereichs kann eingestellt werden, klicken Sie dafür auf den Schieberegler im Visualisierungsbereich und ziehen Sie ihn nach oben bzw. unten. + +\centerpic{kmp/slide}{0.5}{Auswirkung des Schiebereglers zur Skalierung} +\bigskip +\subsection{Aufteilung der Bereiche} +\label{sec:Aufteilung der Bereiche} + +Die Aufteilung zwischen dem Visualisierungs- und dem Dokumentationsbereich kann mit einem Schiebebalken verändert werden. Per Klick auf die Kante können Sie die Grenze verschieben. + +\centerpic{kmp/move}{0.5}{Auswirkung des Schiebereglers} +\bigskip + +\subsection{Beamer - Modus} +\label{sec:BeamerModus} + +Der Beamer-Modus ermöglicht das schnelle Einstellen von Anzeigeoptionen, die die Präsentation in Vorlesungen oder ähnlichen Veranstaltungen begünstigen. Dieser Modus ist zu finden unter 'Knuth Morris Pratt' => 'Beamermodus'. +Die Anzeige ist für die Auflösung 1024x768 optimiert und vergrößert die Elemente um den Faktor 1,5. Im Dokumentationsbereich wird die Perspektive 'Code' angezeigt. +Ist der Modus aktiv, so erscheint vor diesem Menüeintrag ein Häkchen. Um den Modus wieder auszuschalten, entfernen Sie einfach den Haken per Klick. + +\centerpic{kmp/beamermod}{0.5}{Der Beamermodus} +\bigskip +\subsection{Zyklus - Anzeige} +\label{sec:ZyklusAnzeige} + +Im Visualisierungsbereich der Phase 1 'Generierung der Verschiebetabelle' können optional die Zyklen angezeigt werden, setzen Sie dazu das Häkchen 'Zyklen' im Steuerungsbereich. Es werden maximal drei Zyklen gleichzeitig angezeigt. + +\centerpic{kmp/cycle}{0.5}{Beispiel für Zyklen} +\bigskip +\section{Legende} +\label{sec:Legende} + +\subsection{Elemente in der Phase 'Generierung der Verschiebetabelle'} +\label{sec:ElementeInDerPhaseGenerierungDerVerschiebetabelle} + +\bigskip +\centerpic{kmp/phase1screen_ex1}{0.5}{Beispiel für Phase 1} +\bigskip +\textit{Visualisierungsbereich}\newline +\textbf{Pfeil schwarz mit weißem 'P' }- Zeiger auf die Variable 'patpos', die Patternposition\newline +\textbf{Pfeil weiß mit schwarzem 'V' }- Zeiger auf die Variable 'VglInd', der Vergleichsindex\newline +\textbf{schwarzer Pfeil über der Tabelle }- die verglichenen Zeichen\newline +\textbf{gelber Hintergrund von Zellen} - Zellenkopf\newline +\textbf{schwarzer Rahmen um Zelle in der Zeile 'Index' }- aktuell kopierte Verschiebeinformation\newline +\textbf{roter Rahmen um Zellen }- negative boolesche Bedingung\newline +\textbf{lila Strich }- Zyklen, die im Pattern auftreten +\newline\newline +\textit{Schriftfarben}\newline +\textbf{blau} - aktuell geschriebene Verschiebeinformation (entspricht Zuweisungsstatement im Code)\newline +\textbf{rot} - die verglichenen Zeichen stimmen nicht überein (entspricht booleschem Statement im Code)\newline +\textbf{grün} - die verglichenen Zeichen stimmen überein (entspricht booleschem Statement im Code) + +\subsection{Elemente in der Phase 'Suchen im Suchtext'} +\label{sec:ElementeInDerPhaseSuchenImSuchtext} + \bigskip +\centerpic{kmp/phase2screen_ex1}{0.5}{Beispiel für diese Phase} + \bigskip +\textit{Visualisierungsbereich}\newline +\textbf{lila Rahmen }- das Sichtfenster, welches die aktuell betrachteten Zeichen des Textes und des Patterns justiert +\newline\newline +\textit{Schriftfarben}\newline +\textbf{blau} - aktuell geschriebene Verschiebeinformation (entspricht Zuweisungsstatement im Code) + +\subsection{Im Dokumentationsbereich} +\label{sec:ImDokumentationsbereich} + +\bigskip +\centerpic{kmp/phase2screen_ex2}{0.5}{Beispiel für diese Phase} +\bigskip +\textit{Perspektive 'Code'}\newline +\textbf{roter Hintergrund }- negative boolesche Bedingung\newline +\textbf{grüner Hintergrund} - positive boolesche Bedingung\newline +\textbf{blauer Hintergrund }- sonstige Statements +\newline\newline +\textit{Perspektive 'Protokoll'}\newline +\textbf{blaue Schrift} - zuletzt vollzogener Schritt\newline +\textbf{schwarze Schrift} - für den aktuellen Stand irrelevante vorausgegangene Schritte +\newline\newline +\textit{Perspektive 'Suchtext'}\newline +\textbf{gelber Hintergrund} - der Textausschnitt, an dem das Pattern momentan anliegt diff --git a/doc/users_manual_german/modules/kmp/start.tex b/doc/users_manual_german/modules/kmp/start.tex new file mode 100644 index 0000000..24546f2 --- /dev/null +++ b/doc/users_manual_german/modules/kmp/start.tex @@ -0,0 +1,23 @@ +\section{Der Willkommensbildschirm} +\label{sec:DerWillkommensbildschirm} + +\subsection{Modul KMP starten} +\label{sec:ModulKMPStarten} + +Nach Starten des Hauptprogramms j-Algo können Sie über den Button 'Neu' oder mit dem Menüpunkt 'Datei' => 'Neu' eine neue Instanz des Moduls KMP öffnen. Anschließend öffnet sich der Willkommensbildschirm des Moduls, der Ihnen verschiedene Möglichkeiten eröffnet. + +\bigskip +\centerpic{kmp/welcomescreen}{0.5}{Der Willkommensbildschirm des Moduls} +\bigskip + +\subsectionicon{Generierung der Verschiebetabelle}{kmp/welcome_phaseone} +Mit Klick auf das erste Symbol gelangen Sie zur ersten Phase des KMP-Algorithmus, in dem für ein Pattern die Verschiebetabelle erstellt wird. + +\subsectionicon{ Suchen im Suchtext}{kmp/welcome_phasetwo} +Mit Klick auf das zweite Symbol gelangen Sie zur zweiten Phase des KMP-Algorithmus, in dem ein Text nach einem Pattern durchsucht wird. + +\subsectionicon{ Öffnen einer KMP-Sitzung}{kmp/welcome_open} +Mit Klick auf das Ordner-Symbol erhalten Sie die Möglichkeit, ein zuvor gespeichertes KMP-Beispiel zu laden ("*.jalgo" - Datei) + +\subsectionicon{ Präsentation von Lernbeispielen}{kmp/welcome_example} +Mit Klick auf das Tafel-Symbol erhalten Sie die Möglichkeit, anhand gegebener repräsentativer Lernbeispiele die Funktions- und Arbeitsweise des Algorithmus kennenzulernen. \ No newline at end of file diff --git a/doc/users_manual_german/pics/CVS/Entries b/doc/users_manual_german/pics/CVS/Entries new file mode 100644 index 0000000..a560f6d --- /dev/null +++ b/doc/users_manual_german/pics/CVS/Entries @@ -0,0 +1,6 @@ +D/am0c0//// +D/avl//// +D/dijkstra//// +D/ebnf//// +D/kmp//// +D/main//// diff --git a/doc/users_manual_german/pics/CVS/Repository b/doc/users_manual_german/pics/CVS/Repository new file mode 100644 index 0000000..17aaae0 --- /dev/null +++ b/doc/users_manual_german/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics diff --git a/doc/users_manual_german/pics/CVS/Root b/doc/users_manual_german/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/avl/12345.png b/doc/users_manual_german/pics/avl/12345.png new file mode 100644 index 0000000..4b5beb3 Binary files /dev/null and b/doc/users_manual_german/pics/avl/12345.png differ diff --git a/doc/users_manual_german/pics/avl/CVS/Entries b/doc/users_manual_german/pics/avl/CVS/Entries new file mode 100644 index 0000000..8109048 --- /dev/null +++ b/doc/users_manual_german/pics/avl/CVS/Entries @@ -0,0 +1,30 @@ +/12345.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/animregler.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/avlbsp.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/avltest.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/beamermenu.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/bsp_suchbaum.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/clearmessage.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/cleartreemessage.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/icon_abort.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_beamer.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_clear.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_finish.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_help.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_perform.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_perform_blockstep.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_undo.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_undo_blockstep.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/logo.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/navigator1.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/navigator2.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/prgmscreen.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/remove.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/rgd.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/rotateleft.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/rotateright.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/vollerbaum.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/welcome_load.png/1.1/Tue Oct 11 09:08:14 2005/-kb/ +/welcome_manual.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/welcome_random.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/welcomscreen.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ diff --git a/doc/users_manual_german/pics/avl/CVS/Repository b/doc/users_manual_german/pics/avl/CVS/Repository new file mode 100644 index 0000000..7db0d90 --- /dev/null +++ b/doc/users_manual_german/pics/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics/avl diff --git a/doc/users_manual_german/pics/avl/CVS/Root b/doc/users_manual_german/pics/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/avl/animregler.png b/doc/users_manual_german/pics/avl/animregler.png new file mode 100644 index 0000000..162001e Binary files /dev/null and b/doc/users_manual_german/pics/avl/animregler.png differ diff --git a/doc/users_manual_german/pics/avl/avlbsp.png b/doc/users_manual_german/pics/avl/avlbsp.png new file mode 100644 index 0000000..123659a Binary files /dev/null and b/doc/users_manual_german/pics/avl/avlbsp.png differ diff --git a/doc/users_manual_german/pics/avl/avltest.png b/doc/users_manual_german/pics/avl/avltest.png new file mode 100644 index 0000000..f596114 Binary files /dev/null and b/doc/users_manual_german/pics/avl/avltest.png differ diff --git a/doc/users_manual_german/pics/avl/beamermenu.png b/doc/users_manual_german/pics/avl/beamermenu.png new file mode 100644 index 0000000..c3875af Binary files /dev/null and b/doc/users_manual_german/pics/avl/beamermenu.png differ diff --git a/doc/users_manual_german/pics/avl/bsp_suchbaum.png b/doc/users_manual_german/pics/avl/bsp_suchbaum.png new file mode 100644 index 0000000..a55cbc0 Binary files /dev/null and b/doc/users_manual_german/pics/avl/bsp_suchbaum.png differ diff --git a/doc/users_manual_german/pics/avl/clearmessage.png b/doc/users_manual_german/pics/avl/clearmessage.png new file mode 100644 index 0000000..02e8533 Binary files /dev/null and b/doc/users_manual_german/pics/avl/clearmessage.png differ diff --git a/doc/users_manual_german/pics/avl/cleartreemessage.png b/doc/users_manual_german/pics/avl/cleartreemessage.png new file mode 100644 index 0000000..6045700 Binary files /dev/null and b/doc/users_manual_german/pics/avl/cleartreemessage.png differ diff --git a/doc/users_manual_german/pics/avl/icon_abort.png b/doc/users_manual_german/pics/avl/icon_abort.png new file mode 100644 index 0000000..61936b1 Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_abort.png differ diff --git a/doc/users_manual_german/pics/avl/icon_beamer.png b/doc/users_manual_german/pics/avl/icon_beamer.png new file mode 100644 index 0000000..940fa9a Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_beamer.png differ diff --git a/doc/users_manual_german/pics/avl/icon_clear.png b/doc/users_manual_german/pics/avl/icon_clear.png new file mode 100644 index 0000000..5cd2c07 Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_clear.png differ diff --git a/doc/users_manual_german/pics/avl/icon_finish.png b/doc/users_manual_german/pics/avl/icon_finish.png new file mode 100644 index 0000000..d2ae071 Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_finish.png differ diff --git a/doc/users_manual_german/pics/avl/icon_help.png b/doc/users_manual_german/pics/avl/icon_help.png new file mode 100644 index 0000000..f33c88b Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_help.png differ diff --git a/doc/users_manual_german/pics/avl/icon_perform.png b/doc/users_manual_german/pics/avl/icon_perform.png new file mode 100644 index 0000000..8a8e922 Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_perform.png differ diff --git a/doc/users_manual_german/pics/avl/icon_perform_blockstep.png b/doc/users_manual_german/pics/avl/icon_perform_blockstep.png new file mode 100644 index 0000000..3b0b4be Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_perform_blockstep.png differ diff --git a/doc/users_manual_german/pics/avl/icon_undo.png b/doc/users_manual_german/pics/avl/icon_undo.png new file mode 100644 index 0000000..162e786 Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_undo.png differ diff --git a/doc/users_manual_german/pics/avl/icon_undo_blockstep.png b/doc/users_manual_german/pics/avl/icon_undo_blockstep.png new file mode 100644 index 0000000..e357d4d Binary files /dev/null and b/doc/users_manual_german/pics/avl/icon_undo_blockstep.png differ diff --git a/doc/users_manual_german/pics/avl/logo.png b/doc/users_manual_german/pics/avl/logo.png new file mode 100644 index 0000000..db1042a Binary files /dev/null and b/doc/users_manual_german/pics/avl/logo.png differ diff --git a/doc/users_manual_german/pics/avl/navigator1.png b/doc/users_manual_german/pics/avl/navigator1.png new file mode 100644 index 0000000..a385a83 Binary files /dev/null and b/doc/users_manual_german/pics/avl/navigator1.png differ diff --git a/doc/users_manual_german/pics/avl/navigator2.png b/doc/users_manual_german/pics/avl/navigator2.png new file mode 100644 index 0000000..7b2760b Binary files /dev/null and b/doc/users_manual_german/pics/avl/navigator2.png differ diff --git a/doc/users_manual_german/pics/avl/prgmscreen.png b/doc/users_manual_german/pics/avl/prgmscreen.png new file mode 100644 index 0000000..b002040 Binary files /dev/null and b/doc/users_manual_german/pics/avl/prgmscreen.png differ diff --git a/doc/users_manual_german/pics/avl/remove.png b/doc/users_manual_german/pics/avl/remove.png new file mode 100644 index 0000000..2e9932e Binary files /dev/null and b/doc/users_manual_german/pics/avl/remove.png differ diff --git a/doc/users_manual_german/pics/avl/rgd.png b/doc/users_manual_german/pics/avl/rgd.png new file mode 100644 index 0000000..010b958 Binary files /dev/null and b/doc/users_manual_german/pics/avl/rgd.png differ diff --git a/doc/users_manual_german/pics/avl/rotateleft.png b/doc/users_manual_german/pics/avl/rotateleft.png new file mode 100644 index 0000000..fbb963f Binary files /dev/null and b/doc/users_manual_german/pics/avl/rotateleft.png differ diff --git a/doc/users_manual_german/pics/avl/rotateright.png b/doc/users_manual_german/pics/avl/rotateright.png new file mode 100644 index 0000000..ad41bf7 Binary files /dev/null and b/doc/users_manual_german/pics/avl/rotateright.png differ diff --git a/doc/users_manual_german/pics/avl/vollerbaum.png b/doc/users_manual_german/pics/avl/vollerbaum.png new file mode 100644 index 0000000..72ce2f2 Binary files /dev/null and b/doc/users_manual_german/pics/avl/vollerbaum.png differ diff --git a/doc/users_manual_german/pics/avl/welcome_load.png b/doc/users_manual_german/pics/avl/welcome_load.png new file mode 100644 index 0000000..9c1babb Binary files /dev/null and b/doc/users_manual_german/pics/avl/welcome_load.png differ diff --git a/doc/users_manual_german/pics/avl/welcome_manual.png b/doc/users_manual_german/pics/avl/welcome_manual.png new file mode 100644 index 0000000..393ab48 Binary files /dev/null and b/doc/users_manual_german/pics/avl/welcome_manual.png differ diff --git a/doc/users_manual_german/pics/avl/welcome_random.png b/doc/users_manual_german/pics/avl/welcome_random.png new file mode 100644 index 0000000..ab320e9 Binary files /dev/null and b/doc/users_manual_german/pics/avl/welcome_random.png differ diff --git a/doc/users_manual_german/pics/avl/welcomscreen.png b/doc/users_manual_german/pics/avl/welcomscreen.png new file mode 100644 index 0000000..d5ef077 Binary files /dev/null and b/doc/users_manual_german/pics/avl/welcomscreen.png differ diff --git a/doc/users_manual_german/pics/dijkstra/CVS/Entries b/doc/users_manual_german/pics/dijkstra/CVS/Entries new file mode 100644 index 0000000..5144824 --- /dev/null +++ b/doc/users_manual_german/pics/dijkstra/CVS/Entries @@ -0,0 +1,2 @@ +/edit.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/run.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ diff --git a/doc/users_manual_german/pics/dijkstra/CVS/Repository b/doc/users_manual_german/pics/dijkstra/CVS/Repository new file mode 100644 index 0000000..b56d45c --- /dev/null +++ b/doc/users_manual_german/pics/dijkstra/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics/dijkstra diff --git a/doc/users_manual_german/pics/dijkstra/CVS/Root b/doc/users_manual_german/pics/dijkstra/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/dijkstra/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/dijkstra/edit.png b/doc/users_manual_german/pics/dijkstra/edit.png new file mode 100644 index 0000000..7192413 Binary files /dev/null and b/doc/users_manual_german/pics/dijkstra/edit.png differ diff --git a/doc/users_manual_german/pics/dijkstra/run.png b/doc/users_manual_german/pics/dijkstra/run.png new file mode 100644 index 0000000..bd8fad2 Binary files /dev/null and b/doc/users_manual_german/pics/dijkstra/run.png differ diff --git a/doc/users_manual_german/pics/ebnf/CVS/Entries b/doc/users_manual_german/pics/ebnf/CVS/Entries new file mode 100644 index 0000000..2be7e23 --- /dev/null +++ b/doc/users_manual_german/pics/ebnf/CVS/Entries @@ -0,0 +1,63 @@ +/ebnfdisplay_full.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfdisplay_keepbinary.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfdisplay_makebinary.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfdisplay_transbutton.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_addrule.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_addterminal.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_addvariable.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_buttons.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_delrule.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_delterminal.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_delvariable.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_editrule.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_editterminal.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_editvar.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_full.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_popup_startvar.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/ebnfinput_setstartvar.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/ebnfinput_unknownsymbol.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/editebnf.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/editsyndia.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/load.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/logo.gif/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/redo.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_dot.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_frame.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_full.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_keller.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_mouseoverexit.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_mouseoverline.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_terminal.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/rs_variable.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/rs_variable_keller.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/savebuttons.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/savedialog.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/savemenu.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_Button_OK.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_Edit.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_NeuesDiagramm.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_Radiergummi.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_Terminal.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_Variable.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_Leiste_Verzweigung.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Leiste_Wiederholung.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_Popup_Edit.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_Popup_Radiergummi.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Popup_Terminal.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Popup_Variable.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Popup_Verzweigung.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/syndia_Popup_Wiederholung.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_aufteilung.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_startdiagramm.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/syndia_view.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/trans_finish.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/trans_fit.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/trans_gui.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/trans_info.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/trans_last.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/trans_next.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/trans_reset.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/trans_resize.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/trans_stairs.png/1.1/Sat Aug 12 20:59:33 2006/-kb/ +/undo.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ +/welcome.png/1.1/Sat Aug 12 20:59:34 2006/-kb/ diff --git a/doc/users_manual_german/pics/ebnf/CVS/Repository b/doc/users_manual_german/pics/ebnf/CVS/Repository new file mode 100644 index 0000000..2f46b38 --- /dev/null +++ b/doc/users_manual_german/pics/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics/ebnf diff --git a/doc/users_manual_german/pics/ebnf/CVS/Root b/doc/users_manual_german/pics/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/ebnf/ebnfdisplay_full.png b/doc/users_manual_german/pics/ebnf/ebnfdisplay_full.png new file mode 100644 index 0000000..859c5c9 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfdisplay_full.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfdisplay_keepbinary.png b/doc/users_manual_german/pics/ebnf/ebnfdisplay_keepbinary.png new file mode 100644 index 0000000..8c74a44 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfdisplay_keepbinary.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfdisplay_makebinary.png b/doc/users_manual_german/pics/ebnf/ebnfdisplay_makebinary.png new file mode 100644 index 0000000..45723e0 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfdisplay_makebinary.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfdisplay_transbutton.png b/doc/users_manual_german/pics/ebnf/ebnfdisplay_transbutton.png new file mode 100644 index 0000000..bfd8bde Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfdisplay_transbutton.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_addrule.png b/doc/users_manual_german/pics/ebnf/ebnfinput_addrule.png new file mode 100644 index 0000000..ffefd95 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_addrule.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_addterminal.png b/doc/users_manual_german/pics/ebnf/ebnfinput_addterminal.png new file mode 100644 index 0000000..32b5404 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_addterminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_addvariable.png b/doc/users_manual_german/pics/ebnf/ebnfinput_addvariable.png new file mode 100644 index 0000000..7b71403 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_addvariable.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_buttons.png b/doc/users_manual_german/pics/ebnf/ebnfinput_buttons.png new file mode 100644 index 0000000..c48c86d Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_buttons.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_delrule.png b/doc/users_manual_german/pics/ebnf/ebnfinput_delrule.png new file mode 100644 index 0000000..b050754 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_delrule.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_delterminal.png b/doc/users_manual_german/pics/ebnf/ebnfinput_delterminal.png new file mode 100644 index 0000000..9290f98 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_delterminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_delvariable.png b/doc/users_manual_german/pics/ebnf/ebnfinput_delvariable.png new file mode 100644 index 0000000..ecd42c7 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_delvariable.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_editrule.png b/doc/users_manual_german/pics/ebnf/ebnfinput_editrule.png new file mode 100644 index 0000000..33179fc Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_editrule.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_editterminal.png b/doc/users_manual_german/pics/ebnf/ebnfinput_editterminal.png new file mode 100644 index 0000000..4cc14e4 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_editterminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_editvar.png b/doc/users_manual_german/pics/ebnf/ebnfinput_editvar.png new file mode 100644 index 0000000..67053d2 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_editvar.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_full.png b/doc/users_manual_german/pics/ebnf/ebnfinput_full.png new file mode 100644 index 0000000..ae120b1 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_full.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_popup_startvar.png b/doc/users_manual_german/pics/ebnf/ebnfinput_popup_startvar.png new file mode 100644 index 0000000..256b295 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_popup_startvar.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_setstartvar.png b/doc/users_manual_german/pics/ebnf/ebnfinput_setstartvar.png new file mode 100644 index 0000000..a0b4cb5 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_setstartvar.png differ diff --git a/doc/users_manual_german/pics/ebnf/ebnfinput_unknownsymbol.png b/doc/users_manual_german/pics/ebnf/ebnfinput_unknownsymbol.png new file mode 100644 index 0000000..cadb60c Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/ebnfinput_unknownsymbol.png differ diff --git a/doc/users_manual_german/pics/ebnf/editebnf.png b/doc/users_manual_german/pics/ebnf/editebnf.png new file mode 100644 index 0000000..89a2d2b Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/editebnf.png differ diff --git a/doc/users_manual_german/pics/ebnf/editsyndia.png b/doc/users_manual_german/pics/ebnf/editsyndia.png new file mode 100644 index 0000000..e0d2b48 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/editsyndia.png differ diff --git a/doc/users_manual_german/pics/ebnf/load.png b/doc/users_manual_german/pics/ebnf/load.png new file mode 100644 index 0000000..46a021e Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/load.png differ diff --git a/doc/users_manual_german/pics/ebnf/logo.gif b/doc/users_manual_german/pics/ebnf/logo.gif new file mode 100644 index 0000000..46777a3 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/logo.gif differ diff --git a/doc/users_manual_german/pics/ebnf/redo.png b/doc/users_manual_german/pics/ebnf/redo.png new file mode 100644 index 0000000..cad5710 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/redo.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_dot.png b/doc/users_manual_german/pics/ebnf/rs_dot.png new file mode 100644 index 0000000..63a95d8 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_dot.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_frame.png b/doc/users_manual_german/pics/ebnf/rs_frame.png new file mode 100644 index 0000000..ec87dfe Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_frame.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_full.png b/doc/users_manual_german/pics/ebnf/rs_full.png new file mode 100644 index 0000000..1bd343e Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_full.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_keller.png b/doc/users_manual_german/pics/ebnf/rs_keller.png new file mode 100644 index 0000000..21c8678 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_keller.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_mouseoverexit.png b/doc/users_manual_german/pics/ebnf/rs_mouseoverexit.png new file mode 100644 index 0000000..a6275a9 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_mouseoverexit.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_mouseoverline.png b/doc/users_manual_german/pics/ebnf/rs_mouseoverline.png new file mode 100644 index 0000000..8a889ea Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_mouseoverline.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_terminal.png b/doc/users_manual_german/pics/ebnf/rs_terminal.png new file mode 100644 index 0000000..e4c1ee4 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_terminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_variable.png b/doc/users_manual_german/pics/ebnf/rs_variable.png new file mode 100644 index 0000000..369880a Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_variable.png differ diff --git a/doc/users_manual_german/pics/ebnf/rs_variable_keller.png b/doc/users_manual_german/pics/ebnf/rs_variable_keller.png new file mode 100644 index 0000000..e6a65a9 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/rs_variable_keller.png differ diff --git a/doc/users_manual_german/pics/ebnf/savebuttons.png b/doc/users_manual_german/pics/ebnf/savebuttons.png new file mode 100644 index 0000000..d3186a9 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/savebuttons.png differ diff --git a/doc/users_manual_german/pics/ebnf/savedialog.png b/doc/users_manual_german/pics/ebnf/savedialog.png new file mode 100644 index 0000000..c959684 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/savedialog.png differ diff --git a/doc/users_manual_german/pics/ebnf/savemenu.png b/doc/users_manual_german/pics/ebnf/savemenu.png new file mode 100644 index 0000000..b401304 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/savemenu.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Button_OK.png b/doc/users_manual_german/pics/ebnf/syndia_Button_OK.png new file mode 100644 index 0000000..21b6ea3 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Button_OK.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Edit.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Edit.png new file mode 100644 index 0000000..64e5a9c Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Edit.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_NeuesDiagramm.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_NeuesDiagramm.png new file mode 100644 index 0000000..4617dca Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_NeuesDiagramm.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Radiergummi.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Radiergummi.png new file mode 100644 index 0000000..4d7c05c Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Radiergummi.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Terminal.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Terminal.png new file mode 100644 index 0000000..3474e03 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Terminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Variable.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Variable.png new file mode 100644 index 0000000..e3e5727 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Variable.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Verzweigung.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Verzweigung.png new file mode 100644 index 0000000..5cdadb2 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Verzweigung.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Leiste_Wiederholung.png b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Wiederholung.png new file mode 100644 index 0000000..bb4a7e4 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Leiste_Wiederholung.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Edit.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Edit.png new file mode 100644 index 0000000..6123b47 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Edit.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Radiergummi.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Radiergummi.png new file mode 100644 index 0000000..1aca702 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Radiergummi.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Terminal.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Terminal.png new file mode 100644 index 0000000..64c6abc Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Terminal.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Variable.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Variable.png new file mode 100644 index 0000000..c22b544 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Variable.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Verzweigung.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Verzweigung.png new file mode 100644 index 0000000..34c7924 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Verzweigung.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_Popup_Wiederholung.png b/doc/users_manual_german/pics/ebnf/syndia_Popup_Wiederholung.png new file mode 100644 index 0000000..d547aa8 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_Popup_Wiederholung.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_aufteilung.png b/doc/users_manual_german/pics/ebnf/syndia_aufteilung.png new file mode 100644 index 0000000..f796108 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_aufteilung.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_startdiagramm.png b/doc/users_manual_german/pics/ebnf/syndia_startdiagramm.png new file mode 100644 index 0000000..1a46879 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_startdiagramm.png differ diff --git a/doc/users_manual_german/pics/ebnf/syndia_view.png b/doc/users_manual_german/pics/ebnf/syndia_view.png new file mode 100644 index 0000000..d052a6d Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/syndia_view.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_finish.png b/doc/users_manual_german/pics/ebnf/trans_finish.png new file mode 100644 index 0000000..7225b1c Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_finish.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_fit.png b/doc/users_manual_german/pics/ebnf/trans_fit.png new file mode 100644 index 0000000..6909be3 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_fit.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_gui.png b/doc/users_manual_german/pics/ebnf/trans_gui.png new file mode 100644 index 0000000..b314d2f Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_gui.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_info.png b/doc/users_manual_german/pics/ebnf/trans_info.png new file mode 100644 index 0000000..d58a8d2 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_info.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_last.png b/doc/users_manual_german/pics/ebnf/trans_last.png new file mode 100644 index 0000000..0386234 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_last.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_next.png b/doc/users_manual_german/pics/ebnf/trans_next.png new file mode 100644 index 0000000..8960b75 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_next.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_reset.png b/doc/users_manual_german/pics/ebnf/trans_reset.png new file mode 100644 index 0000000..aac9caa Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_reset.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_resize.png b/doc/users_manual_german/pics/ebnf/trans_resize.png new file mode 100644 index 0000000..2c3ecbf Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_resize.png differ diff --git a/doc/users_manual_german/pics/ebnf/trans_stairs.png b/doc/users_manual_german/pics/ebnf/trans_stairs.png new file mode 100644 index 0000000..784c899 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/trans_stairs.png differ diff --git a/doc/users_manual_german/pics/ebnf/undo.png b/doc/users_manual_german/pics/ebnf/undo.png new file mode 100644 index 0000000..0fcefa7 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/undo.png differ diff --git a/doc/users_manual_german/pics/ebnf/welcome.png b/doc/users_manual_german/pics/ebnf/welcome.png new file mode 100644 index 0000000..32165f6 Binary files /dev/null and b/doc/users_manual_german/pics/ebnf/welcome.png differ diff --git a/doc/users_manual_german/pics/kmp/CVS/Entries b/doc/users_manual_german/pics/kmp/CVS/Entries new file mode 100644 index 0000000..6952326 --- /dev/null +++ b/doc/users_manual_german/pics/kmp/CVS/Entries @@ -0,0 +1,28 @@ +/beamermod.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/control.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/cycle.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/endnegativ.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/endpositiv.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/expand.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/go_p2.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/learning.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/load.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/logo_help.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/move.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/pattern.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/pattern1.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/pattern2.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/pattern3.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/phase1screen.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/phase1screen_ex1.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/phase2screen_ex1.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/phase2screen_ex2.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/slide.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/text1.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/text2.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/text3.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/welcome_example.png/1.2/Sat Aug 12 20:14:06 2006/-kb/ +/welcome_open.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ +/welcome_phaseone.png/1.2/Sat Aug 12 20:14:06 2006/-kb/ +/welcome_phasetwo.png/1.2/Sat Aug 12 20:14:06 2006/-kb/ +/welcomescreen.png/1.1/Fri Jun 30 14:39:08 2006/-kb/ diff --git a/doc/users_manual_german/pics/kmp/CVS/Repository b/doc/users_manual_german/pics/kmp/CVS/Repository new file mode 100644 index 0000000..6962d97 --- /dev/null +++ b/doc/users_manual_german/pics/kmp/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics/kmp diff --git a/doc/users_manual_german/pics/kmp/CVS/Root b/doc/users_manual_german/pics/kmp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/kmp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/kmp/beamermod.png b/doc/users_manual_german/pics/kmp/beamermod.png new file mode 100644 index 0000000..9bee223 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/beamermod.png differ diff --git a/doc/users_manual_german/pics/kmp/control.png b/doc/users_manual_german/pics/kmp/control.png new file mode 100644 index 0000000..996ce01 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/control.png differ diff --git a/doc/users_manual_german/pics/kmp/cycle.png b/doc/users_manual_german/pics/kmp/cycle.png new file mode 100644 index 0000000..69c57d5 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/cycle.png differ diff --git a/doc/users_manual_german/pics/kmp/endnegativ.png b/doc/users_manual_german/pics/kmp/endnegativ.png new file mode 100644 index 0000000..33391e1 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/endnegativ.png differ diff --git a/doc/users_manual_german/pics/kmp/endpositiv.png b/doc/users_manual_german/pics/kmp/endpositiv.png new file mode 100644 index 0000000..3ce178a Binary files /dev/null and b/doc/users_manual_german/pics/kmp/endpositiv.png differ diff --git a/doc/users_manual_german/pics/kmp/expand.png b/doc/users_manual_german/pics/kmp/expand.png new file mode 100644 index 0000000..d297a17 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/expand.png differ diff --git a/doc/users_manual_german/pics/kmp/go_p2.png b/doc/users_manual_german/pics/kmp/go_p2.png new file mode 100644 index 0000000..4b33c76 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/go_p2.png differ diff --git a/doc/users_manual_german/pics/kmp/learning.png b/doc/users_manual_german/pics/kmp/learning.png new file mode 100644 index 0000000..6d4bb51 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/learning.png differ diff --git a/doc/users_manual_german/pics/kmp/load.png b/doc/users_manual_german/pics/kmp/load.png new file mode 100644 index 0000000..ef8ca9a Binary files /dev/null and b/doc/users_manual_german/pics/kmp/load.png differ diff --git a/doc/users_manual_german/pics/kmp/logo_help.png b/doc/users_manual_german/pics/kmp/logo_help.png new file mode 100644 index 0000000..97560c8 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/logo_help.png differ diff --git a/doc/users_manual_german/pics/kmp/move.png b/doc/users_manual_german/pics/kmp/move.png new file mode 100644 index 0000000..ca5b8cc Binary files /dev/null and b/doc/users_manual_german/pics/kmp/move.png differ diff --git a/doc/users_manual_german/pics/kmp/pattern.png b/doc/users_manual_german/pics/kmp/pattern.png new file mode 100644 index 0000000..497b95f Binary files /dev/null and b/doc/users_manual_german/pics/kmp/pattern.png differ diff --git a/doc/users_manual_german/pics/kmp/pattern1.png b/doc/users_manual_german/pics/kmp/pattern1.png new file mode 100644 index 0000000..c2ced05 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/pattern1.png differ diff --git a/doc/users_manual_german/pics/kmp/pattern2.png b/doc/users_manual_german/pics/kmp/pattern2.png new file mode 100644 index 0000000..497b95f Binary files /dev/null and b/doc/users_manual_german/pics/kmp/pattern2.png differ diff --git a/doc/users_manual_german/pics/kmp/pattern3.png b/doc/users_manual_german/pics/kmp/pattern3.png new file mode 100644 index 0000000..a11fb16 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/pattern3.png differ diff --git a/doc/users_manual_german/pics/kmp/phase1screen.png b/doc/users_manual_german/pics/kmp/phase1screen.png new file mode 100644 index 0000000..d3131a0 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/phase1screen.png differ diff --git a/doc/users_manual_german/pics/kmp/phase1screen_ex1.png b/doc/users_manual_german/pics/kmp/phase1screen_ex1.png new file mode 100644 index 0000000..e050f8c Binary files /dev/null and b/doc/users_manual_german/pics/kmp/phase1screen_ex1.png differ diff --git a/doc/users_manual_german/pics/kmp/phase2screen_ex1.png b/doc/users_manual_german/pics/kmp/phase2screen_ex1.png new file mode 100644 index 0000000..6dd9000 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/phase2screen_ex1.png differ diff --git a/doc/users_manual_german/pics/kmp/phase2screen_ex2.png b/doc/users_manual_german/pics/kmp/phase2screen_ex2.png new file mode 100644 index 0000000..909534e Binary files /dev/null and b/doc/users_manual_german/pics/kmp/phase2screen_ex2.png differ diff --git a/doc/users_manual_german/pics/kmp/slide.png b/doc/users_manual_german/pics/kmp/slide.png new file mode 100644 index 0000000..3c2ec44 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/slide.png differ diff --git a/doc/users_manual_german/pics/kmp/text1.png b/doc/users_manual_german/pics/kmp/text1.png new file mode 100644 index 0000000..de2385b Binary files /dev/null and b/doc/users_manual_german/pics/kmp/text1.png differ diff --git a/doc/users_manual_german/pics/kmp/text2.png b/doc/users_manual_german/pics/kmp/text2.png new file mode 100644 index 0000000..234ac8a Binary files /dev/null and b/doc/users_manual_german/pics/kmp/text2.png differ diff --git a/doc/users_manual_german/pics/kmp/text3.png b/doc/users_manual_german/pics/kmp/text3.png new file mode 100644 index 0000000..e9699d8 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/text3.png differ diff --git a/doc/users_manual_german/pics/kmp/welcome_example.png b/doc/users_manual_german/pics/kmp/welcome_example.png new file mode 100644 index 0000000..e8f9ec0 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/welcome_example.png differ diff --git a/doc/users_manual_german/pics/kmp/welcome_open.png b/doc/users_manual_german/pics/kmp/welcome_open.png new file mode 100644 index 0000000..42d5fb1 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/welcome_open.png differ diff --git a/doc/users_manual_german/pics/kmp/welcome_phaseone.png b/doc/users_manual_german/pics/kmp/welcome_phaseone.png new file mode 100644 index 0000000..445bc68 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/welcome_phaseone.png differ diff --git a/doc/users_manual_german/pics/kmp/welcome_phasetwo.png b/doc/users_manual_german/pics/kmp/welcome_phasetwo.png new file mode 100644 index 0000000..92e32f4 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/welcome_phasetwo.png differ diff --git a/doc/users_manual_german/pics/kmp/welcomescreen.png b/doc/users_manual_german/pics/kmp/welcomescreen.png new file mode 100644 index 0000000..8023309 Binary files /dev/null and b/doc/users_manual_german/pics/kmp/welcomescreen.png differ diff --git a/doc/users_manual_german/pics/main/CVS/Entries b/doc/users_manual_german/pics/main/CVS/Entries new file mode 100644 index 0000000..fbb9184 --- /dev/null +++ b/doc/users_manual_german/pics/main/CVS/Entries @@ -0,0 +1,12 @@ +/choosedialog.png/1.1/Tue Mar 28 14:21:11 2006/-kb/ +/closebutton.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/closemessage.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_help.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_new.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_open.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_prefs.png/1.1/Tue Mar 28 14:21:11 2006/-kb/ +/icon_save.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/icon_save_as.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/loaddialog.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ +/prefsdialog.png/1.1/Tue Mar 28 14:21:11 2006/-kb/ +/title.png/1.1/Tue Oct 11 09:08:15 2005/-kb/ diff --git a/doc/users_manual_german/pics/main/CVS/Repository b/doc/users_manual_german/pics/main/CVS/Repository new file mode 100644 index 0000000..a111e11 --- /dev/null +++ b/doc/users_manual_german/pics/main/CVS/Repository @@ -0,0 +1 @@ +j-algo/doc/users_manual_german/pics/main diff --git a/doc/users_manual_german/pics/main/CVS/Root b/doc/users_manual_german/pics/main/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/doc/users_manual_german/pics/main/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/doc/users_manual_german/pics/main/choosedialog.png b/doc/users_manual_german/pics/main/choosedialog.png new file mode 100644 index 0000000..bec5aad Binary files /dev/null and b/doc/users_manual_german/pics/main/choosedialog.png differ diff --git a/doc/users_manual_german/pics/main/closebutton.png b/doc/users_manual_german/pics/main/closebutton.png new file mode 100644 index 0000000..9fec29f Binary files /dev/null and b/doc/users_manual_german/pics/main/closebutton.png differ diff --git a/doc/users_manual_german/pics/main/closemessage.png b/doc/users_manual_german/pics/main/closemessage.png new file mode 100644 index 0000000..ec71f4d Binary files /dev/null and b/doc/users_manual_german/pics/main/closemessage.png differ diff --git a/doc/users_manual_german/pics/main/icon_help.png b/doc/users_manual_german/pics/main/icon_help.png new file mode 100644 index 0000000..80f6a4c Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_help.png differ diff --git a/doc/users_manual_german/pics/main/icon_new.png b/doc/users_manual_german/pics/main/icon_new.png new file mode 100644 index 0000000..cd607c9 Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_new.png differ diff --git a/doc/users_manual_german/pics/main/icon_open.png b/doc/users_manual_german/pics/main/icon_open.png new file mode 100644 index 0000000..0e2a174 Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_open.png differ diff --git a/doc/users_manual_german/pics/main/icon_prefs.png b/doc/users_manual_german/pics/main/icon_prefs.png new file mode 100644 index 0000000..b523157 Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_prefs.png differ diff --git a/doc/users_manual_german/pics/main/icon_save.png b/doc/users_manual_german/pics/main/icon_save.png new file mode 100644 index 0000000..d74bc90 Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_save.png differ diff --git a/doc/users_manual_german/pics/main/icon_save_as.png b/doc/users_manual_german/pics/main/icon_save_as.png new file mode 100644 index 0000000..5626e75 Binary files /dev/null and b/doc/users_manual_german/pics/main/icon_save_as.png differ diff --git a/doc/users_manual_german/pics/main/loaddialog.png b/doc/users_manual_german/pics/main/loaddialog.png new file mode 100644 index 0000000..f999b71 Binary files /dev/null and b/doc/users_manual_german/pics/main/loaddialog.png differ diff --git a/doc/users_manual_german/pics/main/prefsdialog.png b/doc/users_manual_german/pics/main/prefsdialog.png new file mode 100644 index 0000000..9d8e584 Binary files /dev/null and b/doc/users_manual_german/pics/main/prefsdialog.png differ diff --git a/doc/users_manual_german/pics/main/title.png b/doc/users_manual_german/pics/main/title.png new file mode 100644 index 0000000..f7be70a Binary files /dev/null and b/doc/users_manual_german/pics/main/title.png differ diff --git a/doc/users_manual_german/users_manual_german.pdf b/doc/users_manual_german/users_manual_german.pdf new file mode 100644 index 0000000..e3e6ac7 Binary files /dev/null and b/doc/users_manual_german/users_manual_german.pdf differ diff --git a/doc/users_manual_german/users_manual_german.tex b/doc/users_manual_german/users_manual_german.tex new file mode 100644 index 0000000..5841717 --- /dev/null +++ b/doc/users_manual_german/users_manual_german.tex @@ -0,0 +1,104 @@ +\documentclass{scrbook} +\usepackage[ngerman]{babel} +\usepackage[T1]{fontenc} +\usepackage[ansinew]{inputenc} +\usepackage{a4wide} + +%verwenden von grafiken +\usepackage[dvipdf, final]{graphicx} + +%verwenden von hyperlinks, stil derselben +\usepackage{color} +\definecolor{darkblue}{rgb}{0,0,0.5} + +\usepackage{hyperref} +\hypersetup{ +% draft, %hyperlinks ausschalten + colorlinks, %hyperlinks farbig darstellen + linkcolor = darkblue, + filecolor = darkblue, + urlcolor = darkblue, + citecolor = darkblue, + pdftitle = {Handbuch}, %titel + pdfsubject = {j-Algo}, %thema + pdfauthor = {Alexander Claus, Matthias Schmidt}, + pdfkeywords = {Algorithmen, Visualisierung}, + pdfcreator = {Distiller}, + pdfproducer = {LaTeX mit Hyperref-Package}} + +%spezielle kommandos +%schreibweise des software-titels +\newcommand{\jalgo}{\mbox{\bfseries {\color{red}j}-Algo} } +%pfad zu den bildern +\newcommand{\pfad}{pics/} +%fügt ein bild an einer bestimmten stelle, relativ zur position des befehls, ein. +%usage: \icon{dateiname}{y-offset}{x-offset}{bildvergrößerung} +\newcommand{\icon}[4]{ + \vspace{#2 ex} + \hspace{#3 ex} + \includegraphics[scale=#4]{\pfad #1} +} +%fügt ein bild mittig mit bildunterschrift ein. +%usage: \centerpic{dateiname}{bildvergrößerung}{untertitel} +\newcommand{\centerpic}[3]{ + \begin{center} + \includegraphics[scale=#2]{\pfad #1}\\ + {\small #3} + \end{center} +} +%fügt eine \subsection mit einem führenden icon ein +%usage: \subsectionicon{text}{icon} +\newcommand{\subsectionicon}[2]{ + \subsection[#1]{\qquad #1} + \icon{#2}{-5}{7}{1} + \\ +} +%fügt eine \subsection mit 2 führenden icons ein +%usage: \subsectiondoubleicon{text}{icon1}{icon2} +\newcommand{\subsectiondoubleicon}[3]{ + \subsection[#1]{\qquad \quad #1} + \icon{#2}{-5}{7}{1} + \icon{#3}{0}{-2}{1} + \\ +} +%fügt eine \subsubsection* mit 2 führenden icons ein +%usage: \subsubsectiondoubleicon{text}{icon1}{icon2} +\newcommand{\subsubsectiondoubleicon}[3]{ + \subsubsection*{\qquad \qquad #1} + \icon{#2}{-4}{1}{1} + \icon{#3}{0}{-2}{1} + \\ +} + +\begin{document} + +\begin{titlepage} +\centerpic{main/title}{1}{} +\vfill +\begin{flushright} +{\Huge \textbf{Benutzerhandbuch}} +\end{flushright} +\end{titlepage} + +\newpage + +\tableofcontents +\newpage + +\part{Das Hauptprogramm} +\input{main/overview} +\input{main/basics} +\input{main/imprint} + +\part{Die Module} +\input{modules/avl/contents} +\input{modules/dijkstra/contents} +\input{modules/kmp/contents} +\input{modules/ebnf/contents} + +\part{Der Anhang} +\begin{appendix} +\input{modules/avl/appendix} +\end{appendix} + +\end{document} \ No newline at end of file diff --git a/err.log b/err.log new file mode 100644 index 0000000..e69de29 diff --git a/examples/CVS/Entries b/examples/CVS/Entries new file mode 100644 index 0000000..f5691e4 --- /dev/null +++ b/examples/CVS/Entries @@ -0,0 +1,14 @@ +D/am0c0//// +D/am1simulator//// +D/app//// +D/avl//// +D/bfsdfs//// +D/c0h0//// +D/dijkstra//// +D/ebnf//// +D/em//// +D/heapsort//// +D/hoare//// +D/kmp//// +D/pulsemem//// +D/unifikation//// diff --git a/examples/CVS/Repository b/examples/CVS/Repository new file mode 100644 index 0000000..f22cdf2 --- /dev/null +++ b/examples/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples diff --git a/examples/CVS/Root b/examples/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/am0c0/12.10b.am0 b/examples/am0c0/12.10b.am0 new file mode 100644 index 0000000..d476201 --- /dev/null +++ b/examples/am0c0/12.10b.am0 @@ -0,0 +1,9 @@ +READ 1; +READ 2; +LOAD 1; +LOAD 2; +LIT 0; +SUB; +JMC 9; +JMP 5; +WRITE 2; diff --git a/examples/am0c0/12.4b.am0 b/examples/am0c0/12.4b.am0 new file mode 100644 index 0000000..e4a5ff4 --- /dev/null +++ b/examples/am0c0/12.4b.am0 @@ -0,0 +1,5 @@ +LIT 1; +LIT 0; +LIT 0; +ADD; +JMC 3; diff --git a/examples/am0c0/12.5b.am0 b/examples/am0c0/12.5b.am0 new file mode 100644 index 0000000..60a61ed --- /dev/null +++ b/examples/am0c0/12.5b.am0 @@ -0,0 +1,17 @@ +READ 1; +LIT 1; +STORE 2; +LOAD 1; +LIT 1; +GT; +JMC 17; +LOAD 2; +LOAD 1; +MUL; +STORE 2; +LOAD 1; +LIT 1; +SUB; +STORE 1; +JMP 4; +WRITE 2; diff --git a/examples/am0c0/12.6b.am0 b/examples/am0c0/12.6b.am0 new file mode 100644 index 0000000..f1b8893 --- /dev/null +++ b/examples/am0c0/12.6b.am0 @@ -0,0 +1,17 @@ +LIT 0; +STORE 2; +READ 1; +LOAD 1; +LIT 0; +GT; +JMC 17; +LOAD 1; +LIT 2; +SUB; +STORE 1; +LOAD 2; +LIT 1; +ADD; +STORE 2; +JMP 4; +WRITE 2; diff --git a/examples/am0c0/12.9b.am0 b/examples/am0c0/12.9b.am0 new file mode 100644 index 0000000..8664e03 --- /dev/null +++ b/examples/am0c0/12.9b.am0 @@ -0,0 +1,17 @@ +READ 2; +LIT 0; +STORE 1; +LOAD 2; +LIT 0; +GT; +JMC 17; +LOAD 2; +LIT 1; +SUB; +STORE 2; +LOAD 1; +LIT 1; +ADD; +STORE 1; +JMP 4; +WRITE 1; diff --git a/examples/am0c0/AM0_testprogramm.am0 b/examples/am0c0/AM0_testprogramm.am0 new file mode 100644 index 0000000..c644985 --- /dev/null +++ b/examples/am0c0/AM0_testprogramm.am0 @@ -0,0 +1,21 @@ +READ 2; +LIT 1; +STORE 1; +LIT 0; +STORE 3; +LOAD 1; +LOAD 2; +LE; +JMC 21; +LOAD 3; +LOAD 1; +LOAD 1; +MUL; +ADD; +STORE 3; +LOAD 1; +LIT 1; +ADD; +STORE 1; +JMP 6; +WRITE 3; diff --git a/examples/am0c0/CVS/Entries b/examples/am0c0/CVS/Entries new file mode 100644 index 0000000..bfff884 --- /dev/null +++ b/examples/am0c0/CVS/Entries @@ -0,0 +1,17 @@ +/12.10b.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/12.4b.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/12.5b.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/12.6b.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/12.9b.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/AM0_testprogramm.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/addlist.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/div2.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/exp.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/ggT.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/invalid01.am0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/invalid01.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/max.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/operation1.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/prog.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/progK.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/summation.c0/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/examples/am0c0/CVS/Repository b/examples/am0c0/CVS/Repository new file mode 100644 index 0000000..c7e9409 --- /dev/null +++ b/examples/am0c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/am0c0 diff --git a/examples/am0c0/CVS/Root b/examples/am0c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/am0c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/am0c0/addlist.c0 b/examples/am0c0/addlist.c0 new file mode 100644 index 0000000..21cba12 --- /dev/null +++ b/examples/am0c0/addlist.c0 @@ -0,0 +1,17 @@ +/* AddList */ +#include + +int main() { + int a, b, sum; + sum = 0; + scanf("%i", &a); + if (a < 0) + a = 0; + while (a > 0) { + scanf("%i", &b); + sum = sum + b; + a = a - 1; + } + printf("%d", sum); + return 0; +} diff --git a/examples/am0c0/div2.c0 b/examples/am0c0/div2.c0 new file mode 100644 index 0000000..79d645b --- /dev/null +++ b/examples/am0c0/div2.c0 @@ -0,0 +1,14 @@ +/* Div2 */ +#include + +int main() { + int x, y; + scanf("%i", &x); + y = 0; + while (x > 0) { + if (x / 2 * 2 == x) y = y + 1; + x = x - 1; + } + printf("%d", y); + return 0; +} diff --git a/examples/am0c0/exp.c0 b/examples/am0c0/exp.c0 new file mode 100644 index 0000000..5096173 --- /dev/null +++ b/examples/am0c0/exp.c0 @@ -0,0 +1,14 @@ +/* exp */ +#include + +int main() { + int x, y; + y = 1; + scanf("%i", &x); + while (x > 0) { + x = x - 1; + y = y * 2; + } + printf("%d", y); + return 0; +} diff --git a/examples/am0c0/ggT.c0 b/examples/am0c0/ggT.c0 new file mode 100644 index 0000000..7f1a3ab --- /dev/null +++ b/examples/am0c0/ggT.c0 @@ -0,0 +1,17 @@ +/* ggT - Klausuraufgabe */ +#include + +int main() { + int a, b, h; + scanf("%i", &a); + scanf("%i", &b); + if (b > 0) { + while (b > 0) { + h = a % b; + a = b; + b = h; + } + printf("%d", a); + } + return 0; +} diff --git a/examples/am0c0/invalid01.am0 b/examples/am0c0/invalid01.am0 new file mode 100644 index 0000000..2f7cb2d --- /dev/null +++ b/examples/am0c0/invalid01.am0 @@ -0,0 +1,17 @@ +READ 2; +LIT 0; +STORE 1; +LOAD 2; +LIT 0; +GT +JMC 17; +LOAD 2; +LIT 1; +SUB 1; +STORE 2222222222222222222222222222; +LOAD 1; +LIT 1; +ADD; +STORE 1; +JMP 4; +WRITE 1 \ No newline at end of file diff --git a/examples/am0c0/invalid01.c0 b/examples/am0c0/invalid01.c0 new file mode 100644 index 0000000..5e4976a --- /dev/null +++ b/examples/am0c0/invalid01.c0 @@ -0,0 +1,23 @@ +/* Invalides C0-Programm / invalid C0 program */ +#include + +int main() +{ + int i, n, s; + + scanf("%i", n); + + i = 1; + s = 0; + nd = 123456789012345; + + while (i <= n) + { + s = s + i * i; + i = i + 1; + } + + printf("%d", s); + return 0; +} + diff --git a/examples/am0c0/max.c0 b/examples/am0c0/max.c0 new file mode 100644 index 0000000..7e95df4 --- /dev/null +++ b/examples/am0c0/max.c0 @@ -0,0 +1,12 @@ +/* Max */ +#include + +int main() { + int a, b, max; + scanf("%i", &a); + scanf("%i", &b); + if (a > b) max = a; + else max = b; + printf("%d", max); + return 0; +} diff --git a/examples/am0c0/operation1.c0 b/examples/am0c0/operation1.c0 new file mode 100644 index 0000000..e94a3f6 --- /dev/null +++ b/examples/am0c0/operation1.c0 @@ -0,0 +1,12 @@ +/* operation1 */ +#include + +int main() { + int x, y, z; + scanf("%i", &x); + scanf("%i", &y); + if (x < y) z = x; + else z = y; + printf("%d", z); + return 0; +} diff --git a/examples/am0c0/prog.c0 b/examples/am0c0/prog.c0 new file mode 100644 index 0000000..da351e5 --- /dev/null +++ b/examples/am0c0/prog.c0 @@ -0,0 +1,14 @@ +/* prog */ +#include + +int main() { + int x1, x2; + scanf("%i", &x1); + while (x1 > 0) { + x2 = x1; + while (x2 > 0) x2 = x2 - 1; + x1 = x1 - 1; + } + printf("%d", x1); + return 0; +} diff --git a/examples/am0c0/progK.c0 b/examples/am0c0/progK.c0 new file mode 100644 index 0000000..7965d16 --- /dev/null +++ b/examples/am0c0/progK.c0 @@ -0,0 +1,15 @@ +/* prog - Klausuraufgabe */ +#include + +int main() { + int x, y, z; + z = 1; + scanf("%i", &x); + scanf("%i", &y); + while (x > y) { + z = y * z; + x = x - 1; + } + printf("%d", z); + return 0; +} diff --git a/examples/am0c0/summation.c0 b/examples/am0c0/summation.c0 new file mode 100644 index 0000000..f4d5c7a --- /dev/null +++ b/examples/am0c0/summation.c0 @@ -0,0 +1,22 @@ +/* Summation */ +#include + +int main() +{ + int i, n, s; + + scanf("%i", &n); + + i = 1; + s = 0; + + while (i <= n) + { + s = s + i * i; + i = i + 1; + } + + printf("%d", s); + return 0; +} + diff --git a/examples/am1simulator/CVS/Entries b/examples/am1simulator/CVS/Entries new file mode 100644 index 0000000..a369dfc --- /dev/null +++ b/examples/am1simulator/CVS/Entries @@ -0,0 +1,3 @@ +/klausur_13.6.am1/1.1/Mon Mar 7 19:57:19 2011/-kb/ +/klausur_13.9.am1/1.1/Mon Mar 7 19:57:19 2011/-kb/ +/script_p_ 222.am1/1.1/Mon Mar 7 19:57:19 2011/-kb/ diff --git a/examples/am1simulator/CVS/Repository b/examples/am1simulator/CVS/Repository new file mode 100644 index 0000000..a33f105 --- /dev/null +++ b/examples/am1simulator/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/am1simulator diff --git a/examples/am1simulator/CVS/Root b/examples/am1simulator/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/am1simulator/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/am1simulator/klausur_13.6.am1 b/examples/am1simulator/klausur_13.6.am1 new file mode 100644 index 0000000..ef5b335 --- /dev/null +++ b/examples/am1simulator/klausur_13.6.am1 @@ -0,0 +1,18 @@ +INIT 1; +CALL 10; +JMP 0; +INIT 1; +LOAD(global,1); +STORE(lokal,1); +LIT 10; +STOREI(-2); +RET 1; +INIT 2; +READ(global,1); +LIT 2; +STORE(lokal,1); +LOADA(lokal,2); +PUSH; +CALL 4; +WRITE(lokal,2); +RET 0; diff --git a/examples/am1simulator/klausur_13.9.am1 b/examples/am1simulator/klausur_13.9.am1 new file mode 100644 index 0000000..d8d5243 --- /dev/null +++ b/examples/am1simulator/klausur_13.9.am1 @@ -0,0 +1,19 @@ +INIT 2; +CALL 10; +JMP 0; +INIT 1; +LOADI(-2); +STORE(global,2); +LIT 7; +STORE(lokal,1); +RET 1; +INIT 2; +READ(lokal,1); +LOAD(lokal,1); +STORE(global,1); +READ(lokal,2); +LOADA(lokal,2); +PUSH; +CALL 4; +WRITE(lokal,2); +RET 0; \ No newline at end of file diff --git a/examples/am1simulator/script_p_ 222.am1 b/examples/am1simulator/script_p_ 222.am1 new file mode 100644 index 0000000..8cd25a9 --- /dev/null +++ b/examples/am1simulator/script_p_ 222.am1 @@ -0,0 +1,32 @@ +INIT 2; +CALL 24; +JMP 0; +INIT 0; +LOAD(lokal,-3); +LIT 0; +GT; +JMC 21; +LOAD(lokal,-3); +LIT 1; +SUB; +PUSH; +LOAD(lokal,-2); +PUSH; +CALL 4; +LOADI(-2); +LIT 2; +ADD; +STOREI(-2); +JMP 23; +LIT 0; +STOREI(-2); +RET 2; +INIT 0; +READ(global,1); +LOAD(global,1); +PUSH; +LOADA(global,2); +PUSH; +CALL 4; +WRITE(global,2); +RET 0; diff --git a/examples/app/CVS/Entries b/examples/app/CVS/Entries new file mode 100644 index 0000000..ac3dd9b --- /dev/null +++ b/examples/app/CVS/Entries @@ -0,0 +1,5 @@ +/Ereichbarkeit.jalgo/1.1/Tue Nov 11 08:13:53 2008/-kb/ +/Kapazitaet.jalgo/1.1/Tue Nov 11 08:13:53 2008/-kb/ +/Kuerzestes-Wege-Problem.jalgo/1.1/Tue Nov 11 08:13:53 2008/-kb/ +/Prozessproblem.jalgo/1.1/Tue Nov 11 08:13:53 2008/-kb/ +/Zuverlaessigkeitsproblem.jalgo/1.1/Tue Nov 11 08:13:53 2008/-kb/ diff --git a/examples/app/CVS/Repository b/examples/app/CVS/Repository new file mode 100644 index 0000000..5955255 --- /dev/null +++ b/examples/app/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/app diff --git a/examples/app/CVS/Root b/examples/app/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/app/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/app/Ereichbarkeit.jalgo b/examples/app/Ereichbarkeit.jalgo new file mode 100644 index 0000000..9a7faa0 Binary files /dev/null and b/examples/app/Ereichbarkeit.jalgo differ diff --git a/examples/app/Kapazitaet.jalgo b/examples/app/Kapazitaet.jalgo new file mode 100644 index 0000000..2e39488 Binary files /dev/null and b/examples/app/Kapazitaet.jalgo differ diff --git a/examples/app/Kuerzestes-Wege-Problem.jalgo b/examples/app/Kuerzestes-Wege-Problem.jalgo new file mode 100644 index 0000000..4ae031b Binary files /dev/null and b/examples/app/Kuerzestes-Wege-Problem.jalgo differ diff --git a/examples/app/Prozessproblem.jalgo b/examples/app/Prozessproblem.jalgo new file mode 100644 index 0000000..c047456 Binary files /dev/null and b/examples/app/Prozessproblem.jalgo differ diff --git a/examples/app/Zuverlaessigkeitsproblem.jalgo b/examples/app/Zuverlaessigkeitsproblem.jalgo new file mode 100644 index 0000000..45b887a Binary files /dev/null and b/examples/app/Zuverlaessigkeitsproblem.jalgo differ diff --git a/examples/avl/CVS/Entries b/examples/avl/CVS/Entries new file mode 100644 index 0000000..b13b561 --- /dev/null +++ b/examples/avl/CVS/Entries @@ -0,0 +1,2 @@ +/avltree.jalgo/1.1/Thu Jun 23 10:02:11 2005/-kb/ +/randomtree.jalgo/1.1/Thu Jun 23 10:02:11 2005/-kb/ diff --git a/examples/avl/CVS/Repository b/examples/avl/CVS/Repository new file mode 100644 index 0000000..01b5deb --- /dev/null +++ b/examples/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/avl diff --git a/examples/avl/CVS/Root b/examples/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/avl/avltree.jalgo b/examples/avl/avltree.jalgo new file mode 100644 index 0000000..d2567a5 Binary files /dev/null and b/examples/avl/avltree.jalgo differ diff --git a/examples/avl/randomtree.jalgo b/examples/avl/randomtree.jalgo new file mode 100644 index 0000000..8b1601e Binary files /dev/null and b/examples/avl/randomtree.jalgo differ diff --git a/examples/bfsdfs/CVS/Entries b/examples/bfsdfs/CVS/Entries new file mode 100644 index 0000000..8e997b0 --- /dev/null +++ b/examples/bfsdfs/CVS/Entries @@ -0,0 +1,2 @@ +/gerichtet.jalgo/1.1/Wed Dec 8 13:47:53 2010// +/ungerichtet.jalgo/1.1/Wed Dec 8 13:47:53 2010// diff --git a/examples/bfsdfs/CVS/Repository b/examples/bfsdfs/CVS/Repository new file mode 100644 index 0000000..49928ea --- /dev/null +++ b/examples/bfsdfs/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/bfsdfs diff --git a/examples/bfsdfs/CVS/Root b/examples/bfsdfs/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/bfsdfs/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/bfsdfs/gerichtet.jalgo b/examples/bfsdfs/gerichtet.jalgo new file mode 100644 index 0000000..6c4fafa Binary files /dev/null and b/examples/bfsdfs/gerichtet.jalgo differ diff --git a/examples/bfsdfs/ungerichtet.jalgo b/examples/bfsdfs/ungerichtet.jalgo new file mode 100644 index 0000000..b7f63fd Binary files /dev/null and b/examples/bfsdfs/ungerichtet.jalgo differ diff --git a/examples/c0h0/3_to_the_power_of_n.c0 b/examples/c0h0/3_to_the_power_of_n.c0 new file mode 100644 index 0000000..e720e95 --- /dev/null +++ b/examples/c0h0/3_to_the_power_of_n.c0 @@ -0,0 +1,17 @@ +#include + +int main() +{ + int x1, x2; + scanf("%i", &x1); + + x2 = 1; + + while(x1>0) { + x1=x1-1; + x2=3*x2; + } + + printf("%d", x2); + return 0; +} diff --git a/examples/c0h0/42.c0 b/examples/c0h0/42.c0 new file mode 100644 index 0000000..0402394 --- /dev/null +++ b/examples/c0h0/42.c0 @@ -0,0 +1,36 @@ +#include + +int main() +{ + int x1, x2, x3; + scanf("%i", &x1); + scanf("%i", &x2); + scanf("%i", &x3); + + x1=1; + x2=0; + + while(x1>=x2){ + while(x1>x2){ + if(x3==2) x2=x2+x1; + x2=x2+x1; + if(x2 == x1){ + x3 = x2; + x3 = x3 * 42; + x2 = x3 / 21; + x3 = x2; + x2 = x1; + } + else + { + x3 = x2 + 42; + x3 = x3 - x2; + } + } + x1=x1-1; + } + + printf("%d", x3); + return 0; +} + diff --git a/examples/c0h0/CVS/Entries b/examples/c0h0/CVS/Entries new file mode 100644 index 0000000..b1f0fc1 --- /dev/null +++ b/examples/c0h0/CVS/Entries @@ -0,0 +1,8 @@ +/3_to_the_power_of_n.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/42.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/abs.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/add.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/max.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/min.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/mult.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/mult2.c0/1.1/Sat Mar 5 14:12:05 2011/-kb/ diff --git a/examples/c0h0/CVS/Repository b/examples/c0h0/CVS/Repository new file mode 100644 index 0000000..fceb08a --- /dev/null +++ b/examples/c0h0/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/c0h0 diff --git a/examples/c0h0/CVS/Root b/examples/c0h0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/c0h0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/c0h0/abs.c0 b/examples/c0h0/abs.c0 new file mode 100644 index 0000000..efa9829 --- /dev/null +++ b/examples/c0h0/abs.c0 @@ -0,0 +1,13 @@ +#include + +int main() +{ + int x1; + scanf("%i", &x1); + + if(x1<0) x1=-x1; + + printf("%d", x1); + return 0; +} + diff --git a/examples/c0h0/add.c0 b/examples/c0h0/add.c0 new file mode 100644 index 0000000..54246ae --- /dev/null +++ b/examples/c0h0/add.c0 @@ -0,0 +1,17 @@ +#include + +int main() +{ + int x1, x2; + scanf("%i", &x1); + scanf("%i", &x2); + + while(x1>=0) { + x1=x1-1; + x2=x2+1; + } + + printf("%d", x2); + return 0; +} + diff --git a/examples/c0h0/max.c0 b/examples/c0h0/max.c0 new file mode 100644 index 0000000..057565c --- /dev/null +++ b/examples/c0h0/max.c0 @@ -0,0 +1,17 @@ +#include + +int main() +{ + int x1, x2, x3; + scanf("%i", &x1); + scanf("%i", &x2); + + + if (x1 > x2) + x3 = x1; + else x3 = x2; + + printf("%d", x3); + return 0; +} + diff --git a/examples/c0h0/min.c0 b/examples/c0h0/min.c0 new file mode 100644 index 0000000..1ecc497 --- /dev/null +++ b/examples/c0h0/min.c0 @@ -0,0 +1,17 @@ +#include + +int main() +{ + int x1, x2, x3; + scanf("%i", &x1); + scanf("%i", &x2); + + if(x1 + +int main() +{ + int x1, x2, x3; + scanf("%i", &x1); + scanf("%i", &x2); + + while (x1>0) { + x1=x1-1; + x2=x2+x2; + } + + printf("%d", x2); + return 0; +} + diff --git a/examples/c0h0/mult2.c0 b/examples/c0h0/mult2.c0 new file mode 100644 index 0000000..a1e4f07 --- /dev/null +++ b/examples/c0h0/mult2.c0 @@ -0,0 +1,18 @@ +#include + +int main() +{ + int x1, x2, x3; + scanf("%i", &x1); + scanf("%i", &x2); + + while (x1>0) { + x1=x1-1; + x2=x2+3; + } + + printf("%d", x2); + return 0; +} + + diff --git a/examples/dijkstra/CVS/Entries b/examples/dijkstra/CVS/Entries new file mode 100644 index 0000000..9dfb03f --- /dev/null +++ b/examples/dijkstra/CVS/Entries @@ -0,0 +1 @@ +/vorlesungsgraph.jalgo/1.3/Sat Mar 4 13:36:29 2006/-kb/ diff --git a/examples/dijkstra/CVS/Repository b/examples/dijkstra/CVS/Repository new file mode 100644 index 0000000..c5cf36d --- /dev/null +++ b/examples/dijkstra/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/dijkstra diff --git a/examples/dijkstra/CVS/Root b/examples/dijkstra/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/dijkstra/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/dijkstra/vorlesungsgraph.jalgo b/examples/dijkstra/vorlesungsgraph.jalgo new file mode 100644 index 0000000..4e0f483 Binary files /dev/null and b/examples/dijkstra/vorlesungsgraph.jalgo differ diff --git a/examples/ebnf/CVS/Entries b/examples/ebnf/CVS/Entries new file mode 100644 index 0000000..716fb4d --- /dev/null +++ b/examples/ebnf/CVS/Entries @@ -0,0 +1,3 @@ +/c0definition.jalgo/1.1/Sat Aug 12 20:02:17 2006/-kb/ +/c0diagramm.jalgo/1.1/Sat Aug 12 20:02:17 2006/-kb/ +/dia01.jalgo/1.1/Sat Aug 12 20:02:17 2006/-kb/ diff --git a/examples/ebnf/CVS/Repository b/examples/ebnf/CVS/Repository new file mode 100644 index 0000000..09490c9 --- /dev/null +++ b/examples/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/ebnf diff --git a/examples/ebnf/CVS/Root b/examples/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/ebnf/c0definition.jalgo b/examples/ebnf/c0definition.jalgo new file mode 100644 index 0000000..ab13c9c Binary files /dev/null and b/examples/ebnf/c0definition.jalgo differ diff --git a/examples/ebnf/c0diagramm.jalgo b/examples/ebnf/c0diagramm.jalgo new file mode 100644 index 0000000..059e96e Binary files /dev/null and b/examples/ebnf/c0diagramm.jalgo differ diff --git a/examples/ebnf/dia01.jalgo b/examples/ebnf/dia01.jalgo new file mode 100644 index 0000000..01575c1 Binary files /dev/null and b/examples/ebnf/dia01.jalgo differ diff --git a/examples/em/Aufgabe10.9bc.em b/examples/em/Aufgabe10.9bc.em new file mode 100644 index 0000000..058e6f4 --- /dev/null +++ b/examples/em/Aufgabe10.9bc.em @@ -0,0 +1,272 @@ + + + + + + 1 + 1 + + + 2 + 2 + + + 2-mal Z + 3.0 + + + + + + + + 2 + 1 + + + + 1-mal Z + 5.0 + + + + 1 + 2 + + + + + + + + + + + 2 + 2 + + + + 0-mal Z + 2.0 + + + + + + + + + + + + + + + +

+ + + 0.2 + + + + 0.2 + + + + 0.3 + + + + 0.3 + +

+ + + + 0.2 + + + + 0.3 + + + + 0.5 + + + + + + 2 + 1 + + 0.6 + + + + 1 + 1 + + 0.4 + + + + 2 + 0 + + 0.5 + + + + 1 + 0 + + 0.5 + + + -4.647817481888637 +
+ +

+ + + 0.1111111111111111 + + + + 0.2222222222222222 + + + + 0.2222222222222222 + + + + 0.4444444444444444 + +

+ + + + 0.2222222222222222 + + + + 0.2222222222222222 + + + + 0.5555555555555556 + + + + + + 2 + 1 + + 0.6666666666666666 + + + + 1 + 1 + + 0.3333333333333333 + + + + 2 + 0 + + 0.3333333333333333 + + + + 1 + 0 + + 0.6666666666666666 + + + -4.542425094393249 +
+ +

+ + + 0.25 + + + + 0.25 + + + + 0.25 + + + + 0.25 + +

+ + + + 0.25 + + + + 0.25 + + + + 0.5 + + + + + + 2 + 1 + + 0.5 + + + + 1 + 1 + + 0.5 + + + + 2 + 0 + + 0.5 + + + + 1 + 0 + + 0.5 + + + -4.515449934959718 +
+
+
+ + 2 + 2 + + 10.0 + 2 + 2 + 2 +
+
\ No newline at end of file diff --git a/examples/em/CVS/Entries b/examples/em/CVS/Entries new file mode 100644 index 0000000..5b73af3 --- /dev/null +++ b/examples/em/CVS/Entries @@ -0,0 +1,2 @@ +/Aufgabe10.9bc.em/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/skriptBeispiel13.23.em/1.1/Mon Jan 30 18:56:51 2012/-kb/ diff --git a/examples/em/CVS/Repository b/examples/em/CVS/Repository new file mode 100644 index 0000000..dd7da7c --- /dev/null +++ b/examples/em/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/em diff --git a/examples/em/CVS/Root b/examples/em/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/em/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/em/skriptBeispiel13.23.em b/examples/em/skriptBeispiel13.23.em new file mode 100644 index 0000000..6a5fa3c --- /dev/null +++ b/examples/em/skriptBeispiel13.23.em @@ -0,0 +1,467 @@ + + + + + + 1 + 1 + + + 2 + 2 + + + 0 + 4.0 + + + + + + + + 2 + 1 + + + + 1 + 9.0 + + + + 1 + 2 + + + + + + + + + + + 2 + 2 + + + + 2 + 2.0 + + + + + + + + + + + + + + + +

+ + + 0.3555555555555555 + + + + 0.3111111111111111 + + + + 0.17777777777777776 + + + + 0.15555555555555556 + +

+ + + + 0.3111111111111111 + + + + 0.17777777777777776 + + + + 0.5111111111111111 + + + + + + 2 + 1 + + 0.3333333333333333 + + + + 1 + 1 + + 0.6666666666666666 + + + + 2 + 0 + + 0.5333333333333333 + + + + 1 + 0 + + 0.4666666666666667 + + + -6.151945065774981 +
+ +

+ + + 0.06666666666666667 + + + + 0.26666666666666666 + + + + 0.13333333333333333 + + + + 0.5333333333333333 + +

+ + + + 0.26666666666666666 + + + + 0.13333333333333333 + + + + 0.6 + + + + + + 2 + 1 + + 0.6666666666666666 + + + + 1 + 1 + + 0.3333333333333333 + + + + 2 + 0 + + 0.2 + + + + 1 + 0 + + 0.8 + + + -6.042886344241483 +
+ +

+ + + 0.1 + + + + 0.4 + + + + 0.1 + + + + 0.4 + +

+ + + + 0.4 + + + + 0.1 + + + + 0.5 + + + + + + 2 + 1 + + 0.5 + + + + 1 + 1 + + 0.5 + + + + 2 + 0 + + 0.2 + + + + 1 + 0 + + 0.8 + + + -6.301029995663981 +
+ +

+ + + 0.36000000000000004 + + + + 0.04000000000000001 + + + + 0.54 + + + + 0.06 + +

+ + + + 0.04000000000000001 + + + + 0.54 + + + + 0.42000000000000004 + + + + + + 2 + 1 + + 0.6 + + + + 1 + 1 + + 0.4 + + + + 2 + 0 + + 0.9 + + + + 1 + 0 + + 0.1 + + + -9.517728901461108 +
+ +

+ + + 1.0000000000000001E-11 + + + + 1.0E-6 + + + + 1.0E-5 + + + + 1.0 + +

+ + + + 1.0E-6 + + + + 1.0E-5 + + + + 1.00000000001 + + + + + + 2 + 1 + + 1.0 + + + + 1 + 1 + + 1.0E-6 + + + + 2 + 0 + + 1.0E-5 + + + + 1 + 0 + + 1.0 + + + -33.99999999996091 +
+ +

+ + + 0.24 + + + + 0.36 + + + + 0.16000000000000003 + + + + 0.24 + +

+ + + + 0.36 + + + + 0.16000000000000003 + + + + 0.48 + + + + + + 2 + 1 + + 0.4 + + + + 1 + 1 + + 0.6 + + + + 2 + 0 + + 0.4 + + + + 1 + 0 + + 0.6 + + + -6.235378895238716 +
+
+
+ + 2 + 2 + + 15.0 + 2 + 1 + -1 +
+
\ No newline at end of file diff --git a/examples/heapsort/CVS/Entries b/examples/heapsort/CVS/Entries new file mode 100644 index 0000000..e0bf2ad --- /dev/null +++ b/examples/heapsort/CVS/Entries @@ -0,0 +1,5 @@ +/digitsandnumbers.jalgo/1.1/Fri Feb 1 13:11:40 2008/-kb/ +/lecture.jalgo/1.1/Fri Feb 1 13:11:40 2008/-kb/ +/sweetlittle15.jalgo/1.1/Fri Feb 1 13:11:40 2008/-kb/ +/sweetlittle31.jalgo/1.1/Fri Feb 1 13:11:40 2008/-kb/ +/test.jalgo/1.1/Fri Feb 1 13:11:40 2008/-kb/ diff --git a/examples/heapsort/CVS/Repository b/examples/heapsort/CVS/Repository new file mode 100644 index 0000000..8300d15 --- /dev/null +++ b/examples/heapsort/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/heapsort diff --git a/examples/heapsort/CVS/Root b/examples/heapsort/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/heapsort/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/heapsort/digitsandnumbers.jalgo b/examples/heapsort/digitsandnumbers.jalgo new file mode 100644 index 0000000..e7ba999 Binary files /dev/null and b/examples/heapsort/digitsandnumbers.jalgo differ diff --git a/examples/heapsort/lecture.jalgo b/examples/heapsort/lecture.jalgo new file mode 100644 index 0000000..4848c67 Binary files /dev/null and b/examples/heapsort/lecture.jalgo differ diff --git a/examples/heapsort/sweetlittle15.jalgo b/examples/heapsort/sweetlittle15.jalgo new file mode 100644 index 0000000..b7823bb Binary files /dev/null and b/examples/heapsort/sweetlittle15.jalgo differ diff --git a/examples/heapsort/sweetlittle31.jalgo b/examples/heapsort/sweetlittle31.jalgo new file mode 100644 index 0000000..41f450b Binary files /dev/null and b/examples/heapsort/sweetlittle31.jalgo differ diff --git a/examples/heapsort/test.jalgo b/examples/heapsort/test.jalgo new file mode 100644 index 0000000..1312d8f Binary files /dev/null and b/examples/heapsort/test.jalgo differ diff --git a/examples/hoare/Beispiel 0.c b/examples/hoare/Beispiel 0.c new file mode 100644 index 0000000..dbefc18 --- /dev/null +++ b/examples/hoare/Beispiel 0.c @@ -0,0 +1,6 @@ +i=1; +s=0; +while(i<=n){ + s=s+i*i; + i=i+1; +} \ No newline at end of file diff --git a/examples/hoare/Beispiel 0.jalgo b/examples/hoare/Beispiel 0.jalgo new file mode 100644 index 0000000..8bc4d47 Binary files /dev/null and b/examples/hoare/Beispiel 0.jalgo differ diff --git a/examples/hoare/Beispiel 1.c b/examples/hoare/Beispiel 1.c new file mode 100644 index 0000000..43bbbd2 --- /dev/null +++ b/examples/hoare/Beispiel 1.c @@ -0,0 +1,4 @@ +while(x>0) { + x=x-1; + z=z+y; +} \ No newline at end of file diff --git a/examples/hoare/Beispiel 1.jalgo b/examples/hoare/Beispiel 1.jalgo new file mode 100644 index 0000000..fb7231c Binary files /dev/null and b/examples/hoare/Beispiel 1.jalgo differ diff --git a/examples/hoare/Beispiel 10.c b/examples/hoare/Beispiel 10.c new file mode 100644 index 0000000..a848d9a --- /dev/null +++ b/examples/hoare/Beispiel 10.c @@ -0,0 +1,5 @@ +while(x>0) { + x=x-1; + y=y+1; +} + diff --git a/examples/hoare/Beispiel 10.jalgo b/examples/hoare/Beispiel 10.jalgo new file mode 100644 index 0000000..b7d6c22 Binary files /dev/null and b/examples/hoare/Beispiel 10.jalgo differ diff --git a/examples/hoare/Beispiel 11.c b/examples/hoare/Beispiel 11.c new file mode 100644 index 0000000..c6fc927 --- /dev/null +++ b/examples/hoare/Beispiel 11.c @@ -0,0 +1,5 @@ +while(x1>0) { + z=z+3*y; + x1=x1-1; +} + diff --git a/examples/hoare/Beispiel 11.jalgo b/examples/hoare/Beispiel 11.jalgo new file mode 100644 index 0000000..1b9bdf1 Binary files /dev/null and b/examples/hoare/Beispiel 11.jalgo differ diff --git a/examples/hoare/Beispiel 2.c b/examples/hoare/Beispiel 2.c new file mode 100644 index 0000000..652a94f --- /dev/null +++ b/examples/hoare/Beispiel 2.c @@ -0,0 +1,5 @@ +while(x1>0) { + x1=x1-1; + y=3*y; +} + diff --git a/examples/hoare/Beispiel 2.jalgo b/examples/hoare/Beispiel 2.jalgo new file mode 100644 index 0000000..3956453 Binary files /dev/null and b/examples/hoare/Beispiel 2.jalgo differ diff --git a/examples/hoare/Beispiel 3.c b/examples/hoare/Beispiel 3.c new file mode 100644 index 0000000..7fb9118 --- /dev/null +++ b/examples/hoare/Beispiel 3.c @@ -0,0 +1,5 @@ +y=1; +while(x1>0){ + x1=x1-1; + y=y*2; +} diff --git a/examples/hoare/Beispiel 3.jalgo b/examples/hoare/Beispiel 3.jalgo new file mode 100644 index 0000000..6632992 Binary files /dev/null and b/examples/hoare/Beispiel 3.jalgo differ diff --git a/examples/hoare/Beispiel 4.c b/examples/hoare/Beispiel 4.c new file mode 100644 index 0000000..643b427 --- /dev/null +++ b/examples/hoare/Beispiel 4.c @@ -0,0 +1,4 @@ +if(a0) { +x=x-1; +y=y+1; +} \ No newline at end of file diff --git a/examples/hoare/Beispiel 5.jalgo b/examples/hoare/Beispiel 5.jalgo new file mode 100644 index 0000000..511a431 Binary files /dev/null and b/examples/hoare/Beispiel 5.jalgo differ diff --git a/examples/hoare/Beispiel 6.c b/examples/hoare/Beispiel 6.c new file mode 100644 index 0000000..c8f7318 --- /dev/null +++ b/examples/hoare/Beispiel 6.c @@ -0,0 +1,4 @@ +while (z>0) { + z=z-1; + y=y+3; +} \ No newline at end of file diff --git a/examples/hoare/Beispiel 6.jalgo b/examples/hoare/Beispiel 6.jalgo new file mode 100644 index 0000000..369ad9f Binary files /dev/null and b/examples/hoare/Beispiel 6.jalgo differ diff --git a/examples/hoare/Beispiel 7.c b/examples/hoare/Beispiel 7.c new file mode 100644 index 0000000..6b1ee48 --- /dev/null +++ b/examples/hoare/Beispiel 7.c @@ -0,0 +1,2 @@ +if(x<0) x=-x; + diff --git a/examples/hoare/Beispiel 7.jalgo b/examples/hoare/Beispiel 7.jalgo new file mode 100644 index 0000000..efafb1e Binary files /dev/null and b/examples/hoare/Beispiel 7.jalgo differ diff --git a/examples/hoare/Beispiel 8.c b/examples/hoare/Beispiel 8.c new file mode 100644 index 0000000..299da8d --- /dev/null +++ b/examples/hoare/Beispiel 8.c @@ -0,0 +1,5 @@ +z=1; +while(x>0) { + z=y*z; + x=x-1; +} diff --git a/examples/hoare/Beispiel 8.jalgo b/examples/hoare/Beispiel 8.jalgo new file mode 100644 index 0000000..03ab595 Binary files /dev/null and b/examples/hoare/Beispiel 8.jalgo differ diff --git a/examples/hoare/Beispiel 9.c b/examples/hoare/Beispiel 9.c new file mode 100644 index 0000000..b102904 --- /dev/null +++ b/examples/hoare/Beispiel 9.c @@ -0,0 +1,2 @@ +if (a > b) max = a; +else max = b; diff --git a/examples/hoare/Beispiel 9.jalgo b/examples/hoare/Beispiel 9.jalgo new file mode 100644 index 0000000..df386bd Binary files /dev/null and b/examples/hoare/Beispiel 9.jalgo differ diff --git a/examples/hoare/Beispiel aus Hilfe.c b/examples/hoare/Beispiel aus Hilfe.c new file mode 100644 index 0000000..00b5ff9 --- /dev/null +++ b/examples/hoare/Beispiel aus Hilfe.c @@ -0,0 +1,2 @@ +while (x>0) x=x-1; + diff --git a/examples/hoare/Beispiel aus Hilfe.jalgo b/examples/hoare/Beispiel aus Hilfe.jalgo new file mode 100644 index 0000000..a1aac64 Binary files /dev/null and b/examples/hoare/Beispiel aus Hilfe.jalgo differ diff --git a/examples/hoare/CVS/Entries b/examples/hoare/CVS/Entries new file mode 100644 index 0000000..3d0c1f0 --- /dev/null +++ b/examples/hoare/CVS/Entries @@ -0,0 +1,26 @@ +/Beispiel 0.c/1.1/Wed Aug 27 13:02:02 2008/-kb/ +/Beispiel 0.jalgo/1.1/Wed Aug 27 13:01:54 2008/-kb/ +/Beispiel 1.c/1.1/Wed Aug 27 13:02:02 2008/-kb/ +/Beispiel 1.jalgo/1.1/Wed Aug 27 13:01:56 2008/-kb/ +/Beispiel 10.c/1.1/Wed Aug 27 13:01:58 2008/-kb/ +/Beispiel 10.jalgo/1.1/Wed Aug 27 13:01:51 2008/-kb/ +/Beispiel 11.c/1.1/Wed Aug 27 13:01:59 2008/-kb/ +/Beispiel 11.jalgo/1.1/Wed Aug 27 13:02:17 2008/-kb/ +/Beispiel 2.c/1.1/Wed Aug 27 13:01:54 2008/-kb/ +/Beispiel 2.jalgo/1.1/Wed Aug 27 13:01:48 2008/-kb/ +/Beispiel 3.c/1.1/Wed Aug 27 13:02:03 2008/-kb/ +/Beispiel 3.jalgo/1.1/Wed Aug 27 13:01:55 2008/-kb/ +/Beispiel 4.c/1.1/Wed Aug 27 13:02:17 2008/-kb/ +/Beispiel 4.jalgo/1.1/Wed Aug 27 13:01:58 2008/-kb/ +/Beispiel 5.c/1.1/Wed Aug 27 13:02:00 2008/-kb/ +/Beispiel 5.jalgo/1.1/Wed Aug 27 13:02:12 2008/-kb/ +/Beispiel 6.c/1.1/Wed Aug 27 13:01:56 2008/-kb/ +/Beispiel 6.jalgo/1.1/Wed Aug 27 13:02:17 2008/-kb/ +/Beispiel 7.c/1.1/Wed Aug 27 13:01:59 2008/-kb/ +/Beispiel 7.jalgo/1.1/Wed Aug 27 13:02:03 2008/-kb/ +/Beispiel 8.c/1.1/Wed Aug 27 13:02:12 2008/-kb/ +/Beispiel 8.jalgo/1.1/Wed Aug 27 13:02:11 2008/-kb/ +/Beispiel 9.c/1.1/Wed Aug 27 13:02:00 2008/-kb/ +/Beispiel 9.jalgo/1.1/Wed Aug 27 13:01:48 2008/-kb/ +/Beispiel aus Hilfe.c/1.1/Wed Aug 27 13:01:55 2008/-kb/ +/Beispiel aus Hilfe.jalgo/1.1/Wed Aug 27 13:01:49 2008/-kb/ diff --git a/examples/hoare/CVS/Repository b/examples/hoare/CVS/Repository new file mode 100644 index 0000000..fcc24fc --- /dev/null +++ b/examples/hoare/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/hoare diff --git a/examples/hoare/CVS/Root b/examples/hoare/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/hoare/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/kmp/CVS/Entries b/examples/kmp/CVS/Entries new file mode 100644 index 0000000..9cdf613 --- /dev/null +++ b/examples/kmp/CVS/Entries @@ -0,0 +1,2 @@ +/buildTab.jalgo/1.1/Fri Jun 30 14:35:20 2006/-kb/ +/search.jalgo/1.1/Fri Jun 30 14:35:20 2006/-kb/ diff --git a/examples/kmp/CVS/Repository b/examples/kmp/CVS/Repository new file mode 100644 index 0000000..bcb393b --- /dev/null +++ b/examples/kmp/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/kmp diff --git a/examples/kmp/CVS/Root b/examples/kmp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/kmp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/kmp/buildTab.jalgo b/examples/kmp/buildTab.jalgo new file mode 100644 index 0000000..92d61e2 Binary files /dev/null and b/examples/kmp/buildTab.jalgo differ diff --git a/examples/kmp/search.jalgo b/examples/kmp/search.jalgo new file mode 100644 index 0000000..ce05c78 Binary files /dev/null and b/examples/kmp/search.jalgo differ diff --git a/examples/pulsemem/CVS/Entries b/examples/pulsemem/CVS/Entries new file mode 100644 index 0000000..126bcc4 --- /dev/null +++ b/examples/pulsemem/CVS/Entries @@ -0,0 +1,18 @@ +/dyn01.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn02.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn03.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn04.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn05.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn06.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn07.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn08.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn09.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn10.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn11.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn12.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn13.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn14.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/dyn15.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/ex01.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ +/ex01.jalgo/1.1/Wed Jan 16 19:19:09 2008/-kb/ +/staticScope.c/1.1/Wed Jan 16 19:19:09 2008/-ko/ diff --git a/examples/pulsemem/CVS/Repository b/examples/pulsemem/CVS/Repository new file mode 100644 index 0000000..956d018 --- /dev/null +++ b/examples/pulsemem/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/pulsemem diff --git a/examples/pulsemem/CVS/Root b/examples/pulsemem/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/pulsemem/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/pulsemem/dyn01.c b/examples/pulsemem/dyn01.c new file mode 100644 index 0000000..1d1b43b --- /dev/null +++ b/examples/pulsemem/dyn01.c @@ -0,0 +1,29 @@ +#include +int e, a; + +void g(int x, int y, int *z); + +void f(int x, int *y) { + int y1; /*label 1*/ + if (x > 0) { + f(x - 1, &y1); /*label 2*/ + g(x - 1, y1, y); /*label 3*/ + } + else *y = 1; +} + +void g(int x, int y, int *z) { + int y1; /*label 4*/ + if (x > 0) { + f(x - 1, &y1); /*label 5*/ + *z = y1 + y; + } + else *z = 1; +} + +int main() { + scanf("%i", &e); /*label 6*/ + f(e, &a); /*label 7*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/dyn02.c b/examples/pulsemem/dyn02.c new file mode 100644 index 0000000..0fcf297 --- /dev/null +++ b/examples/pulsemem/dyn02.c @@ -0,0 +1,43 @@ +#include +int a, b, c; + +void p1(int *c, int b) { + /*label 2*/ + *c = a - b; + b = a + b; + a = *c + b; /*label 3*/ +} + +int p2(int *a, int *b) { + int c; /*label 4*/ + c = *a; + *a = *b; + *b = c + 1; /*label 5*/ + return c; +} + +void p3() { + int a; /*label 6*/ + a = 1; + a = p2(&c, &a); /*label 7*/ +} + +void p4(int *a, int b, int *c) { + /*label 8*/ + p1(c, b); + *a = *a + b + *c; /*label 9*/ +} + +int main() { + a = 1; + b = 2; + c = 3; /*label 1*/ + p1(&b, a); /*label 10*/ + a = p2(&c, &b); /*label 11*/ + p3(); /*label 12*/ + p4(&c, b, &a); /*label 13*/ + printf("%d", a); + printf("%d", b); + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn03.c b/examples/pulsemem/dyn03.c new file mode 100644 index 0000000..dc6531c --- /dev/null +++ b/examples/pulsemem/dyn03.c @@ -0,0 +1,28 @@ +#include +int a, b, c; + +void g(int x, int y, int *z) { + /*label 1*/ + if (x > 0) { + g(x - 1, y, z); /*label 7*/ + *z = *z + 1; + } + else *z = y; +} + +void f(int x, int y, int *z) { + int u; /*label 2*/ + if (x > 0) { + f(x - 1, y, &u); /*label 3*/ + g(u, y, z); /*label 4*/ + } + else *z = 0; +} + +int main() { + scanf("%i", &a); + scanf("%i", &b); /*label 5*/ + f(a, b, &c); /*label 6*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn04.c b/examples/pulsemem/dyn04.c new file mode 100644 index 0000000..6e8b83f --- /dev/null +++ b/examples/pulsemem/dyn04.c @@ -0,0 +1,31 @@ +#include + +void g(int x, int y, int *z); + +void f(int x, int *y) { + int u; /*label 1*/ + if (x > 0) { + f(x - 1, &u); /*label 2*/ + g(x - 1, u, y); + } + else *y = 1; + /*label 3*/ +} + +void g(int x, int y, int *z) { + int u; /*label 4*/ + if (x > 0) { + f(x - 1, &u); /*label 5*/ + *z = u + y; + } + else *z = 1; + /*label 6*/ +} + +int main() { + int e, a; /*label 7*/ + scanf("%i", &e); + f(e, &a); /*label 8*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/dyn05.c b/examples/pulsemem/dyn05.c new file mode 100644 index 0000000..55ab451 --- /dev/null +++ b/examples/pulsemem/dyn05.c @@ -0,0 +1,25 @@ +#include + +void g(int *x, int y) { + /*label 1*/ + *x = *x + y; /*label 2*/ +} + +void f(int x, int *y) { + int z; /*label 3*/ + if (x > 0) { + f(x - 1, &z); /*label 4*/ + *y = x * z; + } + else *y = 1; + if (*y > 2) g(y, x); + /*label 5*/ +} + +int main() { + int e, a; + scanf("%i", &e); /*label 6*/ + f(e, &a); /*label 7*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/dyn06.c b/examples/pulsemem/dyn06.c new file mode 100644 index 0000000..d79192b --- /dev/null +++ b/examples/pulsemem/dyn06.c @@ -0,0 +1,19 @@ +#include + +void g(int x, int *y, int z) { + /*label 3*/ + if (x < 2) { + g(x + 1, y, z); + *y = *y * 2; /*label 4*/ + } + else *y = z; +} + +int main() { + int a, b, c; + scanf("%i", &a); + scanf("%i", &b); /*label 1*/ + g(a, &c, b); /*label 2*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn07.c b/examples/pulsemem/dyn07.c new file mode 100644 index 0000000..2795e02 --- /dev/null +++ b/examples/pulsemem/dyn07.c @@ -0,0 +1,29 @@ +#include +int b; + +void g(int *x, int *y, int z) { + /*label 7*/ + if (z > 2) { + g(x, y, z - 2); + *y = *y * 2; /*label 8*/ + } + else *y = *x + 1; /*label 9*/ +} + +void f(int x, int y, int *z) { + /*label 3*/ + if (x > 0) { + f(x - 2, y, z); /*label 4*/ + g(&y, z, x); /*label 5*/ + } + else *z = y; /*label 6*/ +} + +int main() { + int a, c; + scanf("%i", &a); + scanf("%i", &c); /*label 1*/ + f(a, c, &b); /*label 2*/ + printf("%d", b); + return 0; +} diff --git a/examples/pulsemem/dyn08.c b/examples/pulsemem/dyn08.c new file mode 100644 index 0000000..d3a8987 --- /dev/null +++ b/examples/pulsemem/dyn08.c @@ -0,0 +1,24 @@ +#include + +void g(int x, int *y) { + /*label 1*/ + *y = *y + x; +} + +void f(int *x, int y) { + int z; /*label 2*/ + if (y > 0) { + f(&z, y - 1); + *x = y * z + 1; /*label 3*/ + } + else *x = 2; + if (*x > 2) g(y, x); /*label 4*/ +} + +int main() { + int e, a; + scanf("%i", &e); /*label 5*/ + f(&a, e); /*label 6*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/dyn09.c b/examples/pulsemem/dyn09.c new file mode 100644 index 0000000..40ad65c --- /dev/null +++ b/examples/pulsemem/dyn09.c @@ -0,0 +1,20 @@ +#include +int c; + +void f(int x, int y, int *z) { + /*label 3*/ + if (x > 5) { + f(x - 2, y, z); + *z = *z * x; /*label 4*/ + } + else *z = y; /*label 5*/ +} + +int main() { + int a, b; + scanf("%i", &a); + scanf("%i", &b); /*label 1*/ + f(a, b, &c); /*label 2*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn10.c b/examples/pulsemem/dyn10.c new file mode 100644 index 0000000..c3d5e88 --- /dev/null +++ b/examples/pulsemem/dyn10.c @@ -0,0 +1,20 @@ +#include + +void f(int x, int y, int *z) { + /*label 1*/ + if (x > 0) { + f(x - 1, y, z); /*label 2*/ + *z = x + y; + } + else *z = y; + /*label 3*/ +} + +int main() { + int a, b, c; + scanf("%i", &a); + scanf("%i", &b); /*label 4*/ + f(a, b, &c); /*label 5*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn11.c b/examples/pulsemem/dyn11.c new file mode 100644 index 0000000..71aa755 --- /dev/null +++ b/examples/pulsemem/dyn11.c @@ -0,0 +1,28 @@ +#include +int a; + +void g(int *x, int y) { + /*label 6*/ + if (y > 0) { + g(x, y - 1); + *x = *x + 2; /*label 7*/ + } + else *x = *x + 1; +} + +void f(int y, int *z) { + /*label 3*/ + if (y > 0) { + f(y - 1, z); /*label 4*/ + g(z, y); /*label 5*/ + } + else *z = 1; +} + +int main() { + int b; + scanf("%i", &b); /*label 1*/ + f(b, &a); /*label 2*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/dyn12.c b/examples/pulsemem/dyn12.c new file mode 100644 index 0000000..6681159 --- /dev/null +++ b/examples/pulsemem/dyn12.c @@ -0,0 +1,29 @@ +#include +int a, b; + +void g(int *x, int y) { + /*label 1*/ + if (y > 1) { + g(x, y - 1); + *x = *x * *x; /*label 2*/ + } + else *x = *x + 1; +} + +void f(int x, int *y, int *z) { + /*label 3*/ + if (x > 0) { + f(x - 2, y, z); /*label 4*/ + g(z, x); /*label 5*/ + } + else *z = *y; +} + +int main() { + int c; + scanf("%i", &a); + scanf("%i", &b); /*label 6*/ + f(a, &b, &c); /*label 7*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn13.c b/examples/pulsemem/dyn13.c new file mode 100644 index 0000000..95489b9 --- /dev/null +++ b/examples/pulsemem/dyn13.c @@ -0,0 +1,28 @@ +#include +int a, b, c; + +void g(int *x, int *y, int z) { + /*label 6*/ + if (z > 0) { + g(x, y, z - 2); + *y = *x * *y; /*label 7*/ + } + else *y = *y + 1; +} + +void f(int *x, int y) { + /*label 3*/ + if (y > 1) { + f(x, y - 1); /*label 4*/ + g(&b, x, y); /*label 5*/ + } + else *x = 1; +} + +int main() { + scanf("%i", &a); + scanf("%i", &b); /*label 1*/ + f(&c, a); /*label 2*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn14.c b/examples/pulsemem/dyn14.c new file mode 100644 index 0000000..3462def --- /dev/null +++ b/examples/pulsemem/dyn14.c @@ -0,0 +1,29 @@ +#include +int c; + +void g(int *z, int *y, int x) { + /*label 6*/ + if (x > 2) { + g(z, y, x - 2); + *y = *y * 3; /*label 7*/ + } + else *y = *z ; +} + +void f(int z, int y, int *x) { + /*label 3*/ + if (z > 0) { + f(z - 2, y, x); /*label 4*/ + g(&y, x, z); /*label 5*/ + } + else *x = y + 1; +} + +int main() { + int a, b; + scanf("%i", &a); + scanf("%i", &b); /*label 1*/ + f(a, b, &c); /*label 2*/ + printf("%d", c); + return 0; +} diff --git a/examples/pulsemem/dyn15.c b/examples/pulsemem/dyn15.c new file mode 100644 index 0000000..6186ac0 --- /dev/null +++ b/examples/pulsemem/dyn15.c @@ -0,0 +1,27 @@ +#include +int e; + +void g(int *x, int y) { + /*label 1*/ + *x = *x + y; +} + +void f(int x, int *y) { + int u; /*label 2*/ + if (x > 0) { + f(x - 1, &u); + *y = x * u + 2; /*label 3*/ + } + else *y = 5; + if (*y > 5) { + g(y, x); /*label 4*/ + } +} + +int main() { + int a; + scanf("%i", &e); /*label 5*/ + f(e, &a); /*label 6*/ + printf("%d", a); + return 0; +} diff --git a/examples/pulsemem/ex01.c b/examples/pulsemem/ex01.c new file mode 100644 index 0000000..0fc4f54 --- /dev/null +++ b/examples/pulsemem/ex01.c @@ -0,0 +1,18 @@ +#include +int x; + +void wirksam (int *a, int b) +{ + /*label 1*/ + *a = *a + b; + /*label 2*/ +} + +int main () +{ + x = 3; + /*label 3*/ + wirksam(&x, 4); /*$1*/ + /*label 4*/ + return 0; +} \ No newline at end of file diff --git a/examples/pulsemem/ex01.jalgo b/examples/pulsemem/ex01.jalgo new file mode 100644 index 0000000..17a621d Binary files /dev/null and b/examples/pulsemem/ex01.jalgo differ diff --git a/examples/pulsemem/staticScope.c b/examples/pulsemem/staticScope.c new file mode 100644 index 0000000..be05f55 --- /dev/null +++ b/examples/pulsemem/staticScope.c @@ -0,0 +1,38 @@ +#include + +int x, i; + +void A(); + +void B() +{ int x; + + x = 1; + printf("%d\n", x); + /*label1*/ + A(); + /*label2*/ + printf("%d\n", x); +} + +void A() +{ /*label3*/ + x = 2*x; + printf("%d\n", x); + if (i < 4) + { i = i+1; + /*label4*/ + B(); + } + /*label5*/ + printf("%d\n", x); +} + +int main() +{ i = 1; + x = 2; + /*label6*/ + A(); + /*label7*/ + return 0; +} \ No newline at end of file diff --git a/examples/unifikation/CVS/Entries b/examples/unifikation/CVS/Entries new file mode 100644 index 0000000..06dd711 --- /dev/null +++ b/examples/unifikation/CVS/Entries @@ -0,0 +1,6 @@ +/GAU.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/aufgabe1.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/aufgabe2.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/aufgabe3.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/aufgabe4.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/aufgabe5.jalgo/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/examples/unifikation/CVS/Repository b/examples/unifikation/CVS/Repository new file mode 100644 index 0000000..659d790 --- /dev/null +++ b/examples/unifikation/CVS/Repository @@ -0,0 +1 @@ +j-algo/examples/unifikation diff --git a/examples/unifikation/CVS/Root b/examples/unifikation/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/examples/unifikation/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/examples/unifikation/GAU.jalgo b/examples/unifikation/GAU.jalgo new file mode 100644 index 0000000..e413e65 Binary files /dev/null and b/examples/unifikation/GAU.jalgo differ diff --git a/examples/unifikation/aufgabe1.jalgo b/examples/unifikation/aufgabe1.jalgo new file mode 100644 index 0000000..3d1fb40 Binary files /dev/null and b/examples/unifikation/aufgabe1.jalgo differ diff --git a/examples/unifikation/aufgabe2.jalgo b/examples/unifikation/aufgabe2.jalgo new file mode 100644 index 0000000..32810bf Binary files /dev/null and b/examples/unifikation/aufgabe2.jalgo differ diff --git a/examples/unifikation/aufgabe3.jalgo b/examples/unifikation/aufgabe3.jalgo new file mode 100644 index 0000000..e7ae38d Binary files /dev/null and b/examples/unifikation/aufgabe3.jalgo differ diff --git a/examples/unifikation/aufgabe4.jalgo b/examples/unifikation/aufgabe4.jalgo new file mode 100644 index 0000000..4853f3c Binary files /dev/null and b/examples/unifikation/aufgabe4.jalgo differ diff --git a/examples/unifikation/aufgabe5.jalgo b/examples/unifikation/aufgabe5.jalgo new file mode 100644 index 0000000..73b5b2c Binary files /dev/null and b/examples/unifikation/aufgabe5.jalgo differ diff --git a/extlibs/CVS/Entries b/extlibs/CVS/Entries new file mode 100644 index 0000000..011bd10 --- /dev/null +++ b/extlibs/CVS/Entries @@ -0,0 +1,24 @@ +/antlr-3.0b6.jar/1.2/Mon Aug 16 12:00:56 2010/-kb/ +/antlr-runtime-3.2.jar/1.1/Wed Dec 8 13:01:52 2010/-kb/ +/antlr-runtime-313-custom.jar/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/beaver-rt.jar/1.1/Wed Dec 8 13:01:52 2010/-kb/ +/commons-lang-2.5.jar/1.1/Mon Aug 16 12:00:56 2010/-kb/ +D/freebsd//// +/jep-2.4.1.b.jar/1.2/Wed Aug 27 13:02:59 2008/-kb/ +/jflex.jar/1.1/Mon Aug 16 12:00:56 2010/-kb/ +/jgraph.jar/1.1/Wed Aug 27 13:02:59 2008/-kb/ +/jgraphx.jar/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/jh.jar/1.2/Sat Mar 4 13:36:24 2006/-kb/ +/jmatharray.jar/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/jmathplot.jar/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/jsyntaxpane-0.9.5-b29.jar/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/kxml2-2.3.0.jar/1.1/Mon Jan 30 18:56:52 2012/-kb/ +D/linux//// +D/macosx//// +/neu-ext-1.1.1.b.jar/1.1/Wed Aug 27 13:03:01 2008/-kb/ +/parser.jar/1.2/Mon Aug 16 12:00:56 2010/-kb/ +D/solaris//// +/stringtemplate.jar/1.1/Tue Oct 6 08:43:34 2009/-kb/ +/swing-layout-1.0.jar/1.1/Fri Aug 11 16:37:23 2006/-kb/ +D/win//// +/xstream-1.4.2.jar/1.1/Mon Jan 30 18:56:52 2012/-kb/ diff --git a/extlibs/CVS/Repository b/extlibs/CVS/Repository new file mode 100644 index 0000000..2067fb5 --- /dev/null +++ b/extlibs/CVS/Repository @@ -0,0 +1 @@ +j-algo/extlibs diff --git a/extlibs/CVS/Root b/extlibs/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/extlibs/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/extlibs/antlr-3.0b6.jar b/extlibs/antlr-3.0b6.jar new file mode 100644 index 0000000..6be3922 Binary files /dev/null and b/extlibs/antlr-3.0b6.jar differ diff --git a/extlibs/antlr-runtime-3.2.jar b/extlibs/antlr-runtime-3.2.jar new file mode 100644 index 0000000..52a0528 Binary files /dev/null and b/extlibs/antlr-runtime-3.2.jar differ diff --git a/extlibs/antlr-runtime-313-custom.jar b/extlibs/antlr-runtime-313-custom.jar new file mode 100644 index 0000000..e32b722 Binary files /dev/null and b/extlibs/antlr-runtime-313-custom.jar differ diff --git a/extlibs/beaver-rt.jar b/extlibs/beaver-rt.jar new file mode 100644 index 0000000..e93fc9e Binary files /dev/null and b/extlibs/beaver-rt.jar differ diff --git a/extlibs/commons-lang-2.5.jar b/extlibs/commons-lang-2.5.jar new file mode 100644 index 0000000..ae491da Binary files /dev/null and b/extlibs/commons-lang-2.5.jar differ diff --git a/extlibs/jep-2.4.1.b.jar b/extlibs/jep-2.4.1.b.jar new file mode 100644 index 0000000..d4c4e12 Binary files /dev/null and b/extlibs/jep-2.4.1.b.jar differ diff --git a/extlibs/jflex.jar b/extlibs/jflex.jar new file mode 100644 index 0000000..d5fa871 Binary files /dev/null and b/extlibs/jflex.jar differ diff --git a/extlibs/jgraph.jar b/extlibs/jgraph.jar new file mode 100644 index 0000000..7c5d565 Binary files /dev/null and b/extlibs/jgraph.jar differ diff --git a/extlibs/jgraphx.jar b/extlibs/jgraphx.jar new file mode 100644 index 0000000..a16fd49 Binary files /dev/null and b/extlibs/jgraphx.jar differ diff --git a/extlibs/jh.jar b/extlibs/jh.jar new file mode 100644 index 0000000..c38233a Binary files /dev/null and b/extlibs/jh.jar differ diff --git a/extlibs/jmatharray.jar b/extlibs/jmatharray.jar new file mode 100644 index 0000000..b766e86 Binary files /dev/null and b/extlibs/jmatharray.jar differ diff --git a/extlibs/jmathplot.jar b/extlibs/jmathplot.jar new file mode 100644 index 0000000..b5c72f3 Binary files /dev/null and b/extlibs/jmathplot.jar differ diff --git a/extlibs/jsyntaxpane-0.9.5-b29.jar b/extlibs/jsyntaxpane-0.9.5-b29.jar new file mode 100644 index 0000000..8bca1f6 Binary files /dev/null and b/extlibs/jsyntaxpane-0.9.5-b29.jar differ diff --git a/extlibs/kxml2-2.3.0.jar b/extlibs/kxml2-2.3.0.jar new file mode 100644 index 0000000..6470952 Binary files /dev/null and b/extlibs/kxml2-2.3.0.jar differ diff --git a/extlibs/neu-ext-1.1.1.b.jar b/extlibs/neu-ext-1.1.1.b.jar new file mode 100644 index 0000000..fbff0c3 Binary files /dev/null and b/extlibs/neu-ext-1.1.1.b.jar differ diff --git a/extlibs/parser.jar b/extlibs/parser.jar new file mode 100644 index 0000000..d6a2fb0 Binary files /dev/null and b/extlibs/parser.jar differ diff --git a/extlibs/stringtemplate.jar b/extlibs/stringtemplate.jar new file mode 100644 index 0000000..8e41531 Binary files /dev/null and b/extlibs/stringtemplate.jar differ diff --git a/extlibs/swing-layout-1.0.jar b/extlibs/swing-layout-1.0.jar new file mode 100644 index 0000000..50f1590 Binary files /dev/null and b/extlibs/swing-layout-1.0.jar differ diff --git a/extlibs/xstream-1.4.2.jar b/extlibs/xstream-1.4.2.jar new file mode 100644 index 0000000..fa8e2ed Binary files /dev/null and b/extlibs/xstream-1.4.2.jar differ diff --git a/grammar/CVS/Entries b/grammar/CVS/Entries new file mode 100644 index 0000000..5fa8476 --- /dev/null +++ b/grammar/CVS/Entries @@ -0,0 +1,3 @@ +D/am0c0//// +D/am1simulator//// +D/unifikation//// diff --git a/grammar/CVS/Repository b/grammar/CVS/Repository new file mode 100644 index 0000000..3af1730 --- /dev/null +++ b/grammar/CVS/Repository @@ -0,0 +1 @@ +j-algo/grammar diff --git a/grammar/CVS/Root b/grammar/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/grammar/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/grammar/am0c0/CVS/Entries b/grammar/am0c0/CVS/Entries new file mode 100644 index 0000000..9332f3a --- /dev/null +++ b/grammar/am0c0/CVS/Entries @@ -0,0 +1,4 @@ +/am0-lexer.l/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/am0-parser.g/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/c0-lexer.l/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/c0-parser.g/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/grammar/am0c0/CVS/Repository b/grammar/am0c0/CVS/Repository new file mode 100644 index 0000000..94d587a --- /dev/null +++ b/grammar/am0c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/grammar/am0c0 diff --git a/grammar/am0c0/CVS/Root b/grammar/am0c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/grammar/am0c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/grammar/am0c0/am0-lexer.l b/grammar/am0c0/am0-lexer.l new file mode 100644 index 0000000..45170f2 --- /dev/null +++ b/grammar/am0c0/am0-lexer.l @@ -0,0 +1,60 @@ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +package org.jalgo.module.am0c0.parser.am0; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.am0c0.parser.ParserConstants; +import org.jalgo.module.am0c0.parser.am0.GeneratedAM0Parser.Terminals; + +%% + +%class AM0Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Number = 0 | [1-9][0-9]* +Whitespace = [\t\f ] + +%% + +{Whitespace}+ { /* ignore */ } +{LineTerminator} { return symbol(Terminals.EOL, ParserConstants.EOL); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"-" { return symbol(Terminals.MINUS, "-"); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +"ADD" { return symbol(Terminals.ADD, "ADD"); } +"MUL" { return symbol(Terminals.MUL, "MUL"); } +"SUB" { return symbol(Terminals.SUB, "SUB"); } +"DIV" { return symbol(Terminals.DIV, "DIV"); } +"MOD" { return symbol(Terminals.MOD, "MOD"); } +"EQ" { return symbol(Terminals.EQ, "EQ"); } +"NE" { return symbol(Terminals.NE, "NE"); } +"LT" { return symbol(Terminals.LT, "LT"); } +"GT" { return symbol(Terminals.GT, "GT"); } +"LE" { return symbol(Terminals.LE, "LE"); } +"GE" { return symbol(Terminals.GE, "GE"); } +"LOAD" { return symbol(Terminals.LOAD, "LOAD"); } +"STORE" { return symbol(Terminals.STORE, "STORE"); } +"LIT" { return symbol(Terminals.LIT, "LIT"); } +"JMP" { return symbol(Terminals.JMP, "JMP"); } +"JMC" { return symbol(Terminals.JMC, "JMC"); } +"WRITE" { return symbol(Terminals.WRITE, "WRITE"); } +"READ" { return symbol(Terminals.READ, "READ"); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } + diff --git a/grammar/am0c0/am0-parser.g b/grammar/am0c0/am0-parser.g new file mode 100644 index 0000000..d4fce14 --- /dev/null +++ b/grammar/am0c0/am0-parser.g @@ -0,0 +1,107 @@ +// Author: Martin Morgenstern +%header {: +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +:}; +%package "org.jalgo.module.am0c0.parser.am0"; +%import "org.jalgo.module.am0c0.parser.ErrorEvents"; +%import "org.jalgo.module.am0c0.parser.ParserUtils"; +%import "org.jalgo.module.am0c0.model.LineAddress"; +%import "org.jalgo.module.am0c0.model.AddressException"; +%import "org.jalgo.module.am0c0.model.am0.*"; + +%class "GeneratedAM0Parser"; + +%embed {: + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } +:}; + +%init {: + this.report = ErrorEvents.forAm0(); +:}; + +%terminals ADD, MUL, SUB, DIV, MOD; +%terminals EQ, NE, LT, GT, LE, GE; +%terminals LOAD, STORE, LIT; +%terminals JMP, JMC; +%terminals WRITE, READ; +%terminals EOL, SEMICOLON; +%terminals NUMBER, MINUS; + +%goal Program; + +%typeof CommandList, Program = "AM0Program"; +%typeof Command = "SimulationStatement"; +%typeof UnsignedNumber, Number = "Integer"; + +Program + = CommandList + ; + +CommandList + = Command.a SEMICOLON + {: AM0Program program = new AM0Program(); program.add(a); return new Symbol(program); :} + | CommandList.a EOL Command.b SEMICOLON + {: a.add(b); return new Symbol(a); :} + ; + +Command + = ADD.a + {: return new Symbol(new Add(address(a))); :} + | MUL.a + {: return new Symbol(new Mul(address(a))); :} + | SUB.a + {: return new Symbol(new Sub(address(a))); :} + | DIV.a + {: return new Symbol(new Div(address(a))); :} + | MOD.a + {: return new Symbol(new Mod(address(a))); :} + | EQ.a + {: return new Symbol(new Equal(address(a))); :} + | NE.a + {: return new Symbol(new NotEqual(address(a))); :} + | LT.a + {: return new Symbol(new LesserThen(address(a))); :} + | GT.a + {: return new Symbol(new GreaterThen(address(a))); :} + | LE.a + {: return new Symbol(new LesserEqual(address(a))); :} + | GE.a + {: return new Symbol(new GreaterEqual(address(a))); :} + | JMP.a UnsignedNumber.b + {: return new Symbol(new Jmp(address(a), b)); :} + | JMC.a UnsignedNumber.b + {: return new Symbol(new Jmc(address(a), b)); :} + | LOAD.a UnsignedNumber.b + {: return new Symbol(new Load(address(a), b)); :} + | STORE.a UnsignedNumber.b + {: return new Symbol(new Store(address(a), b)); :} + | LIT.a Number.b + {: return new Symbol(new Lit(address(a), b)); :} + | WRITE.a UnsignedNumber.b + {: return new Symbol(new Write(address(a), b)); :} + | READ.a UnsignedNumber.b + {: return new Symbol(new Read(address(a), b)); :} + ; + +UnsignedNumber + = NUMBER.a + {: return new Symbol(ParserUtils.safeSymbolToInt(a, (ErrorEvents) report)); :} + ; + +Number + = UnsignedNumber.a + {: return new Symbol(a); :} + | MINUS UnsignedNumber.a + {: return new Symbol(-a); :} + ; + diff --git a/grammar/am0c0/c0-lexer.l b/grammar/am0c0/c0-lexer.l new file mode 100644 index 0000000..5a11cb2 --- /dev/null +++ b/grammar/am0c0/c0-lexer.l @@ -0,0 +1,74 @@ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +package org.jalgo.module.am0c0.parser.c0; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.am0c0.parser.ParserConstants; +import org.jalgo.module.am0c0.parser.c0.GeneratedC0Parser.Terminals; + +%% + +%class C0Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Identifier = [:jletter:][:jletterdigit:]* +Number = 0 | [1-9][0-9]* +Comment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +Whitespace = {LineTerminator} | [\t\f ] + +%% + +{Comment} { /* ignore */ } +{Whitespace}+ { /* ignore */ } +"#include" { return symbol(Terminals.INCLUDE, "#include"); } +"" { return symbol(Terminals.STDIO, ""); } +"int" { return symbol(Terminals.INT, "int"); } +"main" { return symbol(Terminals.MAIN, "main"); } +"(" { return symbol(Terminals.LPAREN, "("); } +")" { return symbol(Terminals.RPAREN, ")"); } +"{" { return symbol(Terminals.LBRACKET, "{"); } +"}" { return symbol(Terminals.RBRACKET, "}"); } +"=" { return symbol(Terminals.ASSIGN, "="); } +"," { return symbol(Terminals.COMMA, ","); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"&" { return symbol(Terminals.AMP, "&"); } +"const" { return symbol(Terminals.CONST, "const"); } +"if" { return symbol(Terminals.IF, "if"); } +"else" { return symbol(Terminals.ELSE, "else"); } +"while" { return symbol(Terminals.WHILE, "while"); } +"printf" { return symbol(Terminals.PRINTF, "printf"); } +"scanf" { return symbol(Terminals.SCANF, "scanf"); } +"\"%i\"" { return symbol(Terminals.IFORMAT, "\"%i\""); } +"\"%d\"" { return symbol(Terminals.DFORMAT, "\"%d\""); } +"return" {Whitespace}+ "0" { return symbol(Terminals.RETURN, "return 0"); } +"+" { return symbol(Terminals.PLUS, "+"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"/" { return symbol(Terminals.DIV, "/"); } +"*" { return symbol(Terminals.MULT, "*"); } +"%" { return symbol(Terminals.MOD, "%"); } +"==" { return symbol(Terminals.EQ, "=="); } +"!=" { return symbol(Terminals.NE, "!="); } +">=" { return symbol(Terminals.GE, ">="); } +"<=" { return symbol(Terminals.LE, "<="); } +">" { return symbol(Terminals.GT, ">"); } +"<" { return symbol(Terminals.LT, "<"); } +{Identifier} { return symbol(Terminals.IDENT, yytext()); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } diff --git a/grammar/am0c0/c0-parser.g b/grammar/am0c0/c0-parser.g new file mode 100644 index 0000000..53bdc98 --- /dev/null +++ b/grammar/am0c0/c0-parser.g @@ -0,0 +1,167 @@ +// Author: Martin Morgenstern +%header {: +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +:}; +%package "org.jalgo.module.am0c0.parser.c0"; +%import "org.jalgo.module.am0c0.parser.ErrorEvents"; +%import "org.jalgo.module.am0c0.parser.ParserUtils"; +%import "org.jalgo.module.am0c0.model.c0.ast.*"; +%import "org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType"; + +%class "GeneratedC0Parser"; + +%init {: + this.report = ErrorEvents.forC0(); +:}; + +%embed {: + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + + private int convert(final Symbol symbol) { + return ParserUtils.safeSymbolToInt(symbol, (ErrorEvents) report); + } +:}; + +%terminals INCLUDE, STDIO; +%terminals IF, ELSE, WHILE, MAIN, PRINTF, SCANF, RETURN, INT, CONST; +%terminals IFORMAT, DFORMAT; +%terminals COMMA, SEMICOLON, AMP, ASSIGN; +%terminals PLUS, MINUS, MULT, DIV, MOD; +%terminals EQ, NE, GE, LE, GT, LT; +%terminals LBRACKET, RBRACKET, LPAREN, RPAREN; +%terminals NUMBER, IDENT; + +%typeof Factor = "Factor"; +%typeof Term = "Term"; +%typeof SimpleExpr = "SimpleExpr"; +%typeof Statement = "Statement"; +%typeof Relation = "AtomicType"; +%typeof Program = "Program"; +%typeof Block = "Block"; +%typeof BoolExpr = "BoolExpression"; +%typeof StatementSequence = "StatementSequence"; +%typeof Declaration = "Declaration"; +%typeof ConstDeclaration = "ConstDeclaration"; +%typeof VarDeclaration = "VarDeclaration"; + +%typeof IDENT = "String"; + +// resolve shift-reduce conflict (dangling else) +%nonassoc ELSE; +%nonassoc IF; + +%goal Program; + +Program + = INCLUDE STDIO INT MAIN LPAREN RPAREN Block.b + {: return new Symbol(new Program(b)); :} + ; + +Block + = LBRACKET Declaration.d StatementSequence.s RETURN SEMICOLON RBRACKET + {: return new Symbol(new Block(d, s)); :} + | LBRACKET Declaration.d RETURN SEMICOLON RBRACKET + {: return new Symbol(new Block(d, null)); :} + ; + +StatementSequence + = Statement.stat + {: return new Symbol(new StatementSequence(stat)); :} + | StatementSequence.seq Statement.stat + {: seq.addStatement(stat); return new Symbol(seq); :} + ; + +Declaration + = + {: return new Symbol(new Declaration(null, null)); :} + | ConstDeclaration.constdecl SEMICOLON + {: return new Symbol(new Declaration(constdecl, null)); :} + | VarDeclaration.vardecl SEMICOLON + {: return new Symbol(new Declaration(null, vardecl)); :} + | ConstDeclaration.constdecl SEMICOLON VarDeclaration.vardecl SEMICOLON + {: return new Symbol(new Declaration(constdecl, vardecl)); :} + ; + +ConstDeclaration + = CONST IDENT.i ASSIGN NUMBER.n + {: return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, convert(n)))); :} + | CONST IDENT.i ASSIGN MINUS NUMBER.n + {: return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, -convert(n)))); :} + | ConstDeclaration.d COMMA IDENT.i ASSIGN NUMBER.n + {: d.addConstant(new C0AST.ConstIdent(i, convert(n))); return new Symbol(d); :} + | ConstDeclaration.d COMMA IDENT.i ASSIGN MINUS NUMBER.n + {: d.addConstant(new C0AST.ConstIdent(i, -convert(n))); return new Symbol(d); :} + ; + +VarDeclaration + = INT IDENT.i + {: return new Symbol(new VarDeclaration(new C0AST.Ident(i))); :} + | VarDeclaration.d COMMA IDENT.i + {: d.addVariable(new C0AST.Ident(i)); return new Symbol(d); :} + ; + +Statement + = IDENT.i ASSIGN SimpleExpr.e SEMICOLON + {: return new Symbol(new Statement.AssignmentStatement(i, e)); :} + | IF LPAREN BoolExpr.e RPAREN Statement.s + {: return new Symbol(new Statement.IfStatement(e, s)); :} + | IF LPAREN BoolExpr.e RPAREN Statement.s1 ELSE Statement.s2 + {: return new Symbol(new Statement.IfElseStatement(e, s1, s2)); :} + | WHILE LPAREN BoolExpr.e RPAREN Statement.s + {: return new Symbol(new Statement.WhileStatement(e, s)); :} + | PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON + {: return new Symbol(new Statement.PrintfStatement(i)); :} + | SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON + {: return new Symbol(new Statement.ScanfStatement(i)); :} + | LBRACKET StatementSequence.s RBRACKET + {: return new Symbol(new Statement.CompStatement(s)); :} + ; + +BoolExpr + = SimpleExpr.l Relation.rel SimpleExpr.r + {: return new Symbol(new BoolExpression(l, rel, r)); :} + ; + +Relation + = EQ {: return new Symbol(AtomicType.EQ); :} + | NE {: return new Symbol(AtomicType.NE); :} + | LE {: return new Symbol(AtomicType.LE); :} + | GE {: return new Symbol(AtomicType.GE); :} + | LT {: return new Symbol(AtomicType.LT); :} + | GT {: return new Symbol(AtomicType.GT); :} + ; + +SimpleExpr + = Term.t + {: return new Symbol(new SimpleExpr.UnaryPlusExpr(t)); :} + | PLUS Term.t + {: return new Symbol(new SimpleExpr.UnaryPlusExpr(t)); :} + | MINUS Term.t + {: return new Symbol(new SimpleExpr.UnaryMinusExpr(t)); :} + | SimpleExpr.s PLUS Term.t + {: return new Symbol(new SimpleExpr.PlusExpr(s, t)); :} + | SimpleExpr.s MINUS Term.t + {: return new Symbol(new SimpleExpr.MinusExpr(s, t)); :} + ; + +Term + = Factor.f + {: return new Symbol(new Term.FactorTerm(f)); :} + | Term.t MULT Factor.f + {: return new Symbol(new Term.MultTerm(t, f)); :} + | Term.t DIV Factor.f + {: return new Symbol(new Term.DivTerm(t, f)); :} + | Term.t MOD Factor.f + {: return new Symbol(new Term.ModTerm(t, f)); :} + ; + +Factor + = IDENT.i + {: return new Symbol(new Factor.IdentFactor(i)); :} + | NUMBER.n + {: return new Symbol(new Factor.NumberFactor(convert(n))); :} + | LPAREN SimpleExpr.s RPAREN + {: return new Symbol(new Factor.CompExprFactor(s)); :} + ; diff --git a/grammar/am1simulator/CVS/Entries b/grammar/am1simulator/CVS/Entries new file mode 100644 index 0000000..5438392 --- /dev/null +++ b/grammar/am1simulator/CVS/Entries @@ -0,0 +1,2 @@ +/am1-lexer.l/1.1/Mon Mar 7 19:57:19 2011/-kb/ +/am1-parser.g/1.1/Mon Mar 7 19:57:19 2011/-kb/ diff --git a/grammar/am1simulator/CVS/Repository b/grammar/am1simulator/CVS/Repository new file mode 100644 index 0000000..961d0f1 --- /dev/null +++ b/grammar/am1simulator/CVS/Repository @@ -0,0 +1 @@ +j-algo/grammar/am1simulator diff --git a/grammar/am1simulator/CVS/Root b/grammar/am1simulator/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/grammar/am1simulator/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/grammar/am1simulator/am1-lexer.l b/grammar/am1simulator/am1-lexer.l new file mode 100644 index 0000000..fbcc888 --- /dev/null +++ b/grammar/am1simulator/am1-lexer.l @@ -0,0 +1,76 @@ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +/* Author: Max Leuthäuser */ + +package parser.am1; + +import beaver.Symbol; +import beaver.Scanner; +import parser.ParserConstants; +import parser.am1.GeneratedAM1Parser.Terminals; + +%% + +%class AM1Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Number = 0 | [1-9][0-9]* +Whitespace = [\t\f ] + +%% + +{Whitespace}+ { /* ignore */ } +{LineTerminator} { return symbol(Terminals.EOL, ParserConstants.EOL); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"," { return symbol(Terminals.COMMA, ","); } +"(" { return symbol(Terminals.LBRAKET, "("); } +")" { return symbol(Terminals.RBRAKET, ")"); } +"lokal" { return symbol(Terminals.LOCAL, "lokal"); } +"global" { return symbol(Terminals.GLOBAL, "global"); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +"ADD" { return symbol(Terminals.ADD, "ADD"); } +"MUL" { return symbol(Terminals.MUL, "MUL"); } +"SUB" { return symbol(Terminals.SUB, "SUB"); } +"DIV" { return symbol(Terminals.DIV, "DIV"); } +"MOD" { return symbol(Terminals.MOD, "MOD"); } +"EQ" { return symbol(Terminals.EQ, "EQ"); } +"NE" { return symbol(Terminals.NE, "NE"); } +"LT" { return symbol(Terminals.LT, "LT"); } +"GT" { return symbol(Terminals.GT, "GT"); } +"LE" { return symbol(Terminals.LE, "LE"); } +"GE" { return symbol(Terminals.GE, "GE"); } +"LOAD" { return symbol(Terminals.LOAD, "LOAD"); } +"LOADA" { return symbol(Terminals.LOADA, "LOADA"); } +"LOADI" { return symbol(Terminals.LOADI, "LOADI"); } +"STORE" { return symbol(Terminals.STORE, "STORE"); } +"STOREI" { return symbol(Terminals.STOREI, "STOREI"); } +"LIT" { return symbol(Terminals.LIT, "LIT"); } +"JMP" { return symbol(Terminals.JMP, "JMP"); } +"JMC" { return symbol(Terminals.JMC, "JMC"); } +"WRITE" { return symbol(Terminals.WRITE, "WRITE"); } +"WRITEI" { return symbol(Terminals.WRITEI, "WRITEI"); } +"READ" { return symbol(Terminals.READ, "READ"); } +"READI" { return symbol(Terminals.READI, "READI"); } +"PUSH" { return symbol(Terminals.PUSH, "PUSH"); } +"CALL" { return symbol(Terminals.CALL, "CALL"); } +"INIT" { return symbol(Terminals.INIT, "INIT"); } +"RET" { return symbol(Terminals.RET, "RET"); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } + diff --git a/grammar/am1simulator/am1-parser.g b/grammar/am1simulator/am1-parser.g new file mode 100644 index 0000000..b461615 --- /dev/null +++ b/grammar/am1simulator/am1-parser.g @@ -0,0 +1,145 @@ +// Author: Max Leuthäuser +%header {: +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +:}; +%package "parser.am1"; +%import "parser.ErrorEvents"; +%import "parser.ParserUtils"; +%import "model.LineAddress"; +%import "model.AddressException"; +%import "model.am1.*"; +%import "model.am1.AbstractStatementFactory.Statement"; + +%class "GeneratedAM1Parser"; + +%embed {: + private ArithmeticStatementFactory arithmetic = new ArithmeticStatementFactory(); + private CompareStatementFactory compare = new CompareStatementFactory(); + private IOStatementFactory io = new IOStatementFactory(); + private JumpStatementFactory jump = new JumpStatementFactory(); + private MemoryStatementFactory memory = new MemoryStatementFactory(); + private ProceduralStatementFactory procedural = new ProceduralStatementFactory(); + + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } +:}; + +%init {: + this.report = ErrorEvents.forAm1(); +:}; + +%terminals ADD, MUL, SUB, DIV, MOD; +%terminals EQ, NE, LT, GT, LE, GE; +%terminals LOAD, STORE, LIT; +%terminals LOADA, LOADI, STOREI; +%terminals JMP, JMC; +%terminals WRITE, READ; +%terminals WRITEI, READI; +%terminals PUSH, CALL, INIT, RET; +%terminals EOL, SEMICOLON, COMMA; +%terminals NUMBER, MINUS, LBRAKET, RBRAKET; +%terminals GLOBAL, LOCAL; + +%goal Program; + +%typeof CommandList, Program = "AM1Program"; +%typeof Command = "SimulationStatement"; +%typeof UnsignedNumber, Number = "Integer"; +%typeof Location = "String"; + +Program + = CommandList + ; + +CommandList + = Command.a SEMICOLON + {: AM1Program program = new AM1Program(); program.add(a); return new Symbol(program); :} + | CommandList.a EOL Command.b SEMICOLON + {: a.add(b); return new Symbol(a); :} + ; + +Command + = ADD.a + {: return new Symbol(arithmetic.newStatement(Statement.ADD, new StatementResource.Builder(address(a)).build())); :} + | MUL.a + {: return new Symbol(arithmetic.newStatement(Statement.MUL, new StatementResource.Builder(address(a)).build())); :} + | SUB.a + {: return new Symbol(arithmetic.newStatement(Statement.SUB, new StatementResource.Builder(address(a)).build())); :} + | DIV.a + {: return new Symbol(arithmetic.newStatement(Statement.DIV, new StatementResource.Builder(address(a)).build())); :} + | MOD.a + {: return new Symbol(arithmetic.newStatement(Statement.MOD, new StatementResource.Builder(address(a)).build())); :} + | EQ.a + {: return new Symbol(compare.newStatement(Statement.EQUAL, new StatementResource.Builder(address(a)).build())); :} + | NE.a + {: return new Symbol(compare.newStatement(Statement.NOTEQUAL, new StatementResource.Builder(address(a)).build())); :} + | LT.a + {: return new Symbol(compare.newStatement(Statement.LESSERTHEN, new StatementResource.Builder(address(a)).build())); :} + | GT.a + {: return new Symbol(compare.newStatement(Statement.GREATERTHEN, new StatementResource.Builder(address(a)).build())); :} + | LE.a + {: return new Symbol(compare.newStatement(Statement.LESSEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | GE.a + {: return new Symbol(compare.newStatement(Statement.GREATEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | JMP.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMP, new StatementResource.Builder(address(a)).value(b).build())); :} + | JMC.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMC, new StatementResource.Builder(address(a)).value(b).build())); :} + | LOAD.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOAD, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADA.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADA, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADI, new StatementResource.Builder(address(a)).value(b).build())); :} + | STORE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.STORE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | STOREI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.STOREI, new StatementResource.Builder(address(a)).value(b).build())); :} + | WRITE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | WRITEI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITEI, new StatementResource.Builder(address(a)).value(b).build())); :} + | READ.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.READ, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | READI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.READI, new StatementResource.Builder(address(a)).value(b).build())); :} + | PUSH.a + {: return new Symbol(procedural.newStatement(Statement.PUSH, new StatementResource.Builder(address(a)).build())); :} + | CALL.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.CALL, new StatementResource.Builder(address(a)).value(b).build())); :} + | INIT.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.INIT, new StatementResource.Builder(address(a)).value(b).build())); :} + | RET.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.RET, new StatementResource.Builder(address(a)).value(b).build())); :} + | LIT.a Number.b + {: return new Symbol(procedural.newStatement(Statement.LIT, new StatementResource.Builder(address(a)).value(b).build())); :} + ; + +UnsignedNumber + = NUMBER.a + {: return new Symbol(ParserUtils.safeSymbolToInt(a, (ErrorEvents) report)); :} + ; + +Location + = LOCAL + {: return new Symbol("lokal"); :} + | GLOBAL + {: return new Symbol("global"); :} + ; + +Number + = UnsignedNumber.a + {: return new Symbol(a); :} + | MINUS UnsignedNumber.a + {: return new Symbol(-a); :} + ; + diff --git a/grammar/unifikation/CVS/Entries b/grammar/unifikation/CVS/Entries new file mode 100644 index 0000000..e939b5e --- /dev/null +++ b/grammar/unifikation/CVS/Entries @@ -0,0 +1 @@ +/UnificationSet.g/1.1/Wed Dec 8 13:10:00 2010// diff --git a/grammar/unifikation/CVS/Repository b/grammar/unifikation/CVS/Repository new file mode 100644 index 0000000..4996aeb --- /dev/null +++ b/grammar/unifikation/CVS/Repository @@ -0,0 +1 @@ +j-algo/grammar/unifikation diff --git a/grammar/unifikation/CVS/Root b/grammar/unifikation/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/grammar/unifikation/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/grammar/unifikation/UnificationSet.g b/grammar/unifikation/UnificationSet.g new file mode 100644 index 0000000..559df34 --- /dev/null +++ b/grammar/unifikation/UnificationSet.g @@ -0,0 +1,89 @@ +grammar UnificationSet; +options { + output=AST; + ASTLabelType=CommonTree; + } + +tokens { + X = 'x' ; + Y = 'y' ; + Z = 'z' ; + U = 'u' ; + V = 'v' ; + W = 'w' ; + LBRACKET = '('; + RBRACKET = ')'; + + STARTSET = 'm='; + COMMA = ','; + OPENBRACE = '{'; + CLOSEBRACE = '}'; + SET; + PAIR; + CONSTRUCTOR; + VARIABLE; +} + +@lexer::header{ + package org.jalgo.module.unifikation.parser; +} + +@parser::header{ + package org.jalgo.module.unifikation.parser; + import java.util.Map; + import java.util.HashMap; + import java.util.TreeMap; + import java.util.List; + import java.util.ArrayList; +} + +@parser::members{ + //Constructorsymbol->arity->position + public Map>> constructorArity=new HashMap>>(); + private void AddConstructorArity(String constructorSymbol, int arity, Token tPos){ + int pos=-1; + if(tPos!=null) pos=tPos.getCharPositionInLine(); + if(!constructorArity.containsKey(constructorSymbol)){ + constructorArity.put(constructorSymbol, new TreeMap>()); + } + Map> arityMap=constructorArity.get(constructorSymbol); + if(!arityMap.containsKey(arity)){ + arityMap.put(arity, new ArrayList()); + } + arityMap.get(arity).add(pos); + } +} + +unificationset : set^; +set : STARTSET OPENBRACE ws (pair ( ws COMMA ws pair)* ws)? CLOSEBRACE -> ^(SET pair*); + +pair : LBRACKET ws first=term COMMA second=term ws RBRACKET ->^(PAIR $first $second); + +term : constructor | variable ; + +constructor : symbol=constructorsymbol (ws LBRACKET ws (ids+=term (ws COMMA ws ids+=term)* ws)? RBRACKET)? {AddConstructorArity($symbol.text,$ids==null?0:$ids.size(),$symbol.start);} ->^(CONSTRUCTOR constructorsymbol term*); + +constructorsymbol : ALPHA|BETA|GAMMA|DELTA|EPSILON|THETA; + +variable : varid INT? ->^(VARIABLE varid INT?); +varid : X|Y|Z|U|V|W; + +ws! : WS?; + +ALPHA : '\u03B1'|'a' ; +BETA : '\u03B2'|'b' ; +GAMMA : '\u03B3'|'c' ; +DELTA : '\u03B4'|'d' ; +EPSILON : '\u03B5'|'e' ; +THETA : '\u03B8'|'t' ; + +INT : '0'..'9'+ ; + + +WS : ( ' ' + | '\t' + | '\r' + | '\n' + )+ {$channel=HIDDEN;} + ; + diff --git a/j-Algo.bat b/j-Algo.bat new file mode 100644 index 0000000..7735575 --- /dev/null +++ b/j-Algo.bat @@ -0,0 +1,3 @@ +@echo off +javaw -Djava.library.path=extlibs -Djava.ext.dirs=runtime/modules -jar runtime/j-Algo.jar +@echo on \ No newline at end of file diff --git a/j-Algo.ico b/j-Algo.ico new file mode 100644 index 0000000..dd88002 Binary files /dev/null and b/j-Algo.ico differ diff --git a/j-Algo.sh b/j-Algo.sh new file mode 100644 index 0000000..282d914 --- /dev/null +++ b/j-Algo.sh @@ -0,0 +1,3 @@ +#!/bin/sh +cd `dirname $0` +exec java -Djava.library.path=extlibs -Djava.ext.dirs=runtime/modules -jar runtime/j-Algo.jar $* diff --git a/module-manifest.mf b/module-manifest.mf new file mode 100644 index 0000000..7d170ef --- /dev/null +++ b/module-manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.2 +Class-Path: ../j-Algo.jar + diff --git a/out.log b/out.log new file mode 100644 index 0000000..e69de29 diff --git a/program-manifest.mf b/program-manifest.mf new file mode 100644 index 0000000..7be8d5f --- /dev/null +++ b/program-manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.21 +Main-Class: org.jalgo.main.JAlgoMain +Class-Path: ../extlibs/jh.jar ../extlibs/swing-layout-1.0.jar diff --git a/relicts/CVS/Entries b/relicts/CVS/Entries new file mode 100644 index 0000000..88de5a4 --- /dev/null +++ b/relicts/CVS/Entries @@ -0,0 +1,5 @@ +/build-all.sh/1.1/Mon Feb 18 20:53:18 2008/-kb/ +/build-system.sh/1.1/Mon Feb 18 20:53:18 2008/-kb/ +/build.xml/1.1/Mon Feb 18 20:53:18 2008// +D/org//// +D/pix//// diff --git a/relicts/CVS/Repository b/relicts/CVS/Repository new file mode 100644 index 0000000..bcf6e2c --- /dev/null +++ b/relicts/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts diff --git a/relicts/CVS/Root b/relicts/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/build-all.sh b/relicts/build-all.sh new file mode 100644 index 0000000..50a8479 --- /dev/null +++ b/relicts/build-all.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# $Id: build-all.sh,v 1.1 2005/06/23 09:22:58 jalgosequoia Exp $ + +for SYSTEM in freebsd linux windows macosx; do + echo "Building for $SYSTEM..." + ./build-system.sh $SYSTEM + rm -dR jalgo-$SYSTEM + echo "Building complete for $SYSTEM" + echo "" +done + +echo "Computing checksums..." +openssl sha1 *.tgz *.zip > CHECKSUMS + diff --git a/relicts/build-system.sh b/relicts/build-system.sh new file mode 100644 index 0000000..d7453eb --- /dev/null +++ b/relicts/build-system.sh @@ -0,0 +1,67 @@ +#!/bin/sh + +if [ $# -ne 1 ]; then + echo "Usage: $0 SYSTEM" + exit 1 +fi + +SYSTEM=$1 +TARGETDIR=jalgo-$SYSTEM +TMP=`pwd`/tmp +MANIFEST=manifest.tmp + +echo "Cleaning up..." +rm -dRf $TMP +mkdir $TMP +rm -dRf $TARGETDIR +mkdir $TARGETDIR + +echo "Compiling..." + +( cd .. ; ant -q $SYSTEM ) || exit 1 + +echo "Populating tmp directory..." +cp -R ../bin/* $TMP + +echo "Copying third party stuff into $TARGETDIR..." +mkdir $TARGETDIR/extlibs +cp ../extlibs/*.jar ../extlibs/$SYSTEM/* $TARGETDIR/extlibs +cp -R ../pix $TARGETDIR/ +cp -R ../res $TARGETDIR/ + + +echo "Removing CVS directories..." +find $TMP $TARGETDIR -type d -and -name CVS -print0 | xargs -0 rm -dR + +echo "Creating Manifest..." +echo "Manifest-Version: 1.0" > $MANIFEST +echo "Main-Class: org.jalgo.main.Jalgo" >> $MANIFEST +echo -n "Class-Path:" >> $MANIFEST +for JAR in `( cd $TARGETDIR ; find extlibs -name "*.jar")` ; do + echo -n " $JAR" >> $MANIFEST +done +echo "" >> $MANIFEST + +echo "Creating JAR..." +jar cfm $TARGETDIR/jalgo.jar $MANIFEST -C $TMP/ . + +echo "Writing start script..." +if [ $SYSTEM = windows ]; then + START=$TARGETDIR/start.bat + echo 'javaw -Djava.library.path=extlibs -jar jalgo.jar' > $START + echo "Creating ZIP archive for winy windows users..." + zip -r $TARGETDIR $TARGETDIR +else + START=$TARGETDIR/start.sh + echo '#!/bin/sh' > $START + echo 'java -Djava.library.path=extlibs/ -jar jalgo.jar $*' >> $START + chmod +x $START + echo "Creating tarball..." + tar czf $TARGETDIR.tgz $TARGETDIR +fi + + +echo "Cleaning up (again)..." +rm -dRf $TMP +rm $MANIFEST + diff --git a/relicts/build.xml b/relicts/build.xml new file mode 100644 index 0000000..720dff5 --- /dev/null +++ b/relicts/build.xml @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/CVS/Entries b/relicts/org/CVS/Entries new file mode 100644 index 0000000..9b8af53 --- /dev/null +++ b/relicts/org/CVS/Entries @@ -0,0 +1 @@ +D/jalgo//// diff --git a/relicts/org/CVS/Repository b/relicts/org/CVS/Repository new file mode 100644 index 0000000..4adebfa --- /dev/null +++ b/relicts/org/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org diff --git a/relicts/org/CVS/Root b/relicts/org/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/CVS/Entries b/relicts/org/jalgo/CVS/Entries new file mode 100644 index 0000000..f09dcc5 --- /dev/null +++ b/relicts/org/jalgo/CVS/Entries @@ -0,0 +1,3 @@ +D/main//// +D/module//// +D/tests//// diff --git a/relicts/org/jalgo/CVS/Repository b/relicts/org/jalgo/CVS/Repository new file mode 100644 index 0000000..3114750 --- /dev/null +++ b/relicts/org/jalgo/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo diff --git a/relicts/org/jalgo/CVS/Root b/relicts/org/jalgo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/CVS/Entries b/relicts/org/jalgo/main/CVS/Entries new file mode 100644 index 0000000..9a436c5 --- /dev/null +++ b/relicts/org/jalgo/main/CVS/Entries @@ -0,0 +1,4 @@ +D/gfx//// +D/gui//// +D/trees//// +D/util//// diff --git a/relicts/org/jalgo/main/CVS/Repository b/relicts/org/jalgo/main/CVS/Repository new file mode 100644 index 0000000..b1a6990 --- /dev/null +++ b/relicts/org/jalgo/main/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main diff --git a/relicts/org/jalgo/main/CVS/Root b/relicts/org/jalgo/main/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/gfx/AnimationData.java b/relicts/org/jalgo/main/gfx/AnimationData.java new file mode 100644 index 0000000..e46c12a --- /dev/null +++ b/relicts/org/jalgo/main/gfx/AnimationData.java @@ -0,0 +1,70 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 25.05.2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.geometry.Point; + +/** + * @author Hauke Menges + */ +public class AnimationData { + private org.jalgo.main.util.Timer timer; + private int offset, duration; + private Point endPoint, startPoint; + private IAnimationConcept animationConcept; + + + public AnimationData(Point endPoint, IAnimationConcept animationConcept, int offset, int duration){ + this.endPoint = endPoint; + this.animationConcept = animationConcept; + this.offset = offset; + this.duration = duration; + } + + public org.jalgo.main.util.Timer getTimer(){ + return this.timer; + } + + public int getOffset(){ + return this.offset; + } + + public int getDuration(){ + return this.duration; + } + + public Point getEndPoint(){ + //return new LinearAnimationConcept().calculate(new Point(0,0),new Point(0,0),0.0); //Test... works :). Usually: new Point(); + return this.endPoint; + } + + public Point getStartPoint(){ + return this.startPoint; + } + + public IAnimationConcept getAnimationConcept(){ + return this.animationConcept; + } + +} diff --git a/relicts/org/jalgo/main/gfx/Animator.java b/relicts/org/jalgo/main/gfx/Animator.java new file mode 100644 index 0000000..f67fdeb --- /dev/null +++ b/relicts/org/jalgo/main/gfx/Animator.java @@ -0,0 +1,45 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 25.05.2004 + */ + +package org.jalgo.main.gfx; + +import java.util.HashMap; +import org.eclipse.draw2d.IFigure; + +/** + * Performs animations. + * + * @author Hauke Menges + */ +public class Animator { + + /** + * Calculates and displays all animations that are stored in hashMap. + * + * @param panel The parent figure + * @param hashMap A HashMap of the form (Figure, AnimationDate) + */ + public static void run(IFigure panel, HashMap hashMap){ + } + +} diff --git a/relicts/org/jalgo/main/gfx/BorderFlowLayout.java b/relicts/org/jalgo/main/gfx/BorderFlowLayout.java new file mode 100644 index 0000000..ef73d2c --- /dev/null +++ b/relicts/org/jalgo/main/gfx/BorderFlowLayout.java @@ -0,0 +1,213 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + + +package org.jalgo.main.gfx; +import java.util.*; + +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.*; + +/** + * Lays out children in rows or columns, wrapping when the current row/column is filled. + * The aligment and spacing of rows in the parent can be configured. The aligment and + * spacing of children within a row can be configured. Wraps already 40 before the end + * of the row leaving place for hte connections. + * + * @see org.eclipse.draw2d.FlowLayout + * @author Anne Kersten + */ +public class BorderFlowLayout + extends FlowLayout +{ + +/** The alignment along the minor axis. */ +protected int minorAlignment = ALIGN_LEFTTOP; + +/** The alignment along the major axis. */ +protected int majorAlignment = ALIGN_LEFTTOP; + +/** The spacing along the minor axis. */ +protected int minorSpacing = 5; + +/** The spacing along the major axis. */ +protected int majorSpacing = 5; + +private WorkingData data = null; + +/** + * Holds the necessary information for layout calculations. + */ +class WorkingData { + int rowHeight, rowWidth, rowCount, rowX, rowY, maxWidth; + Rectangle bounds[], area; + IFigure row[]; +} + +/** + * Constructs a BorderFlowLayout with horizontal orientation. + */ +public BorderFlowLayout() { } + +/** + * Constructs a BorderFlowLayout whose orientation is given in the input. + * @param isHorizontal true if the layout should be horizontal + * + */ +public BorderFlowLayout(boolean isHorizontal) { + super.setHorizontal(isHorizontal); +} + +/** + * Initializes state data for laying out children, based on the Figure given as input. + * + * @param parent the parent figure + * @see org.eclipse.draw2d.FlowLayout#initVariables(IFigure) + */ +private void initVariables(IFigure parent) { + data.row = new IFigure[parent.getChildren().size()]; + data.bounds = new Rectangle[data.row.length]; + data.maxWidth = data.area.width; +} + +/** + * Initializes the state of row data, which is internal to the layout process. + * @see org.eclipse.draw2d.FlowLayout#initRow() + */ +private void initRow() { + data.rowX = 0; + data.rowHeight = 0; + data.rowWidth = 0; + data.rowCount = 0; +} + +/** + * Layouts one row of components. This is done based on the layout's orientation, minor + * alignment and major alignment. + * + * @param parent the parent figure + * @since 2.0 + */ +protected void layoutRow(IFigure parent) { + int majorAdjustment = 0; + int minorAdjustment = 0; + int correctMajorAlignment = majorAlignment; + int correctMinorAlignment = minorAlignment; + + majorAdjustment = data.area.width - data.rowWidth + getMinorSpacing(); + + switch (correctMajorAlignment) { + case ALIGN_LEFTTOP: + majorAdjustment = 0; + break; + case ALIGN_CENTER: + majorAdjustment /= 2; + break; + case ALIGN_RIGHTBOTTOM: + break; + } + + for (int j = 0; j < data.rowCount; j++) { + if (fill) { + data.bounds[j].height = data.rowHeight; + } else { + minorAdjustment = data.rowHeight - data.bounds[j].height; + switch (correctMinorAlignment) { + case ALIGN_LEFTTOP: + minorAdjustment = 0; + break; + case ALIGN_CENTER: + minorAdjustment /= 2; + break; + case ALIGN_RIGHTBOTTOM: + break; + } + data.bounds[j].y += minorAdjustment; + } + data.bounds[j].x += majorAdjustment; + + setBoundsOfChild(parent, data.row[j], transposer.t(data.bounds[j])); + } + data.rowY += getMajorSpacing() + data.rowHeight; + initRow(); +} + + +/** * @see org.eclipse.draw2d.LayoutManager#layout(IFigure) + * */ +public void layout(IFigure parent) { + data = new WorkingData(); + Rectangle relativeArea = parent.getClientArea(); + data.area = transposer.t(relativeArea); + + Iterator iterator = parent.getChildren().iterator(); + int dx; + + //Calculate the hints to be passed to children + int wHint = -1; + int hHint = -1; + if (isHorizontal()) + wHint = parent.getClientArea().width; + else + hHint = parent.getClientArea().height; + + initVariables(parent); + initRow(); + int i = 0; + while (iterator.hasNext()) { + IFigure f = (IFigure)iterator.next(); + Dimension pref = transposer.t(getChildSize(f, wHint, hHint)); + Rectangle r = new Rectangle(0, 0, pref.width, pref.height); + + if (data.rowCount > 0) { + if(horizontal) + {if (data.rowWidth + pref.width + 40 > data.maxWidth) + layoutRow(parent);} + else if (data.rowWidth + pref.width > data.maxWidth) + layoutRow(parent); + } + r.x = data.rowX; + r.y = data.rowY; + dx = r.width + getMinorSpacing(); + data.rowX += dx; + data.rowWidth += dx; + data.rowHeight = Math.max(data.rowHeight, r.height); + data.row [data.rowCount] = f; + data.bounds[data.rowCount] = r; + data.rowCount++; + i++; + } + if (data.rowCount != 0) + layoutRow(parent); + data = null; +} + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gfx/BottomLineBorder.java b/relicts/org/jalgo/main/gfx/BottomLineBorder.java new file mode 100644 index 0000000..10b0272 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/BottomLineBorder.java @@ -0,0 +1,64 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Jun 15, 2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.AbstractBorder; +import org.eclipse.draw2d.Graphics; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Insets; +import org.eclipse.draw2d.geometry.Point; + +/** + * @author Malte Blumberg + */ +public class BottomLineBorder extends AbstractBorder { + /* + private int textWidth; + + public BottomLineBorder(int textWidth) + { + this.textWidth=textWidth; + } + */ + public Insets getInsets(IFigure arg0) { + return new Insets(0); + } + + public void paint(IFigure figure, Graphics graphics, Insets insets) { + + graphics.setLineWidth(1); + Point startPoint = + new Point( + getPaintRectangle(figure, insets).getBottomLeft().x, + getPaintRectangle(figure, insets).getBottom().y - 1); + Point endPoint = + new Point( + getPaintRectangle(figure, insets).getBottomRight().x, + getPaintRectangle(figure, insets).getBottom().y - 1); + + graphics.drawLine(startPoint, endPoint); + + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gfx/CVS/Entries b/relicts/org/jalgo/main/gfx/CVS/Entries new file mode 100644 index 0000000..dd2aa65 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/CVS/Entries @@ -0,0 +1,15 @@ +/AnimationData.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/Animator.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/BorderFlowLayout.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/BottomLineBorder.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/ClickListener.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/Dragger.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/EllipseLabel.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/FixPointAnchor.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/IAnimationConcept.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/IClickAction.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/LinearAnimationConcept.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/MarkStyle.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/RectangleLabel.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/RoundedManhattanConnectionRouter.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ +/RoundedRectangleLabel.java/1.2/Sat Mar 4 13:36:01 2006/-kk/ diff --git a/relicts/org/jalgo/main/gfx/CVS/Repository b/relicts/org/jalgo/main/gfx/CVS/Repository new file mode 100644 index 0000000..f4290b1 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/gfx diff --git a/relicts/org/jalgo/main/gfx/CVS/Root b/relicts/org/jalgo/main/gfx/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/gfx/ClickListener.java b/relicts/org/jalgo/main/gfx/ClickListener.java new file mode 100644 index 0000000..958c0d4 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/ClickListener.java @@ -0,0 +1,116 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 13.06.2004 + * + */ +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.MouseEvent; +import org.eclipse.draw2d.MouseListener; +import org.eclipse.draw2d.MouseMotionListener; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Cursor; +import org.jalgo.main.util.ClickCollector; +import org.jalgo.main.util.GfxUtil; + +/** + * A ClickListener informs the ClickCollector that its Figure has been clicked. + * It also reports the click-position to the ClickCollector. + * + * Example: + * new ClickListener(mySWTfigure); + * + * @author Hauke Menges + */ +public class ClickListener + extends MouseMotionListener.Stub + implements MouseListener { + + private Figure myFigure; + private Point lastPoint; + private Color oldColor; + + public ClickListener(IFigure figure) { + figure.addMouseMotionListener(this); + figure.addMouseListener(this); + this.myFigure = (Figure) figure; + } + + public Figure getFigure() { + return myFigure; + } + + public Point getLastPoint() { + return lastPoint; + } + + public void mousePressed(MouseEvent event) { + lastPoint = event.getLocation(); + ClickCollector.addItem(this); + if (!ClickCollector.isCollecting()){ + mouseExited(event); + } + } + + @Override + public void mouseEntered(MouseEvent event) { + oldColor = this.myFigure.getBackgroundColor(); + if (ClickCollector.isCollecting()) { + GfxUtil.getAppShell().setCursor( + new Cursor( + GfxUtil.getAppShell().getDisplay(), + SWT.CURSOR_UPARROW)); + + // maybe change this back later on... + //this.myFigure.setBackgroundColor(ColorConstants.lightBlue); + } + } + + @Override + public void mouseExited(MouseEvent event) { + GfxUtil.getAppShell().setCursor( + new Cursor( + GfxUtil.getAppShell().getDisplay(), + SWT.CURSOR_ARROW)); + this.myFigure.setBackgroundColor(oldColor); + } + + /* (non-Javadoc) + * @see org.eclipse.draw2d.MouseListener#mouseReleased(org.eclipse.draw2d.MouseEvent) + */ + public void mouseReleased(MouseEvent event) { + // this method has no effect + } + + /* (non-Javadoc) + * @see org.eclipse.draw2d.MouseListener#mouseDoubleClicked(org.eclipse.draw2d.MouseEvent) + */ + public void mouseDoubleClicked(MouseEvent event) { + // this method has no effect + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gfx/Dragger.java b/relicts/org/jalgo/main/gfx/Dragger.java new file mode 100644 index 0000000..a06f9aa --- /dev/null +++ b/relicts/org/jalgo/main/gfx/Dragger.java @@ -0,0 +1,73 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 11, 2004 + */ +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.MouseEvent; +import org.eclipse.draw2d.MouseListener; +import org.eclipse.draw2d.MouseMotionListener; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; + +/** + * @author Cornelius Hald + * @author Malte Blumberg + */ +public class Dragger extends MouseMotionListener.Stub implements MouseListener { + public Dragger(IFigure figure) { + figure.addMouseMotionListener(this); + figure.addMouseListener(this); + } + + private Point last; + private Figure dragFigure; + + public void mouseClicked(MouseEvent e) { + // this method has no effect + } + + public void mouseDoubleClicked(MouseEvent e) { + // this method has no effect + } + + public void mousePressed(MouseEvent e) { + last = new Point(Math.round((float) e.getLocation().x/10)*10,Math.round((float) e.getLocation().y/10)*10); + dragFigure=((Figure) e.getSource()); + } + + public void mouseReleased(MouseEvent e) { + dragFigure=null; + } + + public void mouseDragged(MouseEvent e) { + if (dragFigure != null) { + Point p = e.getLocation(); + Point next = new Point(Math.round((float) p.x/10)*10,Math.round((float) p.y/10)*10); + Dimension delta = new Dimension(next.x-last.x,next.y-last.y); + dragFigure.setLocation(dragFigure.getLocation().getTranslated(delta.width,delta.height)); + + last.setLocation(next); + } + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gfx/EllipseLabel.java b/relicts/org/jalgo/main/gfx/EllipseLabel.java new file mode 100644 index 0000000..a86d3c4 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/EllipseLabel.java @@ -0,0 +1,174 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 17, 2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.Border; +import org.eclipse.draw2d.Ellipse; +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.XYLayout; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; + +/** + * This class represents a graphical ellipse with 2 Labels.

+ * One Label is in the middle (mainLabel) and one Label (indexLabel) + * is at the top-right corner. + * + * @author Malte Blumberg + */ +public class EllipseLabel extends Ellipse { + + private Label mainLabel; + private Label indexLabel; + private XYLayout layout; + /** + * Contructs new GfxEllipseLabel + */ + public EllipseLabel() { + + layout = new XYLayout(); + setLayoutManager(layout); + indexLabel = new Label(); + mainLabel = new Label(); + add(indexLabel, new Rectangle(0, 0, -1, -1)); + add(mainLabel, new Rectangle(0, 0, -1, -1)); + + setOpaque(true); + } + + public Dimension getPreferredSize(int arg0, int arg1) { + return new Dimension(mainLabel.getPreferredSize().width + 20, 36); + } + + /** + * @return The mainLabel, which is at the center of this Figure + */ + public Label getLabel() { + return mainLabel; + } + + /** + * @return The indexLabel, which is at the top-right on this Figure + */ + public Label getIndexLabel() { + return indexLabel; + } + + public void setIndexVisible(boolean bool) { + indexLabel.setVisible(bool); + } + + /** + * Sets text on the label + * @param text + */ + public void setText(String text) { + mainLabel.setText(text); + mainLabel.setTextAlignment(PositionConstants.CENTER); + mainLabel.setLabelAlignment(PositionConstants.CENTER); + + readjustText(); + } + + private void readjustText() { + Point textPoint = + new Point( + (getPreferredSize().width / 2) + - (mainLabel.getPreferredSize().width / 2), + (getPreferredSize().height) / 2 + - mainLabel.getPreferredSize().height / 2); + layout.setConstraint( + mainLabel, + new Rectangle( + textPoint.x, + textPoint.y, + mainLabel.getPreferredSize().width, + mainLabel.getPreferredSize().height)); + textPoint = + new Point( + (getPreferredSize().width) + - (indexLabel.getPreferredSize().width) + - 3, + 3); + layout.setConstraint( + indexLabel, + new Rectangle( + textPoint.x, + textPoint.y, + indexLabel.getPreferredSize().width, + indexLabel.getPreferredSize().height)); + + } + + /** + * @return The text from the mainLabel + */ + public String getText() { + return mainLabel.getText(); + } + + public void setTextBackground(Color color) { + mainLabel.setBackgroundColor(color); + } + + /** + * @param bool Enable or disable a line under the mainLabel + */ + public void setTextUnderline(boolean bool) { + if (bool) { + Border labelBorder = new BottomLineBorder(); + mainLabel.setBorder(labelBorder); + } else { + mainLabel.setBorder(null); + } + } + + public void setFont(Font font) { + mainLabel.setFont(font); + indexLabel.setFont(font); + } + + /** + * Set text on the indexLabel + * @param text + */ + public void setIndexText(String text) { + indexLabel.setText(text); + + indexLabel.setTextAlignment(PositionConstants.RIGHT); + indexLabel.setLabelAlignment(PositionConstants.RIGHT); + + readjustText(); + } + + public Label getMainLabel() { + return mainLabel; + } + + // TODO: Draw elliptical Background +} diff --git a/relicts/org/jalgo/main/gfx/FixPointAnchor.java b/relicts/org/jalgo/main/gfx/FixPointAnchor.java new file mode 100644 index 0000000..5073be0 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/FixPointAnchor.java @@ -0,0 +1,65 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.AbstractConnectionAnchor; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.SWT; + +/** + * @author Anne Kersten + */ +public class FixPointAnchor extends AbstractConnectionAnchor { + + + + private int style; + + /** + * Constructs a new FixPointAnchor with the given owner figure at a fixed point. + * @param source The owner Figure + * @param style SWT.TOP, SWT.LEFT, SWT.RIGHT, SWT.BOTTOM

Location of the anchor in the Figure. + */ + public FixPointAnchor(IFigure source, int style){ + super(source); + this.style=style; + } + + /** + * Returns the Point where the FixPointAnchor is located. + * @param reference The reference point + * @return The anchor location + */ + + public Point getLocation(Point reference) { + Rectangle r = getOwner().getBounds().getCopy(); + getOwner().translateToAbsolute(r); + switch (style) + { + case(SWT.TOP):return r.getTop(); + case(SWT.RIGHT):return r.getRight(); + case(SWT.BOTTOM):return r.getBottom().translate(0,-1); + case(SWT.LEFT): return r.getLeft(); + default:return r.getLeft(); + } + } +} diff --git a/relicts/org/jalgo/main/gfx/IAnimationConcept.java b/relicts/org/jalgo/main/gfx/IAnimationConcept.java new file mode 100644 index 0000000..a7d1d6c --- /dev/null +++ b/relicts/org/jalgo/main/gfx/IAnimationConcept.java @@ -0,0 +1,45 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 25.05.2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.geometry.Point; + +/** + * An Interface for different animation path calculations. + * + * @author Hauke Menges + */ +public interface IAnimationConcept { + + /** + * Needed for calculating animation pathes. + * + * @param startPoint Animation start-point + * @param endPoint Animation end-point + * @param percent Current position (from 0.0 to 1.0) + * @return The new position + */ + public Point calculate(Point startPoint, Point endPoint, double percent); + +} diff --git a/relicts/org/jalgo/main/gfx/IClickAction.java b/relicts/org/jalgo/main/gfx/IClickAction.java new file mode 100644 index 0000000..f6b3db3 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/IClickAction.java @@ -0,0 +1,40 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 13.06.2004 + */ + +package org.jalgo.main.gfx; + +import java.util.List; + +/** + * A class that implements IClickAction can be called by the ClickCollector + * which then informs it about a list of all clicked objects. + * + * @author Hauke Menges + */ +public interface IClickAction { + public void performAction(List items); + +} diff --git a/relicts/org/jalgo/main/gfx/LinearAnimationConcept.java b/relicts/org/jalgo/main/gfx/LinearAnimationConcept.java new file mode 100644 index 0000000..4f6099b --- /dev/null +++ b/relicts/org/jalgo/main/gfx/LinearAnimationConcept.java @@ -0,0 +1,47 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 25.05.2004 + */ + +package org.jalgo.main.gfx; +import org.eclipse.draw2d.geometry.Point; + +/** + * Calculates a linear animation path. + * + * @author Hauke Menges + */ +public class LinearAnimationConcept implements IAnimationConcept { + + + /** + * Calculates a linear animation path. + * + * @param startPoint Animation start-point + * @param endPoint Animation end-point + * @param position Current position (from 0.0 to 1.0) + * @return The new position + */ + public Point calculate(Point startPoint, Point endPoint, double position){ + return new Point(); + } + +} diff --git a/relicts/org/jalgo/main/gfx/MarkStyle.java b/relicts/org/jalgo/main/gfx/MarkStyle.java new file mode 100644 index 0000000..69218e2 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/MarkStyle.java @@ -0,0 +1,70 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 29, 2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.swt.graphics.Color; + +/** + * This class is a container for attributes which represents the look + * of a mark in a TextCanvas. + * + * @author Cornelius Hald + */ +public class MarkStyle { + + private Color forground; + private Color backgound; + private int fontstyle; + + /** + * Creates a MarkStyle Object, which holds informations of the visual + * representation of Marks in a TextCanvas.

+ * + * Possible fontsyles are: + *

  • SWT.NORMAL + *
  • SWT.BOLD + *
  • SWT.ITALIC + * + * @param forground The Color of the text forground + * @param background The Color of the text background + * @param fontstyle The fontstyle. May be NORMAL, BOLD or ITALIC + */ + public MarkStyle(Color forground, Color background, int fontstyle) { + this.forground = forground; + this.backgound = background; + this.fontstyle = fontstyle; + } + + public Color getBgColor() { + return backgound; + } + + public Color getFgColor() { + return forground; + } + + public int getFontstyle() { + return fontstyle; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gfx/RectangleLabel.java b/relicts/org/jalgo/main/gfx/RectangleLabel.java new file mode 100644 index 0000000..a138a4e --- /dev/null +++ b/relicts/org/jalgo/main/gfx/RectangleLabel.java @@ -0,0 +1,163 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 17, 2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.Border; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.LineBorder; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.XYLayout; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Point; + +/** + * This class represents a graphical rectangle with 2 Labels.

    + * One Label is in the middel (mainLabel) and one Label (indexLabel) + * is at the top-right corner. + * + * @author Malte Blumberg + */ +public class RectangleLabel extends Figure { + + private Label mainLabel; + private Label indexLabel; + private XYLayout layout; + + /** + * Contructs new GfxEllipseLabel + */ + public RectangleLabel() { + + // DEBUG + setBorder(new LineBorder()); + + layout = new XYLayout(); + setLayoutManager(layout); + + indexLabel = new Label(); + add(indexLabel, new Rectangle(50, 15, -1, -1)); + + mainLabel = new Label(); + add(mainLabel, new Rectangle(5, 15, -1, -1)); + + setOpaque(true); + } + + + public Dimension getPreferredSize(int arg0, int arg1) { + int width = mainLabel.getPreferredSize().width + 20; + int heigth = 36; + + return new Dimension(width, heigth); + } + + + /** + * @return The mainLabel, which is at the center of this Figure + */ + public Label getLabel() { + return mainLabel; + } + + /** + * @return The indexLabel, which is at the top-right on this Figure + */ + public Label getIndexLabel() { + return indexLabel; + } + + public void setIndexVisible(boolean bool) { + indexLabel.setVisible(bool); + } + + /** + * Sets text on the label + * @param text + */ + public void setText(String text) { + mainLabel.setText(text); + mainLabel.setTextAlignment(PositionConstants.CENTER); + mainLabel.setLabelAlignment(PositionConstants.CENTER); + + readjustText(); + } + + private void readjustText(){ + Point textPoint = new Point((getPreferredSize().width/2)-(mainLabel.getPreferredSize().width/2),(getPreferredSize().height)/2-mainLabel.getPreferredSize().height/2); + layout.setConstraint(mainLabel, new Rectangle(textPoint.x, textPoint.y, mainLabel.getPreferredSize().width, mainLabel.getPreferredSize().height)); + textPoint = new Point((getPreferredSize().width)-(indexLabel.getPreferredSize().width)-3,3); + layout.setConstraint(indexLabel, new Rectangle(textPoint.x,textPoint.y, indexLabel.getPreferredSize().width, indexLabel.getPreferredSize().height)); + + } + /** + * @return The text from the mainLabel + */ + public String getText() { + return mainLabel.getText(); + } + + public void setTextBackground(Color color) { + mainLabel.setBackgroundColor(color); + } + + + /** + * @param bool Enable or disable a line under the mainLabel + */ + public void setTextUnderline(boolean bool) { + if(bool){ + Border labelBorder=new BottomLineBorder(); + mainLabel.setBorder(labelBorder); + } + else{ + mainLabel.setBorder(null); + } + } + + public void setFont(Font font) { + mainLabel.setFont(font); + indexLabel.setFont(font); + } + + /** + * Set text on the indexLabel + * @param text + */ + public void setIndexText(String text) { + indexLabel.setText(text); + + indexLabel.setTextAlignment(PositionConstants.RIGHT); + indexLabel.setLabelAlignment(PositionConstants.RIGHT); + + readjustText(); + } + + public Label getMainLabel() { + return mainLabel; + } +} diff --git a/relicts/org/jalgo/main/gfx/RoundedManhattanConnectionRouter.java b/relicts/org/jalgo/main/gfx/RoundedManhattanConnectionRouter.java new file mode 100644 index 0000000..a9c88d0 --- /dev/null +++ b/relicts/org/jalgo/main/gfx/RoundedManhattanConnectionRouter.java @@ -0,0 +1,501 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.AbstractRouter; +import org.eclipse.draw2d.Connection; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.PointList; +import org.eclipse.draw2d.geometry.PrecisionPoint; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.SWT; + +/** + * @author Anne Kersten + */ +public class RoundedManhattanConnectionRouter extends AbstractRouter { + + /** + * Routes the Connection. + * @param conn The Connection to route + * @see org.eclipse.draw2d.ConnectionRouter#route(org.eclipse.draw2d.Connection) + */ + public void route(Connection conn) { + + int offset,i,r1,r2; + + Point start= this.getStartPoint(conn); + conn.translateToRelative(start); + Point end=this.getEndPoint(conn); + conn.translateToRelative(end); + IFigure source=conn.getSourceAnchor().getOwner(); + IFigure target=conn.getTargetAnchor().getOwner(); + Rectangle rs=source.getBounds().getCopy(); + Rectangle rt=target.getBounds().getCopy(); + + if (start.y>=end.y) + if (start.x<=end.x) offset=0; //target oben rechts von source + else offset=1; //target oben links von source + else if (start.x<=end.x) offset=2; //target unten rechts von source + else offset=3; //target unten links von source + if(rs.x+rs.width/2<=start.x) //out rechts + if (rt.x+rt.width/2>=end.x)offset+=0; //in links + else offset+=4; //in rechts + else //out links + if (rt.x+rt.width/2>=end.x)offset+=8; //in links + else offset+=12; //in rechts + + if (Math.abs(start.x-end.x)>=20 &&Math.abs(start.y-end.y)>=20)r1=10; + else r1=Math.min(Math.abs(start.x-end.x)/2,Math.abs(start.y-end.y)/2); + if(Math.abs(start.y-end.y)>=20)r2=10; + else r2=Math.abs((Math.abs(start.y-end.y))/2); + + PointList l=new PointList(); + l.addPoint(start); + switch (offset){ + case 0: + { + PointList p1=leftCorner(new Point(end.x-((end.x-start.x)/2),start.y),SWT.LEFT,r1); + PointList p2=rightCorner(new Point(end.x-((end.x-start.x)/2),end.y),SWT.BOTTOM,r1); + for(i=0;i=40) + { + PointList p1=leftCorner(new Point(start.x+20,start.y),SWT.LEFT,10); + PointList p2=leftCorner(new Point(start.x+20,end.y-(end.y-start.y)/2),SWT.BOTTOM,10); + PointList p3=rightCorner(new Point(end.x-20,end.y-(end.y-start.y)/2),SWT.RIGHT,10); + PointList p4=rightCorner(new Point(end.x-20,end.y),SWT.BOTTOM,10); + for(i=0;i=40) + { + PointList p1=rightCorner(new Point(start.x+20,start.y),SWT.LEFT,10); + PointList p2=rightCorner(new Point(start.x+20,end.y-(end.y-start.y)/2),SWT.TOP,10); + PointList p3=leftCorner(new Point(end.x-20,end.y-(end.y-start.y)/2),SWT.RIGHT,10); + PointList p4=leftCorner(new Point(end.x-20,end.y),SWT.TOP,10); + for(i=0;i=40){ + PointList p1=rightCorner(new Point(start.x-20,start.y),SWT.RIGHT,r2); + PointList p2=rightCorner(new Point(start.x-20,end.y-(end.y-start.y)/2),SWT.BOTTOM,r2); + PointList p3=leftCorner(new Point(end.x+20,end.y-(end.y-start.y)/2),SWT.LEFT,r2); + PointList p4=leftCorner(new Point(end.x+20,end.y),SWT.BOTTOM,r2); + for(i=0;i=40){ + PointList p1=leftCorner(new Point(start.x-20,start.y),SWT.RIGHT,r2); + PointList p2=leftCorner(new Point(start.x-20,end.y-(end.y-start.y)/2),SWT.TOP,r2); + PointList p3=rightCorner(new Point(end.x+20,end.y-(end.y-start.y)/2),SWT.LEFT,r2); + PointList p4=rightCorner(new Point(end.x+20,end.y),SWT.TOP,r2); + for(i=0;i=offset*Math.PI; i-=0.05*Math.PI) + { + pl.addPoint(new PrecisionPoint(m.x+r*Math.cos(i),m.y+r*Math.sin(i))); + } + return pl; + } + + private PointList rightCorner(Point p,int start,int r) + { + double i; + double offset; + PointList pl=new PointList(); + Point m=new PrecisionPoint(); + switch(start) + { + case SWT.TOP:offset=0;m.setLocation(p.x-r,p.y-r);break; + case SWT.RIGHT:offset=0.5;m.setLocation(p.x+r,p.y-r);break; + case SWT.BOTTOM:offset=1;m.setLocation(p.x+r,p.y+r);break; + case SWT.LEFT:offset=1.5;m.setLocation(p.x-r,p.y+r);break; + default:offset=0;m.setLocation(p.x+r,p.y+r); + } + for(i=offset*Math.PI;i<=(offset+0.5)*Math.PI; i+=0.05*Math.PI) + { + pl.addPoint(new PrecisionPoint(m.x+r*Math.cos(i),m.y+r*Math.sin(i))); + } + return pl; + } + + private PointList halfrightCircle(Point p, int start, int r) + { + double i; + double offset; + PointList pl=new PointList(); + Point m=new PrecisionPoint(); + switch(start) + { + case SWT.TOP:offset=0;m.setLocation(p.x-r,p.y-r);break; + case SWT.RIGHT:offset=0.5;m.setLocation(p.x+r,p.y-r);break; + case SWT.BOTTOM:offset=1;m.setLocation(p.x+10,p.y+r);break; + case SWT.LEFT:offset=1.5;m.setLocation(p.x-r,p.y+r);break; + default:offset=0;m.setLocation(p.x+r,p.y+r); + } + for(i=offset*Math.PI;i<=(offset+1)*Math.PI; i+=0.05*Math.PI) + { + pl.addPoint(new PrecisionPoint(m.x+r*Math.cos(i),m.y+r*Math.sin(i))); + } + return pl; + } + + private PointList halfleftCircle(Point p, int start, int r) + { + double i; + double offset; + PointList pl=new PointList(); + Point m=new PrecisionPoint(); + switch(start) + { + case SWT.TOP:offset=0;m.setLocation(p.x+r,p.y-r);break; + case SWT.RIGHT:offset=0.5;m.setLocation(p.x+r,p.y+r);break; + case SWT.BOTTOM:offset=1;m.setLocation(p.x-r,p.y+r);break; + case SWT.LEFT:offset=1.5;m.setLocation(p.x-r,p.y-r);break; + default:offset=0;m.setLocation(p.x-r,p.y-r); + } + for(i=(offset+1)*Math.PI;i>=offset*Math.PI; i-=0.05*Math.PI) + { + pl.addPoint(new PrecisionPoint(m.x+r*Math.cos(i),m.y+r*Math.sin(i))); + } + return pl; + } +} diff --git a/relicts/org/jalgo/main/gfx/RoundedRectangleLabel.java b/relicts/org/jalgo/main/gfx/RoundedRectangleLabel.java new file mode 100644 index 0000000..3d1250b --- /dev/null +++ b/relicts/org/jalgo/main/gfx/RoundedRectangleLabel.java @@ -0,0 +1,118 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 17, 2004 + */ + +package org.jalgo.main.gfx; + +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.RoundedRectangle; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; + + +/** + * This class represents a graphical rounded rectangle with 2 Labels.

    + * One Label is in the middel (mainLabel) and one Label (indexLabel) + * is at the top-right corner. + * + * @author Cornelius Hald + */ +public class RoundedRectangleLabel extends RoundedRectangle { + + private Label mainLabel; + private Label indexLabel; + + /** + * Contructs new GfxEllipseLabel + */ + public RoundedRectangleLabel() { + super(); + + //setLayoutManager(new ToolbarLayout()); + + mainLabel = new Label(); + add(mainLabel); + indexLabel = new Label(); + add(indexLabel); + + + setOpaque(true); + } + + /** + * @return The mainLabel, which is at the center of this Figure + */ + public Label getLabel() { + return mainLabel; + } + + public void setIndexVisible(boolean bool) { + indexLabel.setVisible(bool); + } + + /** + * @return The indexLabel, which is at the top-right on this Figure + */ + public Label getIndexLabel() { + return indexLabel; + } + + /** + * Sets text on the label + * FIXME: Textposition is wrong + * @param text + */ + public void setText(String text) { + mainLabel.setText(text); + setSize(mainLabel.getPreferredSize().width, getSize().height); + mainLabel.setSize(mainLabel.getPreferredSize()); + } + + /** + * @return The text from the mainLabel + */ + public String getText() { + return mainLabel.getText(); + } + + public void setTextBackground(Color color) { + mainLabel.setBackgroundColor(color); + } + + /** + * @param bool Enable or disable a line under the mainLabel + */ + public void setTextUnderline(boolean bool) { + } + + public void setFont(Font font) { + mainLabel.setFont(font); + } + + /** + * Set text on the indexLabel + * @param text + */ + public void setIndexText(String text) { + indexLabel.setText(text); + } +} diff --git a/relicts/org/jalgo/main/gui/CVS/Entries b/relicts/org/jalgo/main/gui/CVS/Entries new file mode 100644 index 0000000..561f57c --- /dev/null +++ b/relicts/org/jalgo/main/gui/CVS/Entries @@ -0,0 +1,6 @@ +/ModuleChooseDialog.java/1.2/Sat Mar 4 13:36:24 2006/-kk/ +/ScrollZoomCanvas.java/1.2/Sat Mar 4 13:36:24 2006/-kk/ +/TextCanvas.java/1.2/Sat Mar 4 13:36:24 2006/-kk/ +/ZoomPanel.java/1.2/Sat Mar 4 13:36:24 2006/-kk/ +D/actions//// +D/widgets//// diff --git a/relicts/org/jalgo/main/gui/CVS/Repository b/relicts/org/jalgo/main/gui/CVS/Repository new file mode 100644 index 0000000..7df01ae --- /dev/null +++ b/relicts/org/jalgo/main/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/gui diff --git a/relicts/org/jalgo/main/gui/CVS/Root b/relicts/org/jalgo/main/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/gui/ModuleChooseDialog.java b/relicts/org/jalgo/main/gui/ModuleChooseDialog.java new file mode 100644 index 0000000..1aa139d --- /dev/null +++ b/relicts/org/jalgo/main/gui/ModuleChooseDialog.java @@ -0,0 +1,185 @@ +/* + * Created on 12.07.2005 + * + */ +package org.jalgo.main.gui; + +import java.util.Iterator; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.viewers.ListViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.util.FileActivity; +import org.jalgo.main.util.Messages; + +public class ModuleChooseDialog extends Dialog implements SelectionListener { + + private JalgoMain main; + private ListViewer moduleListViewer; + private List moduleList; + private Button button; + private Label logoL; + private Label descrL; + private Button check; + private boolean visibilityState; + // file, where the visibilty state of the ModuleChooseDialog is saved + private String iniPath; + + public ModuleChooseDialog(Shell shell, JalgoMain main, String iniPath) { + super(shell); + this.main = main; + this.iniPath = iniPath; + } + + public Control createContents(Composite parent) { + + Composite container = new Composite(parent, SWT.NONE); + container.setLayoutData(new GridData(GridData.FILL_BOTH)); + + GridLayout allLayout = new GridLayout(); + GridLayout topLayout = new GridLayout(); + topLayout.numColumns = 3; + topLayout.makeColumnsEqualWidth = true; + topLayout.marginHeight = 20; + GridLayout downLayout = new GridLayout(); + GridLayout bottomLayout = new GridLayout(); + + container.setLayout(allLayout); + + Composite top = new Composite(container, SWT.NONE); + top.setLayout(topLayout); + top.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL)); + + Composite down = new Composite(container, SWT.BORDER); + down.setLayout(downLayout); + down.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL + | GridData.FILL_BOTH)); + + Composite bottom = new Composite(container, SWT.NONE); + bottom.setLayout(bottomLayout); + bottom.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL + | GridData.FILL_BOTH)); + + // modul list + moduleList = new List(top, SWT.BORDER | SWT.SIMPLE); + moduleListViewer = new ListViewer(moduleList); + for (Iterator modIt = main.getKnownModuleInfos().iterator(); modIt.hasNext();) { + IModuleInfo modInfo = (IModuleInfo) modIt.next(); + moduleList.add(modInfo.getName()); + } + moduleList.addSelectionListener(this); + moduleList.setSelection(-1); + moduleListViewer.getControl().setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL)); + + moduleList.addMouseListener(new MouseAdapter(){ + @SuppressWarnings("synthetic-access") + public void mouseDoubleClick(MouseEvent e){ + main.newInstance(moduleList.getSelectionIndex()); + close(); + } + }); + + // logo + logoL = new Label(top, SWT.CENTER); + logoL.setImage(ImageDescriptor.createFromURL(getClass().getResource( + "/main_pix/jalgo.png")).createImage()); + logoL.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_CENTER)); + + // start button + button = new Button(top, SWT.PUSH); + button.setText("Starten"); + button.setToolTipText("Das ausgewählte Modul starten."); + button.setEnabled(false); + button.addSelectionListener(this); + + // module description + descrL = new Label(down, SWT.LEFT | SWT.WRAP); + descrL.setText(Messages.getJalgoInfo()); + + //descrL.setText("Klicken Sie auf ein Modul, um seine Beschreibung zu sehen."); + descrL.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL + | GridData.FILL_BOTH)); + + // check-box + check = new Button(bottom, SWT.CHECK); + check.setText("Dieses Fenster bei jedem Programmstart anzeigen."); + check.addSelectionListener(this); + visibilityState = FileActivity.readBooleanFrom(iniPath); + check.setSelection(visibilityState); + + return container; + + } + + public Point getInitialSize() { + return new Point(600,400); + } + + /*public Point getInitialLocation(Point initialSize) { + Point mainWindowLoc = shell.getLocation(); + System.out.println(mainWindowLoc.x + ", " + mainWindowLoc.y); + }*/ + + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Modul-Auswahl"); + Rectangle displayBounds = Display.getCurrent().getBounds(); + newShell.setLocation( + (displayBounds.width - newShell.getSize().x) / 2, + (displayBounds.height - newShell.getSize().y) / 2); + } + + // <<--------- implementation of SelectionListener + + public void widgetDefaultSelected(SelectionEvent e) { + // this method has no effect + } + + public void widgetSelected(SelectionEvent ev) { + // button is clicked + if (ev.widget == button) { + main.newInstance(moduleList.getSelectionIndex()); + close(); + } + // selection in list is changed + else if (ev.widget == moduleList) { + button.setEnabled(true); + int modNum = moduleList.getSelectionIndex(); + // set description text of module + descrL.setText(main.getKnownModuleInfos().get(modNum).getName() + + "\n\n" + main.getKnownModuleInfos().get(modNum).getDescription() + + "\n\nVersion: " + main.getKnownModuleInfos().get(modNum).getVersion() + + "\n\nAutoren: " + main.getKnownModuleInfos().get(modNum).getAuthor() + + "\n\nLizenz: " + main.getKnownModuleInfos().get(modNum).getLicense()); + // show module's logo + logoL.setImage(ImageDescriptor.createFromURL( + main.getKnownModuleInfos().get(modNum).getLogoURL()). + createImage()); + } + else if (ev.widget == check) { + // store the visiblity state + FileActivity.writeBooleanTo(iniPath,check.getSelection()); + } + } + + // implementation of SelectionListener ------------------->> + +} diff --git a/relicts/org/jalgo/main/gui/ScrollZoomCanvas.java b/relicts/org/jalgo/main/gui/ScrollZoomCanvas.java new file mode 100644 index 0000000..20286b4 --- /dev/null +++ b/relicts/org/jalgo/main/gui/ScrollZoomCanvas.java @@ -0,0 +1,463 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.gui; + +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.List; + +import org.eclipse.draw2d.AncestorListener; +import org.eclipse.draw2d.Border; +import org.eclipse.draw2d.EventDispatcher; +//import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FigureCanvas; +import org.eclipse.draw2d.FigureListener; +import org.eclipse.draw2d.FocusEvent; +import org.eclipse.draw2d.FocusListener; +import org.eclipse.draw2d.Graphics; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.KeyEvent; +import org.eclipse.draw2d.KeyListener; +import org.eclipse.draw2d.LayoutManager; +import org.eclipse.draw2d.MouseEvent; +import org.eclipse.draw2d.MouseListener; +import org.eclipse.draw2d.MouseMotionListener; +import org.eclipse.draw2d.TreeSearch; +import org.eclipse.draw2d.UpdateManager; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Insets; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Translatable; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Cursor; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.widgets.Composite; + +public class ScrollZoomCanvas extends FigureCanvas { + + public ScrollZoomCanvas(Composite parent) { + super(parent); + initialize(); + } + + private ZoomPanel zoomPane; + + // IFigure-Methoden f?r ZoomPane + + public void add(IFigure figure) { + this.zoomPane.add(figure); + this.zoomPane.repaint(); + } + + public void addMouseListener(MouseListener listener) { + this.zoomPane.addMouseListener(listener); + } + + public void addAncestorListener(AncestorListener listener) { + this.zoomPane.addAncestorListener(listener); + } + + public void addFigureListener(FigureListener listener) { + this.zoomPane.addFigureListener(listener); + } + + public void addFocusListener(FocusListener listener) { + this.zoomPane.addFocusListener(listener); + } + + public void addKeyListener(KeyListener listener) { + this.zoomPane.addKeyListener(listener); + } + + public void addMouseMotionListener(MouseMotionListener listener) { + this.zoomPane.addMouseMotionListener(listener); + } + + public void addNotify() { + this.zoomPane.addNotify(); + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + this.zoomPane.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener( + String property, + PropertyChangeListener listener) { + this.zoomPane.addPropertyChangeListener(property, listener); + } + + public boolean containsPoint(int x, int y) { + return this.zoomPane.containsPoint(x, y); + } + + public void erase() { + this.zoomPane.erase(); + } + + public IFigure findFigureAt(int x, int y) { + + //return this.figure.findFigureAt(x, y); + return this.zoomPane.findFigureAt(x, y); + } + + public IFigure findFigureAt(int x, int y, TreeSearch search) { + return this.zoomPane.findFigureAt(x, y, search); + } + + public IFigure findFigureAtExcluding(int x, int y, Collection collection) { + return this.zoomPane.findFigureAtExcluding(x, y, collection); + } + + public IFigure findMouseEventTargetAt(int x, int y) { + return this.zoomPane.findMouseEventTargetAt(x, y); + } + + public Color getZBackgroundColor() { + return this.zoomPane.getBackgroundColor(); + } + + public Border getZBorder() { + return this.zoomPane.getBorder(); + } + + public List getZPanelChildren() { + return this.zoomPane.getChildren(); + } + + public Cursor getZCursor() { + return this.zoomPane.getCursor(); + } + + public Color getZForegroundColor() { + return this.zoomPane.getForegroundColor(); + } + + public Insets getZInsets() { + return this.zoomPane.getInsets(); + } + + public LayoutManager getLayoutManager() { + return this.zoomPane.getLayoutManager(); + } + + public Color getZLocalBackgroundColor() { + return this.zoomPane.getLocalBackgroundColor(); + } + + public Color getZLocalForegroundColor() { + return this.zoomPane.getLocalForegroundColor(); + } + + public Dimension getZMaximumSize() { + return this.zoomPane.getMaximumSize(); + } + + public Dimension getZMinimumSize() { + return this.zoomPane.getMinimumSize(); + } + + public Dimension getZMinimumSize(int wHint, int hHint) { + return this.zoomPane.getMinimumSize(wHint, hHint); + } + + public Dimension getZPreferredSize() { + return this.zoomPane.getPreferredSize(); + } + + public Dimension getZPreferredSize(int wHint, int hHint) { + return this.zoomPane.getPreferredSize(wHint, hHint); + } + + public IFigure getToolTip() { + return this.zoomPane.getToolTip(); + } + + public UpdateManager getUpdateManager() { + return this.zoomPane.getUpdateManager(); + } + + public void handleFocusGained(FocusEvent event) { + this.zoomPane.handleFocusGained(event); + } + + public void handleFocusLost(FocusEvent event) { + this.zoomPane.handleFocusLost(event); + } + + public void handleKeyPressed(KeyEvent event) { + this.zoomPane.handleKeyPressed(event); + } + + public void handleKeyReleased(KeyEvent event) { + this.zoomPane.handleKeyReleased(event); + } + + public void handleMouseDoubleClicked(MouseEvent event) { + this.zoomPane.handleMouseDoubleClicked(event); + } + + public void handleMouseDragged(MouseEvent event) { + this.zoomPane.handleMouseDragged(event); + } + + public void handleMouseEntered(MouseEvent event) { + this.zoomPane.handleMouseEntered(event); + } + + public void handleMouseExited(MouseEvent event) { + this.zoomPane.handleMouseExited(event); + } + + public void handleMouseHover(MouseEvent event) { + this.zoomPane.handleMouseHover(event); + } + + public void handleMouseMoved(MouseEvent event) { + this.zoomPane.handleMouseMoved(event); + } + + public void handleMousePressed(MouseEvent event) { + this.zoomPane.handleMousePressed(event); + } + + public void handleMouseReleased(MouseEvent event) { + this.zoomPane.handleMouseReleased(event); + } + + public EventDispatcher internalGetEventDispatcher() { + return this.zoomPane.internalGetEventDispatcher(); + } + + public void invalidate() { + this.zoomPane.invalidate(); + } + + public void invalidateTree() { + this.zoomPane.invalidateTree(); + } + + public boolean isFocusTraversable() { + return this.zoomPane.isFocusTraversable(); + } + + public boolean isOpaque() { + return this.zoomPane.isOpaque(); + } + + public boolean isRequestFocusEnabled() { + return this.zoomPane.isRequestFocusEnabled(); + } + + public boolean isVisible() { + return this.zoomPane.isVisible(); + } + + public void paint(Graphics graphics) { + this.zoomPane.paint(graphics); + } + + public void remove(IFigure figure) { + this.zoomPane.remove(figure); + } + + public void removeAncestorListener(AncestorListener listener) { + this.zoomPane.addAncestorListener(listener); + } + + public void removeFigureListener(FigureListener listener) { + this.zoomPane.removeFigureListener(listener); + } + + public void removeFocusListener(FocusListener listener) { + this.zoomPane.removeFocusListener(listener); + } + + public void removeKeyListener(KeyListener listener) { + this.zoomPane.removeKeyListener(listener); + } + + public void removeMouseListener(MouseListener listener) { + this.zoomPane.removeMouseListener(listener); + } + + public void removeMouseMotionListener(MouseMotionListener listener) { + this.zoomPane.removeMouseMotionListener(listener); + } + + public void removeNotify() { + this.zoomPane.removeNotify(); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + this.zoomPane.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener( + String property, + PropertyChangeListener listener) { + this.zoomPane.removePropertyChangeListener(property, listener); + } + + public void repaint() { + this.zoomPane.repaint(); + } + + public void repaint(int x, int y, int w, int h) { + this.zoomPane.repaint(x, y, w, h); + } + + public void revalidate() { + this.zoomPane.revalidate(); + } + + public void setBackgroundColor(Color c) { + this.zoomPane.setBackgroundColor(c); + } + + public void setConstraint(IFigure child, Object constraint) { + this.zoomPane.setConstraint(child, constraint); + } + + public void setCursor(Cursor cursor) { + this.zoomPane.setCursor(cursor); + } + + public void setEnabled(boolean value) { + this.zoomPane.setEnabled(value); + } + + public void setFocusTraversable(boolean value) { + this.zoomPane.setFocusTraversable(value); + } + + public void setFont(Font f) { + this.zoomPane.setFont(f); + } + + public void setForegroundColor(Color c) { + this.zoomPane.setForegroundColor(c); + } + + public void setLayoutManager(LayoutManager lm) { + zoomPane.setLayoutManager(lm); + } + + public void setLocation(Point p) { + this.zoomPane.setLocation(p); + } + + public void setZMaximumSize(Dimension size) { + this.zoomPane.setMaximumSize(size); +// this.figure.setMaximumSize(size); + } + + public void setZMinimumSize(Dimension size) { + this.zoomPane.setMinimumSize(size); +// this.figure.setMinimumSize(size); + } + + public void setOpaque(boolean isOpaque) { + this.zoomPane.setOpaque(isOpaque); + } + + public void setZPreferredSize(Dimension size) { + this.zoomPane.setPreferredSize(size); + } + + public void setRequestFocusEnabled(boolean requestFocusEnabled) { + this.zoomPane.setRequestFocusEnabled(requestFocusEnabled); + } + + public void setToolTip(IFigure figure) { + this.zoomPane.setToolTip(figure); + } + + public void translate(int x, int y) { + this.zoomPane.translate(x, y); + } + + public void translateFromParent(Translatable t) { + this.zoomPane.translateFromParent(t); + } + + public void translateToAbsolute(Translatable t) { + this.zoomPane.translateToAbsolute(t); + } + + public void translateToParent(Translatable t) { + this.zoomPane.translateToParent(t); + } + + public void translateToRelative(Translatable t) { + this.zoomPane.translateToRelative(t); + } + + public void validate() { + this.zoomPane.validate(); + } + + public void setSize(int x, int y) { + super.setSize(x, y); + if ((zoomPane.getSize().height < y) + || (zoomPane.getSize().width < x)) { + zoomPane.setSize(x, y); + } + } + + public void setBounds(int x, int y, int w, int h) { + super.setBounds(x, y, w, h); + if ((zoomPane.getBounds().height < h) + || (zoomPane.getBounds().width < w)) { + zoomPane.setSize(x, y); + } + } + + private void initialize() { + this.zoomPane = new ZoomPanel(); + this.setContents(zoomPane); + this.setZoom(1.0f); + } + + public float getZoom() { + return zoomPane.getZoom(); + } + + public void setZoom(float zoom) { + zoomPane.setZoom(zoom); + } + + public void setZoom(float zoom, Point point) { + zoomPane.setZoom(zoom); + this.scrollSmoothTo( + point.x - this.getLocation().x, + point.y - this.getLocation().y); + } + + public void resetZoom() { + zoomPane.setZoom(1.0f); + zoomPane.repaint(); + + } + + protected boolean useLocalCoordinates(){ + return zoomPane.useLocalCoordinates(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/TextCanvas.java b/relicts/org/jalgo/main/gui/TextCanvas.java new file mode 100644 index 0000000..1ae884e --- /dev/null +++ b/relicts/org/jalgo/main/gui/TextCanvas.java @@ -0,0 +1,385 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 17, 2004 + */ + +package org.jalgo.main.gui; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.jalgo.main.gfx.MarkStyle; + +/** + * This class can be used to display text with one or more highlighted text segments. + * This segments are active, which is indicated with a mark. The style of the + * highlighted text is set using the MarkStyle class. + * + * @author Cornelius Hald + * @author Hauke Menges + */ +public class TextCanvas extends Composite { + + private StyledText styledText; + + private int mode; + public static final int MODE_STYLE_ACTIVE = 1; + public static final int MODE_SHOW_ACTIVE = 2; + + private MarkStyle markStyle; + private int position = 0; + + private String[] textSegments; + private boolean[] activeSegments; + private StyleRange[] styleRanges; + private StyleRange styleRangeAll; + private String text; + + private Color white; + private Color black; + private Color red; + + /** + * Constructs a new TextCanvas. + * A TextCanvas is a {@link Composite} containing a StyledText widget. + * + * @param parent the parent object + * @param style a SWT-Style constant + * + * @see Composite + */ + public TextCanvas(Composite parent, int style) { + super(parent, style); + setLayout(new FillLayout()); + styledText = + new StyledText( + this, + SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | style); + styledText.setEditable(false); + + white = new Color(parent.getDisplay(), 255, 255, 255); + black = new Color(parent.getDisplay(), 0, 0, 0); + red = new Color(parent.getDisplay(), 255, 0, 0); + + mode = MODE_STYLE_ACTIVE; + + styledText.setBackground(white); + + parent.layout(); + } + + /** + * Sets the style of the active text segment which is marked. If no markStyle + * is set, the TextCanvas will use a standard style. + * @param markStyle the style object. + */ + public void setMarkStyle(MarkStyle markStyle) { + this.markStyle = markStyle; + } + + /** + * Marks the next text segment as active and demarks the current segment. + * After reaching the last text segment it will continue at the first element. + */ + public void markNext() { + position++; + demarkAll(); + mark(position); + } + + /** + * Marks the first text segment as active. + */ + public void markFirst() { + position = 0; + demarkAll(); + mark(0); + } + + /** + * Marks the textsegment with the given index. + * + * @param index + */ + public void mark(int index) { + if (index >= textSegments.length) { + index = textSegments.length - 1; + } + + activeSegments[index] = true; + switch (mode) { + case MODE_STYLE_ACTIVE : + int offset = 0; + int length = 0; + + for (int i = 0; i < index; i++) { + + offset += textSegments[i].length(); + } + + length = textSegments[index].length(); + + styleRanges[index].start = offset; + styleRanges[index].length = length; + + if (markStyle != null) { + Color background = markStyle.getBgColor(); + Color foreground = markStyle.getFgColor(); + int fontstyle = markStyle.getFontstyle(); + + styleRanges[index].background = background; + styleRanges[index].foreground = foreground; + styleRanges[index].fontStyle = fontstyle; + + } else { + styleRanges[index].background = red; + styleRanges[index].foreground = black; + } + styledText.setStyleRange(styleRanges[index]); + break; + case MODE_SHOW_ACTIVE : + text = ""; //$NON-NLS-1$ + for (int i = 0; i < textSegments.length; i++) { + if (activeSegments[i] == true) + text += textSegments[i]; + } + styledText.setText(text); + break; + } + } + + /** + * Demarks the textsegment whith the given index. + * + * @param index + */ + public void demark(int index) { + if (index >= textSegments.length) { + index = textSegments.length - 1; + } + + activeSegments[index] = false; + switch (mode) { + case MODE_STYLE_ACTIVE : + int offset = 0; + int length = 0; + + for (int i = 0; i < index; i++) { + + offset += textSegments[i].length(); + } + + length = textSegments[index].length(); + + styleRanges[index].start = offset; + styleRanges[index].length = length; + styleRanges[index].background = styledText.getBackground(); + styleRanges[index].foreground = styledText.getForeground(); + styleRanges[index].fontStyle = SWT.NORMAL; + + styledText.setStyleRange(styleRanges[index]); + break; + case MODE_SHOW_ACTIVE : + text = ""; //$NON-NLS-1$ + for (int i = 0; i < textSegments.length; i++) { + if (activeSegments[i] == true) + text += textSegments[i]; + } + styledText.setText(text); + + break; + } + } + + /** + * gets the position, which is used by markNext() and markFirst. + */ + public int getPosition() { + return position; + } + + /** + * sets the position, which is used by markNext() and markFirst. + */ + public void setPosition(int pos) { + position = pos; + } + + /** + * marks a textsegment - this segment is used as base for markNext(). + * + * @param index The Index of the text segment. + */ + public void markPosition(int index) { + if (index >= textSegments.length) { + index = textSegments.length - 1; + } + + position = index; + demarkAll(); + mark(position); + } + + /** + * Removes all visible marks from the TextCanvas. + */ + public void demarkAll() { + for (int i = 0; i < textSegments.length; i++) { + activeSegments[i] = false; + } + + switch (mode) { + case MODE_STYLE_ACTIVE : + int offset = 0; + int length = text.length(); + + styleRangeAll.start = offset; + styleRangeAll.length = length; + styleRangeAll.background = styledText.getBackground(); + styleRangeAll.foreground = styledText.getForeground(); + styleRangeAll.fontStyle = SWT.NORMAL; + + styledText.setStyleRange(styleRangeAll); + break; + + case MODE_SHOW_ACTIVE : + text = ""; //$NON-NLS-1$ + styledText.setText(text); + break; + } + } + + /** + * Set the text segments which sould be displayed. The segments should be + * entered in the right order and can be marked using the methods provided + * in this class. + * + * @param textSegments + */ + public void setTextSegments(String[] textSegments) { + this.textSegments = textSegments; + + String text = ""; //$NON-NLS-1$ + + for (int i = 0; i < textSegments.length; i++) { + text = text + textSegments[i]; + } + this.text = text; + styledText.setText(text); + + activeSegments = new boolean[textSegments.length]; + styleRanges = new StyleRange[textSegments.length]; + + styleRangeAll = new StyleRange(); + + for (int i = 0; i < styleRanges.length; i++) { + styleRanges[i] = new StyleRange(); + } + } + + /** + * Gets the textSegments. + * @return an array of Strings containing the text segments. + */ + public String[] getText() { + return textSegments; + } + + /** + * Sets the behavior of the TextCanvas. There are several modes:

    + *

  • 1: Changes the forground Color, background Color and the text + * style (normal, bold or italic) of the active text segment. + * The style is set in MarkStyle. + *
  • 2: Shows only the activ text segment. + * + * @param mode the mode changes the behavior + */ + public void setMode(int mode) { + this.mode = mode; + } + + /** + * Gets the behavior of the TextCanvas. + * + * @return the mode of the TextCanvas + */ + public int getMode() { + return mode; + } + + /** + * Gets the background color. + */ + public Color getBackground() { + return styledText.getBackground(); + } + + /** + * Sets the background color. + */ + public void setBackground(Color color) { + styledText.setBackground(color); + } + + /** + * Adds another segment at the end of the segment list. + * + * @param segment new segment string + */ + public void addSegment(String segment) { + String[] textSegments2 = new String[textSegments.length]; + System.arraycopy( + textSegments, + 0, + textSegments2, + 0, + textSegments.length); + textSegments = textSegments2; + textSegments[textSegments.length - 1] = segment; + + boolean[] activeSegments2 = new boolean[activeSegments.length]; + System.arraycopy( + activeSegments, + 0, + activeSegments2, + 0, + activeSegments.length); + activeSegments = activeSegments2; + activeSegments[activeSegments.length - 1] = false; + + StyleRange[] styleRanges2 = new StyleRange[styleRanges.length]; + System.arraycopy(styleRanges, 0, styleRanges2, 0, styleRanges.length); + styleRanges = styleRanges2; + styleRanges[styleRanges.length - 1] = new StyleRange(); + + String text = ""; //$NON-NLS-1$ + for (int i = 0; i < textSegments.length; i++) { + text = text + textSegments[i]; + } + this.text = text; + styledText.setText(text); + + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/ZoomPanel.java b/relicts/org/jalgo/main/gui/ZoomPanel.java new file mode 100644 index 0000000..2a2c76a --- /dev/null +++ b/relicts/org/jalgo/main/gui/ZoomPanel.java @@ -0,0 +1,92 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.gui; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.Graphics; +import org.eclipse.draw2d.ScaledGraphics; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.draw2d.geometry.Translatable; + + +public class ZoomPanel extends Figure { + + private float zoom; + + public float getZoom() { + return zoom; + } + + public Rectangle getClientArea(Rectangle rect) { + super.getClientArea(rect); + rect.width /= zoom; + rect.height /= zoom; + return rect; + } + + public Dimension getPreferredSize(int wHint, int hHint) { + Dimension d = super.getPreferredSize(wHint, hHint); + int w = getInsets().getWidth(); + int h = getInsets().getHeight(); + return d.scale(zoom).expand(w, h); + } + + protected void paintClientArea(Graphics graphics) { + if (getChildren().isEmpty()) + return; + + boolean optimizeClip = getBorder() == null || getBorder().isOpaque(); + ScaledGraphics g = new ScaledGraphics(graphics); + + + if (!optimizeClip) + g.clipRect(getBounds().getCropped(getInsets())); + g.translate( + getBounds().x + getInsets().left, + getBounds().y + getInsets().top); + g.scale(zoom); + g.pushState(); + paintChildren(g); + g.popState(); + g.dispose(); + + graphics.restoreState(); + + } + + public void setZoom(float zoom) { + this.zoom = zoom; + this.revalidate(); + } + + public void translateToParent(Translatable t) { + t.performScale(zoom); + super.translateToParent(t); + } + public void translateFromParent(Translatable t) { + super.translateFromParent(t); + t.performScale(1 / zoom); + } + + protected boolean useLocalCoordinates() { + return false; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/AboutAction.java b/relicts/org/jalgo/main/gui/actions/AboutAction.java new file mode 100644 index 0000000..df2ef3d --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/AboutAction.java @@ -0,0 +1,54 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.gui.JalgoWindow; +import org.jalgo.main.util.Messages; + +/* + * Created on Mar 23, 2004 + */ + +/** + * @author Christopher Friedrich + */ +public class AboutAction +extends Action { + + private JalgoWindow win; + + public AboutAction(JalgoWindow win) { + this.win = win; + + setText(Messages.getString("main", "ui.About")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main","ui.About_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + Messages.getResourceURL("main", "ui.About"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public void run() { + + win.showInfoMessage( + Messages.getString("main", "ui.About"), //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getJalgoInfo()); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/AboutModuleAction.java b/relicts/org/jalgo/main/gui/actions/AboutModuleAction.java new file mode 100644 index 0000000..09389da --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/AboutModuleAction.java @@ -0,0 +1,72 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 28.06.2004 + */ +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.gui.JalgoWindow; +import org.jalgo.main.util.Messages; + +/** + * @author Christopher Friedrich + */ +public class AboutModuleAction +extends Action { + + private JalgoWindow win; + private static final String lineSep = System.getProperty("line.separator"); + + public AboutModuleAction(JalgoWindow win) { + this.win = win; + + setText(Messages.getString("main", "ui.About_module")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main", "ui.About_module_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + Messages.getResourceURL("main", "ui.About_module"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public void run() { + IModuleInfo moduleInfo = + JalgoMain.getInstance().getCurrentInstance().getModuleInfo(); + StringBuffer content = new StringBuffer(); + content.append(moduleInfo.getName()); + content.append(Messages.getString("main", "AboutModule.Version")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(moduleInfo.getVersion()); + content.append(lineSep).append(lineSep); + content.append(moduleInfo.getDescription()); + content.append(lineSep).append(lineSep); + content.append(Messages.getString("main", "About.Authors")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(lineSep); + content.append(moduleInfo.getAuthor()); + content.append(lineSep).append(lineSep); + content.append(Messages.getString("main", "About.License")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(lineSep); + content.append(moduleInfo.getLicense()); + + win.showInfoMessage( + Messages.getString("main", "ui.About_module"), //$NON-NLS-1$ //$NON-NLS-2$ + content.toString()); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/CVS/Entries b/relicts/org/jalgo/main/gui/actions/CVS/Entries new file mode 100644 index 0000000..5b207a5 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/CVS/Entries @@ -0,0 +1,15 @@ +/AboutAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/AboutModuleAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/ExitAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/ExportAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/HelpAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/NewAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/NewModuleAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/OpenAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/PrintAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/PrintViewAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/SaveAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/SaveAsAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/ZoomInAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/ZoomOutAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/ZoomToFitAction.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ diff --git a/relicts/org/jalgo/main/gui/actions/CVS/Repository b/relicts/org/jalgo/main/gui/actions/CVS/Repository new file mode 100644 index 0000000..c306f30 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/gui/actions diff --git a/relicts/org/jalgo/main/gui/actions/CVS/Root b/relicts/org/jalgo/main/gui/actions/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/gui/actions/ExitAction.java b/relicts/org/jalgo/main/gui/actions/ExitAction.java new file mode 100644 index 0000000..f612b2c --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/ExitAction.java @@ -0,0 +1,51 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Mar 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.window.ApplicationWindow; +import org.jalgo.main.util.Messages; + +/** + * This class handles the "Exit" button + * + * @author Cornelius Hald + */ +public class ExitAction extends Action { + + ApplicationWindow window; + + public ExitAction(ApplicationWindow win) { + window = win; + setText(Messages.getString("main", "ui.Exit")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Exit")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/close.gif"))); + } + + public void run() { + window.close(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/ExportAction.java b/relicts/org/jalgo/main/gui/actions/ExportAction.java new file mode 100644 index 0000000..8932403 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/ExportAction.java @@ -0,0 +1,97 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 22, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.SWTGraphics; +import org.eclipse.draw2d.ScaledGraphics; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.ImageLoader; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; + +/** + * @author Cornelius Hald + */ +public class ExportAction extends Action { + + private IFigure figure; + + public ExportAction(IFigure figure) { + this.figure = figure; + + setText(Messages.getString("main", "ui.Export")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Export_image")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/export.gif"))); + } + + public void run() { + // Create Image with double size to enhance quality + if (figure.getPreferredSize().width * figure.getPreferredSize().height == 0) { + JAlgoGUIConnector.getInstance().showErrorMessage( + "Export failure: Nothing to export"); //$NON-NLS-1$ + return; + } + Image img = new Image( + null, + figure.getPreferredSize().width, + figure.getPreferredSize().height); + GC gc = new GC(img); + SWTGraphics swtg = new SWTGraphics(gc); + ScaledGraphics scaled = new ScaledGraphics(swtg); + + // Enter the scale factor + scaled.scale(1); + + // Paint the figure on the scaledGraphics + figure.paint(scaled); + + // Sets ImageData + ImageLoader loader = new ImageLoader(); + loader.data = new ImageData[] { img.getImageData()}; + + // Save to file + FileDialog filer = new FileDialog(new Shell(), SWT.SAVE); + filer.setText(Messages.getString("main", "ui.Export_file")); //$NON-NLS-1$ + filer.setFilterExtensions(new String[] { "*.bmp" }); //$NON-NLS-1$ + filer.setFilterNames(new String[] { + Messages.getString("main", "ExportAction.Bitmap_(*.bmp)_6") }); //$NON-NLS-1$ + String filename = filer.open(); + + if (filename != null) { + loader.save(filename, SWT.IMAGE_BMP); + } + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/HelpAction.java b/relicts/org/jalgo/main/gui/actions/HelpAction.java new file mode 100644 index 0000000..31b121a --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/HelpAction.java @@ -0,0 +1,89 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 26.05.2005 */ +package org.jalgo.main.gui.actions; + +import java.io.IOException; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.gui.JalgoWindow; +import org.jalgo.main.util.BrowserLauncher; +import org.jalgo.main.util.Messages; + +/** + * The class HelpAction defines an Action object, + * which can be added to toolbars and menus. Performing this action opens the + * online help file.
    + * This action comes with the standard key accelerator 'F1'. + * + * @author Alexander Claus + */ +public class HelpAction +extends Action { + + private final String helpPathMain = System.getProperty("user.dir")+ //$NON-NLS-1$ + Messages.getString("main_res", "ui.Help_file"); //$NON-NLS-1$ //$NON-NLS-2$ + private final String helpPathAVL = System.getProperty("user.dir")+ //$NON-NLS-1$ + Messages.getString("main_res", "ui.Help_file_avl"); //$NON-NLS-1$ //$NON-NLS-2$ + private final String helpPathDijkstra = System.getProperty("user.dir")+ //$NON-NLS-1$ + Messages.getString("main_res", "ui.Help_file_dijkstra"); //$NON-NLS-1$ //$NON-NLS-2$ + private JalgoWindow appWin; + private static final String lineSep = System.getProperty("line.separator"); + + /** + * Constructs a HelpAction object with the given reference. + * + * @param appWin the JalgoWindow instance + */ + public HelpAction(JalgoWindow appWin) { + this.appWin = appWin; + + setText(Messages.getString("main", "ui.Help.Contents")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main", "ui.Help_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + Messages.getResourceURL("main", "ui.Help"))); //$NON-NLS-1$ //$NON-NLS-2$ + setAccelerator(SWT.F1); + } + + /** + * Performs the action. + */ + public void run() { + try { + AbstractModuleConnector currentInstance = + JalgoMain.getInstance().getCurrentInstance(); + if (currentInstance == null) BrowserLauncher.openURL(helpPathMain); + else if (currentInstance.getModuleInfo().getName().equals( + Messages.getString("avl", "Module_name"))) + BrowserLauncher.openURL(helpPathAVL); + else if (currentInstance.getModuleInfo().getName().equals("Dijkstra")) + BrowserLauncher.openURL(helpPathDijkstra); + } + catch (IOException ex) { + appWin.showErrorMessage(Messages.getString( + "main", "HelpAction.Error_1") + lineSep + //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("main", "HelpAction.Error_2")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/NewAction.java b/relicts/org/jalgo/main/gui/actions/NewAction.java new file mode 100644 index 0000000..df4d7c0 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/NewAction.java @@ -0,0 +1,53 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.JalgoMain; + +/** + * @author Michael Pradel + * + */ +public class NewAction extends Action { + + private JalgoMain main; + private int modNumber; + + public NewAction(JalgoMain main, int modNumber) { + this.main = main; + this.modNumber = modNumber; + + setText( (main.getKnownModuleInfos().get(modNumber)).getName() ); + setToolTipText((main.getKnownModuleInfos().get(modNumber)).getDescription()); + setImageDescriptor(ImageDescriptor.createFromURL( + main.getKnownModuleInfos().get(modNumber).getLogoURL())); + } + + public void run() { + main.newInstance(modNumber); + } + +} diff --git a/relicts/org/jalgo/main/gui/actions/NewModuleAction.java b/relicts/org/jalgo/main/gui/actions/NewModuleAction.java new file mode 100644 index 0000000..bb03dd3 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/NewModuleAction.java @@ -0,0 +1,54 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 01.08.2004 + */ +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.gui.JalgoWindow; +import org.jalgo.main.gui.ModuleChooseDialog; +import org.jalgo.main.util.Messages; + +/** + * @author Michael Pradel + */ +public class NewModuleAction extends Action { + + JalgoWindow win; + //file, where the visibilty state of the ModuleChooseDialog is saved + private String path; + + public NewModuleAction(JalgoWindow win, String iniPath) { + this.win = win; + setToolTipText(Messages.getString("main", "ui.New")); + setImageDescriptor(ImageDescriptor.createFromURL(getClass() + .getResource("/main_pix/new.gif"))); + path = iniPath; + } + + public void run() { + ModuleChooseDialog dialog = new ModuleChooseDialog(win.getShell(), + JalgoMain.getInstance(),path); + dialog.open(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/OpenAction.java b/relicts/org/jalgo/main/gui/actions/OpenAction.java new file mode 100644 index 0000000..6761384 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/OpenAction.java @@ -0,0 +1,58 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Mar 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.gui.JalgoWindow; +import org.jalgo.main.util.Messages; + +/** + * This is the action responible for the "File open" request. + * + * @author Cornelius Hald + */ +public class OpenAction extends Action { + + private JalgoWindow win; + + public OpenAction(JalgoWindow win) { + + this.win = win; + setText(Messages.getString("main", "ui.Open_file")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main", "ui.Open_file")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/open.gif"))); + } + + /** + * The method is called if the user presses the "File open" button. + * + * + * @see org.eclipse.jface.action.IAction#run() + */ + public void run() { + win.showOpenDialog(true, false); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/PrintAction.java b/relicts/org/jalgo/main/gui/actions/PrintAction.java new file mode 100644 index 0000000..a13f983 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/PrintAction.java @@ -0,0 +1,45 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.util.Messages; + +/** + * @author Cornelius Hald + */ +public class PrintAction extends Action { + + public PrintAction() { + setText(Messages.getString("main", "ui.Print")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Print")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/print.gif"))); + } + + public void run() { + // printing is currently not supported + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/PrintViewAction.java b/relicts/org/jalgo/main/gui/actions/PrintViewAction.java new file mode 100644 index 0000000..a3ed326 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/PrintViewAction.java @@ -0,0 +1,96 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PrintFigureOperation; +import org.eclipse.draw2d.geometry.Insets; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.printing.PrintDialog; +import org.eclipse.swt.printing.Printer; +import org.eclipse.swt.printing.PrinterData; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.PrintDialogNext; +import org.jalgo.main.util.PrintScaledFigureOperation; + +/** + * @author Cornelius Hald + * @author Anne Kersten + */ +public class PrintViewAction extends Action { + + private IFigure figure; + + public PrintViewAction(IFigure figure) { + this.figure = figure; + setText(Messages.getString("main", "ui.Print_view")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Print_view")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/print.gif"))); + } + + public void run() { + Shell shell =new Shell(); + + // New Print-Dialog + PrintDialog printDialog = new PrintDialog(shell); + printDialog.setText(Messages.getString("main", "ui.Select_printer")); //$NON-NLS-1$ + PrinterData printerData = printDialog.open(); + if(printerData==null) return; + + + + Printer printer = new Printer(printerData); + PrintScaledFigureOperation operation = new PrintScaledFigureOperation(printer,figure); + operation.setPrintMargin(new Insets(0, 0, 0, 0)); + PrintDialogNext dialog=new PrintDialogNext(shell); + switch(dialog.open()) + { + case PrintFigureOperation.TILE: + operation.run("JAlgo"); //$NON-NLS-1$ + break; + case PrintFigureOperation.FIT_PAGE: + operation.setPrintMode(PrintFigureOperation.FIT_PAGE); + operation.run("JAlgo"); //$NON-NLS-1$ + break; + case PrintFigureOperation.FIT_WIDTH: + operation.setPrintMode(PrintFigureOperation.FIT_WIDTH); + operation.run("JAlgo"); //$NON-NLS-1$ + break; + case PrintFigureOperation.FIT_HEIGHT: + operation.setPrintMode(PrintFigureOperation.FIT_HEIGHT); + operation.run("JAlgo"); //$NON-NLS-1$ + break; + case PrintScaledFigureOperation.USE_LAYOUT: + operation.setPrintMode(PrintScaledFigureOperation.USE_LAYOUT); + operation.run("JAlgo"); //$NON-NLS-1$ + break; + default: + } + + printer.dispose(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/SaveAction.java b/relicts/org/jalgo/main/gui/actions/SaveAction.java new file mode 100644 index 0000000..3e4171f --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/SaveAction.java @@ -0,0 +1,53 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and platform + * independant. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Mar 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.util.Messages; + +/** + * @author Michael Pradel + */ +public class SaveAction +extends Action { + + public SaveAction() { + // this.mc = mc; + setText(Messages.getString("main", "ui.Save_file")); //$NON-NLS-1$ //$NON-NLS-2$ + setId(Messages.getString("main", "ui.Save_file")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main", "ui.Save_file")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + Messages.getResourceURL("main", "ui.Save_file"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public void run() { + JalgoMain.getInstance().saveFile(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/SaveAsAction.java b/relicts/org/jalgo/main/gui/actions/SaveAsAction.java new file mode 100644 index 0000000..7512256 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/SaveAsAction.java @@ -0,0 +1,66 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.FileDialog; +import org.jalgo.main.JalgoMain; +import org.jalgo.main.util.Messages; + +/** + * @author Cornelius Hald + */ +public class SaveAsAction extends Action { + + private boolean wasSuccessful; + + public SaveAsAction() { + setText(Messages.getString("main", "ui.Save_as")); //$NON-NLS-1$ //$NON-NLS-2$ + setId(Messages.getString("main", "ui.Save_as")); //$NON-NLS-1$ //$NON-NLS-2$ + setToolTipText(Messages.getString("main", "ui.Save_as")); //$NON-NLS-1$ //$NON-NLS-2$ + setImageDescriptor(ImageDescriptor.createFromURL( + Messages.getResourceURL("main", "ui.Save_as"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public void run() { + FileDialog fileChooser = new FileDialog( + Display.getCurrent().getActiveShell(), SWT.SAVE); + fileChooser.setText(Messages.getString("main", "ui.Save_as")); //$NON-NLS-1$ //$NON-NLS-2$ + fileChooser.setFilterPath(System.getProperty("user.dir")); //$NON-NLS-1$ + fileChooser.setFilterExtensions(new String[] {"*.jalgo"}); //$NON-NLS-1$ //$NON-NLS-2$ + fileChooser.setFilterNames(new String[] { + Messages.getString("main", "OpenAction.jAlgo_files")}); //$NON-NLS-1$ //$NON-NLS-2$ + String filename = fileChooser.open(); + if (filename != null) + wasSuccessful = JalgoMain.getInstance().saveFileAs(filename); + else wasSuccessful = false; + } + + public boolean wasSuccessful() { + return wasSuccessful; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/ZoomInAction.java b/relicts/org/jalgo/main/gui/actions/ZoomInAction.java new file mode 100644 index 0000000..c54203c --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/ZoomInAction.java @@ -0,0 +1,57 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.gui.widgets.GraphViewForm; +import org.jalgo.main.util.Messages; + +/** + * This Action can be used to zoom into an Draw2D Figure - Typically this will be a Panel. + * + * @author Cornelius Hald + */ +public class ZoomInAction extends Action { + + private GraphViewForm form; + + /** + * Constructs a new ZoomInAction + * @param form + */ + public ZoomInAction(GraphViewForm form) { + this.form = form; + setText(Messages.getString("main", "ui.Zoom_in")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Zoom_in")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/zoom-in.gif"))); + } + + public void run() { + + form.zoomIn(); + + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/ZoomOutAction.java b/relicts/org/jalgo/main/gui/actions/ZoomOutAction.java new file mode 100644 index 0000000..8219339 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/ZoomOutAction.java @@ -0,0 +1,56 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.gui.widgets.GraphViewForm; +import org.jalgo.main.util.Messages; + +/** + * This Action can be used to zoom out of an Draw2D Figure - Typically this will be a Panel. + * + * @author Cornelius Hald + */ + +public class ZoomOutAction extends Action { + + private GraphViewForm form; + + /** + * Constructs a new ZoomInAction + * @param form + */ + public ZoomOutAction(GraphViewForm form) { + this.form = form; + setText(Messages.getString("main", "ui.Zoom_out")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Zoom_out")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/zoom-out.gif"))); + } + + public void run() { + form.zoomOut(); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/actions/ZoomToFitAction.java b/relicts/org/jalgo/main/gui/actions/ZoomToFitAction.java new file mode 100644 index 0000000..35fdd46 --- /dev/null +++ b/relicts/org/jalgo/main/gui/actions/ZoomToFitAction.java @@ -0,0 +1,51 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 23, 2004 + */ + +package org.jalgo.main.gui.actions; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.resource.ImageDescriptor; +import org.jalgo.main.util.Messages; + +/** + * This Action can be used to zoom a Panel, so that alle Figures can be seen. - Typically this will be a Panel. + * + * @author Cornelius Hald + */ + +public class ZoomToFitAction extends Action { + + /** + * Constructs a new ZoomInAction + * @param panel The Panel which contents should be zoomed. + */ + public ZoomToFitAction(IFigure panel) { + setText(Messages.getString("main", "ui.Zoom_fit")); //$NON-NLS-1$ + setToolTipText(Messages.getString("main", "ui.Zoom_fit")); //$NON-NLS-1$ + setImageDescriptor(ImageDescriptor.createFromURL( + getClass().getResource("/main_pix/zoom_to_fit.gif"))); + } + + public void run() {} +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/widgets/CVS/Entries b/relicts/org/jalgo/main/gui/widgets/CVS/Entries new file mode 100644 index 0000000..3b60c47 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/CVS/Entries @@ -0,0 +1,7 @@ +/CustomViewForm.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/GraphViewForm.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/Splitter.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/StackCanvas.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/StackViewForm.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/StyledTextViewForm.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ +/TextViewForm.java/1.2/Sat Mar 4 13:36:20 2006/-kk/ diff --git a/relicts/org/jalgo/main/gui/widgets/CVS/Repository b/relicts/org/jalgo/main/gui/widgets/CVS/Repository new file mode 100644 index 0000000..a3485f2 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/gui/widgets diff --git a/relicts/org/jalgo/main/gui/widgets/CVS/Root b/relicts/org/jalgo/main/gui/widgets/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/gui/widgets/CustomViewForm.java b/relicts/org/jalgo/main/gui/widgets/CustomViewForm.java new file mode 100644 index 0000000..bf8cd38 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/CustomViewForm.java @@ -0,0 +1,141 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 25.05.2004 + */ +package org.jalgo.main.gui.widgets; + +import org.eclipse.jface.action.ToolBarManager; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CLabel; +import org.eclipse.swt.custom.ViewForm; +import org.eclipse.swt.events.FocusAdapter; +import org.eclipse.swt.events.FocusEvent; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; + +/** + * @author Christopher Friedrich + */ + +// TODO: Add a disposeListener to ALL *ViewForms. Resources which gets allocated need to be disposed if the ViewForm gets disposed. + +public class CustomViewForm extends ViewForm { + + private CLabel label; + + protected ToolBarManager toolbarMgrCenter; + protected ToolBarManager toolbarMgrRight; + + private Color titleBG; + private Color titleFG; + private Color widgetBG; + private Color[] activeGradient; + private int[] activeGradientPercents; + + /** + * @param parent + * @param style + */ + public CustomViewForm(Composite parent, int style) { + + super(parent, style); + + // init some colors + titleBG = + parent.getDisplay().getSystemColor(SWT.COLOR_TITLE_BACKGROUND); + titleFG = + parent.getDisplay().getSystemColor(SWT.COLOR_TITLE_FOREGROUND); + widgetBG = + parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); + activeGradient = new Color[] { titleBG, widgetBG, widgetBG }; + activeGradientPercents = new int[] { 80, 100 }; + + // Create Label + label = new CLabel(this, SWT.BORDER) { + public Point computeSize(int wHint, int hHint, boolean changed) { + return super.computeSize(wHint, Math.max(24, hHint), changed); + } + }; + label.setForeground(titleFG); + label.setBackground(activeGradient, activeGradientPercents); + + // Add Maximize-on-DoubleClick Support + MouseAdapter ml = new MouseAdapter() { + public void mouseDoubleClick(MouseEvent e) { + Control content = getContent(); + if (content != null && content.getBounds().contains(e.x, e.y)) + return; + Control parent = getParent(); + if (parent instanceof Splitter) + ((Splitter) parent).setMaximizedControl( + CustomViewForm.this); + } + }; + addMouseListener(ml); + label.addMouseListener(ml); + + addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + } + public void focusLost(FocusEvent e) { + } + }); + + // Extend TopRight-ToolBarManager + toolbarMgrCenter = new ToolBarManager(SWT.FLAT); + toolbarMgrRight = new ToolBarManager(SWT.FLAT); + + setTopLeft(label); + setTopCenterSeparate(true); + setTopCenter(toolbarMgrCenter.createControl(this)); + setTopRight(toolbarMgrRight.createControl(this)); + } + + /** + * Sets title text. + * + * @param text the text to be displayed in the title + */ + public void setText(String text) { + label.setText(text); + } + + /** + * Sets title image. + * + * @param img the image to be displayed in the title + */ + public void setImage(Image img) { + label.setImage(img); + } + + public ToolBarManager getToolBarManager() { + return toolbarMgrCenter; + } +} diff --git a/relicts/org/jalgo/main/gui/widgets/GraphViewForm.java b/relicts/org/jalgo/main/gui/widgets/GraphViewForm.java new file mode 100644 index 0000000..33b3f6b --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/GraphViewForm.java @@ -0,0 +1,78 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 29, 2004 + */ + +package org.jalgo.main.gui.widgets; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.StackLayout; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.widgets.Composite; +import org.jalgo.main.gui.ScrollZoomCanvas; + +/** + * @author Cornelius Hald + * @author Christopher Friedrich + */ +public class GraphViewForm extends CustomViewForm { + + private ScrollZoomCanvas canvas; + + public GraphViewForm(Composite parent, int style) { + + super(parent, style); + + // Init the canvas + canvas = new ScrollZoomCanvas(this); + canvas.setBackground(new Color(parent.getDisplay(), 255, 255, 255)); + canvas.setScrollBarVisibility(1); + canvas.setLayoutManager(new StackLayout()); + + // Sets the content of this GraphViewForm + setContent(canvas); + canvas.layout(); + canvas.validate(); + canvas.revalidate(); + canvas.redraw(); + + } + + public void zoomIn() { + canvas.setZoom(canvas.getZoom() * 1.2f); + } + + public void zoomToFit() { + canvas.setZoom(1.0f); + } + + public void zoomOut() { + canvas.setZoom(canvas.getZoom() * 0.8f); + } + + public IFigure getPanel() { + return canvas.getContents(); + } + + public void setPanel(IFigure f) { + canvas.setContents(f); + } +} diff --git a/relicts/org/jalgo/main/gui/widgets/Splitter.java b/relicts/org/jalgo/main/gui/widgets/Splitter.java new file mode 100644 index 0000000..dc70790 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/Splitter.java @@ -0,0 +1,149 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.jalgo.main.gui.widgets; + +import org.eclipse.swt.widgets.*; +import org.eclipse.swt.custom.SashForm; + +/** + * The Splitter adds support for nesting to a SashForm. + *

    + * If Splitters are nested directly: + *

      + *
    • changing the visibility of a child may propagate upward to the parent Splitter if the child + * is the last child to become invisible or the first to become visible.
    • + *
    • maximizing a child makes it as large as the topmost enclosing Splitter
    • + *
    + * + * @since 2.1 + */ +public class Splitter extends SashForm { + + private static final String VISIBILITY= "org.eclipse.compare.internal.visibility"; //$NON-NLS-1$ + + /** + * Constructs a new instance of this class given its parent + * and a style value describing its behavior and appearance. + *

    + * The style value is either one of the style constants defined in + * class SWT which is applicable to instances of this + * class, or must be built by bitwise OR'ing together + * (that is, using the int "|" operator) two or more + * of those SWT style constants. The class description + * lists the style constants that are applicable to the class. + * Style bits are also inherited from superclasses. + *

    + * + * @param parent a widget which will be the parent of the new instance (cannot be null) + * @param style the style of widget to construct + * + * @exception IllegalArgumentException
      + *
    • ERROR_NULL_ARGUMENT - if the parent is null
    • + *
    + * @exception org.eclipse.swt.SWTException
      + *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent
    • + *
    + */ + public Splitter(Composite parent, int style) { + super(parent, style); + } + + /** + * Sets the visibility of the given child in this Splitter. If this change + * affects the visibility state of the whole Splitter, and if the Splitter + * is directly nested in one or more Splitters, this method recursively + * propagates the new state upward. + * + * @param child the child control for which the visibility is changed + * @param visible the new visibility state + */ + public void setVisible(Control child, boolean visible) { + + boolean wasEmpty= isEmpty(); + + child.setVisible(visible); + child.setData(VISIBILITY, new Boolean(visible)); + + if (wasEmpty != isEmpty()) { + // recursively walk up + Composite parent= getParent(); + if (parent instanceof Splitter) { + Splitter sp= (Splitter) parent; + sp.setVisible(this, visible); + sp.layout(); + } + } else { + layout(); + } + } + + /* (non-Javadoc) + * Recursively calls setMaximizedControl for all direct parents that are + * itself Splitters. + */ + public void setMaximizedControl(Control control) { + if (control == null || control == getMaximizedControl()) + super.setMaximizedControl(null); + else + super.setMaximizedControl(control); + + // recursively walk upward + Composite parent= getParent(); + if (parent instanceof Splitter) + ((Splitter) parent).setMaximizedControl(this); + else + layout(true); + } + + /* (non-Javadoc) + * Returns true if Splitter has no children or if all children are invisible. + */ + private boolean isEmpty() { + Control[] controls= getChildren(); + for (int i= 0; i < controls.length; i++) + if (isVisible(controls[i])) + return false; + return true; + } + + /* (non-Javadoc) + * Returns the visibility state of the given child control. If the + * control is a Sash, this method always returns false. + */ + private boolean isVisible(Control child) { + if (child instanceof Sash) + return false; + Object data= child.getData(VISIBILITY); + if (data instanceof Boolean) + return ((Boolean)data).booleanValue(); + return true; + } +} diff --git a/relicts/org/jalgo/main/gui/widgets/StackCanvas.java b/relicts/org/jalgo/main/gui/widgets/StackCanvas.java new file mode 100644 index 0000000..7b5375a --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/StackCanvas.java @@ -0,0 +1,91 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 31, 2004 + */ + +package org.jalgo.main.gui.widgets; + +import java.util.Stack; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Text; + +/** + * @author Cornelius Hald + * @author Christopher Friedrich + */ +/* + * This is an adapter because Java don't support multiple inheritance + */ +public class StackCanvas extends Composite { + private Stack stack; + private Text textField; + + private void redrawStack() { + textField.setText(""); //$NON-NLS-1$ + StringBuffer strBuffer = new StringBuffer(); + + for (String item : stack) { + strBuffer.insert(0, item + "\n"); //$NON-NLS-1$ + } + + textField.setText(strBuffer.toString()); + } + + public StackCanvas(Composite parent, int style) { + super(parent, style); + + setLayout(new FillLayout()); + textField = new Text(this, SWT.MULTI); + stack = new Stack(); + } + + public void push(String element) { + stack.push(element); + redrawStack(); + } + + public String pop() { + String obj = null; + if (!stack.isEmpty()) { + obj = stack.pop(); + } + redrawStack(); + return obj; + } + + public void reset() { + stack.clear(); + } + + public Stack getStack() { + return stack; + } + + public void setStack(Stack stack) { + this.stack = stack; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/gui/widgets/StackViewForm.java b/relicts/org/jalgo/main/gui/widgets/StackViewForm.java new file mode 100644 index 0000000..cbd19b7 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/StackViewForm.java @@ -0,0 +1,48 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 29, 2004 + */ + +package org.jalgo.main.gui.widgets; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; + +/** + * @author Cornelius Hald + * @author Christopher Friedrich + */ +public class StackViewForm extends CustomViewForm { + + private StackCanvas stackCanvas; + + public StackViewForm(Composite parent, int style) { + + super(parent, style); + + stackCanvas = new StackCanvas(this, SWT.FLAT); + setContent(stackCanvas); + } + + public StackCanvas getStackCanvas() { + return stackCanvas; + } +} diff --git a/relicts/org/jalgo/main/gui/widgets/StyledTextViewForm.java b/relicts/org/jalgo/main/gui/widgets/StyledTextViewForm.java new file mode 100644 index 0000000..14ae230 --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/StyledTextViewForm.java @@ -0,0 +1,46 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 29, 2004 + */ + +package org.jalgo.main.gui.widgets; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.widgets.Composite; + +/** + * @author Christopher Friedrich + */ +public class StyledTextViewForm extends CustomViewForm { + + private StyledText styledText; + + public StyledTextViewForm (Composite parent, int style) { + super(parent, style); + styledText = new StyledText(this, SWT.FLAT); + setContent(styledText); + } + + public StyledText getStyledText() { + return styledText; + } +} diff --git a/relicts/org/jalgo/main/gui/widgets/TextViewForm.java b/relicts/org/jalgo/main/gui/widgets/TextViewForm.java new file mode 100644 index 0000000..a6b0a3f --- /dev/null +++ b/relicts/org/jalgo/main/gui/widgets/TextViewForm.java @@ -0,0 +1,47 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 29, 2004 + */ + +package org.jalgo.main.gui.widgets; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.jalgo.main.gui.TextCanvas; + +/** + * @author Cornelius Hald + * @author Christopher Friedrich + */ +public class TextViewForm extends CustomViewForm { + + private TextCanvas textCanvas; + + public TextViewForm (Composite parent, int style) { + super(parent, style); + textCanvas = new TextCanvas(this, SWT.FLAT); + setContent(textCanvas); + } + + public TextCanvas getTextCanvas() { + return textCanvas; + } +} diff --git a/relicts/org/jalgo/main/trees/Arrows.java b/relicts/org/jalgo/main/trees/Arrows.java new file mode 100644 index 0000000..a780c58 --- /dev/null +++ b/relicts/org/jalgo/main/trees/Arrows.java @@ -0,0 +1,36 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.ImageFigure; +import org.eclipse.swt.graphics.Image; + +/** + * A {@link Figure}that shows two arrows. + * + * @author Michael Pradel + * + */ +public final class Arrows { + + private static Arrows instance = null; + + // Singleton design pattern + private Arrows() { + } + + public static ImageFigure getArrows(int direction) { + if (instance == null) + instance = new Arrows(); + ImageFigure a = new ImageFigure(); + if (direction == ITreeConstants.LEFT_ROT) + a.setImage(new Image(null, "pix/trees/left_arrows.png")); + else if (direction == ITreeConstants.RIGHT_ROT) + a.setImage(new Image(null, "pix/trees/right_arrows.png")); + return a; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/CVS/Entries b/relicts/org/jalgo/main/trees/CVS/Entries new file mode 100644 index 0000000..a7d583f --- /dev/null +++ b/relicts/org/jalgo/main/trees/CVS/Entries @@ -0,0 +1,10 @@ +/Arrows.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/Edge.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/EdgeFigure.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/ITreeConstants.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/Leaf.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/LeafFigure.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/NodeFigure.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/Tree.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/TreeComponent.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ +/TreeLayout.java/1.2/Sat Mar 4 13:36:08 2006/-kk/ diff --git a/relicts/org/jalgo/main/trees/CVS/Repository b/relicts/org/jalgo/main/trees/CVS/Repository new file mode 100644 index 0000000..9ee0f22 --- /dev/null +++ b/relicts/org/jalgo/main/trees/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/trees diff --git a/relicts/org/jalgo/main/trees/CVS/Root b/relicts/org/jalgo/main/trees/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/trees/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/trees/Edge.java b/relicts/org/jalgo/main/trees/Edge.java new file mode 100644 index 0000000..635d8d6 --- /dev/null +++ b/relicts/org/jalgo/main/trees/Edge.java @@ -0,0 +1,55 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +/** + * An edge is the connection between two nodes of a tree. + * + * @author Michael Pradel + * + */ + +public class Edge { + + private org.eclipse.draw2d.graph.Edge edge; + + private EdgeFigure figure; + + private TreeComponent parent; + + private TreeComponent child; + + public Edge(TreeComponent p, TreeComponent c) { + parent = p; + child = c; + figure = new EdgeFigure(); + edge = new org.eclipse.draw2d.graph.Edge(p.getNode(), c.getNode()); + } + + public void setText(String text) { + figure.setText(text); + } + + public String getText() { + return figure.getText(); + } + + public EdgeFigure getFigure() { + return figure; + } + + public boolean getVisibility() { + return figure.isVisible(); + } + + public void setVisibility(boolean v) { + figure.setVisible(v); + } + + public org.eclipse.draw2d.graph.Edge getEdge() { + return edge; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/EdgeFigure.java b/relicts/org/jalgo/main/trees/EdgeFigure.java new file mode 100644 index 0000000..b1cce1b --- /dev/null +++ b/relicts/org/jalgo/main/trees/EdgeFigure.java @@ -0,0 +1,82 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.ImageFigure; +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.MidpointLocator; +import org.eclipse.draw2d.PolylineConnection; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.swt.graphics.Color; + +/** + * A {@link Figure}that shows the edge between two nodes of a tree. + * + * @author Michael Pradel + * + */ +public class EdgeFigure extends PolylineConnection { + + private Color textColor; + + private ImageFigure myArrow; + + private Label label; + + private MidpointLocator arrowLocator; + + private MidpointLocator textLocator; + + public EdgeFigure() { + this(ITreeConstants.NO_ROT); + } + + public EdgeFigure(int arrowMode) { + setArrows(arrowMode); + textLocator = new MidpointLocator(this, 0); + textLocator.setRelativePosition(PositionConstants.WEST); + textLocator.setGap(30); + label = new Label(); + add(label, textLocator); + } + + public void setText(String t) { + label.setText(t); + } + + public String getText() { + return label.getText(); + } + + public void setTextColor(Color color) { + label.setForegroundColor(color); + } + + public Color getTextColor() { + return label.getForegroundColor(); + } + + /** + * Chose if and how to display the arrows. + * + * @param mode + * no arrows, left or right rotation, see also + * {@link ITreeConstants} + */ + public void setArrows(int mode) { + if ((mode == ITreeConstants.LEFT_ROT) + || (mode == ITreeConstants.RIGHT_ROT)) { + myArrow = Arrows.getArrows(mode); + arrowLocator = new MidpointLocator(this, 0); + add(myArrow, arrowLocator); + } else if (mode == ITreeConstants.NO_ROT) { + // remove old arrows if their exist + if (myArrow != null) + remove(myArrow); + } + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/ITreeConstants.java b/relicts/org/jalgo/main/trees/ITreeConstants.java new file mode 100644 index 0000000..98524c8 --- /dev/null +++ b/relicts/org/jalgo/main/trees/ITreeConstants.java @@ -0,0 +1,19 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +/** + * Definition of constants used in {@link org.jalgo.main.trees}. + * @author Michael Pradel + * + */ +public interface ITreeConstants { + public final int NO_ROT = 0; + public final int LEFT_ROT = 1; + public final int RIGHT_ROT = 2; + + public final int WEIGHT_LEFT = 0; + public final int WEIGHT_RIGHT = 1; +} diff --git a/relicts/org/jalgo/main/trees/Leaf.java b/relicts/org/jalgo/main/trees/Leaf.java new file mode 100644 index 0000000..898a20a --- /dev/null +++ b/relicts/org/jalgo/main/trees/Leaf.java @@ -0,0 +1,59 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Figure; + +/** + * A leaf component of a tree. Leaves cannot have any children. + * @author Michael Pradel + * + */ +public class Leaf extends TreeComponent { + + private LeafFigure figure; + + public Leaf() { + this("NIL"); + } + + public Leaf(String text) { + super(); + figure = new LeafFigure(text); + } + + public void setText(String text) { + figure.setText(text); + } + + public String getText() { + return figure.getText(); + } + + public void setOuterText(String text) { + figure.setOuterText(text); + } + + public String getOuterText() { + return figure.getOuterText(); + } + + public LeafFigure getFigure() { + return figure; + } + + public void setVisibility(boolean v) { + figure.setVisible(v); + } + + public boolean getVisibility() { + return figure.isVisible(); + } + + public Figure getInnerFigure() { + return figure.getInnerFigure(); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/LeafFigure.java b/relicts/org/jalgo/main/trees/LeafFigure.java new file mode 100644 index 0000000..532970e --- /dev/null +++ b/relicts/org/jalgo/main/trees/LeafFigure.java @@ -0,0 +1,88 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.RoundedRectangle; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; + +/** + * A {@link Figure}that shows a leaf of a tree. + * + * @author Michael Pradel + * + */ +public class LeafFigure extends Figure { + + private final int spacing = 10; + + private textFigure rect; + + private Label label; + + private Label outerLabel; + + private class textFigure extends RoundedRectangle { + public Label label; + + public textFigure(String t) { + label = new Label(t); + FlowLayout textLayout = new FlowLayout(); + textLayout.setMajorAlignment(FlowLayout.ALIGN_CENTER); + setLayoutManager(textLayout); + add(label, new Rectangle(-1,-1,-1,-1)); + } + + public Dimension getPreferredSize(int wHint, int hHint) { + Dimension pref = super.getPreferredSize(wHint, hHint); + pref.width += spacing; + return pref; + } + } + + public LeafFigure() { + this("NIL"); + } + + public LeafFigure(String text) { + super(); + outerLabel = new Label(); + + rect = new textFigure(text); + + // TODO: remove after testing + outerLabel.setText("xyz"); + + FlowLayout layout = new FlowLayout(); + setLayoutManager(layout); + + add(outerLabel, new Rectangle(0, 0, -1, -1)); + add(rect, new Rectangle(0, 0, -1, -1)); + + } + + public void setText(String text) { + rect.label.setText(text); + } + + public String getText() { + return rect.label.getText(); + } + + public void setOuterText(String text) { + outerLabel.setText(text); + } + + public String getOuterText() { + return outerLabel.getText(); + } + + public Figure getInnerFigure() { + return rect; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/NodeFigure.java b/relicts/org/jalgo/main/trees/NodeFigure.java new file mode 100644 index 0000000..85b6901 --- /dev/null +++ b/relicts/org/jalgo/main/trees/NodeFigure.java @@ -0,0 +1,96 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Ellipse; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.Label; +import org.eclipse.draw2d.StackLayout; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.graphics.Color; + +/** + * A {@link Figure}that shows a node of a tree. + * + * @author Michael Pradel + * + */ + +public class NodeFigure extends Figure { + + private final int spacing = 5; + + private Label outerLabel; + + private textFigure circle; + + private class textFigure extends Ellipse { + public Label label; + + public textFigure(String t) { + label = new Label(t); + setLayoutManager(new StackLayout()); + add(label, new Rectangle(-1, -1, -1, -1)); + } + + public Dimension getPreferredSize(int wHint, int hHint) { + Dimension pref = super.getPreferredSize(wHint, hHint); + pref.width += spacing; + pref.height = pref.width; + return pref; + } + } + + public NodeFigure() { + this(""); + } + + public NodeFigure(String text) { + super(); + outerLabel = new Label(); + circle = new textFigure(text); + + // TODO: remove after testing + outerLabel.setText("abc"); + + FlowLayout layout = new FlowLayout(); + setLayoutManager(layout); + + add(outerLabel, new Rectangle(0, 0, -1, -1)); + add(circle, new Rectangle(0, 0, -1, -1)); + + } + + public void setTextColor(Color color) { + circle.label.setForegroundColor(color); + } + + public Color getTextColor() { + return circle.label.getForegroundColor(); + } + + public void setText(String text) { + circle.label.setText(text); + } + + public String getText() { + return circle.label.getText(); + } + + public void setOuterText(String text) { + outerLabel.setText(text); + } + + public String getOuterText() { + return outerLabel.getText(); + } + + public Figure getInnerFigure() { + return circle; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/trees/Tree.java b/relicts/org/jalgo/main/trees/Tree.java new file mode 100644 index 0000000..0a01560 --- /dev/null +++ b/relicts/org/jalgo/main/trees/Tree.java @@ -0,0 +1,142 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import java.util.Iterator; +import java.util.LinkedList; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; + +/** + * A tree can be a single node or a node with children. This class represents + * the composite of the composite design pattern. + * + * @author Michael Pradel + * + */ +public class Tree extends TreeComponent { + + private NodeFigure nodeFigure; + + private LinkedList children; // LinkedList of TreeComponent + + private LinkedList edges; // LinkedList of Edge + + public Tree() { + this(""); + } + + public Tree(String text) { + super(); + nodeFigure = new NodeFigure(text); + children = new LinkedList(); + edges = new LinkedList(); + } + + public Figure layout() { + Figure treeF = new Figure(); + FlowLayout treeFL = new FlowLayout(false); + treeFL.setMinorAlignment(FlowLayout.ALIGN_CENTER); + treeFL.setMinorSpacing(20); + treeF.setLayoutManager(treeFL); + + // children + Figure childrenF = new Figure(); + FlowLayout childrenFL = new FlowLayout(true); + childrenFL.setMinorSpacing(20); + childrenF.setLayoutManager(childrenFL); + for (Iterator childrenIt = children.iterator(); childrenIt.hasNext();) { + TreeComponent child = (TreeComponent) childrenIt.next(); + // HIER WEITER!! + // children layouten, figure nehmen und in treeF einfügen, layout für andere treecomponents implementieren, fertig?? + } + + + treeF.add(nodeFigure); + treeF.add(childrenF); + + // TODO: remove when finished + return null; + } + + public boolean isTree() { + return true; + } + + public void addChild(TreeComponent c) { + children.add(c); + Edge newEdge = new Edge(this, c); + edges.add(newEdge); + c.setParent(this); + c.setEdgeToParent(newEdge); + } + + public boolean removeChild(TreeComponent c) { + if (!children.contains(c)) + return false; + int i = children.indexOf(c); + children.remove(i); + edges.remove(i); + c.setParent(null); + c.setEdgeToParent(null); + return true; + } + + public LinkedList getChildren() { + return children; + } + + public Edge getEdgeTo(TreeComponent c) { + int i = children.indexOf(c); + return (Edge) edges.get(i); + } + + public void setAllVisibility(boolean visible) { + // change visibility of children + Iterator i = children.iterator(); + while(i.hasNext()) { + ((TreeComponent) i.next()).setVisibility(visible); + } + // change visibility of edges to children + i = edges.iterator(); + while(i.hasNext()) { + ((Edge) i.next()).setVisibility(visible); + } + } + + public void setVisibility(boolean visible) { + nodeFigure.setVisible(visible); + } + + public boolean getVisibility() { + return nodeFigure.isVisible(); + } + + public void setText(String text) { + nodeFigure.setText(text); + } + + public String getText() { + return nodeFigure.getText(); + } + + public void setOuterText(String text) { + nodeFigure.setOuterText(text); + } + + public String getOuterText() { + return nodeFigure.getOuterText(); + } + + public NodeFigure getNodeFigure() { + return nodeFigure; + } + + public Figure getInnerFigure() { + return nodeFigure.getInnerFigure(); + } + +} diff --git a/relicts/org/jalgo/main/trees/TreeComponent.java b/relicts/org/jalgo/main/trees/TreeComponent.java new file mode 100644 index 0000000..3c7f41e --- /dev/null +++ b/relicts/org/jalgo/main/trees/TreeComponent.java @@ -0,0 +1,94 @@ +/* + * Created on 27.05.2005 + * + */ +package org.jalgo.main.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.graph.Node; + +/** + * Abstract class to represent a component of a tree, independant of its + * specific properties (following the "Composite" design pattern). + * + * @author Michael Pradel + * + */ +public abstract class TreeComponent { + + protected int weight = 0; + + protected TreeComponent parent; + + protected Edge edgeToParent; + + private org.eclipse.draw2d.graph.Node node; + + //protected Figure outerFigure; + + public TreeComponent() { + node = new Node(this); + } + + public org.eclipse.draw2d.graph.Node getNode() { + return node; + } + + /** + * Get the weight of this component. A node, leaf or subtree with a higher + * weight will appear on the right of one with a lower weigth. + * + * @return The weight of this component, see also {@link ITreeConstants}. + */ + public int getWeight() { + return weight; + } + + /** + * Set the weight of this component. A node, leaf or subtree with a higher + * weight will appear on the right of one with a lower weigth. + * + * @param weight + * The new weight of this component, see also + * {@link ITreeConstants}. + */ + public void setWeight(int weight) { + this.weight = weight; + } + + public abstract boolean getVisibility(); + + public abstract void setVisibility(boolean visible); + + public boolean isTree() { + return false; + } + + public TreeComponent getParent() { + return parent; + } + + public Edge getEdgeToParent() { + return edgeToParent; + } + + public abstract Figure getInnerFigure(); + + protected void setParent(TreeComponent p) { + parent = p; + } + + protected void setEdgeToParent(Edge e) { + edgeToParent = e; + } + + /** + * Get a figure that containing the whole + * TreeComponent + * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms + * that are not part of the standard JDK. What we're trying to do, though, is to take something + * that's frequently desirable but inherently platform-specific -- opening a default browser -- + * and allow programmers (you, for example) to do so without worrying about dropping into native + * code or doing anything else similarly evil. + *

    + * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without + * modification or a need for additional libraries. All classes that are required on certain + * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not + * found, will not cause this to do anything other than returning an error when opening the + * browser. + *

    + * There are certain system requirements for this class, as it's running through Runtime.exec(), + * which is Java's way of making a native system call. Currently, this requires that a Macintosh + * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that + * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder + * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and + * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems + * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops + * back from the inherently platform-sensitive concept of a default browser and simply attempts + * to launch mozilla via a shell command. + *

    + * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be + * redistributed or modified in any form without restrictions as long as the portion of this + * comment from this paragraph through the end of the comment is not removed. The author + * requests that he be notified of any application, applet, or other binary that makes use of + * this code, but that's more out of curiosity than anything and is not required. This software + * includes no warranty. The author is not repsonsible for any loss of data or functionality + * or any adverse or unexpected effects of using this software. + *

    + * Credits: + *
    Steven Spencer, JavaWorld magazine (Java Tip 66) + *
    Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, + * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk + * + * @author Eric Albert (ejalbert@cs.stanford.edu) + * @version 1.4b1 (Released June 20, 2001) + */ +@SuppressWarnings("all") +public class BrowserLauncher { + + /** + * The Java virtual machine that we are running on. Actually, in most cases we only care + * about the operating system, but some operating systems require us to switch on the VM. */ + private static int jvm; + + /** The browser for the system */ + private static Object browser; + + /** + * Caches whether any classes, methods, and fields that are not part of the JDK and need to + * be dynamically loaded at runtime loaded successfully. + *

    + * Note that if this is false, openURL() will always return an + * IOException. + */ + private static boolean loadedWithoutErrors; + + /** The com.apple.mrj.MRJFileUtils class */ + private static Class mrjFileUtilsClass; + + /** The com.apple.mrj.MRJOSType class */ + private static Class mrjOSTypeClass; + + /** The com.apple.MacOS.AEDesc class */ + private static Class aeDescClass; + + /** The (int) method of com.apple.MacOS.AETarget */ + private static Constructor aeTargetConstructor; + + /** The (int, int, int) method of com.apple.MacOS.AppleEvent */ + private static Constructor appleEventConstructor; + + /** The (String) method of com.apple.MacOS.AEDesc */ + private static Constructor aeDescConstructor; + + /** The findFolder method of com.apple.mrj.MRJFileUtils */ + private static Method findFolder; + + /** The getFileCreator method of com.apple.mrj.MRJFileUtils */ + private static Method getFileCreator; + + /** The getFileType method of com.apple.mrj.MRJFileUtils */ + private static Method getFileType; + + /** The openURL method of com.apple.mrj.MRJFileUtils */ + private static Method openURL; + + /** The makeOSType method of com.apple.MacOS.OSUtils */ + private static Method makeOSType; + + /** The putParameter method of com.apple.MacOS.AppleEvent */ + private static Method putParameter; + + /** The sendNoReply method of com.apple.MacOS.AppleEvent */ + private static Method sendNoReply; + + /** Actually an MRJOSType pointing to the System Folder on a Macintosh */ + private static Object kSystemFolderType; + + /** The keyDirectObject AppleEvent parameter type */ + private static Integer keyDirectObject; + + /** The kAutoGenerateReturnID AppleEvent code */ + private static Integer kAutoGenerateReturnID; + + /** The kAnyTransactionID AppleEvent code */ + private static Integer kAnyTransactionID; + + /** The linkage object required for JDirect 3 on Mac OS X. */ + private static Object linkage; + + /** The framework to reference on Mac OS X */ + private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox"; + + /** JVM constant for MRJ 2.0 */ + private static final int MRJ_2_0 = 0; + + /** JVM constant for MRJ 2.1 or later */ + private static final int MRJ_2_1 = 1; + + /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */ + private static final int MRJ_3_0 = 3; + + /** JVM constant for MRJ 3.1 */ + private static final int MRJ_3_1 = 4; + + /** JVM constant for any Windows NT JVM */ + private static final int WINDOWS_NT = 5; + + /** JVM constant for any Windows 9x JVM */ + private static final int WINDOWS_9x = 6; + + /** JVM constant for any other platform */ + private static final int OTHER = -1; + + /** + * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English + * systems from working properly. + */ + private static final String FINDER_TYPE = "FNDR"; + + /** + * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the + * application. + */ + private static final String FINDER_CREATOR = "MACS"; + + /** The name for the AppleEvent type corresponding to a GetURL event. */ + private static final String GURL_EVENT = "GURL"; + + /** + * The first parameter that needs to be passed into Runtime.exec() to open the default web + * browser on Windows. + */ + private static final String FIRST_WINDOWS_PARAMETER = "/c"; + + /** The second parameter for Runtime.exec() on Windows. */ + private static final String SECOND_WINDOWS_PARAMETER = "start"; + + /** + * The third parameter for Runtime.exec() on Windows. This is a "title" + * parameter that the command line expects. Setting this parameter allows + * URLs containing spaces to work. + */ + private static final String THIRD_WINDOWS_PARAMETER = "\"\""; + + /** + * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape + * on many command-line systems. + */ + private static final String NETSCAPE_REMOTE_PARAMETER = "-remote"; + private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL("; + private static final String NETSCAPE_OPEN_PARAMETER_END = ",new-tab)'"; + + /** + * The message from any exception thrown throughout the initialization process. + */ + private static String errorMessage; + + /** + * An initialization block that determines the operating system and loads the necessary + * runtime data. + */ + static { + loadedWithoutErrors = true; + String osName = System.getProperty("os.name"); + if (osName.startsWith("Mac OS")) { + String mrjVersion = System.getProperty("mrj.version"); + String majorMRJVersion = mrjVersion.substring(0, 3); + try { + double version = Double.valueOf(majorMRJVersion).doubleValue(); + if (version == 2) { + jvm = MRJ_2_0; + } else if (version >= 2.1 && version < 3) { + // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually + // works via Runtime.exec() and 2.2 supports that but has an openURL() method + // as well that we currently ignore. + jvm = MRJ_2_1; + } else if (version == 3.0) { + jvm = MRJ_3_0; + } else if (version >= 3.1) { + // Assume that all 3.1 and later versions of MRJ work the same. + jvm = MRJ_3_1; + } else { + loadedWithoutErrors = false; + errorMessage = "Unsupported MRJ version: " + version; + } + } catch (NumberFormatException nfe) { + loadedWithoutErrors = false; + errorMessage = "Invalid MRJ version: " + mrjVersion; + } + } else if (osName.startsWith("Windows")) { + if (osName.indexOf("9") != -1) { + jvm = WINDOWS_9x; + } else { + jvm = WINDOWS_NT; + } + } else { + jvm = OTHER; + } + + if (loadedWithoutErrors) { // if we haven't hit any errors yet + loadedWithoutErrors = loadClasses(); + } + } + + /** + * This class should be never be instantiated; this just ensures so. + */ + private BrowserLauncher() { } + + /** + * Called by a static initializer to load any classes, fields, and methods required at runtime + * to locate the user's web browser. + * @return true if all intialization succeeded + * false if any portion of the initialization failed + */ + private static boolean loadClasses() { + switch (jvm) { + case MRJ_2_0: + try { + Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget"); + Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils"); + Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent"); + Class aeClass = Class.forName("com.apple.MacOS.ae"); + aeDescClass = Class.forName("com.apple.MacOS.AEDesc"); + + aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class }); + appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class }); + aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class }); + + makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class }); + putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass }); + sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { }); + + Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject"); + keyDirectObject = (Integer) keyDirectObjectField.get(null); + Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID"); + kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null); + Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID"); + kAnyTransactionID = (Integer) anyTransactionIDField.get(null); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (NoSuchFieldException nsfe) { + errorMessage = nsfe.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_2_1: + try { + mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); + mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType"); + Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType"); + kSystemFolderType = systemFolderField.get(null); + findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass }); + getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class }); + getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchFieldException nsfe) { + errorMessage = nsfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (SecurityException se) { + errorMessage = se.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_3_0: + try { + Class linker = Class.forName("com.apple.mrj.jdirect.Linker"); + Constructor constructor = linker.getConstructor(new Class[]{ Class.class }); + linkage = constructor.newInstance(new Object[] { BrowserLauncher.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } catch (InvocationTargetException ite) { + errorMessage = ite.getMessage(); + return false; + } catch (InstantiationException ie) { + errorMessage = ie.getMessage(); + return false; + } catch (IllegalAccessException iae) { + errorMessage = iae.getMessage(); + return false; + } + break; + case MRJ_3_1: + try { + mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); + openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class }); + } catch (ClassNotFoundException cnfe) { + errorMessage = cnfe.getMessage(); + return false; + } catch (NoSuchMethodException nsme) { + errorMessage = nsme.getMessage(); + return false; + } + break; + default: + break; + } + return true; + } + + /** + * Attempts to locate the default web browser on the local system. Caches results so it + * only locates the browser once for each use of this class per JVM instance. + * @return The browser for the system. Note that this may not be what you would consider + * to be a standard web browser; instead, it's the application that gets called to + * open the default web browser. In some cases, this will be a non-String object + * that provides the means of calling the default browser. + */ + private static Object locateBrowser() { + if (browser != null) { + return browser; + } + switch (jvm) { + case MRJ_2_0: + try { + Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR }); + Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode }); + Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT }); + Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID }); + // Don't set browser = appleEvent because then the next time we call + // locateBrowser(), we'll get the same AppleEvent, to which we'll already have + // added the relevant parameter. Instead, regenerate the AppleEvent every time. + // There's probably a way to do this better; if any has any ideas, please let + // me know. + return appleEvent; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InstantiationException ie) { + browser = null; + errorMessage = ie.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getMessage(); + return browser; + } + case MRJ_2_1: + File systemFolder; + try { + systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType }); + } catch (IllegalArgumentException iare) { + browser = null; + errorMessage = iare.getMessage(); + return browser; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); + return browser; + } + String[] systemFolderFiles = systemFolder.list(); + // Avoid a FilenameFilter because that can't be stopped mid-list + for(int i = 0; i < systemFolderFiles.length; i++) { + try { + File file = new File(systemFolder, systemFolderFiles[i]); + if (!file.isFile()) { + continue; + } + // We're looking for a file with a creator code of 'MACS' and + // a type of 'FNDR'. Only requiring the type results in non-Finder + // applications being picked up on certain Mac OS 9 systems, + // especially German ones, and sending a GURL event to those + // applications results in a logout under Multiple Users. + Object fileType = getFileType.invoke(null, new Object[] { file }); + if (FINDER_TYPE.equals(fileType.toString())) { + Object fileCreator = getFileCreator.invoke(null, new Object[] { file }); + if (FINDER_CREATOR.equals(fileCreator.toString())) { + browser = file.toString(); // Actually the Finder, but that's OK + return browser; + } + } + } catch (IllegalArgumentException iare) { + browser = null; + errorMessage = iare.getMessage(); + return null; + } catch (IllegalAccessException iae) { + browser = null; + errorMessage = iae.getMessage(); + return browser; + } catch (InvocationTargetException ite) { + browser = null; + errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage(); + return browser; + } + } + browser = null; + break; + case MRJ_3_0: + case MRJ_3_1: + browser = ""; // Return something non-null + break; + case WINDOWS_NT: + browser = "cmd.exe"; + break; + case WINDOWS_9x: + browser = "command.com"; + break; + case OTHER: + default: + String[] possibleMozillaNames = { "firefox", "mozilla" }; + + for (int i = 0; i < possibleMozillaNames.length; i++) { + try { + Process mozilla = Runtime.getRuntime().exec(possibleMozillaNames[i] + " -v"); + if (mozilla.waitFor() == 0) { + browser = possibleMozillaNames[i]; + break; + } + } catch (InterruptedException e) { + + } catch (IOException e) { + + } + } + break; + } + return browser; + } + + /** + * Attempts to open the default web browser to the given URL. + * @param url The URL to open + * @throws IOException If the web browser could not be located or does not run + */ + public static void openURL(String url) throws IOException { + if (!loadedWithoutErrors) { + throw new IOException("Exception in finding browser: " + errorMessage); + } + Object browser = locateBrowser(); + if (browser == null) { + throw new IOException("Unable to locate browser: " + errorMessage); + } + + switch (jvm) { + case MRJ_2_0: + Object aeDesc = null; + try { + aeDesc = aeDescConstructor.newInstance(new Object[] { url }); + putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc }); + sendNoReply.invoke(browser, new Object[] { }); + } catch (InvocationTargetException ite) { + throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage()); + } catch (IllegalAccessException iae) { + throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage()); + } catch (InstantiationException ie) { + throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage()); + } finally { + aeDesc = null; // Encourage it to get disposed if it was created + browser = null; // Ditto + } + break; + case MRJ_2_1: + Runtime.getRuntime().exec(new String[] { (String) browser, url } ); + break; + case MRJ_3_0: + int[] instance = new int[1]; + int result = ICStart(instance, 0); + if (result == 0) { + int[] selectionStart = new int[] { 0 }; + byte[] urlBytes = url.getBytes(); + int[] selectionEnd = new int[] { urlBytes.length }; + result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, + urlBytes.length, selectionStart, + selectionEnd); + if (result == 0) { + // Ignore the return value; the URL was launched successfully + // regardless of what happens here. + ICStop(instance); + } else { + throw new IOException("Unable to launch URL: " + result); + } + } else { + throw new IOException("Unable to create an Internet Config instance: " + result); + } + break; + case MRJ_3_1: + try { + openURL.invoke(null, new Object[] { url }); + } catch (InvocationTargetException ite) { + throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage()); + } catch (IllegalAccessException iae) { + throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage()); + } + break; + case WINDOWS_NT: + case WINDOWS_9x: + // Add quotes around the URL to allow ampersands and other special + // characters to work. + Process process = Runtime.getRuntime().exec(new String[] { (String) browser, + FIRST_WINDOWS_PARAMETER, + SECOND_WINDOWS_PARAMETER, + THIRD_WINDOWS_PARAMETER, + '"' + url + '"' }); + // This avoids a memory leak on some versions of Java on Windows. + // That's hinted at in . + /* + try { + //process.waitFor(); + //process.exitValue(); + } catch (InterruptedException ie) { + throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); + } + */ + break; + case OTHER: + // Assume that we're on Unix and that Mozilla is installed + + // First, attempt to open the URL in a currently running session of Mozilla + process = Runtime.getRuntime().exec(new String[] { (String) browser, + NETSCAPE_REMOTE_PARAMETER, + NETSCAPE_OPEN_PARAMETER_START + + url + + NETSCAPE_OPEN_PARAMETER_END }); + try { + int exitCode = process.waitFor(); + if (exitCode != 0) { // if Netscape was not open + Runtime.getRuntime().exec(new String[] { (String) browser, url }); + } + } catch (InterruptedException ie) { + throw new IOException("InterruptedException while launching browser: " + ie.getMessage()); + } + break; + default: + // This should never occur, but if it does, we'll try the simplest thing possible + Runtime.getRuntime().exec(new String[] { (String) browser, url }); + break; + } + } + + /** + * Methods required for Mac OS X. The presence of native methods does not cause + * any problems on other platforms. + */ + private native static int ICStart(int[] instance, int signature); + private native static int ICStop(int[] instance); + private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len, + int[] selectionStart, int[] selectionEnd); + +} diff --git a/relicts/org/jalgo/main/util/CVS/Entries b/relicts/org/jalgo/main/util/CVS/Entries new file mode 100644 index 0000000..5cce610 --- /dev/null +++ b/relicts/org/jalgo/main/util/CVS/Entries @@ -0,0 +1,16 @@ +/BrowserLauncher.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/ClickCollector.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/ConvertCr.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/ConvertCrLf.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/ConvertHtml.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/ConvertJpg.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/ConvertLf.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/ConvertPng.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/Exporter.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/GfxUtil.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/IConverter.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/IGfxConvert.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/ITxtConvert.java/1.2/Sat Mar 4 13:36:17 2006/-kk/ +/PrintDialogNext.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/PrintScaledFigureOperation.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ +/Timer.java/1.2/Sat Mar 4 13:36:16 2006/-kk/ diff --git a/relicts/org/jalgo/main/util/CVS/Repository b/relicts/org/jalgo/main/util/CVS/Repository new file mode 100644 index 0000000..f76033c --- /dev/null +++ b/relicts/org/jalgo/main/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/main/util diff --git a/relicts/org/jalgo/main/util/CVS/Root b/relicts/org/jalgo/main/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/main/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/main/util/ClickCollector.java b/relicts/org/jalgo/main/util/ClickCollector.java new file mode 100644 index 0000000..fdaf002 --- /dev/null +++ b/relicts/org/jalgo/main/util/ClickCollector.java @@ -0,0 +1,86 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 13.06.2004 + */ + +package org.jalgo.main.util; + +import java.util.ArrayList; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.geometry.Point; +import org.jalgo.main.gfx.ClickListener; +import org.jalgo.main.gfx.IClickAction; + +/** + * The ClickCollector collects figures that are reported by a figures + * ClickListener. + * It receives a list of numberOfClicks swt-figures and the last + * position where a click occured. + * It then calls actionObject.performAction(items). + * + * @author Hauke Menges + */ +public class ClickCollector { + + private static boolean isCollecting; + private static int numberOfClicks; + private static IClickAction

    actionObject; + private static ArrayList
    items; + + private static Point lastPoint; + + public static void init(int numberOfClicks_, IClickAction actionObject_) { + isCollecting = true; + numberOfClicks = numberOfClicks_; + actionObject = actionObject_; + items = new ArrayList
    (); + } + + public static boolean addItem(ClickListener clickListener) { + if ((isCollecting == true) && (numberOfClicks > 0)) { + items.add(clickListener.getFigure()); + lastPoint = clickListener.getLastPoint(); + numberOfClicks--; + if (numberOfClicks == 0) { + actionObject.performAction(items); + stopCollecting(); + return true; + } + } + return false; + } + + public static void stopCollecting() { + isCollecting = false; + numberOfClicks = 0; + actionObject = null; + items = null; + } + + public static Point getLastPoint(){ + return lastPoint; + } + + public static boolean isCollecting(){ + return isCollecting; + } +} diff --git a/relicts/org/jalgo/main/util/ConvertCr.java b/relicts/org/jalgo/main/util/ConvertCr.java new file mode 100644 index 0000000..b6b2b4f --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertCr.java @@ -0,0 +1,43 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Benjamin Scholz + * @author Stephan Creutz + */ +public class ConvertCr implements ITxtConvert { + + public String convert(String text) { + Matcher matcher = Pattern.compile("(\r\n)|\n").matcher(text); + return matcher.replaceAll("\r"); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ConvertCrLf.java b/relicts/org/jalgo/main/util/ConvertCrLf.java new file mode 100644 index 0000000..d78534e --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertCrLf.java @@ -0,0 +1,42 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ +package org.jalgo.main.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Benjamin Scholz + * @author Stephan Creutz + */ +public class ConvertCrLf implements ITxtConvert { + + public String convert(String text) { + Matcher matcher = Pattern.compile("\r|\n").matcher(text); + return matcher.replaceAll("\r\n"); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ConvertHtml.java b/relicts/org/jalgo/main/util/ConvertHtml.java new file mode 100644 index 0000000..8976274 --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertHtml.java @@ -0,0 +1,54 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +import java.util.regex.Pattern; + +/** + * @author Benjamin Scholz + * @author Stephan Creutz + */ +public class ConvertHtml implements ITxtConvert { + + public String convert(String text) { + text = Pattern.compile("&").matcher(text).replaceAll("&"); + text = Pattern.compile("<").matcher(text).replaceAll("<"); + text = Pattern.compile(">").matcher(text).replaceAll(">"); + text = Pattern.compile("\"").matcher(text).replaceAll("""); + text = Pattern.compile("ä").matcher(text).replaceAll("ä"); + text = Pattern.compile("Ä").matcher(text).replaceAll("Ä"); + text = Pattern.compile("ö").matcher(text).replaceAll("ö"); + text = Pattern.compile("Ö").matcher(text).replaceAll("Ö"); + text = Pattern.compile("ü").matcher(text).replaceAll("ü"); + text = Pattern.compile("Ãœ").matcher(text).replaceAll("Ü"); + text = Pattern.compile("ß").matcher(text).replaceAll("ß"); + return "\n\n" + + text + + "\n"; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ConvertJpg.java b/relicts/org/jalgo/main/util/ConvertJpg.java new file mode 100644 index 0000000..fe81548 --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertJpg.java @@ -0,0 +1,38 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +import java.io.DataInputStream; +import java.io.DataOutputStream; + +/** + * @author Benjamin Scholz + */ +public class ConvertJpg implements IGfxConvert { + + public DataOutputStream convert(DataInputStream input) { + return null; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ConvertLf.java b/relicts/org/jalgo/main/util/ConvertLf.java new file mode 100644 index 0000000..41fab94 --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertLf.java @@ -0,0 +1,43 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and + * platform independant. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 05-May-2004 + */ + +package org.jalgo.main.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @author Benjamin Scholz + * @author Stephan Creutz + */ +public class ConvertLf implements ITxtConvert { + + public String convert(String text) { + Matcher matcher = Pattern.compile("(\r\n)|\r").matcher(text); + return matcher.replaceAll("\n"); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ConvertPng.java b/relicts/org/jalgo/main/util/ConvertPng.java new file mode 100644 index 0000000..70bcae4 --- /dev/null +++ b/relicts/org/jalgo/main/util/ConvertPng.java @@ -0,0 +1,38 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +import java.io.DataInputStream; +import java.io.DataOutputStream; + +/** + * @author Benjamin Scholz + */ +public class ConvertPng implements IGfxConvert { + + public DataOutputStream convert(DataInputStream inputstream) { + return null; + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/Exporter.java b/relicts/org/jalgo/main/util/Exporter.java new file mode 100644 index 0000000..3804ef5 --- /dev/null +++ b/relicts/org/jalgo/main/util/Exporter.java @@ -0,0 +1,107 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Apr 18, 2004 + */ + +package org.jalgo.main.util; + +//import java.io.DataOutputStream; +import java.util.Collection; + +import org.eclipse.draw2d.Panel; + +/** + * @author Cornelius Hald + * @author Benjamin Scholz + * @author Stephan Creutz + */ +public class Exporter { + + //private static String[] knownTxtConverters = { "txt_Lf", "txt_Cr", "txt_LfCr", "html" }; + //private static String[] knownGfxConverters = { "png", "jpg" }; + private IConverter converter; + + private Panel panel; + + public Exporter() { + } + + public Exporter(Panel panel) { + this.panel = panel; + } + + public void setCanvas(Panel panel) { + } + + /** + * @return Returns a Collection of Strings like "gif" or "txt" + */ + public Collection getFileFormats() { + return null; + } + + public void setConverter(IConverter converter) { + this.converter = converter; + } + + /** + * manages the whole export process + * calls: getData(), convert() and getFilename() + */ + public void export() { + } + + /** + * sets the Canvas and calls export() + */ + public void export(Panel panel) { + this.panel = panel; + } + + /** + * sets the Canvas, and calls setConverter and export + * @param converter + */ + public void export(Panel panel, IConverter converter) { + this.panel = panel; + } + + /* + private void getData() { + } + */ + + /** + * @return Returns converted DataStream. This Stream may be written to harddisk. + */ + /* + private DataOutputStream convert() { + //IConverter converter; either txt or gfxConverter will be created + return null; + } + + private String getFilename() { + // opens the Filechooser Dialog + return null; + } + */ + +} diff --git a/relicts/org/jalgo/main/util/GfxUtil.java b/relicts/org/jalgo/main/util/GfxUtil.java new file mode 100644 index 0000000..9ae1dd8 --- /dev/null +++ b/relicts/org/jalgo/main/util/GfxUtil.java @@ -0,0 +1,126 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 08.06.2004 + */ + +package org.jalgo.main.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.PolylineConnection; +import org.eclipse.swt.widgets.Shell; + +/** + * @author Hauke Menges + * @author Cornelius Hald + * @author Babett Schaliz + * @author Marco Zimmerling + */ +public class GfxUtil { + + /** + * Returns a collection of all incoming (source) connections of a node/figure. + * @param panel The Figure that contains the node. + * @param node The Figure in which connections you are interested in. + * @return A collection of all incoming (source) connections of node. + */ + public static Collection getSourceConnections(Figure panel, Figure node) { + List list = panel.getChildren(); + List returnList = new ArrayList(); + + Iterator it = list.iterator(); + + while (it.hasNext()) { + Object obj = it.next(); + if (obj instanceof PolylineConnection) { + if (node.equals(((PolylineConnection) obj).getTargetAnchor().getOwner())) { + returnList.add((PolylineConnection)obj); + } + } + } + + return returnList; + } + + /** + * Returns a collection of all outgoing (target) connections of a node/figure. + * @param panel The Figure that contains the node. + * @param node The Figure in which connections you are interested in. + * @return A collection of all outgoing (target) connections of node. + */ + public static Collection getTargetConnections(Figure panel, Figure node) { + List list = panel.getChildren(); + List returnList = new ArrayList(); + + Iterator it = list.iterator(); + + while (it.hasNext()) { + Object obj = it.next(); + if (obj instanceof PolylineConnection) { + if (node.equals(((PolylineConnection) obj).getSourceAnchor().getOwner())) { + returnList.add((PolylineConnection)obj); + } + } + } + + return returnList; + } + + /** + * Returns a collection of all outgoing (target) connections of a node/figure. + * @param panel The Figure that contains the node. + * @param sourceNode The Figure in which connections you are interested in. + * @return A collection of all outgoing (target) connections of node. + */ + public static PolylineConnection getConnection(Figure panel, Figure sourceNode, Figure targetNode) { + //TODO eventuell auch mehrere Connections zwischen 2 Knoten -> Anpassen!!!! + List list = panel.getChildren(); + + Iterator it = list.iterator(); + + while (it.hasNext()) { + Object obj = it.next(); + if (obj instanceof PolylineConnection) { + if ( sourceNode.equals(((PolylineConnection) obj).getSourceAnchor().getOwner()) + && targetNode.equals(((PolylineConnection) obj).getTargetAnchor().getOwner())) { + return (PolylineConnection)obj; + } + } + } + + return null; + } + + private static Shell appShell; + + public static Shell getAppShell(){ + return appShell; + } + + public static void setAppShell(Shell appShell_){ + appShell = appShell_; + } + +} diff --git a/relicts/org/jalgo/main/util/IConverter.java b/relicts/org/jalgo/main/util/IConverter.java new file mode 100644 index 0000000..b39c0db --- /dev/null +++ b/relicts/org/jalgo/main/util/IConverter.java @@ -0,0 +1,31 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2004 + */ + +package org.jalgo.main.util; + +/** + * @author Benjamin Scholz + */ +public interface IConverter { + +} diff --git a/relicts/org/jalgo/main/util/IGfxConvert.java b/relicts/org/jalgo/main/util/IGfxConvert.java new file mode 100644 index 0000000..962166f --- /dev/null +++ b/relicts/org/jalgo/main/util/IGfxConvert.java @@ -0,0 +1,37 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +import java.io.DataInputStream; +import java.io.DataOutputStream; + +/** + * @author Benjamin Scholz + */ +public interface IGfxConvert extends IConverter { + + public DataOutputStream convert(DataInputStream input); + // TODO type needs to be proved + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/ITxtConvert.java b/relicts/org/jalgo/main/util/ITxtConvert.java new file mode 100644 index 0000000..ce6c1b8 --- /dev/null +++ b/relicts/org/jalgo/main/util/ITxtConvert.java @@ -0,0 +1,33 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 23.04.2004 + */ + +package org.jalgo.main.util; + +/** + * @author Benjamin Scholz + */ +public interface ITxtConvert extends IConverter { + + public String convert(String text); + +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/PrintDialogNext.java b/relicts/org/jalgo/main/util/PrintDialogNext.java new file mode 100644 index 0000000..842d3fd --- /dev/null +++ b/relicts/org/jalgo/main/util/PrintDialogNext.java @@ -0,0 +1,135 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and platform + * independant. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.util; + +import org.eclipse.draw2d.PrintFigureOperation; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.gui.DialogConstants; +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * Used after a usual PrintDialog to decide about the scaling. + * + * @author Anne Kersten + */ +public class PrintDialogNext +extends Dialog { + + private Combo select; + + private int selectionIndex; + + /** + * Constructs a new PrintDialogNext. + * + * @param parent the parent-shell + */ + public PrintDialogNext(Shell parent) { + super(parent); + } + + /** + * Creates a Combo where you can chose the scaling. + * + * @param parent the parent composite to contain the dialog area + * @return the parent composite holding a combo + * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) + */ + protected Control createDialogArea(Composite parent) { + Label title = new Label(parent, SWT.LEFT); + title.setText(Messages.getString( + "main", "PrintDialogNext.Select_scaling_mode_1")); //$NON-NLS-1$ + parent.setLayout(new GridLayout()); + select.add(Messages.getString( + "main", "PrintDialogNext.Scale_to_fit_on_one_page_2")); //$NON-NLS-1$ + select.add(Messages.getString( + "main", "PrintDialogNext.Scale_only_width_3")); //$NON-NLS-1$ + select.add(Messages.getString( + "main", "PrintDialogNext.Scale_only_height_4")); //$NON-NLS-1$ + select.add(Messages.getString("main", "PrintDialogNext.No_scaling_5")); //$NON-NLS-1$ + selectionIndex = 3; + select.select(selectionIndex); + select.addSelectionListener(new SelectionListener() { + @SuppressWarnings("synthetic-access") + public void widgetSelected(SelectionEvent e) { + selectionIndex = select.getSelectionIndex(); + } + + public void widgetDefaultSelected(SelectionEvent arg0) { + /* this block is intended to be empty */ + } + }); + return parent; + } + + /** + * Opens the PrintDialogNext + * + * @return PrintScaledFigureOperation.FIT_PAGE for "Scale to fit on one + * page" + *

    + * PrintScaledFigureOperation.FIT_WIDTH for "Scale only width" + *

    + * PrintScaledFigureOperation.FIT_HEIGHT for "Scale only height" + *

    + * PrintScaledFigureOperation.TILE for "No scaling" + *

    + * -1 for Window.CANCEL + */ + public int open() { + if (super.open() == Window.OK) switch (selectionIndex) { + case 0: + selectionIndex = PrintFigureOperation.FIT_PAGE; + break; + case 1: + selectionIndex = PrintFigureOperation.FIT_WIDTH; + break; + case 2: + selectionIndex = PrintFigureOperation.FIT_HEIGHT; + break; + case 4: + if (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("main", "PrintDialogNext.Layout_warning_7"), + DialogConstants.YES_NO_OPTION) == DialogConstants.YES_OPTION) + selectionIndex = PrintScaledFigureOperation.USE_LAYOUT; //$NON-NLS-1$ //$NON-NLS-2$ + else selectionIndex = -1; + break; + default: + selectionIndex = PrintFigureOperation.TILE; + } + else selectionIndex = -1; + + return selectionIndex; + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/main/util/PrintScaledFigureOperation.java b/relicts/org/jalgo/main/util/PrintScaledFigureOperation.java new file mode 100644 index 0000000..9adf0c1 --- /dev/null +++ b/relicts/org/jalgo/main/util/PrintScaledFigureOperation.java @@ -0,0 +1,130 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.main.util; + +import org.eclipse.draw2d.ColorConstants; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PrintFigureOperation; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.printing.Printer; +import org.eclipse.swt.widgets.Display; + +/** + * Class responsible for printing Figures. + * + * @author Anne Kersten + */ +public class PrintScaledFigureOperation extends PrintFigureOperation { + +/** + * A print mode that resizes the printed image as the size of a page and then uses the + * existing layout of that figure to readjust the children. + * + * Note: Works only for figures with a given layout. + */ +public static final int USE_LAYOUT = 5; + +private int printMode = TILE; +private Color oldBGColor; +private Rectangle oldBounds; + + +/** + * Constructor for PrintScaledFigureOperation. + *

    + * Note: Descendants must call setPrintSource(IFigure) to set the IFigure that is to be + * printed. + * @see org.eclipse.draw2d.PrintOperation#PrintOperation(Printer) + * @see org.eclipse.draw2d.PrintFigureOperation#PrintFigureOperation(Printer) + */ +protected PrintScaledFigureOperation(Printer p) { + super(p); +} + +/** + * Constructor for PrintScaledFigureOperation. + * + * @param p Printer to print on + * @param srcFigure Figure to print + * @see org.eclipse.draw2d.PrintFigureOperation#PrintFigureOperation(Printer, IFigure) + */ +public PrintScaledFigureOperation(Printer p, IFigure srcFigure) { + super(p); + setPrintSource(srcFigure); +} + +/** + * Returns the current print mode. The print mode is one of: {@link #FIT_HEIGHT}, + * {@link #FIT_PAGE}, {@link #FIT_WIDTH}, or {@link #USE_LAYOUT}. + * @return the print mode + */ +protected int getPrintMode() { + return printMode; +} + + +/** + * @see org.eclipse.draw2d.PrintOperation#preparePrintSource() + */ +protected void preparePrintSource() { + oldBGColor = getPrintSource().getLocalBackgroundColor(); + getPrintSource().setBackgroundColor(ColorConstants.white); + + double dpiScale = getPrinter().getDPI().x / Display.getCurrent().getDPI().x; + Rectangle printRegion = getPrintRegion(); + // put the print region in display coordinates + printRegion.width /= dpiScale; + printRegion.height /= dpiScale; + if (getPrintMode()==USE_LAYOUT) + { + oldBounds = getPrintSource().getBounds(); + getPrintSource().setBounds(printRegion); + getPrintSource().validate(); + + } +} + + + +/** + * @see org.eclipse.draw2d.PrintOperation#restorePrintSource() + */ +protected void restorePrintSource() { + getPrintSource().setBackgroundColor(oldBGColor); + oldBGColor = null; + if(getPrintMode() == USE_LAYOUT) + { + getPrintSource().setBounds(oldBounds); + oldBounds = null; + getPrintSource().validate(); + } +} + +/** + * Sets the print mode. Possible values are {@link #TILE}, {@link #FIT_HEIGHT}, + * {@link #FIT_WIDTH}, {@link #FIT_PAGE} and {@link #USE_LAYOUT}. + * @param mode the print mode + */ +public void setPrintMode(int mode) { + super.setPrintMode(mode); +} + +} diff --git a/relicts/org/jalgo/main/util/Timer.java b/relicts/org/jalgo/main/util/Timer.java new file mode 100644 index 0000000..3fab40c --- /dev/null +++ b/relicts/org/jalgo/main/util/Timer.java @@ -0,0 +1,52 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 19.04.2004 + */ + +package org.jalgo.main.util; + +/** + * A Timer especially used for animations. + * + * @author Hauke Menges + */ +public class Timer { + //private long msStart, msEnd; + + /** + * Initializes the timer. + * + * @param msOffset Offset in milliseconds + * @param msLength Length/duration in milliseconds + */ + public Timer(int msOffset, int msLength) { + } + + /** + * Calculates the new position. + * + * @return The new position (from 0.0 to 1.0) + */ + public double getPosition() { + return 0.0; + } + +} diff --git a/relicts/org/jalgo/tests/CVS/Entries b/relicts/org/jalgo/tests/CVS/Entries new file mode 100644 index 0000000..40aa564 --- /dev/null +++ b/relicts/org/jalgo/tests/CVS/Entries @@ -0,0 +1,3 @@ +D/chars//// +D/modules//// +D/trees//// diff --git a/relicts/org/jalgo/tests/CVS/Repository b/relicts/org/jalgo/tests/CVS/Repository new file mode 100644 index 0000000..bc5eb97 --- /dev/null +++ b/relicts/org/jalgo/tests/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests diff --git a/relicts/org/jalgo/tests/CVS/Root b/relicts/org/jalgo/tests/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/chars/CVS/Entries b/relicts/org/jalgo/tests/chars/CVS/Entries new file mode 100644 index 0000000..3427bd3 --- /dev/null +++ b/relicts/org/jalgo/tests/chars/CVS/Entries @@ -0,0 +1,2 @@ +/CharTest1.java/1.2/Sat Mar 4 13:36:29 2006/-kk/ +/CharTestWindow1.java/1.2/Sat Mar 4 13:36:29 2006/-kk/ diff --git a/relicts/org/jalgo/tests/chars/CVS/Repository b/relicts/org/jalgo/tests/chars/CVS/Repository new file mode 100644 index 0000000..6c775f6 --- /dev/null +++ b/relicts/org/jalgo/tests/chars/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/chars diff --git a/relicts/org/jalgo/tests/chars/CVS/Root b/relicts/org/jalgo/tests/chars/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/chars/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/chars/CharTest1.java b/relicts/org/jalgo/tests/chars/CharTest1.java new file mode 100644 index 0000000..91a9e61 --- /dev/null +++ b/relicts/org/jalgo/tests/chars/CharTest1.java @@ -0,0 +1,39 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 10.12.2004 + */ +package org.jalgo.tests.chars; + +import org.eclipse.swt.widgets.Display; + +/** + * @author Michael Pradel + */ +public class CharTest1 { + + public static void main(String[] args) { + CharTestWindow1 win = new CharTestWindow1(); + win.setBlockOnOpen(true); + win.open(); + + Display.getCurrent().dispose(); + } +} diff --git a/relicts/org/jalgo/tests/chars/CharTestWindow1.java b/relicts/org/jalgo/tests/chars/CharTestWindow1.java new file mode 100644 index 0000000..8f51e23 --- /dev/null +++ b/relicts/org/jalgo/tests/chars/CharTestWindow1.java @@ -0,0 +1,59 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 10.12.2004 + */ +package org.jalgo.tests.chars; + +import org.eclipse.jface.window.ApplicationWindow; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; + +/** + * @author Michael Pradel + */ +public class CharTestWindow1 extends ApplicationWindow { + + Composite parent; + + public CharTestWindow1 () { + super(null); + } + + protected Control createContents(Composite parent) { + parent.getShell().setText("Character Test 1"); + parent.getShell().setSize(400,250); + + Label label = new Label(parent, SWT.VERTICAL); + label.setText("Umlaute:\n" + + "ä - ae\n" + + "ö - oe\n" + "ü - ue\n" + "\n" + + "griechische Buchstaben:\n" + "\u03B5 - Epsilon\n" + "\u03A3 - Sigma\n" + "\u03B1\u2081 - Alpha unten 1\n" + "\n" + "Sonstiges:\n" + "\u2208 - ist Element"); + + return label; + } + + /* + * -Djava.library.path=/home/michi/eclipse_fuer_sopra/eclipse/plugins/org.eclipse.swt.gtk_2.1.3/os/linux/x86 + */ + +} diff --git a/relicts/org/jalgo/tests/modules/CVS/Entries b/relicts/org/jalgo/tests/modules/CVS/Entries new file mode 100644 index 0000000..e3ec7b9 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/CVS/Entries @@ -0,0 +1,2 @@ +D/avl//// +D/ebnf//// diff --git a/relicts/org/jalgo/tests/modules/CVS/Repository b/relicts/org/jalgo/tests/modules/CVS/Repository new file mode 100644 index 0000000..2bed7f7 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules diff --git a/relicts/org/jalgo/tests/modules/CVS/Root b/relicts/org/jalgo/tests/modules/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/avl/CVS/Entries b/relicts/org/jalgo/tests/modules/avl/CVS/Entries new file mode 100644 index 0000000..89996b3 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/CVS/Entries @@ -0,0 +1,4 @@ +/Graphics2DRenderer.java/1.1/Sun Jul 2 18:44:29 2006// +/Graphics2DRendererTest.java/1.1/Sun Jul 2 18:44:29 2006// +D/algorithm//// +D/gui//// diff --git a/relicts/org/jalgo/tests/modules/avl/CVS/Repository b/relicts/org/jalgo/tests/modules/avl/CVS/Repository new file mode 100644 index 0000000..84f3695 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/avl diff --git a/relicts/org/jalgo/tests/modules/avl/CVS/Root b/relicts/org/jalgo/tests/modules/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/avl/Graphics2DRenderer.java b/relicts/org/jalgo/tests/modules/avl/Graphics2DRenderer.java new file mode 100644 index 0000000..aa91928 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/Graphics2DRenderer.java @@ -0,0 +1,208 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + ----------------------------------------------------------------------------- + (c) Copyright IBM Corp. 2004 All rights reserved. + + The sample program(s) is/are owned by International Business Machines + Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and + licensed, not sold. + + You may copy, modify, and distribute this/these sample program(s) in any form + without payment to IBM, for any purpose including developing, using, marketing + or distributing programs that include or are derivative works of the sample + program(s). + + The sample program(s) is/are provided to you on an "AS IS" basis, without + warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER + EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do + not allow for the exclusion or limitation of implied warranties, so the above + limitations or exclusions may not apply to you. IBM shall not be liable for + any damages you suffer as a result of using, modifying or distributing the + sample program(s) or its/their derivatives. + + Each copy of any portion of this/these sample program(s) or any derivative + work, must include the above copyright notice and disclaimer of warranty. + + ----------------------------------------------------------------------------- +* + +package org.jalgo.tests.avl; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.PaletteData; +import org.eclipse.swt.widgets.Display; + +/** + * Helper class allowing the use of Java2D on SWT or Draw2D graphical + * context. + * @author Yannick Saillet + * +public class Graphics2DRenderer +{ + private static final PaletteData PALETTE_DATA = new PaletteData(0xFF0000, 0xFF00, 0xFF); + + private BufferedImage awtImage; + private Image swtImage; + private ImageData swtImageData; + private int[] awtPixels; + + /** RGB value to use as transparent color * / + private static final int TRANSPARENT_COLOR = 0x123456; + + /** + * Prepare to render on a SWT graphics context. + * + public void prepareRendering(GC gc) + { + org.eclipse.swt.graphics.Rectangle clip = gc.getClipping(); + prepareRendering(clip.x, clip.y, clip.width, clip.height); + } + + /** + * Prepare to render on a Draw2D graphics context. + * + public void prepareRendering(org.eclipse.draw2d.Graphics graphics) + { + org.eclipse.draw2d.geometry.Rectangle clip = + graphics.getClip(new org.eclipse.draw2d.geometry.Rectangle()); + prepareRendering(clip.x, clip.y, clip.width, clip.height); + } + + /** + * Prepare the AWT offscreen image for the rendering of the rectangular + * region given as parameter. + * + private void prepareRendering(int clipX, int clipY, int clipW, int clipH) + { + // check that the offscreen images are initialized and large enough + checkOffScreenImages(clipW, clipH); + // fill the region in the AWT image with the transparent color + java.awt.Graphics awtGraphics = awtImage.getGraphics(); + awtGraphics.setColor(new java.awt.Color(TRANSPARENT_COLOR)); + awtGraphics.fillRect(clipX, clipY, clipW, clipH); + } + + /** + * Returns the Graphics2D context to use. + * + public Graphics2D getGraphics2D() + { + if (awtImage == null) return null; + return (Graphics2D) awtImage.getGraphics(); + } + + /** + * Complete the rendering by flushing the 2D renderer on a SWT graphical + * context. + * + public void render(GC gc) + { + if (awtImage == null) return; + + org.eclipse.swt.graphics.Rectangle clip = gc.getClipping(); + transferPixels(clip.x, clip.y, clip.width, clip.height); + gc.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height, clip.x, clip.y, clip.width, clip.height); + } + + /** + * Complete the rendering by flushing the 2D renderer on a Draw2D + * graphical context. + * + public void render(org.eclipse.draw2d.Graphics graphics) + { + if (awtImage == null) return; + + org.eclipse.draw2d.geometry.Rectangle clip = graphics.getClip(new org.eclipse.draw2d.geometry.Rectangle()); + transferPixels(clip.x, clip.y, clip.width, clip.height); + graphics.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height, clip.x, clip.y, clip.width, clip.height); + } + + /** + * Transfer a rectangular region from the AWT image to the SWT image. + * + private void transferPixels(int clipX, int clipY, int clipW, int clipH) + { + int step = swtImageData.depth / 8; + byte[] data = swtImageData.data; + awtImage.getRGB(clipX, clipY, clipW, clipH, awtPixels, 0, clipW); + for (int i = 0; i < clipH; i++) + { + int idx = (clipY + i) * swtImageData.bytesPerLine + clipX * step; + for (int j = 0; j < clipW; j++) + { + int rgb = awtPixels[j + i * clipW]; + for (int k = swtImageData.depth - 8; k >= 0; k -= 8) + { + data[idx++] = (byte) ((rgb >> k) & 0xFF); + } + } + } + if (swtImage != null) + swtImage.dispose(); + swtImage = new Image(Display.getDefault(), swtImageData); + } + + /** + * Dispose the resources attached to this 2D renderer. + * + public void dispose() + { + if (awtImage != null) awtImage.flush(); + if (swtImage != null) swtImage.dispose(); + awtImage = null; + swtImageData = null; + awtPixels = null; + } + + /** + * Ensure that the offscreen images are initialized and are at least + * as large as the size given as parameter. + * + private void checkOffScreenImages(int width, int height) + { + int currentImageWidth = 0; + int currentImageHeight = 0; + if (swtImage != null) + { + currentImageWidth = swtImage.getImageData().width; + currentImageHeight = swtImage.getImageData().height; + } + + // if the offscreen images are too small, recreate them + if (width > currentImageWidth || height > currentImageHeight) + { + dispose(); + width = Math.max(width, currentImageWidth); + height = Math.max(height, currentImageHeight); + awtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + swtImageData = new ImageData(width, height, 24, PALETTE_DATA); + swtImageData.transparentPixel = TRANSPARENT_COLOR; + awtPixels = new int[width * height]; + } + } +} +*/ \ No newline at end of file diff --git a/relicts/org/jalgo/tests/modules/avl/Graphics2DRendererTest.java b/relicts/org/jalgo/tests/modules/avl/Graphics2DRendererTest.java new file mode 100644 index 0000000..a3ec6fc --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/Graphics2DRendererTest.java @@ -0,0 +1,76 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + * + +package org.jalgo.tests.avl; + +import java.awt.*; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; + +/** + * The class Graphics2DRendererTest shows, that it is possible to use the + * Java2D API within the SWT framework. But, it also shows the stunning speed of the + * translation: An area of 400 x 400 p. takes approx. 2 seconds to be displayed. So this + * technique is only recommended for static display contents. + * + * @author Alexander Claus + * +public class Graphics2DRendererTest { + + public static void main(String[] args) { + final Graphics2DRenderer renderer = new Graphics2DRenderer(); + Display display = new Display(); + Shell shell = new Shell(display); + shell.setSize(400, 400); + + shell.open(); + shell.setText("Java2d to Draw2d"); + LightweightSystem lws = new LightweightSystem(shell); + IFigure figure = new Figure() { + @SuppressWarnings("synthetic-access") + protected void paintClientArea(org.eclipse.draw2d.Graphics graphics) { + Dimension controlSize = getSize(); + renderer.prepareRendering(graphics); + + Graphics2D g2d = renderer.getGraphics2D(); + paintNode(g2d, 200, 210); + paintNode(g2d, 10, 351); + paintNode(g2d, 395, 40); + paintNode(g2d, 100, -2); + + renderer.render(graphics); + } + }; + lws.setContents(figure); + while (!shell.isDisposed()) if (!display.readAndDispatch()) display.sleep(); + renderer.dispose(); + } + + private static void paintNode(Graphics2D g, int x, int y) { + g.setColor(Color.black); + g.fillOval(x-11, y-11, 22, 22); + g.setColor(Color.orange); + g.fillOval(x-10, y-10, 20, 20); + } +}*/ \ No newline at end of file diff --git a/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Entries b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Entries new file mode 100644 index 0000000..bbec2ce --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Entries @@ -0,0 +1,6 @@ +/CreateRandomTreeTest.java/1.1/Sun Jul 2 18:44:29 2006// +/InsertAVLTestCase.java/1.1/Sun Jul 2 18:44:29 2006// +/InsertTestCase.java/1.1/Sun Jul 2 18:44:29 2006// +/RandomTreeTestCase.java/1.1/Sun Jul 2 18:44:29 2006// +/RotateLeftTestCase.java/1.1/Sun Jul 2 18:44:29 2006// +/RotateRightTestCase.java/1.1/Sun Jul 2 18:44:29 2006// diff --git a/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Repository b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Repository new file mode 100644 index 0000000..ac15119 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/avl/algorithm diff --git a/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Root b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/algorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/avl/algorithm/CreateRandomTreeTest.java b/relicts/org/jalgo/tests/modules/avl/algorithm/CreateRandomTreeTest.java new file mode 100644 index 0000000..aced7f2 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/algorithm/CreateRandomTreeTest.java @@ -0,0 +1,56 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 14.05.2005 + * + */ +package org.jalgo.tests.avl.algorithm; + +import org.jalgo.module.avl.datastructure.*; +import org.jalgo.module.avl.*; + +/** + * @author Matthias Schmidt + * + */ +public class CreateRandomTreeTest{ + + //TODO: change this to a jUnit test + public static void main(String[] args) { + + SearchTree st = new SearchTree(); + Controller cont = new Controller(st); + + cont.setAVLMode(false); + cont.createRandomTree(10); + + try {while (cont.algorithmHasNextStep()) cont.perform();} + catch (NoActionException ex) {ex.printStackTrace();} + + // der zufällige Baum inOrder + System.out.println("Der Baum inOrder!"); + SearchTree tree = new SearchTree(); + tree.printToConsole(); + + // der zufällige Baum inLevelOrder + System.out.println("Der Baum inLevelOrder!"); + System.out.println(tree.exportLevelOrder()); + } +} \ No newline at end of file diff --git a/relicts/org/jalgo/tests/modules/avl/algorithm/InsertAVLTestCase.java b/relicts/org/jalgo/tests/modules/avl/algorithm/InsertAVLTestCase.java new file mode 100644 index 0000000..1b96c3f --- /dev/null +++ b/relicts/org/jalgo/tests/modules/avl/algorithm/InsertAVLTestCase.java @@ -0,0 +1,93 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer sience. It is written in Java and platform independant. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.tests.avl.algorithm; + +import junit.framework.TestCase; + +import org.jalgo.module.avl.algorithm.CommandFactory; +import org.jalgo.module.avl.algorithm.MacroCommand; +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.WorkNode; + +public class InsertAVLTestCase extends TestCase { + + private SearchTree tree; + private AVLNode n; + int [] keys = {13,8,4,10,12}; + int [] orderedkeys = {8,4,12,10,13}; + public static void main(String[] args) { + new InsertAVLTestCase("testInsertAVL"); + } + + public InsertAVLTestCase(String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + tree = new SearchTree(); + WorkNode wn = null; + for (int i = 0; i synelems; + private Concat left; + private Concat right; + + private Arc2D branch1; + private Arc2D branch2; + private Line2D line; + protected RoundRectangle2D.Double kreis; + + /** + * + * @param type could be "open", "close", "full" - choose between rightopened, leftopened or full branch + */public Branch(String type) { + + //synelems = new ArrayList(); + left = new Concat(); + right = new Concat(); + this.color = new Color(0, 200, 0); + this.setSize(2*HEIGHT + 1, 2*HEIGHT + 1); + kreis = new RoundRectangle2D.Double(0, 0, width, HEIGHT, HEIGHT, HEIGHT); + this.setEnabled(true); + + + } + + public void addElem(SynDiaElem el) { + + //synelems.add(el); + + } + + protected void paintComponent( Graphics g ) + { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + //g2d.clearRect(0,0,this.getWidth(), this.getHeight()); + g2d.setColor( Color.WHITE ); + g2d.fill(kreis); + g2d.setColor( Color.BLACK ); + g2d.draw(kreis); + + } + + + public void update() { + + this.setSize(width+2, HEIGHT+2); + kreis = new RoundRectangle2D.Double(0, 0, width, HEIGHT, HEIGHT, HEIGHT); + + } + + public boolean contains(Point p) { + return branch1.contains(p.getX(), p.getY()); + } + + public String sayHello() { + + String ausgabe = new String(""); + ausgabe += "--> Branch\n"; + for (SynDiaElem elem : synelems) { + + ausgabe += "\t\t"+elem.sayHello()+"\n"; + + } + return ausgabe; + + } + public String contentToString() { + + String ausgabe = new String(""); + ausgabe += "("; + for (SynDiaElem elem : synelems) { + + ausgabe += elem.contentToString()+"|"; + + + } + ausgabe = ausgabe.substring(0, ausgabe.length()-1); + ausgabe += ")"; + return ausgabe; + + } + + public void setWidth(int w) { + + this.width = w; + + this.update(); + + } + + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/BranchCreateExample.java b/relicts/org/jalgo/tests/modules/ebnf/BranchCreateExample.java new file mode 100644 index 0000000..05ebdb6 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/BranchCreateExample.java @@ -0,0 +1,232 @@ +package org.jalgo.tests.ebnf; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.Random; + +//<<<<<<< JComponentSymbolExample.java + +/* Test, ob ich was überschreiben kann*/ +/* nein, kannst du nicht *g* - war hier nur noch alles rot... + public class JComponentSymbolExample extends JPanel implements KeyListener, MouseMotionListener, MouseListener, ActionListener { + ======= + import java.util.List; + import java.util.ArrayList; + /* Test, ob ich was �berschreiben kann*/ +public class BranchCreateExample extends JPanel implements + MouseMotionListener, MouseListener, ActionListener { + + + /** + * + */ + private static final long serialVersionUID = 1L; + + private JPopupMenu pMenu; + + private int diff_x = 0; + + private int diff_y = 0; + + private Point pMouse; + + private JMenuItem termitem = new JMenuItem("Terminalsymbol"); + + private JMenuItem varitem = new JMenuItem("Variable"); + + private JMenuItem branchitem = new JMenuItem("Verzweigung"); + + private JTextField editText; + + private SynDiaElem lastElem; + + private SyntaxDiagram syndia; + + private boolean creating = false; + + private SynDiaElem createdElem = null; + + + /** + * + */ + public BranchCreateExample() { + + this.setLayout(null); + + editText = new JTextField(); + editText.addActionListener(this); + add(editText); + + addMouseListener(this); + addMouseMotionListener(this); + + this.setBackground(Color.WHITE); + + termitem.addActionListener(this); + varitem.addActionListener(this); + branchitem.addActionListener(this); + + pMenu = new JPopupMenu(); + pMenu.add(termitem); + pMenu.add(varitem); + pMenu.add(branchitem); + + pMouse = new Point(); + pMouse.setLocation(50, 50); + + } + + public void actionPerformed(ActionEvent event) { + + + + + } + + public SynDiaElem reactToMenuSelection(String elem) { + + System.out.println("Creating new " + elem + "-Symbol-Object [JPanel]"); + SynDiaElem el = SymbolFactory.createElement(elem); + el.addMouseListener(this); + el.addMouseMotionListener(this); + el.setLocation(pMouse.x, pMouse.y); + this.add(el); + el.setVisible(true); + + setComponentZOrder(el, 0); + el.repaint(); + + System.out.println(el.getText()); + + if (elem != "branch") + this.showEditText((Component) el); + + return el; + } + + public void mouseMoved(MouseEvent e) { + + if (creating && e.getComponent().getClass() == BranchCreateExample.class) { + + int width = e.getX() - diff_x; + if (width < createdElem.HEIGHT) width = createdElem.HEIGHT; + createdElem.setWidth(width); + repaint(); + } + + } + + public void mouseDragged(MouseEvent e) { + + if (e.getComponent().getClass() != BranchCreateExample.class) + e.getComponent().setLocation( + e.getComponent().getX() - (diff_x - e.getX()), + e.getComponent().getY() - (diff_y - e.getY())); + + setComponentZOrder((SynDiaElem) e.getComponent(), 0); + + /* + * Zur Neusetzung der Panelgröße, fürs Scrollen + */ + Component[] comps = getComponents(); + int x = 0; + int y = 0; + + for (Component c : comps) { + + if (c.getX() + c.getWidth() > x) + x = c.getX() + c.getWidth(); + if (c.getY() + c.getHeight() > y) + y = c.getY() + c.getHeight(); + } + + setSize(x, y); + revalidate(); + + System.out.println(this.getWidth()+" x "+this.getHeight()); + + + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mousePressed(MouseEvent e) { + diff_x = e.getX(); + diff_y = e.getY(); + } + + public void showEditText(Component c) { + + int x = 50; + if (c.getWidth() > 65) + x = c.getWidth() - 15; + editText.setBounds(c.getX() + 6, c.getY() + 5, x, 20); + + editText.setText(((SynDiaElem) c).getText()); + editText.setVisible(true); + setComponentZOrder(editText, 0); + editText.requestFocus(true); + editText.selectAll(); + lastElem = (SynDiaElem) c; + + } + + public void mouseClicked(MouseEvent e) { + + System.out.println(e.getComponent().getClass().toString()); + + if (e.getClickCount() == 2 + && e.getComponent().getClass().getGenericSuperclass() == SynDiaElem.class) { + + this.showEditText(e.getComponent()); + } else if (e.getClickCount() == 1 && editText.isVisible()) { + + editText.setVisible(false); + if (lastElem != null && !editText.getText().equals("")) + lastElem.setText(editText.getText()); + lastElem = null; + + repaint(); + editText.setText(""); + + } else if(!creating) { + + pMouse.setLocation(e.getX(), e.getY()); + createdElem = this.reactToMenuSelection("branch"); + createdElem.setWidth(30); + this.creating = true; + + } else if (creating) { + + creating = false; + createdElem = null; + } + } + + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + + pMenu.show(e.getComponent(), e.getX(), e.getY()); + pMouse.setLocation(e.getX(), e.getY()); + } + + } + + public static void main(String[] args) { + + JFrame f = new JFrame("moin"); + f.setSize(800, 600); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + f.add(new BranchCreateExample()); + + f.setVisible(true); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/tests/modules/ebnf/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/CVS/Entries new file mode 100644 index 0000000..2c809c7 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/CVS/Entries @@ -0,0 +1,13 @@ +/Branch.java/1.1/Fri Aug 11 16:37:21 2006// +/BranchCreateExample.java/1.1/Fri Aug 11 16:37:21 2006// +/Concat.java/1.1/Fri Aug 11 16:37:21 2006// +/JComponentSymbolExample.java/1.1/Fri Aug 11 16:37:21 2006// +/SymbolFactory.java/1.1/Fri Aug 11 16:37:21 2006// +/SynDiaElem.java/1.1/Fri Aug 11 16:37:21 2006// +/SynDiaRendererTest.java/1.1/Fri Aug 11 16:37:21 2006// +/SyntaxDiagram.java/1.1/Fri Aug 11 16:37:21 2006// +/Terminal.java/1.1/Fri Aug 11 16:37:21 2006// +/Variable.java/1.1/Fri Aug 11 16:37:21 2006// +D/ebnfinput//// +D/junit//// +D/parser//// diff --git a/relicts/org/jalgo/tests/modules/ebnf/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/CVS/Repository new file mode 100644 index 0000000..3327d2e --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf diff --git a/relicts/org/jalgo/tests/modules/ebnf/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/Concat.java b/relicts/org/jalgo/tests/modules/ebnf/Concat.java new file mode 100644 index 0000000..7ea5423 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/Concat.java @@ -0,0 +1,88 @@ +package org.jalgo.tests.ebnf; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + + +public class Concat extends SynDiaElem { + + /** + * + */ + private static final long serialVersionUID = -377359652483309748L; + private List elems; + + private int width; + private int height; + + public Concat() { + + elems = new ArrayList(); + + } + + public void addElem(SynDiaElem el) { + + elems.add(el); + + } + + public void getRenderListFromDiagram(List list) { + /* + JPanel p = new JPanel(); + p.setSize(this.getWidth(), this.getHeight()); + list.add(); + */ + + } + + public void update() { + + + } + + + public void getWidth(int width) { + + this.width = width; + } + + public void getHeight(int width) { + + this.width = width; + } + + + public String sayHello() { + + String ausgabe = new String(""); + ausgabe += "--> Concatenation .. \n"; + for (SynDiaElem elem : elems) { + + ausgabe += "\t" + elem.sayHello() + "\n"; + + } + return ausgabe; + + } + + public String contentToString() { + String ausgabe = new String(""); + + for (SynDiaElem elem : elems) { + + ausgabe += elem.contentToString(); + + } + return ausgabe; + + + + } + + + + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/JComponentSymbolExample.java b/relicts/org/jalgo/tests/modules/ebnf/JComponentSymbolExample.java new file mode 100644 index 0000000..3321fdf --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/JComponentSymbolExample.java @@ -0,0 +1,256 @@ +package org.jalgo.tests.ebnf; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.Random; + +import org.jalgo.module.ebnf.renderer.*; + + + +//<<<<<<< JComponentSymbolExample.java + +/* Test, ob ich was überschreiben kann*/ +/* nein, kannst du nicht *g* - war hier nur noch alles rot... + public class JComponentSymbolExample extends JPanel implements KeyListener, MouseMotionListener, MouseListener, ActionListener { + ======= + import java.util.List; + import java.util.ArrayList; + /* Test, ob ich was �berschreiben kann*/ +public class JComponentSymbolExample extends JPanel implements + MouseMotionListener, MouseListener, ActionListener { + + + /** + * + */ + private static final long serialVersionUID = 1L; + + private JPopupMenu pMenu; + + private int diff_x = 0; + + private int diff_y = 0; + + private Point pMouse; + + private JMenuItem termitem = new JMenuItem("Terminalsymbol"); + + private JMenuItem varitem = new JMenuItem("Variable"); + + private JMenuItem branchitem = new JMenuItem("Verzweigung"); + + private JTextField editText; + + private SynDiaElem lastElem; + + private SyntaxDiagram syndia; + + /** + * + */ + public JComponentSymbolExample() { + + this.setLayout(null); + + + + //System.out.println(syndia.sayHello()); + //System.out.println(syndia.contentToString()); + //System.out.println(b1.contentToString()); + //System.out.println(c2.contentToString()); + + editText = new JTextField(); + editText.addActionListener(this); + add(editText); + + addMouseListener(this); + + this.setBackground(Color.WHITE); + + termitem.addActionListener(this); + varitem.addActionListener(this); + branchitem.addActionListener(this); + + pMenu = new JPopupMenu(); + pMenu.add(termitem); + pMenu.add(varitem); + pMenu.add(branchitem); + + pMouse = new Point(); + pMouse.setLocation(50, 50); + + } + + public void actionPerformed(ActionEvent event) { + + /* + * Das Abfangen des Enterdrucks bei Änderung eines Symbols des + * Syntaxdiagrammes + */ + if (editText.isVisible()) { + + editText.setVisible(false); + if (lastElem != null && !editText.getText().equals("")) + lastElem.setText(editText.getText()); + lastElem = null; + + repaint(); + editText.setText(""); + + } + if (event.getSource() == termitem) + reactToMenuSelection("terminal"); + else if (event.getSource() == varitem) + reactToMenuSelection("variable"); + else if (event.getSource() == branchitem) + reactToMenuSelection("branch"); + + } + + public void reactToMenuSelection(String elem) { + + System.out.println("Creating new " + elem + "-Symbol-Object [JPanel]"); + SynDiaElem el = SymbolFactory.createElement(elem); + el.addMouseListener(this); + el.addMouseMotionListener(this); + el.setLocation(pMouse.x, pMouse.y); + this.add(el); + el.setVisible(true); + + setComponentZOrder(el, 0); + el.repaint(); + + System.out.println(el.getText()); + + if (elem != "branch") + this.showEditText((Component) el); + + System.out.println("got HashCode: " + el.hashCode()); + } + + /* + * public void reactToVarMenuSelection() { + * + * + * System.out.println("Creating new Var-Symbol-Object [JPanel]"); Variable + * var = new Variable(varlist[random.nextInt(15)]); + * var.addMouseListener(this); var.addMouseMotionListener(this); + * var.setLocation(pMouse.x, pMouse.y); this.add(var); var.setVisible(true); + * + * setComponentZOrder(var, 0); var.repaint(); } + * + * public void keyPressed(KeyEvent e) { + * + * if (e.getKeyChar() == 10) { + * + * System.out.println("jipppie"); } System.out.println(e.getKeyChar()); } + * + * public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} + */ + + public void mouseMoved(MouseEvent e) { + } + + public void mouseDragged(MouseEvent e) { + + if (e.getComponent().getClass() != JComponentSymbolExample.class) + e.getComponent().setLocation( + e.getComponent().getX() - (diff_x - e.getX()), + e.getComponent().getY() - (diff_y - e.getY())); + + setComponentZOrder((SynDiaElem) e.getComponent(), 0); + + /* + * Zur Neusetzung der Panelgröße, fürs Scrollen + */ + Component[] comps = getComponents(); + int x = 0; + int y = 0; + + for (Component c : comps) { + + if (c.getX() + c.getWidth() > x) + x = c.getX() + c.getWidth(); + if (c.getY() + c.getHeight() > y) + y = c.getY() + c.getHeight(); + } + + setSize(x, y); + revalidate(); + + // System.out.println(this.getWidth()+" x "+this.getHeight()); + System.out.println("HashCode: " + e.getComponent().hashCode()); + repaint(); + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mousePressed(MouseEvent e) { + diff_x = e.getX(); + diff_y = e.getY(); + } + + public void showEditText(Component c) { + + int x = 50; + if (c.getWidth() > 65) + x = c.getWidth() - 15; + editText.setBounds(c.getX() + 6, c.getY() + 5, x, 20); + + editText.setText(((SynDiaElem) c).getText()); + editText.setVisible(true); + setComponentZOrder(editText, 0); + editText.requestFocus(true); + editText.selectAll(); + lastElem = (SynDiaElem) c; + + } + + public void mouseClicked(MouseEvent e) { + + System.out.println(e.getComponent().getClass().toString()); + + if (e.getClickCount() == 2 + && e.getComponent().getClass().getGenericSuperclass() == SynDiaElem.class) { + + this.showEditText(e.getComponent()); + } else if (e.getClickCount() == 1 && editText.isVisible()) { + + editText.setVisible(false); + if (lastElem != null && !editText.getText().equals("")) + lastElem.setText(editText.getText()); + lastElem = null; + + repaint(); + editText.setText(""); + + } + } + + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + + pMenu.show(e.getComponent(), e.getX(), e.getY()); + pMouse.setLocation(e.getX(), e.getY()); + } + + } + + public static void main(String[] args) { + + JFrame f = new JFrame("moin"); + f.setSize(800, 600); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + f.add(new JComponentSymbolExample()); + + f.setVisible(true); + } + +} \ No newline at end of file diff --git a/relicts/org/jalgo/tests/modules/ebnf/SymbolFactory.java b/relicts/org/jalgo/tests/modules/ebnf/SymbolFactory.java new file mode 100644 index 0000000..4612311 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/SymbolFactory.java @@ -0,0 +1,23 @@ +package org.jalgo.tests.ebnf; + +public class SymbolFactory { + + private static SynDiaElem element; + + public SymbolFactory() {} + + public static SynDiaElem createElement(String type) { + + if (type.equals("terminal")) + element = new Terminal("leer"); + else if (type.equals("variable")) + element = new Variable(""); + else if (type.equals("branch")) + element = new Branch("close"); + return element; + + } + + + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/SynDiaElem.java b/relicts/org/jalgo/tests/modules/ebnf/SynDiaElem.java new file mode 100644 index 0000000..20b4daa --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/SynDiaElem.java @@ -0,0 +1,60 @@ +package org.jalgo.tests.ebnf; +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.geom.RoundRectangle2D; + + +import javax.swing.JPanel; + +public abstract class SynDiaElem extends JPanel{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public static final int HEIGHT = 30; + + protected String strValue = ""; + protected Color color; + protected int width; + protected Font font; + protected FontMetrics fm; + + public boolean transformed = false; + + public abstract String sayHello(); + public abstract String contentToString(); + protected abstract void update(); + + protected int getLength() { + + return (int) Math.round(this.getSize().getWidth()); + + } + + protected AlphaComposite makeComposite(float alpha) { + int type = AlphaComposite.SRC_OVER; + return(AlphaComposite.getInstance(type, alpha)); + } + + protected void setText(String text) { + + strValue = text; + update(); + + + } + + + + protected String getText() { + + return strValue; + + } + + protected void setWidth(int w) {} +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/SynDiaRendererTest.java b/relicts/org/jalgo/tests/modules/ebnf/SynDiaRendererTest.java new file mode 100644 index 0000000..9c736d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/SynDiaRendererTest.java @@ -0,0 +1,56 @@ +/** + * + */ +package org.jalgo.tests.ebnf; + +import org.jalgo.module.ebnf.model.*; +import org.jalgo.module.ebnf.renderer.*; + +import java.util.List; +import java.util.ArrayList; + + +/** + * @author Andre + * + */ +public class SynDiaRendererTest { + + public static void main(String[] args) { + + SyntaxDiagram syndia = new SyntaxDiagram("S"); + + Concat c1 = new Concat(); + Concat c2 = new Concat(); + + Branch b1 = new Branch("open"); + + Terminal t1 = new Terminal("a"); + Terminal t2 = new Terminal("a"); + Terminal t3 = new Terminal("b"); + + c1.addElem(t1); + c2.addElem(t2); + c2.addElem(t3); + + b1.addElem(c1); + b1.addElem(c2); + + + syndia.addElem(b1); + + + + + + + + + + + + } + + + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/SyntaxDiagram.java b/relicts/org/jalgo/tests/modules/ebnf/SyntaxDiagram.java new file mode 100644 index 0000000..8a6dab4 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/SyntaxDiagram.java @@ -0,0 +1,70 @@ +package org.jalgo.tests.ebnf; + +import javax.swing.JPanel; + +import org.jalgo.module.ebnf.renderer.*; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +import java.util.List; + +public class SyntaxDiagram extends JPanel { + + /** + * + */ + private static final long serialVersionUID = 3573499574510961338L; + public final static int NULLLENGTH = 100; + public final static int ELEMSPACE = 20; + + private Concat concat; + private String name; + private int x = 10; + private int y = 10; + + public SyntaxDiagram(String name) { + + setSize(1280, 1024); + setVisible(true); + setLayout(null); + + concat = new Concat(); + this.name = name; + } + + public void addElem(SynDiaElem el) { + + concat.addElem(el); + + this.add(el); + + if (x + el.getLength() > this.getSize().getWidth()) { + x = 10; + y += 50; + } + + + el.setLocation(x, y); + el.setVisible(true); + + System.out.println(x); + x += el.getLength() + 10; + + } + + public void getRenderListFromDiagram(List list) { + + concat.getRenderListFromDiagram(list); + + } + + public String sayHello() { + + return concat.sayHello(); + + } + public String contentToString() { + + return concat.contentToString(); + + } +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/Terminal.java b/relicts/org/jalgo/tests/modules/ebnf/Terminal.java new file mode 100644 index 0000000..5d84f21 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/Terminal.java @@ -0,0 +1,99 @@ +package org.jalgo.tests.ebnf; + +import java.awt.*; +import java.awt.geom.*; + +public class Terminal extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + protected RoundRectangle2D.Double kreis; + + + + public Terminal(String val) { + + this.strValue = val; + + //this.color = new Color(0, 200, 0); + font = new Font("Courier", Font.BOLD, 17); + + fm = getFontMetrics(font); + width = fm.stringWidth(strValue) + 15; + + + if (width + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/ChoicePanel/ChoicePanel.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/ChoicePanel/ChoicePanel.java new file mode 100644 index 0000000..1bbe151 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/ChoicePanel/ChoicePanel.java @@ -0,0 +1,100 @@ + +package org.jalgo.tests.ebnf.ebnfinput.ChoicePanel; + +import javax.swing.JFrame; + +public class ChoicePanel extends JFrame { + + /** Creates new form Find */ + public ChoicePanel() { + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + ChoicePanel = new javax.swing.JPanel(); + buttonPanel = new javax.swing.JPanel(); + transButton = new javax.swing.JButton(); + editButton = new javax.swing.JButton(); + + buttonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Bitte W\u00e4hlen Sie...", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + transButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + transButton.setText("
    trans()-Algorithmus
    anwenden
    "); + + editButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + editButton.setText("
    Definition
    \u00fcberarbeiten
    "); + + org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel); + buttonPanel.setLayout(buttonPanelLayout); + buttonPanelLayout.setHorizontalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup() + .addContainerGap(416, Short.MAX_VALUE) + .add(transButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(editButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + buttonPanelLayout.setVerticalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(buttonPanelLayout.createSequentialGroup() + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(editButton) + .add(transButton)) + .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout ChoicePanelLayout = new org.jdesktop.layout.GroupLayout(ChoicePanel); + ChoicePanel.setLayout(ChoicePanelLayout); + ChoicePanelLayout.setHorizontalGroup( + ChoicePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanelLayout.createSequentialGroup() + .addContainerGap() + .add(buttonPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + ChoicePanelLayout.setVerticalGroup( + ChoicePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanelLayout.createSequentialGroup() + .addContainerGap() + .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 82, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(ChoicePanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + }//
    //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new ChoicePanel().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel ChoicePanel; + private javax.swing.JPanel buttonPanel; + private javax.swing.JButton editButton; + private javax.swing.JButton transButton; + // End of variables declaration//GEN-END:variables + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.form b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.form new file mode 100644 index 0000000..e6f8b40 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.form @@ -0,0 +1,664 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.java new file mode 100644 index 0000000..b2801e7 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUI.java @@ -0,0 +1,455 @@ +/* + * GUI.java + * + * Created on 16. April 2006, 13:54 + */ + +package org.jalgo.tests.ebnf.ebnfinput; + +/** + * + * @author Johannes, Tom + */ +public class GUI extends javax.swing.JFrame { + + /** Creates new form GUI */ + public GUI() { + + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + mainPanel = new javax.swing.JPanel(); + inputPanel = new javax.swing.JPanel(); + buttonPanel = new javax.swing.JPanel(); + addParenthLeftButton = new javax.swing.JButton(); + addParenthRightButton = new javax.swing.JButton(); + addBarButton = new javax.swing.JButton(); + addBraceLeftButton = new javax.swing.JButton(); + addBraceRightButton = new javax.swing.JButton(); + addBracketLeftButton = new javax.swing.JButton(); + addBracketRightButton = new javax.swing.JButton(); + addEpsilonButton = new javax.swing.JButton(); + addRuleLeftSideComboBox = new javax.swing.JComboBox(); + addRuleAssignSymbolLabel = new javax.swing.JLabel(); + addRuleRightSideTextbox = new javax.swing.JTextField(); + addRuleButton = new javax.swing.JButton(); + terminalSymbolPanel = new javax.swing.JPanel(); + addTerminalButton = new javax.swing.JButton(); + addTerminalTextField = new javax.swing.JTextField(); + variableSymbolPanel = new javax.swing.JPanel(); + addVariableButton = new javax.swing.JButton(); + addVariableTextField = new javax.swing.JTextField(); + StartvariableLabel = new javax.swing.JLabel(); + startVariableComboBox = new javax.swing.JComboBox(); + finishInputButton = new javax.swing.JButton(); + checkDefinitionButton = new javax.swing.JButton(); + definitionViewPanel = new javax.swing.JSplitPane(); + definitionHeaderViewScrollPanel = new javax.swing.JScrollPane(); + definitionHeaderViewlPanel = new javax.swing.JPanel(); + headerLabel1 = new javax.swing.JLabel(); + headerLabel2 = new javax.swing.JLabel(); + headerLabel3 = new javax.swing.JLabel(); + definitionRulesViewScrollPanel = new javax.swing.JScrollPane(); + definitionRulesViewPanel = new javax.swing.JPanel(); + ruleLabel1 = new javax.swing.JLabel(); + ruleLabel2 = new javax.swing.JLabel(); + ruleLabel3 = new javax.swing.JLabel(); + ruleLabel5 = new javax.swing.JLabel(); + ruleLabel6 = new javax.swing.JLabel(); + ruleLabel7 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setName("EBNF"); + buttonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Regeln", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + addParenthLeftButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addParenthLeftButton.setText("("); + addParenthLeftButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addParenthRightButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addParenthRightButton.setText(")"); + addParenthRightButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBarButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBarButton.setText("|"); + addBarButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBraceLeftButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBraceLeftButton.setText("{"); + addBraceLeftButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBraceRightButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBraceRightButton.setText("}"); + addBraceRightButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBracketLeftButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBracketLeftButton.setText("["); + addBracketLeftButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBracketRightButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBracketRightButton.setText("]"); + addBracketRightButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addEpsilonButton.setFont(new java.awt.Font("Tahoma", 0, 20)); + addEpsilonButton.setText("\u03b5"); + addEpsilonButton.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addRuleLeftSideComboBox.setFont(new java.awt.Font("Tahoma", 0, 16)); + addRuleLeftSideComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" })); + + addRuleAssignSymbolLabel.setFont(new java.awt.Font("Tahoma", 1, 16)); + addRuleAssignSymbolLabel.setText("::="); + + addRuleRightSideTextbox.setFont(new java.awt.Font("Tahoma", 0, 16)); + + addRuleButton.setFont(new java.awt.Font("Tahoma", 0, 16)); + addRuleButton.setText("Hinzuf\u00fcgen"); + addRuleButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel); + buttonPanel.setLayout(buttonPanelLayout); + buttonPanelLayout.setHorizontalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(buttonPanelLayout.createSequentialGroup() + .addContainerGap() + .add(addRuleLeftSideComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 135, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addRuleAssignSymbolLabel) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(buttonPanelLayout.createSequentialGroup() + .add(addParenthLeftButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBarButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addParenthRightButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBraceLeftButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBraceRightButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBracketLeftButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBracketRightButton) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addEpsilonButton) + .addContainerGap()) + .add(buttonPanelLayout.createSequentialGroup() + .add(addRuleRightSideTextbox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addRuleButton)))) + ); + buttonPanelLayout.setVerticalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(buttonPanelLayout.createSequentialGroup() + .addContainerGap() + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(buttonPanelLayout.createSequentialGroup() + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addBarButton) + .add(addParenthRightButton) + .add(addBraceLeftButton) + .add(addBraceRightButton) + .add(addBracketLeftButton) + .add(addBracketRightButton) + .add(addEpsilonButton) + .add(addParenthLeftButton)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addRuleButton) + .add(addRuleRightSideTextbox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(addRuleAssignSymbolLabel))) + .add(org.jdesktop.layout.GroupLayout.TRAILING, addRuleLeftSideComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) + ); + + terminalSymbolPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Terminalsymbole", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + terminalSymbolPanel.setMinimumSize(new java.awt.Dimension(22, 36)); + addTerminalButton.setFont(new java.awt.Font("Tahoma", 0, 16)); + addTerminalButton.setText("Hinzuf\u00fcgen"); + addTerminalButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + addTerminalTextField.setFont(new java.awt.Font("Tahoma", 0, 14)); + + org.jdesktop.layout.GroupLayout terminalSymbolPanelLayout = new org.jdesktop.layout.GroupLayout(terminalSymbolPanel); + terminalSymbolPanel.setLayout(terminalSymbolPanelLayout); + terminalSymbolPanelLayout.setHorizontalGroup( + terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, terminalSymbolPanelLayout.createSequentialGroup() + .add(addTerminalTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addTerminalButton)) + ); + terminalSymbolPanelLayout.setVerticalGroup( + terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(terminalSymbolPanelLayout.createSequentialGroup() + .add(terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addTerminalButton) + .add(addTerminalTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(40, Short.MAX_VALUE)) + ); + + variableSymbolPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Variablensymbole", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + addVariableButton.setFont(new java.awt.Font("Tahoma", 0, 16)); + addVariableButton.setText("Hinzuf\u00fcgen"); + addVariableButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + addVariableTextField.setFont(new java.awt.Font("Tahoma", 0, 14)); + + StartvariableLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); + StartvariableLabel.setText("Startvariable:"); + + startVariableComboBox.setFont(new java.awt.Font("Tahoma", 0, 12)); + startVariableComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" })); + + org.jdesktop.layout.GroupLayout variableSymbolPanelLayout = new org.jdesktop.layout.GroupLayout(variableSymbolPanel); + variableSymbolPanel.setLayout(variableSymbolPanelLayout); + variableSymbolPanelLayout.setHorizontalGroup( + variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, variableSymbolPanelLayout.createSequentialGroup() + .add(addVariableTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addVariableButton)) + .add(org.jdesktop.layout.GroupLayout.TRAILING, variableSymbolPanelLayout.createSequentialGroup() + .add(StartvariableLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(startVariableComboBox, 0, 137, Short.MAX_VALUE)) + ); + variableSymbolPanelLayout.setVerticalGroup( + variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(variableSymbolPanelLayout.createSequentialGroup() + .add(variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addVariableButton) + .add(addVariableTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(StartvariableLabel) + .add(startVariableComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + finishInputButton.setFont(new java.awt.Font("Tahoma", 1, 14)); + finishInputButton.setText("
    Eingabe
    beenden
    "); + + checkDefinitionButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + checkDefinitionButton.setText("
    Defintion
    pr\u00fcfenn
    "); + + org.jdesktop.layout.GroupLayout inputPanelLayout = new org.jdesktop.layout.GroupLayout(inputPanel); + inputPanel.setLayout(inputPanelLayout); + inputPanelLayout.setHorizontalGroup( + inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(inputPanelLayout.createSequentialGroup() + .addContainerGap() + .add(inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) + .add(inputPanelLayout.createSequentialGroup() + .add(variableSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(terminalSymbolPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) + .add(checkDefinitionButton, 0, 0, Short.MAX_VALUE) + .add(finishInputButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .add(25, 25, 25)) + ); + inputPanelLayout.setVerticalGroup( + inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(inputPanelLayout.createSequentialGroup() + .addContainerGap() + .add(inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(terminalSymbolPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(variableSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(inputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) + .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(inputPanelLayout.createSequentialGroup() + .add(checkDefinitionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 49, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(finishInputButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) + ); + + definitionViewPanel.setDividerLocation(100); + definitionViewPanel.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); + definitionHeaderViewScrollPanel.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + definitionHeaderViewScrollPanel.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); + definitionHeaderViewlPanel.setBackground(new java.awt.Color(255, 255, 255)); + headerLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel1.setText("E = (V, \u03a3, , R)"); + + headerLabel2.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel2.setText("V = {, , }"); + + headerLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel3.setText("\u03a3 = {, , +, -, *, /, (, )}"); + + org.jdesktop.layout.GroupLayout definitionHeaderViewlPanelLayout = new org.jdesktop.layout.GroupLayout(definitionHeaderViewlPanel); + definitionHeaderViewlPanel.setLayout(definitionHeaderViewlPanelLayout); + definitionHeaderViewlPanelLayout.setHorizontalGroup( + definitionHeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(definitionHeaderViewlPanelLayout.createSequentialGroup() + .addContainerGap() + .add(definitionHeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(headerLabel1) + .add(headerLabel2) + .add(headerLabel3)) + .addContainerGap(1141, Short.MAX_VALUE)) + ); + definitionHeaderViewlPanelLayout.setVerticalGroup( + definitionHeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(definitionHeaderViewlPanelLayout.createSequentialGroup() + .addContainerGap() + .add(headerLabel1) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(headerLabel2) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(headerLabel3) + .addContainerGap(38, Short.MAX_VALUE)) + ); + definitionHeaderViewScrollPanel.setViewportView(definitionHeaderViewlPanel); + + definitionViewPanel.setTopComponent(definitionHeaderViewScrollPanel); + + definitionRulesViewPanel.setBackground(new java.awt.Color(255, 255, 255)); + ruleLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel1.setText("::= [+|-] {(+|-)}"); + + ruleLabel2.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel2.setText("::= {(*|/|%)}"); + + ruleLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel3.setText(""); + + ruleLabel5.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel5.setText("::= ||()"); + + ruleLabel6.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel6.setText(""); + + ruleLabel7.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel7.setText(""); + + org.jdesktop.layout.GroupLayout definitionRulesViewPanelLayout = new org.jdesktop.layout.GroupLayout(definitionRulesViewPanel); + definitionRulesViewPanel.setLayout(definitionRulesViewPanelLayout); + definitionRulesViewPanelLayout.setHorizontalGroup( + definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(definitionRulesViewPanelLayout.createSequentialGroup() + .addContainerGap() + .add(definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) + .add(ruleLabel3) + .add(ruleLabel6) + .add(ruleLabel7)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ruleLabel1) + .add(ruleLabel2) + .add(ruleLabel5)) + .addContainerGap(822, Short.MAX_VALUE)) + ); + definitionRulesViewPanelLayout.setVerticalGroup( + definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(definitionRulesViewPanelLayout.createSequentialGroup() + .addContainerGap() + .add(definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel1) + .add(ruleLabel7)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel2) + .add(ruleLabel6)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(definitionRulesViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel3) + .add(ruleLabel5)) + .addContainerGap(278, Short.MAX_VALUE)) + ); + definitionRulesViewScrollPanel.setViewportView(definitionRulesViewPanel); + + definitionViewPanel.setBottomComponent(definitionRulesViewScrollPanel); + + org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); + mainPanel.setLayout(mainPanelLayout); + mainPanelLayout.setHorizontalGroup( + mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(inputPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE) + .add(definitionViewPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE) + ); + mainPanelLayout.setVerticalGroup( + mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(mainPanelLayout.createSequentialGroup() + .add(inputPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(definitionViewPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + pack(); + }//
    //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new GUI().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JLabel StartvariableLabel; + private javax.swing.JButton addBarButton; + private javax.swing.JButton addBraceLeftButton; + private javax.swing.JButton addBraceRightButton; + private javax.swing.JButton addBracketLeftButton; + private javax.swing.JButton addBracketRightButton; + private javax.swing.JButton addEpsilonButton; + private javax.swing.JButton addParenthLeftButton; + private javax.swing.JButton addParenthRightButton; + private javax.swing.JLabel addRuleAssignSymbolLabel; + private javax.swing.JButton addRuleButton; + private javax.swing.JComboBox addRuleLeftSideComboBox; + private javax.swing.JTextField addRuleRightSideTextbox; + private javax.swing.JButton addTerminalButton; + private javax.swing.JTextField addTerminalTextField; + private javax.swing.JButton addVariableButton; + private javax.swing.JTextField addVariableTextField; + private javax.swing.JPanel buttonPanel; + private javax.swing.JButton checkDefinitionButton; + private javax.swing.JScrollPane definitionHeaderViewScrollPanel; + private javax.swing.JPanel definitionHeaderViewlPanel; + private javax.swing.JPanel definitionRulesViewPanel; + private javax.swing.JScrollPane definitionRulesViewScrollPanel; + private javax.swing.JSplitPane definitionViewPanel; + private javax.swing.JButton finishInputButton; + private javax.swing.JLabel headerLabel1; + private javax.swing.JLabel headerLabel2; + private javax.swing.JLabel headerLabel3; + private javax.swing.JPanel inputPanel; + private javax.swing.JPanel mainPanel; + private javax.swing.JLabel ruleLabel1; + private javax.swing.JLabel ruleLabel2; + private javax.swing.JLabel ruleLabel3; + private javax.swing.JLabel ruleLabel5; + private javax.swing.JLabel ruleLabel6; + private javax.swing.JLabel ruleLabel7; + private javax.swing.JComboBox startVariableComboBox; + private javax.swing.JPanel terminalSymbolPanel; + private javax.swing.JPanel variableSymbolPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Entries new file mode 100644 index 0000000..55c87ce --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Entries @@ -0,0 +1,2 @@ +/GuiPanel.form/1.1/Fri Aug 11 16:37:23 2006/-kb/ +/GuiPanel.java/1.1/Fri Aug 11 16:37:23 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Repository new file mode 100644 index 0000000..8daabd4 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.form b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.form new file mode 100644 index 0000000..6706842 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.form @@ -0,0 +1,86 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.java new file mode 100644 index 0000000..f4fdbf1 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/GUIPanel/GuiPanel.java @@ -0,0 +1,90 @@ + +package org.jalgo.tests.ebnf.ebnfinput.GUIPanel; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; + +import org.jalgo.module.ebnf.gui.ebnf.ChoicePanel; +import org.jalgo.module.ebnf.gui.ebnf.HeaderViewPanel; +import org.jalgo.module.ebnf.gui.ebnf.InputPanel; +import org.jalgo.module.ebnf.gui.ebnf.RuleViewPanel; + +public class GuiPanel extends JPanel { + + private static final long serialVersionUID = -5877808882853415899L; + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JScrollPane definitionHeaderViewScrollPanel; + private javax.swing.JScrollPane definitionRulesViewScrollPanel; + private javax.swing.JSplitPane definitionViewPanel; + private javax.swing.JPanel mainPanel; + // End of variables declaration//GEN-END:variables + + public ChoicePanel choicePanel; + public RuleViewPanel ruleViewPanel; + public HeaderViewPanel headerViewPanel; + public InputPanel inputPanel; + + /** Creates new form GuiPanel */ + public GuiPanel() { + + + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + mainPanel = new javax.swing.JPanel(); + definitionViewPanel = new JSplitPane(); + definitionHeaderViewScrollPanel = new JScrollPane(); + definitionRulesViewScrollPanel = new JScrollPane(); + + definitionViewPanel.setDividerLocation(100); + definitionViewPanel.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); + definitionHeaderViewScrollPanel.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + definitionHeaderViewScrollPanel.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); + + definitionViewPanel.setTopComponent(definitionHeaderViewScrollPanel); + definitionViewPanel.setBottomComponent(definitionRulesViewScrollPanel); + + org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); + mainPanel.setLayout(mainPanelLayout); + mainPanelLayout.setHorizontalGroup( + mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(inputPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(definitionViewPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE) + ); + + mainPanelLayout.setVerticalGroup( + mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(mainPanelLayout.createSequentialGroup() + //.add(235, 235, 235) + .add(inputPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(definitionViewPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); + setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(0, 795, Short.MAX_VALUE) + .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(0, 628, Short.MAX_VALUE) + .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + + definitionHeaderViewScrollPanel.setViewportView(headerViewPanel); + definitionRulesViewScrollPanel.setViewportView(ruleViewPanel); + }// //GEN-END:initComponents + + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Entries new file mode 100644 index 0000000..d23b319 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Entries @@ -0,0 +1,2 @@ +/HeaderViewPanel.form/1.1/Fri Aug 11 16:37:22 2006/-kb/ +/HeaderViewPanel.java/1.1/Fri Aug 11 16:37:22 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Repository new file mode 100644 index 0000000..2b32901 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.form b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.form new file mode 100644 index 0000000..eb3e703 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.form @@ -0,0 +1,96 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.java new file mode 100644 index 0000000..5f0095e --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/HeaderViewPanel/HeaderViewPanel.java @@ -0,0 +1,81 @@ + +package org.jalgo.tests.ebnf.ebnfinput.HeaderViewPanel; + +import javax.swing.JPanel; + +public class HeaderViewPanel extends JPanel { + + /** Creates new form HeaderViewPanel */ + public HeaderViewPanel() { + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + HeaderViewlPanel = new javax.swing.JPanel(); + headerLabel1 = new javax.swing.JLabel(); + headerLabel2 = new javax.swing.JLabel(); + headerLabel3 = new javax.swing.JLabel(); + + HeaderViewlPanel.setBackground(new java.awt.Color(255, 255, 255)); + headerLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel1.setText("E = (V, \u03a3, , R)"); + + headerLabel2.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel2.setText("V = {, , }"); + + headerLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); + headerLabel3.setText("\u03a3 = {, , +, -, *, /, (, )}"); + + org.jdesktop.layout.GroupLayout HeaderViewlPanelLayout = new org.jdesktop.layout.GroupLayout(HeaderViewlPanel); + HeaderViewlPanel.setLayout(HeaderViewlPanelLayout); + HeaderViewlPanelLayout.setHorizontalGroup( + HeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(HeaderViewlPanelLayout.createSequentialGroup() + .addContainerGap() + .add(HeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(headerLabel1) + .add(headerLabel2) + .add(headerLabel3)) + .addContainerGap(1141, Short.MAX_VALUE)) + ); + HeaderViewlPanelLayout.setVerticalGroup( + HeaderViewlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(HeaderViewlPanelLayout.createSequentialGroup() + .addContainerGap() + .add(headerLabel1) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(headerLabel2) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(headerLabel3) + .addContainerGap(38, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); + setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(0, 1496, Short.MAX_VALUE) + .add(HeaderViewlPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(0, 121, Short.MAX_VALUE) + .add(HeaderViewlPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel HeaderViewlPanel; + private javax.swing.JLabel headerLabel1; + private javax.swing.JLabel headerLabel2; + private javax.swing.JLabel headerLabel3; + // End of variables declaration//GEN-END:variables + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Entries new file mode 100644 index 0000000..db2ba55 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Entries @@ -0,0 +1,2 @@ +/InputPanel.form/1.1/Fri Aug 11 16:37:22 2006/-kb/ +/InputPanel.java/1.1/Fri Aug 11 16:37:22 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Repository new file mode 100644 index 0000000..3b0f1fb --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.form b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.form new file mode 100644 index 0000000..7d3f432 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.form @@ -0,0 +1,453 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.java new file mode 100644 index 0000000..ececf5b --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/InputPanel/InputPanel.java @@ -0,0 +1,313 @@ + +package org.jalgo.tests.ebnf.ebnfinput.InputPanel; + +import javax.swing.JFrame; + +public class InputPanel extends JFrame { + + /** Creates new form Find */ + public InputPanel() { + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + InputPanel = new javax.swing.JPanel(); + variableSymbolPanel = new javax.swing.JPanel(); + addVariableButton4 = new javax.swing.JButton(); + addVariableTextField4 = new javax.swing.JTextField(); + StartvariableLabel4 = new javax.swing.JLabel(); + startVariableComboBox4 = new javax.swing.JComboBox(); + terminalSymbolPanel = new javax.swing.JPanel(); + addTerminalButton5 = new javax.swing.JButton(); + addTerminalTextField5 = new javax.swing.JTextField(); + rulePanel = new javax.swing.JPanel(); + addParenthLeftButton5 = new javax.swing.JButton(); + addParenthRightButton5 = new javax.swing.JButton(); + addBarButton5 = new javax.swing.JButton(); + addBraceLeftButton5 = new javax.swing.JButton(); + addBraceRightButton5 = new javax.swing.JButton(); + addBracketLeftButton5 = new javax.swing.JButton(); + addBracketRightButton5 = new javax.swing.JButton(); + addRuleLeftSideComboBox5 = new javax.swing.JComboBox(); + addRuleAssignSymbolLabel5 = new javax.swing.JLabel(); + addRuleRightSideTextbox5 = new javax.swing.JTextField(); + addRuleButton5 = new javax.swing.JButton(); + buttonPanel = new javax.swing.JPanel(); + checkDefinitionButton5 = new javax.swing.JButton(); + finishInputButton5 = new javax.swing.JButton(); + + variableSymbolPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Variablensymbole", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + addVariableButton4.setFont(new java.awt.Font("Tahoma", 0, 16)); + addVariableButton4.setText("Hinzuf\u00fcgen"); + addVariableButton4.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + addVariableTextField4.setFont(new java.awt.Font("Tahoma", 0, 14)); + + StartvariableLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); + StartvariableLabel4.setText("Startvariable:"); + + startVariableComboBox4.setFont(new java.awt.Font("Tahoma", 0, 12)); + startVariableComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" })); + + org.jdesktop.layout.GroupLayout variableSymbolPanelLayout = new org.jdesktop.layout.GroupLayout(variableSymbolPanel); + variableSymbolPanel.setLayout(variableSymbolPanelLayout); + variableSymbolPanelLayout.setHorizontalGroup( + variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, variableSymbolPanelLayout.createSequentialGroup() + .add(addVariableTextField4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addVariableButton4)) + .add(org.jdesktop.layout.GroupLayout.TRAILING, variableSymbolPanelLayout.createSequentialGroup() + .add(StartvariableLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(startVariableComboBox4, 0, 130, Short.MAX_VALUE)) + ); + variableSymbolPanelLayout.setVerticalGroup( + variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(variableSymbolPanelLayout.createSequentialGroup() + .add(variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addVariableButton4) + .add(addVariableTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(variableSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(StartvariableLabel4) + .add(startVariableComboBox4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(12, Short.MAX_VALUE)) + ); + + terminalSymbolPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Terminalsymbole", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + terminalSymbolPanel.setMinimumSize(new java.awt.Dimension(22, 36)); + addTerminalButton5.setFont(new java.awt.Font("Tahoma", 0, 16)); + addTerminalButton5.setText("Hinzuf\u00fcgen"); + addTerminalButton5.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + addTerminalTextField5.setFont(new java.awt.Font("Tahoma", 0, 14)); + + org.jdesktop.layout.GroupLayout terminalSymbolPanelLayout = new org.jdesktop.layout.GroupLayout(terminalSymbolPanel); + terminalSymbolPanel.setLayout(terminalSymbolPanelLayout); + terminalSymbolPanelLayout.setHorizontalGroup( + terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, terminalSymbolPanelLayout.createSequentialGroup() + .add(addTerminalTextField5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addTerminalButton5)) + ); + terminalSymbolPanelLayout.setVerticalGroup( + terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(terminalSymbolPanelLayout.createSequentialGroup() + .add(terminalSymbolPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addTerminalButton5) + .add(addTerminalTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(41, Short.MAX_VALUE)) + ); + + rulePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Regeln", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + addParenthLeftButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addParenthLeftButton5.setText("("); + addParenthLeftButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addParenthRightButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addParenthRightButton5.setText(")"); + addParenthRightButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBarButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBarButton5.setText("|"); + addBarButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBraceLeftButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBraceLeftButton5.setText("{"); + addBraceLeftButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBraceRightButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBraceRightButton5.setText("}"); + addBraceRightButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBracketLeftButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBracketLeftButton5.setText("["); + addBracketLeftButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addBracketRightButton5.setFont(new java.awt.Font("Tahoma", 0, 20)); + addBracketRightButton5.setText("]"); + addBracketRightButton5.setMargin(new java.awt.Insets(3, 5, 2, 5)); + + addRuleLeftSideComboBox5.setFont(new java.awt.Font("Tahoma", 0, 16)); + addRuleLeftSideComboBox5.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" })); + + addRuleAssignSymbolLabel5.setFont(new java.awt.Font("Tahoma", 1, 16)); + addRuleAssignSymbolLabel5.setText("::="); + + addRuleRightSideTextbox5.setFont(new java.awt.Font("Tahoma", 0, 18)); + + addRuleButton5.setFont(new java.awt.Font("Tahoma", 0, 16)); + addRuleButton5.setText("Hinzuf\u00fcgen"); + addRuleButton5.setMargin(new java.awt.Insets(2, 4, 2, 4)); + + org.jdesktop.layout.GroupLayout rulePanelLayout = new org.jdesktop.layout.GroupLayout(rulePanel); + rulePanel.setLayout(rulePanelLayout); + rulePanelLayout.setHorizontalGroup( + rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(rulePanelLayout.createSequentialGroup() + .addContainerGap() + .add(addRuleLeftSideComboBox5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 135, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addRuleAssignSymbolLabel5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(rulePanelLayout.createSequentialGroup() + .add(addParenthLeftButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBarButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addParenthRightButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBraceLeftButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBraceRightButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBracketLeftButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addBracketRightButton5) + .addContainerGap()) + .add(rulePanelLayout.createSequentialGroup() + .add(addRuleRightSideTextbox5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(addRuleButton5) + .add(0, 0, 0)))) + ); + rulePanelLayout.setVerticalGroup( + rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(rulePanelLayout.createSequentialGroup() + .add(rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addBarButton5) + .add(addParenthRightButton5) + .add(addBraceLeftButton5) + .add(addBraceRightButton5) + .add(addBracketLeftButton5) + .add(addBracketRightButton5) + .add(addParenthLeftButton5)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(rulePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(addRuleRightSideTextbox5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(addRuleAssignSymbolLabel5) + .add(addRuleButton5)) + .add(org.jdesktop.layout.GroupLayout.TRAILING, addRuleLeftSideComboBox5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) + ); + + buttonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Weiter", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + checkDefinitionButton5.setFont(new java.awt.Font("Tahoma", 0, 14)); + checkDefinitionButton5.setText("
    Defintion
    pr\u00fcfenn
    "); + + finishInputButton5.setFont(new java.awt.Font("Tahoma", 1, 14)); + finishInputButton5.setText("
    Eingabe
    beenden
    "); + + org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel); + buttonPanel.setLayout(buttonPanelLayout); + buttonPanelLayout.setHorizontalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(checkDefinitionButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE) + .add(finishInputButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + buttonPanelLayout.setVerticalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup() + .addContainerGap(85, Short.MAX_VALUE) + .add(checkDefinitionButton5) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(finishInputButton5)) + ); + + org.jdesktop.layout.GroupLayout InputPanelLayout = new org.jdesktop.layout.GroupLayout(InputPanel); + InputPanel.setLayout(InputPanelLayout); + InputPanelLayout.setHorizontalGroup( + InputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(InputPanelLayout.createSequentialGroup() + .addContainerGap() + .add(InputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) + .add(org.jdesktop.layout.GroupLayout.TRAILING, InputPanelLayout.createSequentialGroup() + .add(variableSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(terminalSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .add(rulePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(buttonPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + InputPanelLayout.linkSize(new java.awt.Component[] {terminalSymbolPanel, variableSymbolPanel}, org.jdesktop.layout.GroupLayout.HORIZONTAL); + + InputPanelLayout.setVerticalGroup( + InputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, InputPanelLayout.createSequentialGroup() + .addContainerGap() + .add(InputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) + .add(buttonPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(org.jdesktop.layout.GroupLayout.LEADING, InputPanelLayout.createSequentialGroup() + .add(InputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) + .add(variableSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(terminalSymbolPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .add(rulePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) + .addContainerGap()) + ); + + InputPanelLayout.linkSize(new java.awt.Component[] {rulePanel, terminalSymbolPanel, variableSymbolPanel}, org.jdesktop.layout.GroupLayout.VERTICAL); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(InputPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(InputPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 229, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + }//
    //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new InputPanel().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel InputPanel; + private javax.swing.JLabel StartvariableLabel4; + private javax.swing.JButton addBarButton5; + private javax.swing.JButton addBraceLeftButton5; + private javax.swing.JButton addBraceRightButton5; + private javax.swing.JButton addBracketLeftButton5; + private javax.swing.JButton addBracketRightButton5; + private javax.swing.JButton addParenthLeftButton5; + private javax.swing.JButton addParenthRightButton5; + private javax.swing.JLabel addRuleAssignSymbolLabel5; + private javax.swing.JButton addRuleButton5; + private javax.swing.JComboBox addRuleLeftSideComboBox5; + private javax.swing.JTextField addRuleRightSideTextbox5; + private javax.swing.JButton addTerminalButton5; + private javax.swing.JTextField addTerminalTextField5; + private javax.swing.JButton addVariableButton4; + private javax.swing.JTextField addVariableTextField4; + private javax.swing.JPanel buttonPanel; + private javax.swing.JButton checkDefinitionButton5; + private javax.swing.JButton finishInputButton5; + private javax.swing.JPanel rulePanel; + private javax.swing.JComboBox startVariableComboBox4; + private javax.swing.JPanel terminalSymbolPanel; + private javax.swing.JPanel variableSymbolPanel; + // End of variables declaration//GEN-END:variables + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/Main.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/Main.java new file mode 100644 index 0000000..56ed975 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/Main.java @@ -0,0 +1,39 @@ +/* + * Main.java + * + * Created on 13. April 2006, 20:29 + * + * To change this template, choose Tools | Template Manager + * and open the template in the editor. + */ + + + +package org.jalgo.tests.ebnf.ebnfinput; + +import javax.swing.*; + +/** + * + * @author jm + */ +public class Main { + + /** Creates a new instance of Main */ + public Main() { + } + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + // TODO code application logic here + GUI gui = new GUI(); + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + SwingUtilities.updateComponentTreeUI(gui); + } catch (Exception e){} + gui.setVisible(true); + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Entries new file mode 100644 index 0000000..c071898 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Entries @@ -0,0 +1,2 @@ +/RuleViewPanel.form/1.1/Fri Aug 11 16:37:22 2006/-kb/ +/RuleViewPanel.java/1.1/Fri Aug 11 16:37:22 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Repository new file mode 100644 index 0000000..1a25dfa --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.form b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.form new file mode 100644 index 0000000..ffaaf29 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.form @@ -0,0 +1,133 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.java b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.java new file mode 100644 index 0000000..82bd576 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/ebnfinput/RuleViewPanel/RuleViewPanel.java @@ -0,0 +1,104 @@ + +package org.jalgo.tests.ebnf.ebnfinput.RuleViewPanel; + +import javax.swing.JPanel; + +public class RuleViewPanel extends JPanel { + + /** Creates new form RuleViewPanel */ + public RuleViewPanel() { + initComponents(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + RuleViewPanel = new javax.swing.JPanel(); + ruleLabel1 = new javax.swing.JLabel(); + ruleLabel2 = new javax.swing.JLabel(); + ruleLabel3 = new javax.swing.JLabel(); + ruleLabel5 = new javax.swing.JLabel(); + ruleLabel6 = new javax.swing.JLabel(); + ruleLabel7 = new javax.swing.JLabel(); + + RuleViewPanel.setBackground(new java.awt.Color(255, 255, 255)); + ruleLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel1.setText("::= [+|-] {(+|-)}"); + + ruleLabel2.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel2.setText("::= {(*|/|%)}"); + + ruleLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel3.setText(""); + + ruleLabel5.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel5.setText("::= ||()"); + + ruleLabel6.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel6.setText(""); + + ruleLabel7.setFont(new java.awt.Font("Tahoma", 0, 16)); + ruleLabel7.setText(""); + + org.jdesktop.layout.GroupLayout RuleViewPanelLayout = new org.jdesktop.layout.GroupLayout(RuleViewPanel); + RuleViewPanel.setLayout(RuleViewPanelLayout); + RuleViewPanelLayout.setHorizontalGroup( + RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(RuleViewPanelLayout.createSequentialGroup() + .addContainerGap() + .add(RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) + .add(ruleLabel3) + .add(ruleLabel6) + .add(ruleLabel7)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ruleLabel1) + .add(ruleLabel2) + .add(ruleLabel5)) + .addContainerGap(470, Short.MAX_VALUE)) + ); + RuleViewPanelLayout.setVerticalGroup( + RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(RuleViewPanelLayout.createSequentialGroup() + .addContainerGap() + .add(RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel1) + .add(ruleLabel7)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel2) + .add(ruleLabel6)) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(RuleViewPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(ruleLabel3) + .add(ruleLabel5)) + .addContainerGap(278, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); + setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(RuleViewPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(RuleViewPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + }// //GEN-END:initComponents + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel RuleViewPanel; + private javax.swing.JLabel ruleLabel1; + private javax.swing.JLabel ruleLabel2; + private javax.swing.JLabel ruleLabel3; + private javax.swing.JLabel ruleLabel5; + private javax.swing.JLabel ruleLabel6; + private javax.swing.JLabel ruleLabel7; + // End of variables declaration//GEN-END:variables + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/AllTests.java b/relicts/org/jalgo/tests/modules/ebnf/junit/AllTests.java new file mode 100644 index 0000000..cde8cf6 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/AllTests.java @@ -0,0 +1,21 @@ +package org.jalgo.tests.ebnf.junit; + + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite = new TestSuite("Test for org.jalgo.tests.ebnf.junit"); + + //$JUnit-BEGIN$ + suite.addTest(org.jalgo.tests.ebnf.junit.model.ebnf.AllTests.suite()); + suite.addTest(org.jalgo.tests.ebnf.junit.model.wordalgorithm.AllTests.suite()); + suite.addTest(org.jalgo.tests.ebnf.junit.controller.wordalgorithm.AllTests.suite()); + suite.addTest(org.jalgo.tests.ebnf.junit.util.AllTests.suite()); + //$JUnit-END$ + return suite; + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Entries new file mode 100644 index 0000000..b647d10 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Entries @@ -0,0 +1,4 @@ +/AllTests.java/1.1/Fri Aug 11 16:37:22 2006// +D/controller//// +D/model//// +D/util//// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Repository new file mode 100644 index 0000000..61c9fff --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Entries new file mode 100644 index 0000000..e3e80c7 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Entries @@ -0,0 +1 @@ +D/wordalgorithm//// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Repository new file mode 100644 index 0000000..9cc58eb --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/controller diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/AllTests.java b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/AllTests.java new file mode 100644 index 0000000..9033072 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/AllTests.java @@ -0,0 +1,17 @@ +package org.jalgo.tests.ebnf.junit.controller.wordalgorithm; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite = new TestSuite( + "Test for org.jalgo.tests.ebnf.junit.model.ebnf"); + //$JUnit-BEGIN$ + suite.addTestSuite(WordAlgorithmControllerTest.class); + //$JUnit-END$ + return suite; + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..aa439dd --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Entries @@ -0,0 +1,2 @@ +/AllTests.java/1.1/Fri Aug 11 16:37:22 2006// +/WordAlgorithmControllerTest.java/1.1/Fri Aug 11 16:37:22 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..f7455fc --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/WordAlgorithmControllerTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/WordAlgorithmControllerTest.java new file mode 100644 index 0000000..b9fc6f6 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/controller/wordalgorithm/WordAlgorithmControllerTest.java @@ -0,0 +1,648 @@ +package org.jalgo.tests.ebnf.junit.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.WordAlgorithmController; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystemLibrary; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +import junit.framework.TestCase; + +public class WordAlgorithmControllerTest extends TestCase { + + //FIXME + private static String EXPL_BEFORE_START = Messages.getString("ebnf", + "WordAlgo.Explanation_BeforeStart"); + private static String EXPL_ALGORITHM_START = Messages.getString("ebnf", + "WordAlgo.Explanation_AlgorithmStart"); + private static String EXPL_CONTINUEINDIAGRAM = Messages.getString("ebnf", + "WordAlgo.Explanation_ContinueDiagram"); + private static String EXPL_TERMINAL = Messages.getString("ebnf", + "WordAlgo.Explanation_Terminal"); + private static String EXPL_VARIABLE = Messages.getString("ebnf", + "WordAlgo.Explanation_Variable"); + private static String EXPL_JUMPTODIAGRAM = Messages.getString("ebnf", + "WordAlgo.Explanation_JumpToDiagram"); + private static String EXPL_LEAVEDIAGRAMM_WITHADRESS = Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramWithAdress"); + private static String EXPL_RETURNTODIAGRAM = Messages.getString("ebnf", + "WordAlgo.Explanation_ReturnToDiagram"); + + private static String WARNING_TERMINAL = Messages.getString("ebnf", + "WordAlgo.Warning_Terminal"); + private static String WARNING_JUMPTODIAGRAM = Messages.getString("ebnf", + "WordAlgo.Warning_JumpToDiagram"); + + SynDiaSystem synDiaSystem1; + + SynDiaSystem synDiaSystem2; + + SyntaxDiagram diaS; + + SyntaxDiagram diaA; + + WordAlgoModel myModel; + + WordAlgorithmController myController; + + Repetition rep1; + + TerminalSymbol terminalCinS; + + Variable varAinS; + + Branch bra1; + + TerminalSymbol terminalAinAleft; + + TerminalSymbol terminalBinA; + + Variable varAinA; + + TerminalSymbol terminalAinAright; + + protected void setUp() { + // synDiaSystem1: + // S :== {c}A + // A :== (aAb|a) + synDiaSystem1 = SynDiaSystemLibrary.getSynDiaSystem1(); + synDiaSystem1.removeNullElems(); + + // Getting references to all SynDiaElems in System1 + // DiagramS: + diaS = null; + // DiagramA: + diaA = null; + try { + diaS = synDiaSystem1.getSyntaxDiagram("S"); + diaA = synDiaSystem1.getSyntaxDiagram("A"); + } catch (Exception e) { + System.out.println("Exception thrown: " + e.toString()); + } + // DiagramS: + rep1 = (Repetition) diaS.getRoot().getSynDiaElem(0); + terminalCinS = (TerminalSymbol) rep1.getRight().getSynDiaElem(0); + varAinS = (Variable) diaS.getRoot().getSynDiaElem(1); + // DiagramA: + bra1 = (Branch) diaA.getRoot().getSynDiaElem(0); + terminalAinAleft = (TerminalSymbol) bra1.getLeft().getSynDiaElem(0); + terminalBinA = (TerminalSymbol) bra1.getLeft().getSynDiaElem(2); + varAinA = (Variable) bra1.getLeft().getSynDiaElem(1); + terminalAinAright = (TerminalSymbol) bra1.getRight().getSynDiaElem(0); + + try { + myModel = new WordAlgoModel(synDiaSystem1); + myController = new WordAlgorithmController(null, null, + synDiaSystem1); + } catch (Exception e) { + System.out.println(e.toString()); + } + } + + public void testActionsWithDiagram1() { + System.out + .println("Begin WordAlgorithmController Test **********************************"); + + // Check if each Variable got an different AdressNumber + assertTrue(myController.getAdressNumber(varAinS) != null); + assertTrue(myController.getAdressNumber(varAinA) != null); + assertTrue(myController.getAdressNumber(varAinA) != myController + .getAdressNumber(varAinS)); + + // Test if all Informations are correct before starting algorithm. + assertEquals("", myController.getWord()); + assertEquals("", myController.getOutput()); + assertEquals(EXPL_BEFORE_START, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaS.getRoot() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Set word to cccaaabb + myController.setWord("cccaaabb"); + assertEquals("cccaaabb", myController.getWord()); + + // Start Algorithm + myController.startAlgorithm(); + assertTrue("".equals(myController.getOutput())); + assertEquals(EXPL_ALGORITHM_START + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1 == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram S + myController.gotoVariable(varAinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo Click on Var A + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("cc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("cccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals( + WARNING_TERMINAL, myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo Click on c in S + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Redo Click on c in S + try { + myController.redo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("cccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals(WARNING_TERMINAL, myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo Click on c in S + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on a in A + // Model will not change because a in A in unreachable! + myController.gotoTerminal(terminalAinAleft); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram S + myController.gotoVariable(varAinS); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Return to A in Diagram S + // Model will not change because S was not already left. + myController.returnToDiagram(varAinS); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // JumpToDiagram S + // The model will warn + myController.jumpToDiagram(diaS); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals(WARNING_JUMPTODIAGRAM, + myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // JumpToDiagramA + myController.jumpToDiagram(diaA); + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_JUMPTODIAGRAM, myController.getExplanation()); + assertEquals("", myController.getWarning()); + System.out.println("Actual position: " + myController.getPosition()); + assertTrue(diaA.getRoot().getSynDiaElem(0) == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on a in Diagram A right part of Branch + myController.gotoTerminal(terminalAinAright); + // Check results + assertTrue("ccca".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_LEAVEDIAGRAMM_WITHADRESS, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(bra1 == myController.getPosition()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo click on a in Diagram A right part of Branch + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("ccc".equals(myController.getOutput())); + assertEquals(EXPL_JUMPTODIAGRAM, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaA.getRoot().getSynDiaElem(0) == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on a in Diagram A left part of Branch + myController.gotoTerminal(terminalAinAleft); + // Check results + assertTrue("ccca".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinA == myController.getPosition()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram A + myController.gotoVariable(varAinA); + // Check results + assertTrue("ccca".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinA == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // JumpToDiagramA + myController.jumpToDiagram(diaA); + // Check results + assertTrue("ccca".equals(myController.getOutput())); + assertEquals(EXPL_JUMPTODIAGRAM, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaA.getRoot().getSynDiaElem(0) == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on a in Diagram A left part of Branch + myController.gotoTerminal(terminalAinAleft); + // Check results + assertTrue("cccaa".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL+ "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinA == myController.getPosition()); + assertTrue("[1, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram A + myController.gotoVariable(varAinA); + // Check results + assertTrue("cccaa".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinA == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1, 2, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // JumpToDiagramA + myController.jumpToDiagram(diaA); + // Check results + assertTrue("cccaa".equals(myController.getOutput())); + assertEquals(EXPL_JUMPTODIAGRAM, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaA.getRoot().getSynDiaElem(0) == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1, 2, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on a in Diagram A right part of Branch + myController.gotoTerminal(terminalAinAright); + // Check results + assertTrue("cccaaa".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_LEAVEDIAGRAMM_WITHADRESS, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(bra1 == myController.getPosition()); + assertTrue("[1, 2, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Return to diagram A + myController.returnToDiagram(varAinA); + // Check results + assertTrue("cccaaa".equals(myController.getOutput())); + assertEquals(EXPL_RETURNTODIAGRAM + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(terminalBinA == myController.getPosition()); + assertTrue("[1, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on b in Diagram A + myController.gotoTerminal(terminalBinA); + // Check results + assertTrue("cccaaab".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_LEAVEDIAGRAMM_WITHADRESS, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(bra1 == myController.getPosition()); + assertTrue("[1, 2]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Return to diagram A + myController.returnToDiagram(varAinA); + // Check results + assertTrue("cccaaab".equals(myController.getOutput())); + assertEquals(EXPL_RETURNTODIAGRAM + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(terminalBinA == myController.getPosition()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on b in Diagram A + myController.gotoTerminal(terminalBinA); + // Check results + assertTrue("cccaaabb".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_LEAVEDIAGRAMM_WITHADRESS, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(bra1 == myController.getPosition()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Return to diagram S + myController.returnToDiagram(varAinS); + // Check results + assertTrue("cccaaabb".equals(myController.getOutput())); + assertEquals(EXPL_RETURNTODIAGRAM, + myController.getExplanation()); + //assertEquals(EXPL_LEAVEDIAGRAMM_FINISHWITHSUCCESS, myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + System.out + .println("End WordAlgorithmController Test ************************************"); + } + + public void testReset() { + System.out + .println("Begin WordAlgorithmControllerReset Test ************************************"); + // Start Algorithm + myController.startAlgorithm(); + assertTrue("".equals(myController.getOutput())); + assertEquals(EXPL_ALGORITHM_START + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaS.getRoot().getSynDiaElem(0) == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram S + myController.gotoVariable(varAinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo Click on Var A + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Reset algorithm + // The test perform the same Actions again. + // That must work! + try { + myController.resetAlgorithm(); + } catch (Exception e) { + + } + // Test if all Informations are correct before starting algorithm. + assertEquals("", myController.getWord()); + assertEquals("", myController.getOutput()); + assertEquals(EXPL_BEFORE_START, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaS.getRoot() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Start Algorithm + myController.startAlgorithm(); + assertTrue("".equals(myController.getOutput())); + assertEquals(EXPL_ALGORITHM_START + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(diaS.getRoot().getSynDiaElem(0) == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on c in Diagram S + myController.gotoTerminal(terminalCinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Click on A in Diagram S + myController.gotoVariable(varAinS); + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_VARIABLE, myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(varAinS == myController.getPosition()); + System.out.println(myController.getAdressNumbersFromStack()); + assertTrue("[1]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + // Undo Click on Var A + try { + myController.undo(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + // Check results + assertTrue("c".equals(myController.getOutput())); + assertEquals(EXPL_TERMINAL + "\n" + EXPL_CONTINUEINDIAGRAM, + myController.getExplanation()); + assertEquals("", myController.getWarning()); + assertTrue(rep1.getLeft() == myController.getPosition()); + assertTrue("[]".equals(myController.getAdressNumbersFromStack() + .toString())); + printStatus(); + + System.out + .println("End WordAlgorithmControllerReset Test ************************************"); + } + + private void printStatus() { +// System.out.println(); +// System.out.println("Word: " + myController.getWord()); +// System.out.println("Output: " + myController.getOutput()); +// System.out.println("Explanation : " + myController.getExplanation()); +// System.out.println("Warning: " + myController.getWarning()); +// System.out.println("Position: " + myController.getPosition()); +// System.out.println("Vars on Stack:" +// + myController.getAdressNumbersFromStack().toString()); +// System.out.println(); + } +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Entries new file mode 100644 index 0000000..41fc04c --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Entries @@ -0,0 +1,2 @@ +D/ebnf//// +D/wordalgorithm//// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Repository new file mode 100644 index 0000000..28ea1e4 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/model diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/AllTests.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/AllTests.java new file mode 100644 index 0000000..d2ee23f --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/AllTests.java @@ -0,0 +1,22 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite = new TestSuite( + "Test for org.jalgo.tests.ebnf.junit.model.ebnf"); + //$JUnit-BEGIN$ + suite.addTestSuite(RuleTest.class); + suite.addTestSuite(EOptionTest.class); + suite.addTestSuite(ERepetitionTest.class); + suite.addTestSuite(EVariableTest.class); + suite.addTestSuite(ETerminalSymbolTest.class); + suite.addTestSuite(EAlternativeTest.class); + //$JUnit-END$ + return suite; + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Entries new file mode 100644 index 0000000..dac8cba --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Entries @@ -0,0 +1,9 @@ +/AllTests.java/1.1/Fri Aug 11 16:37:21 2006// +/DefinitionLibrary.java/1.1/Fri Aug 11 16:37:21 2006// +/DefinitionTest.java/1.1/Fri Aug 11 16:37:21 2006// +/EAlternativeTest.java/1.1/Fri Aug 11 16:37:21 2006// +/EOptionTest.java/1.1/Fri Aug 11 16:37:21 2006// +/ERepetitionTest.java/1.1/Fri Aug 11 16:37:21 2006// +/ETerminalSymbolTest.java/1.1/Fri Aug 11 16:37:21 2006// +/EVariableTest.java/1.1/Fri Aug 11 16:37:21 2006// +/RuleTest.java/1.1/Fri Aug 11 16:37:21 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Repository new file mode 100644 index 0000000..77a158c --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/DefinitionLibrary.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/DefinitionLibrary.java new file mode 100644 index 0000000..666e608 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/DefinitionLibrary.java @@ -0,0 +1,235 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.*; + +/** + * This is a class that contains some static functions that return some EBNF + * definitions. Its purpose is to simplify the testing of the EBNF definition + * + * @author jm + * + */ +public class DefinitionLibrary { + + + static EVariable v1 = null; + static EVariable v2 = null; + static EVariable v4 = null; + static EVariable v5 = null; + static EVariable v6 = null; + static EVariable v7 = null; + static EVariable v8 = null; + static EVariable v10 = null; + static EVariable v9 = null; + static EVariable v3 = null; + + static ETerminalSymbol s1 = null; + static ETerminalSymbol s2 = null; + static ETerminalSymbol s3 = null; + static ETerminalSymbol s4 = null; + static ETerminalSymbol s5 = null; + static ETerminalSymbol s6 = null; + static ETerminalSymbol s7 = null; + static ETerminalSymbol s8 = null; + static ETerminalSymbol s9 = null; + static ETerminalSymbol s10 = null; + + static Term t1 = null; + static Term t2 = null; + static Term t3 = null; + static Term t4 = null; + static Term t5 = null; + static Term t6 = null; + static Term t7 = null; + static Term t8 = null; + static Term t9 = null; + static Term t10 = null; + + static Definition d1 = null; + static Definition d2 = null; + static Definition d3 = null; + static Definition d4 = null; + static Definition d5 = null; + static Definition d6 = null; + static Definition d7 = null; + static Definition d8 = null; + static Definition d9 = null; + static Definition d10 = null; + + // a list that contains the rules + private static java.util.List definitions + = new java.util.ArrayList(); + + // a list that contains the terms + private static java.util.List terms = new java.util.ArrayList(); + + // a list that contains the rules + private static java.util.List rules = new java.util.ArrayList(); + + + + private DefinitionLibrary() { + } + + public static void setUp() { + + setUpSymbols(); + setUpTerms(); + setUpRules(); + setUpDefinitions(); + } + + private static void setUpSymbols() { + try { + v1 = new EVariable("v1"); + v2 = new EVariable("v2"); + v3 = new EVariable("v3"); + v4 = new EVariable("v4"); + v5 = new EVariable("v5"); + v6 = new EVariable("v6"); + v7 = new EVariable("v7"); + v8 = new EVariable("v8"); + v9 = new EVariable("v9"); + v10 = new EVariable("v10"); + } catch (DefinitionFormatException e) { + // there should be no errors here :-) + System.out.println("ANFANG Fehler beim hinzufügen von Variablen!"); + e.printStackTrace(); + System.out.println("ENDE Fehler beim hinzufügen von Variablen!"); + } + + try { + s1 = new ETerminalSymbol("t1"); + s2 = new ETerminalSymbol("t2"); + s3 = new ETerminalSymbol("t3"); + s4 = new ETerminalSymbol("t4"); + s5 = new ETerminalSymbol("t5"); + s6 = new ETerminalSymbol("t6"); + s7 = new ETerminalSymbol("t7"); + s8 = new ETerminalSymbol("t8"); + s9 = new ETerminalSymbol("t9"); + s10 = new ETerminalSymbol("t10"); + } catch (DefinitionFormatException e) { + // there should be no errors here :-) + e.printStackTrace(); + } + } + + private static void setUpTerms() { + // a temporary list + java.util.List tlist = new java.util.ArrayList(); + + // creating some symbols + + + + // creating some funny looking terms :-) + try { + + // TERM 1 BEGIN ---------------------------------------------------- + t1 = new EAlternative(v1,v2); + tlist.clear(); + tlist.add(s1); + tlist.add(s2); + tlist.add(s3); + tlist.add(s4); + t2 = new EAlternative(tlist); + t3 = new EAlternative(t1,t2); + + terms.add(t3); + // ----------------------------------------------------------------- + // ((v1|v2)|(t1|t2|t3|t4)) + // TERM 1 END ------------------------------------------------------ + + // TERM 2 BEGIN ---------------------------------------------------- + tlist.clear(); + tlist.add(new ERepetition(s3)); + tlist.add(v1); + t1 = new EConcatenation(tlist); + + terms.add(t1); + // ----------------------------------------------------------------- + // Skript Seite 149: {s3}v1 + // TERM 2 END ------------------------------------------------------ + + // TERM 3 BEGIN ---------------------------------------------------- + + tlist.clear(); + tlist.add(s1); + tlist.add(v1); + tlist.add(s2); + + t1 = new EConcatenation(tlist); + t2 = new ECompoundTerm(t1); + t3 = new EAlternative(t2, v1); + + terms.add(t3); + // ----------------------------------------------------------------- + // Skript Seite 149: ((s1v1s2)|s1) + // TERM 3 END ------------------------------------------------------ + + } catch (DefinitionFormatException e) { + // there should be no errors here :-) + e.printStackTrace(); + } + } + + private static void setUpRules() { + // set up rules -------------------------------------------------------- + try { + rules.add(new Rule(v1, getTerm(0))); + rules.add(new Rule(v2, getTerm(1))); + rules.add(new Rule(v1, getTerm(2))); + } catch (DefinitionFormatException e) { + // there should be no errors here :-) + e.printStackTrace(); + } + // --------------------------------------------------------------------- + } + + private static void setUpDefinitions() { + d1 = new Definition(); + try { + d1.addTerminal(s1); + d1.addTerminal(s2); + d1.addTerminal(s3); + d1.addVariable(v1); + d1.addVariable(v2); + + d1.addRule(rules.get(1)); + d1.addRule(rules.get(2)); + + d1.setStartVariable(v2); + + } catch (DefinitionFormatException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + definitions.add(d1); + + } + + public static Definition getDefinition(int i) { + + if(i>=0 && i=0 && i=0 && i terms = new java.util.ArrayList(); + v1 = new EVariable("var1"); + v2 = new EVariable("var2"); + t1 = new ETerminalSymbol("term1"); + t2 = new ETerminalSymbol("term2"); + o1 = new EOption(v1); + r1 = new ERepetition(t2); + + a1 = new EAlternative(v1,t1); + terms.clear(); + terms.add(v2); + terms.add(t2); + terms.add(t2); + a2 = new EAlternative(terms); + terms.clear(); + terms.add(v2); + terms.add(v1); + terms.add(t1); + terms.add(o1); + a3 = new EAlternative(terms); + terms.clear(); + terms.add(t1); + terms.add(r1); + a4 = new EAlternative(terms); + terms.clear(); + terms.add(o1); + terms.add(r1); + terms.add(a2); + a5 = new EAlternative(terms); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.isStrict()' + */ + public void testIsStrict() { + assertTrue(a1.isStrict()); + assertFalse(a2.isStrict()); + assertFalse(a3.isStrict()); + assertTrue(a4.isStrict()); + assertFalse(a5.isStrict()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.getStrict()' + */ + public void testGetStrict() { + // now here have to test if getStrict *really* works for the first time + + // now a1 should be strict already + try { + assertEquals(a1.getStrict().getTerms().get(0),a1.getTerms().get(0)); + assertEquals(a1.getStrict().getTerms().get(1),a1.getTerms().get(1)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + // a2 (v2, t2, t2) isn't strict at the moment - so there should be a structure change + try { + assertEquals("(var2|(term2|term2))",a2.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + // same thing here with a3 (v2,v1,t1,o1(v1)) + try { + assertEquals("(var2|(var1|(term1|[var1])))",a3.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + // and a4 is already binary + try { + assertEquals(a4.toString(),a4.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + +// same thing here with a5 (o1(v1), r(t2), a2(v2, t2, t2)) + try { + assertEquals("([var1]|({term2}|(var2|(term2|term2))))",a5.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.contains(ESymbol)' + */ + public void testContains() { + assertTrue(a1.contains(v1)); + assertTrue(a2.contains(v2)); + assertTrue(a5.contains(v1)); + assertTrue(a5.contains(a2)); + assertFalse(a1.contains(v2)); + assertFalse(a3.contains(t2)); + assertFalse(a5.contains(a1)); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.EAlternative(Term)' + */ + public void testEAlternative() { + java.util.List terms = new java.util.ArrayList(); + // Constructor with valid names + try { + new EAlternative(v1,v2); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + new EAlternative(o1,a2); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + +// Constructor with invalid names + try { + new EAlternative(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + terms.clear(); + terms.add(v1); + try { + new EAlternative(terms); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + terms.clear(); + terms.add(null); + terms.add(null); + terms.add(null); + try { + new EAlternative(terms); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.addTerm(Term)' + */ + public void testAddTerm() { + EAlternative a6 = null; + + // try to get new EAlternative + try { + a6 = new EAlternative(t1,t2); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + +// try to add correct terms + try { + a6.addTerm(v1); + if (!a6.contains(v1)) fail("Should contain v1"); + } catch (DefinitionFormatException expected) { + fail("unexpected throws Exception"); + } + + //try to set the term to null + try { + a6.addTerm(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } +// try to set the term to itself + try { + a6.addTerm(a6); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.toString()' + */ + public void testToString() { + + assertEquals("(var1|term1)", a1.toString()); + assertEquals("(var2|term2|term2)", a2.toString()); + assertEquals("(var2|var1|term1|[var1])", a3.toString()); + assertEquals("(term1|{term2})", a4.toString()); + assertEquals("([var1]|{term2}|(var2|term2|term2))", a5.toString()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EAlternative.getTerms()' + */ + public void testGetTerms() { + //Check for various list contents if they are equal to the terms got from the function + java.util.List returnList = new java.util.ArrayList(); + returnList.clear(); + returnList.add(v1); + returnList.add(t1); + assertEquals(returnList, a1.getTerms()); + returnList.clear(); + returnList.add(v2); + returnList.add(t2); + returnList.add(t2); + assertEquals(returnList, a2.getTerms()); + returnList.clear(); + returnList.add(v2); + returnList.add(v1); + returnList.add(t1); + assertNotSame(returnList, a3.getTerms()); + returnList.add(o1); + assertEquals(returnList, a3.getTerms()); + returnList.clear(); + returnList.add(a1); + returnList.add(o1); + returnList.add(r1); + assertNotSame(returnList, a5.getTerms()); + returnList.clear(); + returnList.add(o1); + returnList.add(r1); + returnList.add(a2); + assertEquals(returnList, a5.getTerms()); + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EOptionTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EOptionTest.java new file mode 100644 index 0000000..10a5451 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EOptionTest.java @@ -0,0 +1,167 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.*; + +import junit.framework.TestCase; + +/** + * + * @author Johannes, Tom + * + */public class EOptionTest extends TestCase { + + Term t1, t2, t3, t4; + + EOption o1, o2, o3, o4, o5; + + protected void setUp() throws Exception { + t1 = new EVariable("var1"); + t2 = new EVariable("var2"); + t3 = new ETerminalSymbol("term1"); + t4 = new ETerminalSymbol("term2"); + + o1 = new EOption(t1); + o2 = new EOption(t2); + o3 = new EOption(t3); + o4 = new EOption(t4); + o5 = new EOption(o1); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.isStrict()' + */ + public void testIsStrict() { + assertEquals(t1.isStrict(),o1.isStrict()); + assertEquals(t2.isStrict(),o2.isStrict()); + assertEquals(t3.isStrict(),o3.isStrict()); + assertEquals(t4.isStrict(),o4.isStrict()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.getStrict()' + */ + public void testGetStrict() { + // since the terms are only variable and terminal symbols, the strict + // term must contain the same term as the original one. + + try { + assertEquals(o1.getStrict().getTerms().get(0),o1.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(o2.getStrict().getTerms().get(0),o2.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(o3.getStrict().getTerms().get(0),o3.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(o4.getStrict().getTerms().get(0),o4.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + // this is tricky, because the the Lists are not equal, only the + // contianed terminals + try { + assertEquals(o5.getStrict().getTerms().get(0) + .getTerms().get(0),o5.getTerms().get(0).getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.contains(ESymbol)' + */ + public void testContains() { + assertTrue(o1.contains(t1)); + assertTrue(o2.contains(t2)); + assertTrue(o5.contains(t1)); + assertTrue(o5.contains(o1)); + assertFalse(o1.contains(t2)); + assertFalse(o3.contains(t4)); + assertFalse(o5.contains(o2)); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.EOption(Term)' + */ + public void testEOption() { + // Constructor with invalid names + try { + new EOption(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.setTerm(Term)' + */ + public void testSetTerm() { +// try to set the term to the Option itself + try { + o1.setTerm(o1); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + //try to set the term to null + try { + o2.setTerm(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.toString()' + */ + public void testToString() { + + assertEquals("[var1]", o1.toString()); + assertEquals("[var2]", o2.toString()); + assertEquals("[term1]", o3.toString()); + assertEquals("[term2]", o4.toString()); + assertEquals("[[var1]]", o5.toString()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.getTerm()' + */ + public void testGetTerm() { + assertEquals(t1, o1.getTerm()); + assertEquals(t2, o2.getTerm()); + assertEquals(t2, o2.getTerm()); + assertEquals(o1, o5.getTerm()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.EOption.getTerms()' + */ + public void testGetTerms() { + java.util.List returnList = new java.util.ArrayList(); + returnList.add(t1); + assertEquals(returnList, o1.getTerms()); + returnList.clear(); + returnList.add(t2); + assertEquals(returnList, o2.getTerms()); + returnList.clear(); + returnList.add(t3); + assertEquals(returnList, o3.getTerms()); + returnList.clear(); + returnList.add(o1); + assertEquals(returnList, o5.getTerms()); + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ERepetitionTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ERepetitionTest.java new file mode 100644 index 0000000..ae899c3 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ERepetitionTest.java @@ -0,0 +1,172 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import junit.framework.TestCase; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ERepetition; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.model.ebnf.Term; + +/** + * + * @author Johannes, Tom + * + */public class ERepetitionTest extends TestCase { + + + Term v1, v2, t1, t2; + + ERepetition r1, r2, r3, r4, r5; + + protected void setUp() throws Exception { + v1 = new EVariable("var1"); + v2 = new EVariable("var2"); + t1 = new ETerminalSymbol("term1"); + t2 = new ETerminalSymbol("term2"); + + r1 = new ERepetition(v1); + r2 = new ERepetition(v2); + r3 = new ERepetition(t1); + r4 = new ERepetition(t2); + r5 = new ERepetition(r1); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.isStrict()' + */ + public void testIsStrict() { + assertEquals(v1.isStrict(),r1.isStrict()); + assertEquals(v2.isStrict(),r2.isStrict()); + assertEquals(t1.isStrict(),r3.isStrict()); + assertEquals(t2.isStrict(),r4.isStrict()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.getStrict()' + */ + public void testGetStrict() { + // since the terms are only variable and terminal symbols, the strict + // term must contain the same term as the original one. + + try { + assertEquals(r1.getStrict().getTerms().get(0),r1.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(r2.getStrict().getTerms().get(0),r2.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(r3.getStrict().getTerms().get(0),r3.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + try { + assertEquals(r4.getStrict().getTerms().get(0),r4.getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + // this is tricky, because the the Lists are not equal, only the + // contianed terminals + try { + assertEquals(r5.getStrict().getTerms().get(0) + .getTerms().get(0),r5.getTerms().get(0).getTerms().get(0)); + } catch (DefinitionFormatException e) { + fail("unexpected throws Exception"); + } + + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.contains(ESymbol)' + */ + public void testContains() { + assertTrue(r1.contains(v1)); + assertTrue(r2.contains(v2)); + assertTrue(r5.contains(v1)); + assertTrue(r5.contains(r1)); + assertFalse(r1.contains(v2)); + assertFalse(r3.contains(t2)); + assertFalse(r5.contains(r2)); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.ERepetition(Term)' + */ + public void testERepetition() { + // Constructor with invalid names + try { + new ERepetition(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.setTerm(Term)' + */ + public void testSetTerm() { +// try to set the term to the Option itself + try { + r1.setTerm(r1); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + //try to set the term to null + try { + r2.setTerm(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.toString()' + */ + public void testToString() { + + assertEquals("{var1}", r1.toString()); + assertEquals("{var2}", r2.toString()); + assertEquals("{term1}", r3.toString()); + assertEquals("{term2}", r4.toString()); + assertEquals("{{var1}}", r5.toString()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.getTerm()' + */ + public void testGetTerm() { + assertEquals(v1, r1.getTerm()); + assertEquals(v2, r2.getTerm()); + assertEquals(v2, r2.getTerm()); + assertEquals(r1, r5.getTerm()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.ERepetition.getTerms()' + */ + public void testGetTerms() { + java.util.List returnList = new java.util.ArrayList(); + returnList.add(v1); + assertEquals(returnList, r1.getTerms()); + returnList.clear(); + returnList.add(v2); + assertEquals(returnList, r2.getTerms()); + returnList.clear(); + returnList.add(t1); + assertEquals(returnList, r3.getTerms()); + returnList.clear(); + returnList.add(r1); + assertEquals(returnList, r5.getTerms()); + } + + } diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ETerminalSymbolTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ETerminalSymbolTest.java new file mode 100644 index 0000000..d02ce78 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/ETerminalSymbolTest.java @@ -0,0 +1,159 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import junit.framework.TestCase; + +public class ETerminalSymbolTest extends TestCase { + + ETerminalSymbol t1, t2, t3, t4, t5, t6; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + + t1 = new ETerminalSymbol("a"); + t2 = new ETerminalSymbol("IchBinEinTerminalsymbol"); + t3 = new ETerminalSymbol("Ich auch"); + t4 = new ETerminalSymbol(" x"); + t5 = new ETerminalSymbol("!!!!!!"); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testIsStrict() { + + assertTrue(t1.isStrict()); + assertTrue(t2.isStrict()); + assertTrue(t3.isStrict()); + assertTrue(t4.isStrict()); + assertTrue(t5.isStrict()); + + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testGetStrict() { + + assertEquals(t1,t1.getStrict()); + assertEquals(t2,t2.getStrict()); + assertEquals(t3,t3.getStrict()); + assertEquals(t4,t4.getStrict()); + assertEquals(t5,t5.getStrict()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testContains() { + + assertTrue(t1.contains(t1)); + assertTrue(t2.contains(t2)); + assertTrue(t3.contains(t3)); + assertFalse(t4.contains(t3)); + assertFalse(t5.contains(t1)); + assertFalse(t1.contains(t6)); + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.toString()' + */ + public void testToString() { + + assertEquals("a", t1.toString()); + assertEquals("IchBinEinTerminalsymbol", t2.toString()); + assertEquals("Ich auch", t3.toString()); + assertEquals(" x", t4.toString()); + assertEquals("!!!!!!", t5.toString()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.toString()' + */ + + /* + * Test method for + * 'org.jalgo.module.ebnf.model.ebnf.Terminal.Terminal(String)' + */ + public void testTerminal() { + + // Constructor with valid names + assertEquals("a", t1.toString()); + assertEquals("IchBinEinTerminalsymbol", t2.toString()); + assertEquals("Ich auch", t3.toString()); + assertEquals(" x", t4.toString()); + assertEquals("!!!!!!", t5.toString()); + + // Constructor with invalid names + try { + new ETerminalSymbol(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + new ETerminalSymbol(""); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + new ETerminalSymbol(" "); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for + * 'org.jalgo.module.ebnf.model.ebnf.Terminal.setName(String)' + */ + public void testSetName() { + + try { + t1.setName("another name"); + } catch (DefinitionFormatException unexpected) { + fail("unexpected throws Exception"); + } + + assertEquals("another name", t1.getName()); + + // Constructor with invalid names + try { + t3.setName(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + t4.setName(""); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + t5.setName(" "); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + t5.setName(" "); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EVariableTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EVariableTest.java new file mode 100644 index 0000000..a3b1bdb --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/EVariableTest.java @@ -0,0 +1,153 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import junit.framework.TestCase; + +public class EVariableTest extends TestCase { + + EVariable v1, v2, v3, v4, v5, v6; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + + v1 = new EVariable("a"); + v2 = new EVariable("IchBinEinTerminalsymbol"); + v3 = new EVariable("Ich auch"); + v4 = new EVariable(" x"); + v5 = new EVariable("!!!!!!"); + v6 = new EVariable("a"); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testIsStrict() { + + assertTrue(v1.isStrict()); + assertTrue(v2.isStrict()); + assertTrue(v3.isStrict()); + assertTrue(v4.isStrict()); + assertTrue(v5.isStrict()); + + } + + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testGetStrict() { + + assertEquals(v1,v1.getStrict()); + assertEquals(v2,v2.getStrict()); + assertEquals(v3,v3.getStrict()); + assertEquals(v4,v4.getStrict()); + assertEquals(v5,v5.getStrict()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.isStrict()' + */ + public void testContains() { + + assertTrue(v1.contains(v1)); + assertTrue(v2.contains(v2)); + assertTrue(v3.contains(v3)); + assertFalse(v4.contains(v3)); + assertFalse(v5.contains(v1)); + assertFalse(v1.contains(v6)); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.toString()' + */ + public void testToString() { + + assertEquals("a", v1.toString()); + assertEquals("IchBinEinTerminalsymbol", v2.toString()); + assertEquals("Ich auch", v3.toString()); + assertEquals(" x", v4.toString()); + assertEquals("!!!!!!", v5.toString()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Terminal.toString()' + */ + + /* + * Test method for + * 'org.jalgo.module.ebnf.model.ebnf.Terminal.Terminal(String)' + */ + public void testEVariable() { + + // Constructor with valid names + assertEquals("a", v1.toString()); + assertEquals("IchBinEinTerminalsymbol", v2.toString()); + assertEquals("Ich auch", v3.toString()); + assertEquals(" x", v4.toString()); + assertEquals("!!!!!!", v5.toString()); + + // Constructor with invalid names + try { + new EVariable(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + new EVariable(""); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + new EVariable(" "); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + + /* + * Test method for + * 'org.jalgo.module.ebnf.model.ebnf.Terminal.setName(String)' + */ + public void testSetName() { + + try { + v1.setName("another name"); + } catch (DefinitionFormatException unexpected) { + fail("unexpected throws Exception"); + } + + assertEquals("another name", v1.getName()); + + // Constructor with invalid names + try { + v3.setName(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + v4.setName(""); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + + try { + v5.setName(" "); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException expected) { + } + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/RuleTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/RuleTest.java new file mode 100644 index 0000000..ac8b820 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/ebnf/RuleTest.java @@ -0,0 +1,213 @@ +package org.jalgo.tests.ebnf.junit.model.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.*; + + +import junit.framework.TestCase; + +public class RuleTest extends TestCase { + + Term t1, t2, t3, t4, t5, t6, t7, t8; + Rule r1, r2, r3, r4, r5, r6, r7, r8; + EVariable v1, v2, v3, v4, v5, v6, v7, v8; + + protected void setUp() throws Exception { + + // create the variables + v1 = new EVariable("var1"); + v2 = new EVariable("var2"); + v3 = new EVariable("var3"); + v4 = new EVariable("var4"); + v5 = new EVariable("var5"); + v6 = new EVariable("var6"); + v7 = new EVariable("var7"); + v8 = new EVariable("var8"); + + + // create the terms + t1 = new ETerminalSymbol("term1"); + t2 = new EOption(t1); + t2 = new EOption(t2); + t3 = new EAlternative(t1,v1); + java.util.List list = new java.util.ArrayList(); + list.add(t1); + list.add(v1); + list.add(t2); + list.add(t3); + t4 = new EConcatenation(list); + t5 = new ERepetition(t3); + t6 = new EAlternative(list); + t7 = new EAlternative(t6,t3); + t8 = new EAlternative(t6,t7); + + r1 = new Rule(v1,t1); + r2 = new Rule(v2,t2); + r3 = new Rule(v3,t3); + r4 = new Rule(v4,t4); + r5 = new Rule(v5,t5); + r6 = new Rule(v6,t6); + r7 = new Rule(v7,t7); + r8 = new Rule(v8,t8); + + super.setUp(); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.Rule(EVariable, Term)' + */ + public void testRule() { + // create the rules + try { + r1 = new Rule(v1,t1); + r2 = new Rule(v2,t2); + r3 = new Rule(v3,t3); + r4 = new Rule(v4,t4); + r5 = new Rule(v5,t5); + } catch (DefinitionFormatException e) { + fail("creation of rules failed"); + } + + try { + r1 = new Rule(null, t1); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException e) { + + } + + try { + r1 = new Rule(v1, null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException e) { + + } + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.isStrict()' + */ + public void testIsStrict() { + assertTrue(r1.isStrict()); + assertTrue(r2.isStrict()); + assertTrue(r3.isStrict()); + assertTrue(r4.isStrict()); + assertTrue(r5.isStrict()); + + assertFalse(r6.isStrict()); + assertFalse(r7.isStrict()); + assertFalse(r8.isStrict()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.getStrict()' + */ + public void testGetStrict() { + // this should be the same as in the toString test + try { + assertEquals("var1 ::= term1", r1.getStrict().toString()); + assertEquals("var2 ::= [[term1]]",r2.getStrict().toString()); + assertEquals("var3 ::= (term1|var1)",r3.getStrict().toString()); + assertEquals("var4 ::= term1var1[[term1]](term1|var1)", + r4.getStrict().toString()); + assertEquals("var5 ::= {(term1|var1)}",r5.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unhandled DefinitionFormatException in Rule.getStrict"); + } + + try { + assertEquals("var6 ::= (term1|(var1|([[term1]]|(term1|var1))))", + r6.getStrict().toString()); + assertEquals("var7 ::= ((term1|(var1|([[term1]]|(term1|var1))))" + + "|(term1|var1))",r7.getStrict().toString()); + assertEquals("var8 ::= ((term1|(var1|([[term1]]|(term1|var1))))" + + "|((term1|(var1|([[term1]]|(term1|var1))))|(term1|var1)))" + ,r8.getStrict().toString()); + } catch (DefinitionFormatException e) { + fail("unhandled DefinitionFormatException in Rule.getStrict"); + } + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.toString()' + */ + public void testToString() { + assertEquals("var1 ::= term1", r1.toString()); + assertEquals("var2 ::= [[term1]]",r2.toString()); + assertEquals("var3 ::= (term1|var1)",r3.toString()); + assertEquals("var4 ::= term1var1[[term1]](term1|var1)",r4.toString()); + assertEquals("var5 ::= {(term1|var1)}",r5.toString()); + assertEquals("var6 ::= (term1|var1|[[term1]]|(term1|var1))", + r6.toString()); + assertEquals("var7 ::= ((term1|var1|[[term1]]|(term1|var1))" + + "|(term1|var1))",r7.toString()); + assertEquals("var8 ::= ((term1|var1|[[term1]]|(term1|var1))" + + "|((term1|var1|[[term1]]|(term1|var1))|(term1|var1)))" + ,r8.toString()); + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.getName()' + */ + public void testGetName() { + assertEquals(v1,r1.getName()); + assertEquals(v2,r2.getName()); + assertEquals(v3,r3.getName()); + assertEquals(v4,r4.getName()); + assertEquals(v5,r5.getName()); + + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.setName(EVariable)' + */ + public void testSetName() { + try { + r1.setName(v2); + } catch (DefinitionFormatException e) { + fail("unhandled DefinitionFormatException in Rule.setName"); + } + assertEquals(v2,r1.getName()); + + try { + r1.setName(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException e) { + + } + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.getTerm()' + */ + public void testGetTerm() { + assertEquals(t1, r1.getTerm()); + assertEquals(t2, r2.getTerm()); + assertEquals(t3, r3.getTerm()); + assertEquals(t4, r4.getTerm()); + assertEquals(t5, r5.getTerm()); + + } + + /* + * Test method for 'org.jalgo.module.ebnf.model.ebnf.Rule.setTerm(Term)' + */ + public void testSetTerm() { + try { + r1.setTerm(t2); + } catch (DefinitionFormatException e) { + fail("unhandled DefinitionFormatException in Rule.setName"); + } + assertEquals(t2,r1.getTerm()); + + try { + r1.setTerm(null); + fail("Should have raised an DefinitionFormatException"); + } catch (DefinitionFormatException e) { + + } + + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/AllTests.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/AllTests.java new file mode 100644 index 0000000..ac6866c --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/AllTests.java @@ -0,0 +1,17 @@ +package org.jalgo.tests.ebnf.junit.model.wordalgorithm; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite = new TestSuite( + "Test for org.jalgo.tests.ebnf.junit.model.wordalgorithm"); + //$JUnit-BEGIN$ + suite.addTestSuite(WordAlgoModelTest.class); + //$JUnit-END$ + return suite; + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..b0b4c0c --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Entries @@ -0,0 +1,2 @@ +/AllTests.java/1.1/Fri Aug 11 16:37:23 2006// +/WordAlgoModelTest.java/1.1/Fri Aug 11 16:37:23 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..d3221d7 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/WordAlgoModelTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/WordAlgoModelTest.java new file mode 100644 index 0000000..b0b30e3 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/model/wordalgorithm/WordAlgoModelTest.java @@ -0,0 +1,94 @@ +package org.jalgo.tests.ebnf.junit.model.wordalgorithm; + +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystemLibrary; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import junit.framework.TestCase; + +public class WordAlgoModelTest extends TestCase { + + SynDiaSystem consistentSystem; + + SynDiaSystem inconsistentSystem; + + WordAlgoModel myModel; + + protected void setUp() { + consistentSystem = SynDiaSystemLibrary.getSynDiaSystem2(); + inconsistentSystem = new SynDiaSystem(); + try { + System.out.println(consistentSystem.getStartDiagram()); + myModel = new WordAlgoModel(consistentSystem); + } catch (Exception e) { + System.out.println(e.toString()); + } + } + + public void testConsistenceFailure() { + boolean initializationFailed = false; + try { + @SuppressWarnings("unused") WordAlgoModel newModel = new WordAlgoModel(inconsistentSystem); + } + catch (Exception e) { + initializationFailed = true; + } + assertTrue(initializationFailed); + } + + public void testIsAlgorithmRunning() { + assertFalse(myModel.isAlgorithmRunning()); + myModel.enableAlgorithmRunning(); + assertTrue(myModel.isAlgorithmRunning()); + myModel.disableAlgorithmRunning(); + assertFalse(myModel.isAlgorithmRunning()); + myModel.enableAlgorithmRunning(); + assertTrue(myModel.isAlgorithmRunning()); + try { + myModel.reset(); + assertFalse(myModel.isAlgorithmRunning()); + } + catch (Exception e) { + System.out.println(e); + } + } + + public void testIsWarningsOn() { + assertTrue(myModel.isWarningsOn()); + myModel.disableWarnings(); + assertFalse(myModel.isWarningsOn()); + try { + myModel.reset(); + assertTrue(myModel.isWarningsOn()); + } + catch (Exception e) { + System.out.println(e); + } + } + + public void testIsStackEmpty() { + assertTrue(myModel.isStackEmpty()); + myModel.pushToStack(new Variable(null, "a", null)); + assertFalse(myModel.isStackEmpty()); + myModel.pushToStack(new Variable(null, "a", null)); + assertFalse(myModel.isStackEmpty()); + myModel.popFromStack(); + assertFalse(myModel.isStackEmpty()); + myModel.popFromStack(); + assertTrue(myModel.isStackEmpty()); + myModel.pushToStack(new Variable(null, "a", null)); + try { + myModel.reset(); + assertTrue(myModel.isStackEmpty()); + } + catch (Exception e) { + System.out.println(e); + } + myModel.pushToStack(new Variable(null, "a", null)); + assertFalse(myModel.isStackEmpty()); + myModel.emptyStack(); + assertTrue(myModel.isStackEmpty()); + } + + // Getters and Setters are not tested +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/ActionStackTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/util/ActionStackTest.java new file mode 100644 index 0000000..291c984 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/ActionStackTest.java @@ -0,0 +1,226 @@ +package org.jalgo.tests.ebnf.junit.util; + +import org.jalgo.module.ebnf.util.ActionStack; +import org.jalgo.module.ebnf.util.IAction; + +import junit.framework.TestCase; + +public class ActionStackTest extends TestCase { + + ControllerTest myController; + + ActionStack myActionStack; + + IAction firstAction, secondAction, thirdAction, fourthAction, fifthAction; + + protected void setUp() { + /* A Controller used as a Model to perform some IActions */ + myController = new ControllerTest(); + + /* An ActionStack to check the work of the ActionStacks. */ + myActionStack = new ActionStack(myController); + + /* + * Create some Actions Because IAction is an Interface, there is an + * TestAction class in this package. + */ + firstAction = new IActionTest(myController, "performed 1", "undone 1"); + secondAction = new IActionTest(myController, "performed 2", "undone 2"); + thirdAction = new IActionTest(myController, "performed 3", "undone 3"); + fourthAction = new IActionTest(myController, "performed 4", "undone 4"); + fifthAction = new IActionTest(myController, "performed 5", "undone 5"); + + } + + protected void tearDown() { + myActionStack = null; + myController = null; + firstAction = null; + secondAction = null; + thirdAction = null; + fourthAction = null; + fifthAction = null; + } + + public void testIsUndoPossible() throws Exception { + try { + assertFalse(myActionStack.isUndoPossible()); + + myActionStack.perform(firstAction); + System.out.println(myController.myString); + /* Undo is now possible */ + assertTrue(myActionStack.isUndoPossible()); + + myActionStack.undo(); + System.out.println(myController.myString); + /* Undo is not possible any longer */ + assertFalse(myActionStack.isUndoPossible()); + /* Undo is now possible */ + + myActionStack.redo(); + System.out.println(myController.myString); + assertTrue(myActionStack.isUndoPossible()); + + System.out.println("testIsUndoPossbile finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } + } + + public void testIsRedoPossible() throws Exception { + try { + assertFalse(myActionStack.isRedoPossible()); + myActionStack.perform(firstAction); + assertFalse(myActionStack.isRedoPossible()); + myActionStack.undo(); + assertTrue(myActionStack.isRedoPossible()); + myActionStack.redo(); + assertFalse(myActionStack.isRedoPossible()); + + System.out.println("testIsRedoPossbile finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } +} + + public void testUndo() throws Exception { + try { + myActionStack.perform(firstAction); + myActionStack.perform(secondAction); + myActionStack.undo(); + assertEquals("undone 2", myController.myString); + myActionStack.perform(thirdAction); + myActionStack.undo(); + assertEquals("undone 3", myController.myString); + myActionStack.undo(); + assertEquals("undone 1", myController.myString); + + System.out.println("testUndo finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } +} + + public void testRedo() throws Exception { + try { + /* On RedoStack: { } */ + myActionStack.perform(firstAction); + myActionStack.undo(); + /* On RedoStack: { Action 1 } */ + + myActionStack.redo(); + assertEquals("performed 1", myController.myString); + myActionStack.perform(secondAction); + myActionStack.undo(); + /* On RedoStack: { Action 2 } */ + + myActionStack.undo(); + /* On RedoStack: { Action 1, Action 2 } */ + + myActionStack.redo(); + /* On RedoStack: { Action 2 } */ + assertEquals("performed 1", myController.myString); + + myActionStack.redo(); + /* On RedoStack: { } */ + assertEquals("performed 2", myController.myString); + + myActionStack.perform(thirdAction); + myActionStack.undo(); + /* On RedoStack: { Action 3 } */ + + myActionStack.undo(); + /* On RedoStack: { Action 2, Action 3 } */ + + myActionStack.redo(); + /* On RedoStack: { Action 3 } */ + assertEquals("performed 2", myController.myString); + + myActionStack.undo(); + /* On RedoStack: { Action2, Action 3 } */ + + myActionStack.perform(thirdAction); + /* On RedoStack: { } */ + + myActionStack.undo(); + /* On RedoStack: { Action 3 } */ + + myActionStack.undo(); + /* On RedoStack: { Action1, Action 3 } */ + + myActionStack.redo(); + /* On RedoStack: { Action 3 } */ + assertEquals("performed 1", myController.myString); + + myActionStack.redo(); + /* On RedoStack: { } */ + assertEquals("performed 3", myController.myString); + + System.out.println("testRedo finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } + } + + public void testPerform() throws Exception { + try { + myActionStack.perform(firstAction); + assertEquals("performed 1", myController.myString); + myActionStack.perform(secondAction); + assertEquals("performed 2", myController.myString); + myActionStack.perform(thirdAction); + assertEquals("performed 3", myController.myString); + myActionStack.perform(fourthAction); + assertEquals("performed 4", myController.myString); + myActionStack.perform(fifthAction); + assertEquals("performed 5", myController.myString); + + System.out.println("testPerform finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } + } + + public void testObservers() throws Exception { + try { + assertEquals(0, myController.observerTest); + myActionStack.perform(firstAction); + /* Undo is now possible */ + assertEquals(1, myController.observerTest); + myActionStack.perform(secondAction); + assertEquals(1, myController.observerTest); + myActionStack.perform(thirdAction); + assertEquals(1, myController.observerTest); + myActionStack.perform(fourthAction); + assertEquals(1, myController.observerTest); + myActionStack.undo(); + /* Redo is now possible */ + assertEquals(2, myController.observerTest); + myActionStack.redo(); + /* Redo is now not possible any longer */ + assertEquals(3, myController.observerTest); + myActionStack.undo(); + /* Redo is now possible */ + assertEquals(4, myController.observerTest); + myActionStack.perform(fifthAction); + /* Redo is now not possible any longer */ + assertEquals(5, myController.observerTest); + + System.out.println("testObservers finished."); + System.out.println(); + } + catch (Exception e) { + throw e; + } + } +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/AllTests.java b/relicts/org/jalgo/tests/modules/ebnf/junit/util/AllTests.java new file mode 100644 index 0000000..ebd956b --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/AllTests.java @@ -0,0 +1,17 @@ +package org.jalgo.tests.ebnf.junit.util; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite = new TestSuite( + "Test for org.jalgo.tests.ebnf.junit.model.ebnf"); + //$JUnit-BEGIN$ + suite.addTestSuite(ActionStackTest.class); + //$JUnit-END$ + return suite; + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Entries new file mode 100644 index 0000000..82b0c25 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Entries @@ -0,0 +1,4 @@ +/ActionStackTest.java/1.1/Fri Aug 11 16:37:20 2006// +/AllTests.java/1.1/Fri Aug 11 16:37:20 2006// +/ControllerTest.java/1.1/Fri Aug 11 16:37:20 2006// +/IActionTest.java/1.1/Fri Aug 11 16:37:20 2006// diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Repository new file mode 100644 index 0000000..8ef8cac --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/junit/util diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/ControllerTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/util/ControllerTest.java new file mode 100644 index 0000000..4e5074c --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/ControllerTest.java @@ -0,0 +1,20 @@ +package org.jalgo.tests.ebnf.junit.util; + +import java.util.Observer; +import java.util.Observable; + +/* This is a Controller which has just a public String. + * Used in the TestClasses. + */ +public class ControllerTest implements Observer { + + public String myString; + + public int observerTest = 0; + + public void update(Observable o, Object obj) { + observerTest++; + System.out.println("Observer notified."); + } + +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/junit/util/IActionTest.java b/relicts/org/jalgo/tests/modules/ebnf/junit/util/IActionTest.java new file mode 100644 index 0000000..d58c265 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/junit/util/IActionTest.java @@ -0,0 +1,40 @@ +package org.jalgo.tests.ebnf.junit.util; + +import org.jalgo.module.ebnf.util.IAction; + +public class IActionTest implements IAction { + + ControllerTest myController; + + String undoneString; + + String performString; + + /* + * undoneString and performString are used to test the right perform-methods + * of diferent IActionsTests. + */ + public IActionTest(ControllerTest aController, String performString, String undoneString) { + myController = aController; + this.undoneString = undoneString; + this.performString = performString; + } + + public void perform() { + myController.myString = performString; + System.out.println("Action " + performString + "."); + } + + public void undo() { + myController.myString = undoneString; + System.out.println("Action " + undoneString + "."); + } + + public String getUndoneString() { + return undoneString; + } + + public String getPerformString() { + return performString; + } +} diff --git a/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Entries b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Entries new file mode 100644 index 0000000..a99ae88 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Entries @@ -0,0 +1 @@ +/new_file.jj/1.1/Fri Aug 11 16:37:23 2006/-kb/ diff --git a/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Repository b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Repository new file mode 100644 index 0000000..861e7b4 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/modules/ebnf/parser diff --git a/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Root b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/modules/ebnf/parser/new_file.jj b/relicts/org/jalgo/tests/modules/ebnf/parser/new_file.jj new file mode 100644 index 0000000..aaf78bb --- /dev/null +++ b/relicts/org/jalgo/tests/modules/ebnf/parser/new_file.jj @@ -0,0 +1,226 @@ +/** + * JavaCC file + */ + + + + options{ JDK_VERSION = "1.5"; + STATIC = false; } PARSER_BEGIN(EbnfParser) + package org.jalgo.tests.ebnf.parser; + +import org.jalgo.module.ebnf.model.ebnf.*; +import org.jalgo.module.ebnf.controller.ebnf.EbnfController; + +/** This is the parser for EBNF terms. It is automatically created by JavaCC + * + */ +public class EbnfParser{ + private EbnfController ebnfController; + + public EbnfParser(EbnfController ebnfController, String term) { + this.ebnfController = ebnfController; + java.io.StringReader sr = new java.io.StringReader( term ); + java.io.Reader r = new java.io.BufferedReader( sr ); + jj_input_stream = new SimpleCharStream(r, 1, 1); + token_source = new EbnfParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + + /** + * + * @param symbols a String with parsed symbols + * @return a concatenation (or a simple term) of all terminal symbols and variables that are valid for this ebnf definition. + */ + private Term parseSymbols(String symbols) throws ParseException { + java.util.List termList = new java.util.ArrayList(); + boolean changed = true; + while (!symbols.equals("") && changed==true) { + changed = false; + for (EVariable var : ebnfController.getDefinition().getVariables()) { + if (symbols.startsWith(var.getName())) { + termList.add(var); + symbols = symbols.substring(var.getName().length()); + changed = true; + } + } + for (ETerminalSymbol terminal : ebnfController.getDefinition().getTerminals()) { + if (symbols.startsWith(terminal.getName())) { + termList.add(terminal); + symbols = symbols.substring(terminal.getName().length()); + changed = true; + } + } + if (!symbols.equals("") && changed==false) { + changed = ebnfController.getGuiController().showUnknownSymbolDialog(symbols); + + } + } + Term t = null; + try { + if (termList.size() == 1) { + t = termList.get(0); + } else { + t = new EConcatenation(termList); + } + } catch (DefinitionFormatException e) { + throw new ParseException(); + } + return t; + } + } PARSER_END(EbnfParser) + +SKIP:{ " " | "\t" + | "\r" + | "\n" } + +TOKEN:/* Brackets */ { + | + | + | | | + | } + +TOKEN:{ + +} + +Term parse(): +{ Term term; } +{ + term = term() + { + return term; + } +} + Term term(): +{ Token t; Term term; Term term2 = null; } +{ + + LOOKAHEAD (2) term = repetition() (term2 = term())? + { + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + throw new ParseException(); + } + } + return term; + } + | LOOKAHEAD (2) term = parentheses() (term2 = term())? + { + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + throw new ParseException(); + } + } + return term; + } + | LOOKAHEAD (2) term = option() (term2 = term())? + { + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + throw new ParseException(); + } + } + return term; + } + | t = + { + term = parseSymbols(t.image); + } + (term2 = term())? + { + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e){ + throw new ParseException(); + } + } + return term; + } +} + +java.util.List specialTerm(): +{ + Term term; + java.util.List terms = new java.util.ArrayList(); + java.util.List subTerms = new java.util.ArrayList(); +} +{ + term = term() + { + terms.add(term); + } + ( subTerms = specialTerm())? + { + terms.addAll(subTerms); + return terms; + } + { + return terms; + } +} + +Term repetition(): +{ Term term; } +{ + (term = term()) + { + ERepetition rep = null; + try { + rep = new ERepetition(term); + } catch (Exception e) { + throw new ParseException(); + } + return rep; + } +} + +Term parentheses(): +{ java.util.List subTerms; } +{ + subTerms = specialTerm() + { if (subTerms.size() == 1){ + ECompoundTerm ct = null; + try { + ct = new ECompoundTerm(subTerms.get(0)); + } catch (Exception e) { + throw new ParseException(); + } + return ct; + } else { + EAlternative alt = null; + try { + alt = new EAlternative(subTerms); + } catch (Exception e) { + throw new ParseException(); + } + return alt; + } + } +} + +Term option(): +{ Term term; } +{ + (term = term()) + { + EOption opt = null; + try { + opt = new EOption(term); + } catch (Exception e) { + throw new ParseException(); + } + return opt; + } +} diff --git a/relicts/org/jalgo/tests/trees/AbstractTree1.java b/relicts/org/jalgo/tests/trees/AbstractTree1.java new file mode 100644 index 0000000..5be5361 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/AbstractTree1.java @@ -0,0 +1,45 @@ +/* + * Created on 30.05.2005 + * + */ +package org.jalgo.tests.trees; + +import org.jalgo.main.trees.Tree; + +/** + * @author Michael Pradel + * + */ +public class AbstractTree1 { + + public static void main(String[] args) { + Tree t11 = new Tree("11"); + Tree t7 = new Tree("7"); + Tree t2 = new Tree("2"); + Tree t8 = new Tree("8"); + Tree t1 = new Tree("1"); + Tree t5 = new Tree("5"); + Tree t4 = new Tree("4"); + Tree t14 = new Tree("14"); + Tree t15 = new Tree("15"); + + t11.addChild(t7); + t11.addChild(t14); + t7.addChild(t2); + t7.addChild(t8); + t2.addChild(t1); + t2.addChild(t5); + t5.addChild(t4); + t14.addChild(t15); + + System.out.println("Children of 11: " + t11.getChildren()); + System.out.println("Parent of 4: " + t4.getParent()); + System.out.println("Parent of 2: " + t2.getParent()); + + System.out.println("Node from t4: " + t4.getNode()); + + System.out.println("Edge from 11 to 7: " + t11.getEdgeTo(t7)); + System.out.println("Edge from 15 to its parent: " + t15.getEdgeToParent()); + System.out.println("Edge from 14 to 15 (should be equal): " + t14.getEdgeTo(t15)); + } +} diff --git a/relicts/org/jalgo/tests/trees/CVS/Entries b/relicts/org/jalgo/tests/trees/CVS/Entries new file mode 100644 index 0000000..4636915 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/CVS/Entries @@ -0,0 +1,6 @@ +/AbstractTree1.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphicalTree1.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphicalTree2.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphicalTree3.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphicalTree4.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphicalTree5.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ diff --git a/relicts/org/jalgo/tests/trees/CVS/Repository b/relicts/org/jalgo/tests/trees/CVS/Repository new file mode 100644 index 0000000..1ffe499 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/org/jalgo/tests/trees diff --git a/relicts/org/jalgo/tests/trees/CVS/Root b/relicts/org/jalgo/tests/trees/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/org/jalgo/tests/trees/GraphicalTree1.java b/relicts/org/jalgo/tests/trees/GraphicalTree1.java new file mode 100644 index 0000000..935af00 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/GraphicalTree1.java @@ -0,0 +1,70 @@ +/* + * Created on 03.06.2005 + * + */ +package org.jalgo.tests.trees; + +import org.eclipse.draw2d.ColorConstants; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.ImageFigure; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.trees.Arrows; +import org.jalgo.main.trees.ITreeConstants; +import org.jalgo.main.trees.LeafFigure; +import org.jalgo.main.trees.NodeFigure; + +/** + * @author Michael Pradel + * + */ +public class GraphicalTree1 { + + public static void main(String[] args) { + Display d = new Display(); + final Shell shell = new Shell(d); + shell.setSize(400, 400); + shell.setText("Tree test"); + LightweightSystem lws = new LightweightSystem(shell); + Figure contents = new Figure(); + contents.setLayoutManager(new FlowLayout()); + + LeafFigure l1 = new LeafFigure("NILLLLLPFERDDDDDDDDE"); + contents.add(l1); + LeafFigure l2 = new LeafFigure(); + contents.add(l2); + l2.setText("FLUSSPFERD"); + + l2.setBackgroundColor(ColorConstants.cyan); + + NodeFigure n1 = new NodeFigure("13"); + contents.add(n1); + NodeFigure n2 = new NodeFigure("13331313138"); + contents.add(n2); + n2.setBackgroundColor(ColorConstants.green); + n2.setTextColor(ColorConstants.white); + NodeFigure n3 = new NodeFigure(); + contents.add(n3); + NodeFigure n4 = new NodeFigure("a"); + contents.add(n4); + + ImageFigure imf = Arrows.getArrows(ITreeConstants.RIGHT_ROT); + contents.add(imf); + + ImageFigure imf2 = Arrows.getArrows(ITreeConstants.RIGHT_ROT); + contents.add(imf2); + + ImageFigure imf3 = Arrows.getArrows(ITreeConstants.LEFT_ROT); + contents.add(imf3); + + + + lws.setContents(contents); + shell.open(); + while (!shell.isDisposed()) + while (!d.readAndDispatch()) + d.sleep(); + } +} diff --git a/relicts/org/jalgo/tests/trees/GraphicalTree2.java b/relicts/org/jalgo/tests/trees/GraphicalTree2.java new file mode 100644 index 0000000..de2ccd5 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/GraphicalTree2.java @@ -0,0 +1,57 @@ +/* + * Created on 10.06.2005 + * + */ +package org.jalgo.tests.trees; + +import org.eclipse.draw2d.ChopboxAnchor; +import org.eclipse.draw2d.ColorConstants; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.draw2d.XYLayout; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.trees.EdgeFigure; +import org.jalgo.main.trees.ITreeConstants; +import org.jalgo.main.trees.LeafFigure; + +/** + * @author Michael Pradel + * + */ +public class GraphicalTree2 { + + public static void main(String[] args) { + Display d = new Display(); + final Shell shell = new Shell(d); + shell.setSize(400, 400); + shell.setText("Tree test"); + LightweightSystem lws = new LightweightSystem(shell); + Figure contents = new Figure(); + contents.setLayoutManager(new XYLayout()); + + LeafFigure l1 = new LeafFigure(); + LeafFigure l2 = new LeafFigure(); + l2.setLocation(new Point(250,150)); + + EdgeFigure e = new EdgeFigure(ITreeConstants.RIGHT_ROT); + ChopboxAnchor a1 = new ChopboxAnchor(l1); + ChopboxAnchor a2 = new ChopboxAnchor(l2); + e.setSourceAnchor(a1); + e.setTargetAnchor(a2); + + e.setText("Rechtsrotation!"); + e.setTextColor(ColorConstants.yellow); + + contents.add(l1); + contents.add(l2); + contents.add(e); + + lws.setContents(contents); + shell.open(); + while (!shell.isDisposed()) + while (!d.readAndDispatch()) + d.sleep(); + } +} diff --git a/relicts/org/jalgo/tests/trees/GraphicalTree3.java b/relicts/org/jalgo/tests/trees/GraphicalTree3.java new file mode 100644 index 0000000..ef18dbf --- /dev/null +++ b/relicts/org/jalgo/tests/trees/GraphicalTree3.java @@ -0,0 +1,58 @@ +/* + * Created on 10.06.2005 + * + */ +package org.jalgo.tests.trees; + +import org.eclipse.draw2d.ChopboxAnchor; +import org.eclipse.draw2d.ColorConstants; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.draw2d.XYLayout; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.trees.EdgeFigure; +import org.jalgo.main.trees.ITreeConstants; +import org.jalgo.main.trees.LeafFigure; +import org.jalgo.main.trees.Tree; + +/** + * @author Michael Pradel + * + */ +public class GraphicalTree3 { + + public static void main(String[] args) { + Display d = new Display(); + final Shell shell = new Shell(d); + shell.setSize(400, 400); + shell.setText("Tree test"); + LightweightSystem lws = new LightweightSystem(shell); + Figure contents = new Figure(); + contents.setLayoutManager(new XYLayout()); + + LeafFigure l1 = new LeafFigure(); + Tree t1 = new Tree("23"); + t1.getNodeFigure().setLocation(new Point(250,80)); + + EdgeFigure e = new EdgeFigure(ITreeConstants.RIGHT_ROT); + ChopboxAnchor a1 = new ChopboxAnchor(l1.getInnerFigure()); + ChopboxAnchor a2 = new ChopboxAnchor(t1.getNodeFigure().getInnerFigure()); + e.setSourceAnchor(a1); + e.setTargetAnchor(a2); + + e.setText("Rechtsrotation!"); + e.setTextColor(ColorConstants.yellow); + + contents.add(l1); + contents.add(t1.getNodeFigure()); + contents.add(e); + + lws.setContents(contents); + shell.open(); + while (!shell.isDisposed()) + while (!d.readAndDispatch()) + d.sleep(); + } +} diff --git a/relicts/org/jalgo/tests/trees/GraphicalTree4.java b/relicts/org/jalgo/tests/trees/GraphicalTree4.java new file mode 100644 index 0000000..f155860 --- /dev/null +++ b/relicts/org/jalgo/tests/trees/GraphicalTree4.java @@ -0,0 +1,51 @@ +/* + * Created on 11.06.2005 + * + */ +package org.jalgo.tests.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.trees.Leaf; +import org.jalgo.main.trees.Tree; + +/** + * @author Michael Pradel + * + */ +public class GraphicalTree4 { + + public static void main(String[] args) { + Display d = new Display(); + final Shell shell = new Shell(d); + shell.setSize(400, 400); + shell.setText("Tree test"); + LightweightSystem lws = new LightweightSystem(shell); + Figure contents = new Figure(); + contents.setLayoutManager(new FlowLayout()); + + Tree t1 = new Tree("11"); + Tree t2 = new Tree("22"); + Leaf l1 = new Leaf(); + Tree t3 = new Tree("33"); + t1.addChild(t2); + t1.addChild(l1); + t2.addChild(t3); + Figure f = t1.layout(); + + contents.add(f); + //contents.add(t2.getNodeFigure()); + //contents.add(l1.getFigure()); + + + + lws.setContents(contents); + shell.open(); + while (!shell.isDisposed()) + while (!d.readAndDispatch()) + d.sleep(); + } +} diff --git a/relicts/org/jalgo/tests/trees/GraphicalTree5.java b/relicts/org/jalgo/tests/trees/GraphicalTree5.java new file mode 100644 index 0000000..b8f828a --- /dev/null +++ b/relicts/org/jalgo/tests/trees/GraphicalTree5.java @@ -0,0 +1,82 @@ +/* + * Created on 11.06.2005 + * + */ +package org.jalgo.tests.trees; + +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.LightweightSystem; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.jalgo.main.trees.Leaf; +import org.jalgo.main.trees.Tree; + +/** + * @author Michael Pradel + * + */ +public class GraphicalTree5 { + + public static void main(String[] args) { + Display d = new Display(); + final Shell shell = new Shell(d); + shell.setSize(400, 400); + shell.setText("Tree test"); + LightweightSystem lws = new LightweightSystem(shell); + Figure contents = new Figure(); + contents.setLayoutManager(new FlowLayout()); + + Tree t1 = new Tree("1"); + Tree t2 = new Tree("2"); + Leaf l1 = new Leaf(); + Leaf l2 = new Leaf("NILPFERD"); + Leaf l3 = new Leaf(); + t1.addChild(t2); + t1.addChild(l1); + t2.addChild(l2); + t2.addChild(l3); + + Figure all = new Figure(); + FlowLayout allLayout = new FlowLayout(false); + allLayout.setMinorAlignment(FlowLayout.ALIGN_CENTER); + allLayout.setMinorSpacing(20); + all.setLayoutManager(allLayout); + + all.add(t1.getNodeFigure()); + Figure children1 = new Figure(); + FlowLayout children1Layout = new FlowLayout(true); + children1Layout.setMinorSpacing(20); + children1.setLayoutManager(children1Layout); + + Figure subTree = new Figure(); + FlowLayout subTreeLayout = new FlowLayout(false); + subTreeLayout.setMinorAlignment(FlowLayout.ALIGN_CENTER); + subTreeLayout.setMinorSpacing(20); + subTree.setLayoutManager(subTreeLayout); + + subTree.add(t2.getNodeFigure()); + Figure children2 = new Figure(); + FlowLayout children2Layout = new FlowLayout(true); + children2Layout.setMinorSpacing(20); + children2.setLayoutManager(children2Layout); + + children2.add(l2.getFigure()); + children2.add(l3.getFigure()); + subTree.add(t2.getNodeFigure()); + subTree.add(children2); + children1.add(subTree); + children1.add(l1.getFigure()); + all.add(t1.getNodeFigure()); + all.add(children1); + + contents.add(all); + + + lws.setContents(contents); + shell.open(); + while (!shell.isDisposed()) + while (!d.readAndDispatch()) + d.sleep(); + } +} diff --git a/relicts/pix/CVS/Entries b/relicts/pix/CVS/Entries new file mode 100644 index 0000000..9642ab7 --- /dev/null +++ b/relicts/pix/CVS/Entries @@ -0,0 +1,11 @@ +/close_view.gif/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/createEbnf.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/createSynDia.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/ebnf.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/jalgo.gif/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/maximize.gif/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/performNext.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/restore.gif/1.1/Sun Mar 26 11:46:58 2006/-kb/ +D/trees//// +/wizard.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/zoom_to_fit.gif/1.1/Sun Mar 26 11:46:58 2006/-kb/ diff --git a/relicts/pix/CVS/Repository b/relicts/pix/CVS/Repository new file mode 100644 index 0000000..56866a8 --- /dev/null +++ b/relicts/pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/pix diff --git a/relicts/pix/CVS/Root b/relicts/pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/pix/close_view.gif b/relicts/pix/close_view.gif new file mode 100644 index 0000000..1aca259 Binary files /dev/null and b/relicts/pix/close_view.gif differ diff --git a/relicts/pix/createEbnf.png b/relicts/pix/createEbnf.png new file mode 100644 index 0000000..f75d04c Binary files /dev/null and b/relicts/pix/createEbnf.png differ diff --git a/relicts/pix/createSynDia.png b/relicts/pix/createSynDia.png new file mode 100644 index 0000000..d18b734 Binary files /dev/null and b/relicts/pix/createSynDia.png differ diff --git a/relicts/pix/ebnf.png b/relicts/pix/ebnf.png new file mode 100644 index 0000000..599505a Binary files /dev/null and b/relicts/pix/ebnf.png differ diff --git a/relicts/pix/jalgo.gif b/relicts/pix/jalgo.gif new file mode 100644 index 0000000..0a009cb Binary files /dev/null and b/relicts/pix/jalgo.gif differ diff --git a/relicts/pix/maximize.gif b/relicts/pix/maximize.gif new file mode 100644 index 0000000..aa7960d Binary files /dev/null and b/relicts/pix/maximize.gif differ diff --git a/relicts/pix/performNext.png b/relicts/pix/performNext.png new file mode 100644 index 0000000..9dadb9f Binary files /dev/null and b/relicts/pix/performNext.png differ diff --git a/relicts/pix/restore.gif b/relicts/pix/restore.gif new file mode 100644 index 0000000..a1ba3aa Binary files /dev/null and b/relicts/pix/restore.gif differ diff --git a/relicts/pix/trees/CVS/Entries b/relicts/pix/trees/CVS/Entries new file mode 100644 index 0000000..1fa9085 --- /dev/null +++ b/relicts/pix/trees/CVS/Entries @@ -0,0 +1,2 @@ +/left_arrows.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ +/right_arrows.png/1.1/Sun Mar 26 11:46:58 2006/-kb/ diff --git a/relicts/pix/trees/CVS/Repository b/relicts/pix/trees/CVS/Repository new file mode 100644 index 0000000..b6b80b7 --- /dev/null +++ b/relicts/pix/trees/CVS/Repository @@ -0,0 +1 @@ +j-algo/relicts/pix/trees diff --git a/relicts/pix/trees/CVS/Root b/relicts/pix/trees/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/relicts/pix/trees/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/relicts/pix/trees/left_arrows.png b/relicts/pix/trees/left_arrows.png new file mode 100644 index 0000000..59a9863 Binary files /dev/null and b/relicts/pix/trees/left_arrows.png differ diff --git a/relicts/pix/trees/right_arrows.png b/relicts/pix/trees/right_arrows.png new file mode 100644 index 0000000..2349285 Binary files /dev/null and b/relicts/pix/trees/right_arrows.png differ diff --git a/relicts/pix/wizard.png b/relicts/pix/wizard.png new file mode 100644 index 0000000..48380a4 Binary files /dev/null and b/relicts/pix/wizard.png differ diff --git a/relicts/pix/zoom_to_fit.gif b/relicts/pix/zoom_to_fit.gif new file mode 100644 index 0000000..b5ff847 Binary files /dev/null and b/relicts/pix/zoom_to_fit.gif differ diff --git a/res/CVS/Entries b/res/CVS/Entries new file mode 100644 index 0000000..81ec355 --- /dev/null +++ b/res/CVS/Entries @@ -0,0 +1,3 @@ +D/help//// +D/main//// +D/module//// diff --git a/res/CVS/Repository b/res/CVS/Repository new file mode 100644 index 0000000..1a2ed37 --- /dev/null +++ b/res/CVS/Repository @@ -0,0 +1 @@ +j-algo/res diff --git a/res/CVS/Root b/res/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/CVS/Entries b/res/main/CVS/Entries new file mode 100644 index 0000000..ff980e7 --- /dev/null +++ b/res/main/CVS/Entries @@ -0,0 +1,4 @@ +D/help//// +/main.prefs/1.1/Fri Mar 24 16:02:29 2006/-kk/ +D/main_pix//// +/style.css/1.1/Sun Mar 12 16:04:41 2006/-kb/ diff --git a/res/main/CVS/Repository b/res/main/CVS/Repository new file mode 100644 index 0000000..2c48144 --- /dev/null +++ b/res/main/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main diff --git a/res/main/CVS/Root b/res/main/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/CVS/Entries b/res/main/help/CVS/Entries new file mode 100644 index 0000000..b931d74 --- /dev/null +++ b/res/main/help/CVS/Entries @@ -0,0 +1,3 @@ +D/html//// +D/jhelp//// +D/pics//// diff --git a/res/main/help/CVS/Repository b/res/main/help/CVS/Repository new file mode 100644 index 0000000..d652d5f --- /dev/null +++ b/res/main/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help diff --git a/res/main/help/CVS/Root b/res/main/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/html/CVS/Entries b/res/main/help/html/CVS/Entries new file mode 100644 index 0000000..a69dad2 --- /dev/null +++ b/res/main/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.2/Sat Mar 18 11:49:36 2006// +D/data//// +/index.htm/1.1/Sun Mar 12 16:04:57 2006// +/top_frame.htm/1.1/Sun Mar 12 16:04:57 2006// diff --git a/res/main/help/html/CVS/Repository b/res/main/help/html/CVS/Repository new file mode 100644 index 0000000..35205da --- /dev/null +++ b/res/main/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help/html diff --git a/res/main/help/html/CVS/Root b/res/main/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/html/contents.htm b/res/main/help/html/contents.htm new file mode 100644 index 0000000..2df6ea4 --- /dev/null +++ b/res/main/help/html/contents.htm @@ -0,0 +1,76 @@ + + + Inhaltsverzeichnis + + + +
      + Das Hauptprogramm + +
    + + \ No newline at end of file diff --git a/res/main/help/html/data/CVS/Entries b/res/main/help/html/data/CVS/Entries new file mode 100644 index 0000000..79a6969 --- /dev/null +++ b/res/main/help/html/data/CVS/Entries @@ -0,0 +1,4 @@ +/basics.htm/1.3/Wed Mar 22 21:01:26 2006// +/dialogs.htm/1.2/Wed Mar 22 21:01:26 2006// +/impressum.htm/1.2/Wed Mar 22 21:01:26 2006// +/overview.htm/1.3/Wed Mar 22 21:01:27 2006// diff --git a/res/main/help/html/data/CVS/Repository b/res/main/help/html/data/CVS/Repository new file mode 100644 index 0000000..c2d0dbc --- /dev/null +++ b/res/main/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help/html/data diff --git a/res/main/help/html/data/CVS/Root b/res/main/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/html/data/basics.htm b/res/main/help/html/data/basics.htm new file mode 100644 index 0000000..dc6795a --- /dev/null +++ b/res/main/help/html/data/basics.htm @@ -0,0 +1,73 @@ + + + Grundfunktionen + + + + +

    Grundfunktionen

    +

    j-Algo bietet eine + Reihe von Grundfunktionen, die unabhängig von den Modulen zur Verfügung stehen, + bzw. für jedes Modul die gleiche Bedeutung haben. Im Einzelnen sind das das + Öffnen von Modulen sowie das Laden und Speichern von Sitzungsdaten. Die + Grundfunktionen sind über die Werkzeugleiste oder den Menüpunkt <Datei> + erreichbar.

    +

    + +  Neues + Modul öffnen +

    +

    Ein Klick auf den Button <Neu> in der + Werkzeugleiste gibt Ihnen die Möglichkeit, ein beliebiges neues Modul zu + öffnen. Dabei wird ein Auswahldialog geöffnet, in welchem die installierten + Module aufgelistet sind. Hier werden Ihnen außerdem kurze Informationen zu + diesen Modulen angezeigt. Sie können wählen, ob dieser Auswahldialog bei jedem + Start des Programmes angezeigt werden soll oder nicht. Alternativ dazu kann + über das Menü <Datei> => <Neu> + das gewünschte Modul geladen werden. Dies ist der schnellere Weg und zu + empfehlen, wenn man bereits einen Überblick über die installierten Module hat.

    +

    + +  Gespeicherte + Sitzungsdaten laden

    +

    Mit einem Klick auf den Button <Öffnen> erscheint ein + Dialog zur Dateiauswahl. Hier haben Sie die Möglichkeit, eine Datei + auszuwählen, in welcher modulspezifische Sitzungsdaten gespeichert wurden. Die + Dateien, die von j-Algo gespeichert + werden, tragen die Dateiendung ".jalgo".

    +

    Achtung: Da jedes Modul von j-Algo + seine Daten in einer solchen Datei ablegt, kann man beim Blick auf die + ungeöffnete Datei nicht erkennen, mit welchem Modul diese assoziiert wurde. Es + wird jeweils das assoziierte Modul zu der geladenen Datei geöffnet. Achten Sie + daher bei der Vergabe der Dateinamen auf möglichst eindeutige Bezeichner.
    + Anmerkung: In einer späteren Version wird direkt bei der + Dateiauswahl das zugehörige Modul mit angezeigt.

    +

    + + +  Sitzungsdaten speichern

    + + +

    Per Klick auf die Buttons <Speichern> und <Speichern + unter> können Sie die Sitzungsdaten des gerade aktiven Moduls in + einer Datei speichern. Wie beim Laden öffnet sich auch hier ein Dialog zur + Dateiauswahl, in welchem Sie Zielpfad und Name der neuen Datei eintragen + können. Die Angabe der Dateiendung ist nicht nötig, das Programm ergänzt diese + automatisch. Je nach Implementierung des aktiven Moduls steht die + Speicherfunktion nur zur Verfügung, wenn gerade kein Algorithmus läuft. Sollte + noch ein Algorithmus aktiv sein, so beenden Sie diesen bitte vorher oder + brechen ihn ab.

    +

     

    +

    + + Modul schließen

    + +

    Sie haben die Möglichkeit, jede Modulinstanz durch Klick auf das + Kreuz der dazugehörigen Registerkarte zu schließen. Dabei werden Sie + gegebenenfalls gefragt, ob Sie Ihre Arbeit speichern wollen. Um das gesamte + Programm zu schließen, ist es nicht nötig, die Module einzeln zu schliessen, + das erledigt das Programm für Sie.

    + +

     

    + + \ No newline at end of file diff --git a/res/main/help/html/data/dialogs.htm b/res/main/help/html/data/dialogs.htm new file mode 100644 index 0000000..e80882d --- /dev/null +++ b/res/main/help/html/data/dialogs.htm @@ -0,0 +1,64 @@ + + + Grundfunktionen + + + + + +

    Einstellungen

    +

    Per Auswahl des Menüeintrages <Datei>=> <Einstellungen> + gelangen Sie zu einem Dialogfenster, welches Ihnen erlaubt alle Einstellungen des Hauptprogrammes zu verändern.

    + +
      +
    • + Logo beim Start anzeigen
      + Ist dieser Punkt aktiviert wird wärend der Ladephase des Programmes ein kleiner Willkommensbildschirm angezeigt. +
    • + Modulauswahldialog beim Start anzeigen
      + Ist dieser Punkt aktiviert wird nach dem Start von j-Algo der + Modulauswahldialog angezeigt. Zu den Funktionen des Dialoges später mehr. +
    • + Sprachauswahl
      + Hier können Sie die Sprache auswählen mit der Sie unter j-Algo arbeiten + möchten. Standardmäßig stehen Ihnen die Sprachen Englisch und Deutsch zur Verfügung. +
    • + Oberfläche
      + Hier können Sie das Aussehen der Oberfläche in gewissem Maße verändern. Wählen Sie einfach einen der + Look-And-Feel-Varianten aus der Liste aus.
      + Achtung: Manche der Oberflächen werden nur von bestimmten Betriebssystemen unterstützt. +
    + +

    +

    + + +

    Modulauswahldialog

    +

    Der Modulauswahldialog stellt eine schnelle Variante dar ein Modul zu Starten. Er bietet Ihnen zu + diesem Zweck eine Liste der installierten Module und eine Kurzbeschreibung zu jedem Modul an. Per Klick auf den Button + <Datei öffnen> haben Sie die Möglichkeit zuvor gespeicherte Sitzungsdaten zu laden und so ein neues + Modul zu starten. (Siehe auch: "Sitzungsdaten laden").

    +

    +

    +

    + + +

    +  Hilfe

    +

    Die Online-Hilfe stellt ein wichtiges Nachschlagewerk für all + diejenigen dar, die nicht auf Anhieb mit allen Funktionen von + j-Algo und seinen Modulen klar kommen. Hier können Sie + noch einmal eine genaue Beschreibung zu den einzelnen Programmelementen + nachlesen. Sie erreichen die Hilfe über den Menüpunkt <Hilfe> + => <Inhalt> oder indem Sie einfach auf die Taste <F1>Ihrer + Tastatur drücken.
    + Zusätzlich wird zu den meisten Kontrollelementen, also Buttons, Menüeinträge, + etc., ein kurzer Hinweistext neben dem Mauszeiger bzw. in der Statuszeile des + Programmes angezeigt. Dies sollte als schnelle Hilfestellung den meisten + Anforderungen genügen.
    + Darüber hinaus gibt es noch das ausführliche Handbuch in Form einer pdf-Datei, + die der Software beiliegt. Hier sind auch teilweise fachliche Hintergründe + enthalten.

    + + + \ No newline at end of file diff --git a/res/main/help/html/data/impressum.htm b/res/main/help/html/data/impressum.htm new file mode 100644 index 0000000..a461dbd --- /dev/null +++ b/res/main/help/html/data/impressum.htm @@ -0,0 +1,40 @@ + + + Grundfunktionen + + + + + +

    Impressum

    + j-Algo ist ein Projekt von Studenten des Studiengangs Informatik der + TU Dresden. Es wird im Rahmen des Softwarepraktikums des Lehrstuhles für Softwaretechnologie entwickelt. Die aktuellen Module + werden in Lehrveranstaltungen des Lehrstuhles für Grundlagen der Programmierung eingesetzt.
    + Bei Fragen, Kritiken und Anregungen wenden Sie sich bitte an das + j-Algo-Entwicklerteam.

    + + + + \ No newline at end of file diff --git a/res/main/help/html/data/overview.htm b/res/main/help/html/data/overview.htm new file mode 100644 index 0000000..82a56d3 --- /dev/null +++ b/res/main/help/html/data/overview.htm @@ -0,0 +1,73 @@ + + + Einleitung + + + + +

    + +

    Einleitung

    +

    Dieses Handbuch stellt eine Einführung und Hilfe für die Arbeit + mit j-Algo dar. + j-Algo ist eine Software, + die sich mit der Visualisierung von Algorithmen beschäftigt. Sie soll dazu dienen, + verschiedene Algorithmen zu veranschaulichen um sie so Studenten und anderen Interessierten + verständlicher zu machen. Die Anwendung basiert auf einer Plugin-Struktur, die + es ermöglicht, einzelne Module, die jeweils einen Algorithmus oder ein + Themengebiet abdecken können, in das Programm zu integrieren und zu laden. + Sowohl j-Algo als auch die + einzelnen Module entstanden im Rahmen des externen Softwarepraktikums im + Studiengang Informatik der TU Dresden in Zusammenarbeit mit dem Lehrstuhl + Programmierung. Die implementierten Module orientieren sich daher an den + Lehrveranstaltungen "Algorithmen und Datenstrukturen" sowie "Programmierung" im + Grundstudium Informatik an der TU Dresden. Das Einsatzgebiet soll vor allem die + Vorlesung und das studentische Lernen zu Hause umfassen. + j-Algo + ist eine freie Software, die beliebig oft kopiert werden darf.
    +

    +

    Technische Hinweise

    +

    Systemvoraussetzungen

    +

    Folgende minimale Systemanforderungen werden für den reibungslosen Einsatz von + j-Algo benötigt: +

    +
      +
    • + IBM-kompatibler PC +
    • + Mindestens 64 MB RAM +
    • + Windows 98(SE)/ME/2000/XP , Linux SuSE/Red Had +
    • + Java 2 Platform Standard Edition 5.0 (siehe: http://java.sun.com/) +
    • + Maus und Tastatur +
    • + Monitor mit einer Auflösung von mindestens 800x600 +
    • +
    + +

    Installation

    +

    Windows

    +

    Entpacken Sie nach dem Herunterladen das ZIP-komprimierte Archiv in einen Ordner + Ihrer Wahl. In diesem Ordner finden Sie eine Datei namens ”j-algo.bat“. + Öffnen Sie diese Datei mit einem Doppelklick, und das Programm wird gestartet.

    +

    Unix

    +

    Entpacken Sie nach dem Herunterladen das ZIP-komprimierte Archiv in einen Ordner + Ihrer Wahl. In diesem Ordner finden Sie eine Datei namens "j-algo.sh". + "Öffnen Sie diese Datei mit einem Doppelklick, und das Programm wird gestartet.

    + +

    Deinstallation

    +

    Der komplette Programmordner kann jederzeit gefahrlos von der Festplatte + gelöscht werden.

    + +

    Module installieren

    +

    Neue Module werden als JAR-komprimiertes Archiv zum Download angeboten. + Kopieren Sie nach dem Herunterladen die jar-Datei in den Ordner "\runtime\modules" des Hauptprogrammes. + Dannach steht Ihnen das neue Modul im Programm zur Verfügung.

    + +

    Module deinstallieren

    +

    Löschen Sie die zugehörige jar-Datei aus dem Ordner "\runtime\modules" des Hauptprogrammes.

    + + + \ No newline at end of file diff --git a/res/main/help/html/index.htm b/res/main/help/html/index.htm new file mode 100644 index 0000000..d386d3b --- /dev/null +++ b/res/main/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zu j-Algo + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/main/help/html/top_frame.htm b/res/main/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/main/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/main/help/jhelp/CVS/Entries b/res/main/help/jhelp/CVS/Entries new file mode 100644 index 0000000..a6feeee --- /dev/null +++ b/res/main/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/mainIndex.xml/1.2/Wed Mar 22 11:52:24 2006// +/mainTOC.xml/1.2/Wed Mar 22 11:52:24 2006// +/main_help.hs/1.1/Sun Mar 12 16:04:02 2006/-kb/ +/map.jhm/1.2/Wed Mar 22 11:52:24 2006/-kb/ diff --git a/res/main/help/jhelp/CVS/Repository b/res/main/help/jhelp/CVS/Repository new file mode 100644 index 0000000..7de5cf6 --- /dev/null +++ b/res/main/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help/jhelp diff --git a/res/main/help/jhelp/CVS/Root b/res/main/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/jhelp/JavaHelpSearch/CVS/Entries b/res/main/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..8112e3b --- /dev/null +++ b/res/main/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,8 @@ +/DOCS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/DOCS.TAB/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/OFFSETS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/POSITIONS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/SCHEMA/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/TMAP/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/config.ini/1.1/Sun Mar 12 16:04:28 2006// +/stopwords.txt/1.1/Sun Mar 12 16:04:28 2006// diff --git a/res/main/help/jhelp/JavaHelpSearch/CVS/Repository b/res/main/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..a054bef --- /dev/null +++ b/res/main/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help/jhelp/JavaHelpSearch diff --git a/res/main/help/jhelp/JavaHelpSearch/CVS/Root b/res/main/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/jhelp/JavaHelpSearch/DOCS b/res/main/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..079b9e0 Binary files /dev/null and b/res/main/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/main/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/main/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..5f7e699 --- /dev/null +++ b/res/main/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿö_ÿÿÿÿÿÿý—ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÐoªî®þªê««ªëªº®ïªªªªªªª®ºªª®ª¾ªº®º«ªª«ªªªêªªªªªªªª®®®êªªªª¾ªª«ª®ºª»ÿªîª»ªªªªªªªªªªªªªªªªªªªªªªªªªªªªª¦ \ No newline at end of file diff --git a/res/main/help/jhelp/JavaHelpSearch/OFFSETS b/res/main/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..0a49800 --- /dev/null +++ b/res/main/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +f–º€ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/main/help/jhelp/mainTOC.xml b/res/main/help/jhelp/mainTOC.xml new file mode 100644 index 0000000..0771cc7 --- /dev/null +++ b/res/main/help/jhelp/mainTOC.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/main/help/jhelp/main_help.hs b/res/main/help/jhelp/main_help.hs new file mode 100644 index 0000000..77e3be6 --- /dev/null +++ b/res/main/help/jhelp/main_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zu j-Algo + + + + + main.intro + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + mainTOC.xml + + + + Index + + javax.help.IndexView + mainIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/main/help/jhelp/map.jhm b/res/main/help/jhelp/map.jhm new file mode 100644 index 0000000..dd4e15d --- /dev/null +++ b/res/main/help/jhelp/map.jhm @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/main/help/pics/CVS/Entries b/res/main/help/pics/CVS/Entries new file mode 100644 index 0000000..26bc35f --- /dev/null +++ b/res/main/help/pics/CVS/Entries @@ -0,0 +1,11 @@ +/closemessage.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/help.gif/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/icon_help.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/icon_new.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/icon_open.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/icon_saveall.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/logo_help.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/logo_orginal.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ +/mcd.png/1.1/Wed Mar 22 21:01:32 2006/-kb/ +/options.png/1.1/Wed Mar 22 21:01:32 2006/-kb/ +/savedialog.png/1.1/Sun Mar 12 16:04:12 2006/-kb/ diff --git a/res/main/help/pics/CVS/Repository b/res/main/help/pics/CVS/Repository new file mode 100644 index 0000000..c57f6e3 --- /dev/null +++ b/res/main/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/help/pics diff --git a/res/main/help/pics/CVS/Root b/res/main/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/help/pics/closemessage.png b/res/main/help/pics/closemessage.png new file mode 100644 index 0000000..6d424f7 Binary files /dev/null and b/res/main/help/pics/closemessage.png differ diff --git a/res/main/help/pics/help.gif b/res/main/help/pics/help.gif new file mode 100644 index 0000000..0c3f517 Binary files /dev/null and b/res/main/help/pics/help.gif differ diff --git a/res/main/help/pics/icon_help.png b/res/main/help/pics/icon_help.png new file mode 100644 index 0000000..4f206d5 Binary files /dev/null and b/res/main/help/pics/icon_help.png differ diff --git a/res/main/help/pics/icon_new.png b/res/main/help/pics/icon_new.png new file mode 100644 index 0000000..5b22c54 Binary files /dev/null and b/res/main/help/pics/icon_new.png differ diff --git a/res/main/help/pics/icon_open.png b/res/main/help/pics/icon_open.png new file mode 100644 index 0000000..60920eb Binary files /dev/null and b/res/main/help/pics/icon_open.png differ diff --git a/res/main/help/pics/icon_saveall.png b/res/main/help/pics/icon_saveall.png new file mode 100644 index 0000000..8e5806e Binary files /dev/null and b/res/main/help/pics/icon_saveall.png differ diff --git a/res/main/help/pics/logo_help.png b/res/main/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/main/help/pics/logo_help.png differ diff --git a/res/main/help/pics/logo_orginal.png b/res/main/help/pics/logo_orginal.png new file mode 100644 index 0000000..5657620 Binary files /dev/null and b/res/main/help/pics/logo_orginal.png differ diff --git a/res/main/help/pics/mcd.png b/res/main/help/pics/mcd.png new file mode 100644 index 0000000..5b2f24b Binary files /dev/null and b/res/main/help/pics/mcd.png differ diff --git a/res/main/help/pics/options.png b/res/main/help/pics/options.png new file mode 100644 index 0000000..7081e52 Binary files /dev/null and b/res/main/help/pics/options.png differ diff --git a/res/main/help/pics/savedialog.png b/res/main/help/pics/savedialog.png new file mode 100644 index 0000000..2bd5a22 Binary files /dev/null and b/res/main/help/pics/savedialog.png differ diff --git a/res/main/main.prefs b/res/main/main.prefs new file mode 100644 index 0000000..6282152 --- /dev/null +++ b/res/main/main.prefs @@ -0,0 +1,6 @@ +#j-Algo Default-Settings for Main-Program +Version=1.0.1 +Language=de +ShowSplashOnStartup=true +ShowModuleChooserOnStartup=true +MaximizeWindowOnStartup=false diff --git a/res/main/main_pix/CVS/Entries b/res/main/main_pix/CVS/Entries new file mode 100644 index 0000000..4789ad6 --- /dev/null +++ b/res/main/main_pix/CVS/Entries @@ -0,0 +1,36 @@ +/abortAlg.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/about.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/aboutHeader.png/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/advice.gif/1.1/Fri Aug 11 16:39:26 2006/-kb/ +/advice_selected.gif/1.1/Fri Aug 11 16:39:26 2006/-kb/ +/beamer.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/clear.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/close.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/exit.gif/1.1/Tue Aug 30 07:20:14 2005/-kb/ +/export.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/finishAlg.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/help.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/jalgo-file.png/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/jalgo.png/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/logo_small.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/msgError.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/msgInfo.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/new.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/open.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/performAll.gif/1.1/Fri Aug 11 16:39:26 2006/-kb/ +/performBlockStep.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/performStep.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/prefs.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/print.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/rectangle.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/redo.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/rounded_rectangle.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/save.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/save_as.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/splash.png/1.5/Tue Jul 12 12:47:23 2011/-kb/ +/undo.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/undoAll.gif/1.1/Fri Aug 11 16:39:26 2006/-kb/ +/undoBlockStep.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/undoStep.gif/1.2/Sat Mar 4 13:36:26 2006/-kb/ +/zoom-in.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ +/zoom-out.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ diff --git a/res/main/main_pix/CVS/Repository b/res/main/main_pix/CVS/Repository new file mode 100644 index 0000000..968243d --- /dev/null +++ b/res/main/main_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/main/main_pix diff --git a/res/main/main_pix/CVS/Root b/res/main/main_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/main/main_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/main/main_pix/abortAlg.gif b/res/main/main_pix/abortAlg.gif new file mode 100644 index 0000000..346d169 Binary files /dev/null and b/res/main/main_pix/abortAlg.gif differ diff --git a/res/main/main_pix/about.gif b/res/main/main_pix/about.gif new file mode 100644 index 0000000..1918133 Binary files /dev/null and b/res/main/main_pix/about.gif differ diff --git a/res/main/main_pix/aboutHeader.png b/res/main/main_pix/aboutHeader.png new file mode 100644 index 0000000..1f8a59f Binary files /dev/null and b/res/main/main_pix/aboutHeader.png differ diff --git a/res/main/main_pix/advice.gif b/res/main/main_pix/advice.gif new file mode 100644 index 0000000..fe61d2e Binary files /dev/null and b/res/main/main_pix/advice.gif differ diff --git a/res/main/main_pix/advice_selected.gif b/res/main/main_pix/advice_selected.gif new file mode 100644 index 0000000..1125739 Binary files /dev/null and b/res/main/main_pix/advice_selected.gif differ diff --git a/res/main/main_pix/beamer.gif b/res/main/main_pix/beamer.gif new file mode 100644 index 0000000..9507c3c Binary files /dev/null and b/res/main/main_pix/beamer.gif differ diff --git a/res/main/main_pix/clear.gif b/res/main/main_pix/clear.gif new file mode 100644 index 0000000..dd61d6c Binary files /dev/null and b/res/main/main_pix/clear.gif differ diff --git a/res/main/main_pix/close.gif b/res/main/main_pix/close.gif new file mode 100644 index 0000000..23fe64b Binary files /dev/null and b/res/main/main_pix/close.gif differ diff --git a/res/main/main_pix/exit.gif b/res/main/main_pix/exit.gif new file mode 100644 index 0000000..036a2a9 Binary files /dev/null and b/res/main/main_pix/exit.gif differ diff --git a/res/main/main_pix/export.gif b/res/main/main_pix/export.gif new file mode 100644 index 0000000..045e3d8 Binary files /dev/null and b/res/main/main_pix/export.gif differ diff --git a/res/main/main_pix/finishAlg.gif b/res/main/main_pix/finishAlg.gif new file mode 100644 index 0000000..347d32c Binary files /dev/null and b/res/main/main_pix/finishAlg.gif differ diff --git a/res/main/main_pix/help.gif b/res/main/main_pix/help.gif new file mode 100644 index 0000000..0c3f517 Binary files /dev/null and b/res/main/main_pix/help.gif differ diff --git a/res/main/main_pix/jalgo-file.png b/res/main/main_pix/jalgo-file.png new file mode 100644 index 0000000..d6cec82 Binary files /dev/null and b/res/main/main_pix/jalgo-file.png differ diff --git a/res/main/main_pix/jalgo.png b/res/main/main_pix/jalgo.png new file mode 100644 index 0000000..a32373b Binary files /dev/null and b/res/main/main_pix/jalgo.png differ diff --git a/res/main/main_pix/logo_small.gif b/res/main/main_pix/logo_small.gif new file mode 100644 index 0000000..a40170f Binary files /dev/null and b/res/main/main_pix/logo_small.gif differ diff --git a/res/main/main_pix/msgError.gif b/res/main/main_pix/msgError.gif new file mode 100644 index 0000000..3d22e21 Binary files /dev/null and b/res/main/main_pix/msgError.gif differ diff --git a/res/main/main_pix/msgInfo.gif b/res/main/main_pix/msgInfo.gif new file mode 100644 index 0000000..ef55bef Binary files /dev/null and b/res/main/main_pix/msgInfo.gif differ diff --git a/res/main/main_pix/new.gif b/res/main/main_pix/new.gif new file mode 100644 index 0000000..da98fca Binary files /dev/null and b/res/main/main_pix/new.gif differ diff --git a/res/main/main_pix/open.gif b/res/main/main_pix/open.gif new file mode 100644 index 0000000..daa1f0c Binary files /dev/null and b/res/main/main_pix/open.gif differ diff --git a/res/main/main_pix/performAll.gif b/res/main/main_pix/performAll.gif new file mode 100644 index 0000000..be79869 Binary files /dev/null and b/res/main/main_pix/performAll.gif differ diff --git a/res/main/main_pix/performBlockStep.gif b/res/main/main_pix/performBlockStep.gif new file mode 100644 index 0000000..57bcaea Binary files /dev/null and b/res/main/main_pix/performBlockStep.gif differ diff --git a/res/main/main_pix/performStep.gif b/res/main/main_pix/performStep.gif new file mode 100644 index 0000000..b5ee47e Binary files /dev/null and b/res/main/main_pix/performStep.gif differ diff --git a/res/main/main_pix/prefs.gif b/res/main/main_pix/prefs.gif new file mode 100644 index 0000000..76f83d7 Binary files /dev/null and b/res/main/main_pix/prefs.gif differ diff --git a/res/main/main_pix/print.gif b/res/main/main_pix/print.gif new file mode 100644 index 0000000..6c79d35 Binary files /dev/null and b/res/main/main_pix/print.gif differ diff --git a/res/main/main_pix/rectangle.gif b/res/main/main_pix/rectangle.gif new file mode 100644 index 0000000..a5e55cb Binary files /dev/null and b/res/main/main_pix/rectangle.gif differ diff --git a/res/main/main_pix/redo.gif b/res/main/main_pix/redo.gif new file mode 100644 index 0000000..c84e5b1 Binary files /dev/null and b/res/main/main_pix/redo.gif differ diff --git a/res/main/main_pix/rounded_rectangle.gif b/res/main/main_pix/rounded_rectangle.gif new file mode 100644 index 0000000..f0ccdcd Binary files /dev/null and b/res/main/main_pix/rounded_rectangle.gif differ diff --git a/res/main/main_pix/save.gif b/res/main/main_pix/save.gif new file mode 100644 index 0000000..cbe3657 Binary files /dev/null and b/res/main/main_pix/save.gif differ diff --git a/res/main/main_pix/save_as.gif b/res/main/main_pix/save_as.gif new file mode 100644 index 0000000..e4ff5f7 Binary files /dev/null and b/res/main/main_pix/save_as.gif differ diff --git a/res/main/main_pix/splash.png b/res/main/main_pix/splash.png new file mode 100644 index 0000000..5c59821 Binary files /dev/null and b/res/main/main_pix/splash.png differ diff --git a/res/main/main_pix/undo.gif b/res/main/main_pix/undo.gif new file mode 100644 index 0000000..eae118a Binary files /dev/null and b/res/main/main_pix/undo.gif differ diff --git a/res/main/main_pix/undoAll.gif b/res/main/main_pix/undoAll.gif new file mode 100644 index 0000000..5d27cb6 Binary files /dev/null and b/res/main/main_pix/undoAll.gif differ diff --git a/res/main/main_pix/undoBlockStep.gif b/res/main/main_pix/undoBlockStep.gif new file mode 100644 index 0000000..a8ab64f Binary files /dev/null and b/res/main/main_pix/undoBlockStep.gif differ diff --git a/res/main/main_pix/undoStep.gif b/res/main/main_pix/undoStep.gif new file mode 100644 index 0000000..4551e4f Binary files /dev/null and b/res/main/main_pix/undoStep.gif differ diff --git a/res/main/main_pix/zoom-in.gif b/res/main/main_pix/zoom-in.gif new file mode 100644 index 0000000..d6a15a1 Binary files /dev/null and b/res/main/main_pix/zoom-in.gif differ diff --git a/res/main/main_pix/zoom-out.gif b/res/main/main_pix/zoom-out.gif new file mode 100644 index 0000000..13dce8b Binary files /dev/null and b/res/main/main_pix/zoom-out.gif differ diff --git a/res/main/style.css b/res/main/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/main/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/CVS/Entries b/res/module/CVS/Entries new file mode 100644 index 0000000..53e2df6 --- /dev/null +++ b/res/module/CVS/Entries @@ -0,0 +1,18 @@ +D/am0c0//// +D/am1simulator//// +D/app//// +D/avl//// +D/bTree//// +D/bellmanFord//// +D/bfsdfs//// +D/c0h0//// +D/dijkstra//// +D/ebnf//// +D/em//// +D/heapsort//// +D/hoare//// +D/kmp//// +D/lambda//// +D/pulsemem//// +D/testModule//// +D/unifikation//// diff --git a/res/module/CVS/Repository b/res/module/CVS/Repository new file mode 100644 index 0000000..2832827 --- /dev/null +++ b/res/module/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module diff --git a/res/module/CVS/Root b/res/module/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/CVS/Entries b/res/module/am0c0/CVS/Entries new file mode 100644 index 0000000..a4428d6 --- /dev/null +++ b/res/module/am0c0/CVS/Entries @@ -0,0 +1,2 @@ +D/am0c0_pix//// +D/help//// diff --git a/res/module/am0c0/CVS/Repository b/res/module/am0c0/CVS/Repository new file mode 100644 index 0000000..753a56f --- /dev/null +++ b/res/module/am0c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0 diff --git a/res/module/am0c0/CVS/Root b/res/module/am0c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/am0c0_pix/CVS/Entries b/res/module/am0c0/am0c0_pix/CVS/Entries new file mode 100644 index 0000000..f4e4418 --- /dev/null +++ b/res/module/am0c0/am0c0_pix/CVS/Entries @@ -0,0 +1,11 @@ +/back_to_editor.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/clear.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +D/ilovecandy//// +/initial_configuration.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/last.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/logo.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/next.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/open.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/previous.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/run.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/save.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/res/module/am0c0/am0c0_pix/CVS/Repository b/res/module/am0c0/am0c0_pix/CVS/Repository new file mode 100644 index 0000000..70dcbde --- /dev/null +++ b/res/module/am0c0/am0c0_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/am0c0_pix diff --git a/res/module/am0c0/am0c0_pix/CVS/Root b/res/module/am0c0/am0c0_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/am0c0_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/am0c0_pix/back_to_editor.png b/res/module/am0c0/am0c0_pix/back_to_editor.png new file mode 100644 index 0000000..8b0fef9 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/back_to_editor.png differ diff --git a/res/module/am0c0/am0c0_pix/clear.png b/res/module/am0c0/am0c0_pix/clear.png new file mode 100644 index 0000000..9c15c09 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/clear.png differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Entries b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Entries new file mode 100644 index 0000000..6311b7f --- /dev/null +++ b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Entries @@ -0,0 +1,14 @@ +/down1.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/down2.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/down3.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/ghost.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/left1.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/left2.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/left3.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/pacman.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/right1.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/right2.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/right3.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/up1.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/up2.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/up3.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Repository b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Repository new file mode 100644 index 0000000..c6fceb7 --- /dev/null +++ b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/am0c0_pix/ilovecandy diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Root b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/am0c0_pix/ilovecandy/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/down1.gif b/res/module/am0c0/am0c0_pix/ilovecandy/down1.gif new file mode 100644 index 0000000..982b6cf Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/down1.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/down2.gif b/res/module/am0c0/am0c0_pix/ilovecandy/down2.gif new file mode 100644 index 0000000..0a1fae0 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/down2.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/down3.gif b/res/module/am0c0/am0c0_pix/ilovecandy/down3.gif new file mode 100644 index 0000000..abc4e12 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/down3.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/ghost.gif b/res/module/am0c0/am0c0_pix/ilovecandy/ghost.gif new file mode 100644 index 0000000..fbcd8bb Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/ghost.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/left1.gif b/res/module/am0c0/am0c0_pix/ilovecandy/left1.gif new file mode 100644 index 0000000..b6e2260 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/left1.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/left2.gif b/res/module/am0c0/am0c0_pix/ilovecandy/left2.gif new file mode 100644 index 0000000..41e3a64 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/left2.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/left3.gif b/res/module/am0c0/am0c0_pix/ilovecandy/left3.gif new file mode 100644 index 0000000..c4d3211 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/left3.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/pacman.gif b/res/module/am0c0/am0c0_pix/ilovecandy/pacman.gif new file mode 100644 index 0000000..0ddd525 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/pacman.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/right1.gif b/res/module/am0c0/am0c0_pix/ilovecandy/right1.gif new file mode 100644 index 0000000..e5fa957 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/right1.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/right2.gif b/res/module/am0c0/am0c0_pix/ilovecandy/right2.gif new file mode 100644 index 0000000..7c193a3 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/right2.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/right3.gif b/res/module/am0c0/am0c0_pix/ilovecandy/right3.gif new file mode 100644 index 0000000..82a4a08 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/right3.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/up1.gif b/res/module/am0c0/am0c0_pix/ilovecandy/up1.gif new file mode 100644 index 0000000..7c1f28d Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/up1.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/up2.gif b/res/module/am0c0/am0c0_pix/ilovecandy/up2.gif new file mode 100644 index 0000000..ed98cc7 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/up2.gif differ diff --git a/res/module/am0c0/am0c0_pix/ilovecandy/up3.gif b/res/module/am0c0/am0c0_pix/ilovecandy/up3.gif new file mode 100644 index 0000000..74c8dc3 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/ilovecandy/up3.gif differ diff --git a/res/module/am0c0/am0c0_pix/initial_configuration.png b/res/module/am0c0/am0c0_pix/initial_configuration.png new file mode 100644 index 0000000..ab0e8ea Binary files /dev/null and b/res/module/am0c0/am0c0_pix/initial_configuration.png differ diff --git a/res/module/am0c0/am0c0_pix/last.png b/res/module/am0c0/am0c0_pix/last.png new file mode 100644 index 0000000..6e904ef Binary files /dev/null and b/res/module/am0c0/am0c0_pix/last.png differ diff --git a/res/module/am0c0/am0c0_pix/logo.gif b/res/module/am0c0/am0c0_pix/logo.gif new file mode 100644 index 0000000..c399def Binary files /dev/null and b/res/module/am0c0/am0c0_pix/logo.gif differ diff --git a/res/module/am0c0/am0c0_pix/next.png b/res/module/am0c0/am0c0_pix/next.png new file mode 100644 index 0000000..6ef8de7 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/next.png differ diff --git a/res/module/am0c0/am0c0_pix/open.png b/res/module/am0c0/am0c0_pix/open.png new file mode 100644 index 0000000..ab94046 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/open.png differ diff --git a/res/module/am0c0/am0c0_pix/previous.png b/res/module/am0c0/am0c0_pix/previous.png new file mode 100644 index 0000000..659cd90 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/previous.png differ diff --git a/res/module/am0c0/am0c0_pix/run.png b/res/module/am0c0/am0c0_pix/run.png new file mode 100644 index 0000000..d90ab66 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/run.png differ diff --git a/res/module/am0c0/am0c0_pix/save.png b/res/module/am0c0/am0c0_pix/save.png new file mode 100644 index 0000000..22ff495 Binary files /dev/null and b/res/module/am0c0/am0c0_pix/save.png differ diff --git a/res/module/am0c0/help/CVS/Entries b/res/module/am0c0/help/CVS/Entries new file mode 100644 index 0000000..d872071 --- /dev/null +++ b/res/module/am0c0/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Mon Aug 16 12:12:08 2010// diff --git a/res/module/am0c0/help/CVS/Repository b/res/module/am0c0/help/CVS/Repository new file mode 100644 index 0000000..aedd04e --- /dev/null +++ b/res/module/am0c0/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help diff --git a/res/module/am0c0/help/CVS/Root b/res/module/am0c0/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/html/CVS/Entries b/res/module/am0c0/help/html/CVS/Entries new file mode 100644 index 0000000..9b7be17 --- /dev/null +++ b/res/module/am0c0/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Mon Aug 16 12:12:08 2010// +D/data//// +/index.htm/1.1/Mon Aug 16 12:12:08 2010// +/top_frame.htm/1.1/Mon Aug 16 12:12:08 2010// diff --git a/res/module/am0c0/help/html/CVS/Repository b/res/module/am0c0/help/html/CVS/Repository new file mode 100644 index 0000000..78da2ec --- /dev/null +++ b/res/module/am0c0/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help/html diff --git a/res/module/am0c0/help/html/CVS/Root b/res/module/am0c0/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/html/contents.htm b/res/module/am0c0/help/html/contents.htm new file mode 100644 index 0000000..1d0d419 --- /dev/null +++ b/res/module/am0c0/help/html/contents.htm @@ -0,0 +1,65 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul AM0/C0 + +
    + + \ No newline at end of file diff --git a/res/module/am0c0/help/html/data/CVS/Entries b/res/module/am0c0/help/html/data/CVS/Entries new file mode 100644 index 0000000..3f2b7d4 --- /dev/null +++ b/res/module/am0c0/help/html/data/CVS/Entries @@ -0,0 +1,5 @@ +/editor.htm/1.1/Mon Aug 16 12:12:08 2010// +/overview.htm/1.1/Mon Aug 16 12:12:08 2010// +/presentation_mode.htm/1.1/Mon Aug 16 12:12:08 2010// +/simulator.htm/1.1/Mon Aug 16 12:12:08 2010// +/transformator.htm/1.1/Mon Aug 16 12:12:08 2010// diff --git a/res/module/am0c0/help/html/data/CVS/Repository b/res/module/am0c0/help/html/data/CVS/Repository new file mode 100644 index 0000000..53f1ecc --- /dev/null +++ b/res/module/am0c0/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help/html/data diff --git a/res/module/am0c0/help/html/data/CVS/Root b/res/module/am0c0/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/html/data/editor.htm b/res/module/am0c0/help/html/data/editor.htm new file mode 100644 index 0000000..2032b02 --- /dev/null +++ b/res/module/am0c0/help/html/data/editor.htm @@ -0,0 +1,36 @@ + + + AM0/C0-Editor + + + +

    AM0/C0-Editor

    +

    Übersicht

    +

    Das erste Fenster, welches nach dem Start des Moduls erscheint ist der + Editor. Hier hat man die Möglichkeit C0 oder AM0 Programme zu schreiben oder + zu laden.

    +

    + Editor +

    Datei laden/speichern

    +

    Im Editor-Fenster oben rechts sieht man über der Auswahl für den C0- oder + AM0-Code den Laden- und Speicher-Button. Nach einem Klick auf den entsprechenden + Button öffnet sich ein Dialog-Fenster zur Auswahl der Datei. Im unteren Bereich + kann jetzt ausgewählt werden, ob es sich um eine C0- oder AM0-Datei handelt. Nun + kann wie gewohnt die entsprechende Datei ausgewählt werden.

    +

    + Laden/Speichern-Dialog +

    Code validieren

    +

    Nachdem der Code eingeben oder geladen wurde, kann der Code validiert werden. + Vor der Validierung sollte man überprüfen, ob oben rechts unter dem Laden- und + Speichern-Button der richtige Code-Typ ausgewählt ist. Nun kann man mit einem Klick + auf dem Validiere-Button den Code überprüfen. Sollten Fehler aufgetreten sein, werden + diese nun unten links in der Konsole angezeigt. Andernfalls erhält man in der Konsole + eine Meldung, dass der Code syntaktisch korrekt ist.

    +

    Transformation/Simulation starten

    +

    Um die Transformation oder die Simulation zu starten, muss der Code zuvor + validiert werden. Nach der erfolgreichen Validierung + wird unten rechts der Start-Button aktiv. Mit einem Klick auf diesen öffnet sich bei + C0-Code das Transformationsfenster und bei AM0-Code das + Simulationsfenster.

    + + diff --git a/res/module/am0c0/help/html/data/overview.htm b/res/module/am0c0/help/html/data/overview.htm new file mode 100644 index 0000000..9581098 --- /dev/null +++ b/res/module/am0c0/help/html/data/overview.htm @@ -0,0 +1,36 @@ + + + Einleitung + + + + +

    Das Modul AM0/C0

    + +

    Einleitung

    + +

    Dieses Modul dient zur Verdeutlichung der C0 zu AM0 Transformation + und der AM0-Simulation. Orientiert wird sich hierbei an der Vorlesung + "Programmierung" von Prof. Vogler. Der konkrete Algorithmus + zur Transformation, sowie auch zur Simulation können im Vorlesungsskript + nachgelesen werden.

    + + +

    Funktionsübersicht

    + +

    Das Modul AM0/C0 realisiert folgende Funktionen: +

  • Parsen eines C0-Quelltextes
  • +
  • Parsen eines AM0-Programms
  • +
  • Editor zum eingeben von C0-Quelltexten und AM0-Programmen
  • +
  • Speichern und Laden von C0-Quelltexten und AM0-Programmen
  • +
  • Editor unterstützt Syntaxhervorhebung für C0 und AM0
  • +
  • Transformation eines C0-Quelltextes zu einem AM0-Programm (in einem Schritt oder Schrittweise)
  • +
  • Anzeige einer Vorschau vor jedem Transformationsschritt
  • +
  • Simulation eines AM0-Programms (in einem Schritt oder Schrittweise)
  • +
  • Hervorhebung des nächsten auszuführenden Schritts im AM0-Programm
  • +
  • Anzeige der entsprechenden Definition bei jedem Schritt
  • +
  • Rückgängig machen/Wiederherstellen von Schritten
  • +

    + + + diff --git a/res/module/am0c0/help/html/data/presentation_mode.htm b/res/module/am0c0/help/html/data/presentation_mode.htm new file mode 100644 index 0000000..2cf7643 --- /dev/null +++ b/res/module/am0c0/help/html/data/presentation_mode.htm @@ -0,0 +1,15 @@ + + + Präsentations-Modus + + + +

    Präsentations-Modus

    +

    Um die Nutzung an einem Beamer zu vereinfachen, gibt es einen + Präsentations-Modus, welcher die Schriftgröße in allen Bereichen des Moduls + vergrößert. Dieser kann in jedem Bereich über das Menü, welches sich + am oberen Fensterrand befindet, aktiviert und auch wieder deaktiviert werden.

    +

    + Präsentations-Modus + + diff --git a/res/module/am0c0/help/html/data/simulator.htm b/res/module/am0c0/help/html/data/simulator.htm new file mode 100644 index 0000000..65ee156 --- /dev/null +++ b/res/module/am0c0/help/html/data/simulator.htm @@ -0,0 +1,43 @@ + + + AM0-Simulator + + + +

    AM0-Simulator

    +

    Übersicht

    +

    Im Simulations-Fenster hat man nun die Möglichkeit, ein zu zuvor + transformiertes, geladenes oder eingegebenes Programm auf einer AM0 zu simulieren. + Das AM0-Programm ist im oberen linkten Teil des Fensters zu sehen. Hier wird der + nächste auszuführende Befehl markiert. Im unteren linken Teil ist die Befehlssemantik + für den markierten Befehl zu sehen. Im rechten Teil des Fensters ist die Tabelle zu + sehen, welche die Maschinenkonfiguration nach jedem ausgeführten Schritt dokumentiert. + Diese Tabelle ist in Seiten eingeteilt. Auf jeder Seite sind 50 Maschinenkonfigurationen + dokumentiert. Um die Seite zu wechseln gibt es über und unter dem vertikalen Scrollbalken + der Tabelle entsprechende Buttons. Desweiteren gibt es unter der Tabelle einen Tabellenanfang- bzw. + einen Tabellenende-Button um auf die erste bzw. letzte Seite zu gelangen.

    +

    + AM0-Simulator +

    Initiale Konfiguration

    +

    Bevor eine Simulation gestartet werden kann muss eine Startkonfiguration angegeben + werden. Dies geschieht entweder mit einem Klick auf den Button Initiale Konfiguration + oder der Dialog wird automatisch eingeblendet, wenn beim Ausführen des ersten + Schritts noch keine Anfangskonfiguration existiert. Im Dialogfenster kann dann der + Befehlszähler, der Datenkeller, der Hauptspeicher, das Eingabeband, das Ausgabeband + und die Anzahl auszuführender Schritte bis zur Nachfrage zur Fortsetzung festgelegt werden.

    +

    + initiale Konfiguration +

    Simulationsschritt ausführen

    +

    Bevor der erste Schritt ausgeführt werden kann muss eine initiale + Konfiguration existieren. Danach kann mit jedem Klick auf den Weiter-Button der nächste + Befehl auf die aktuelle Maschinenkonfiguration angewendet werden. Sollte ein Befehl nicht + ausgeführt werden können (beispielsweise, wenn vom leeren Eingabeband gelesen werden + soll) wird eine entsprechende Fehlermeldung ausgegeben. Andernfalls wird der Schritt + ausgeführt und die Tabelle erweitert. Mit einem Klick auf den Button Alles in einem Schritt wird + das Programm bis zum Ende durchlaufen. Sollten dabei mehr als die eingestellte Anzahl von Schritten + durchlaufen werden erscheint eine Abfrage, ob weitere Schritte ausgeführt werden sollen. Die Anzahl + von Schritten bis zur Abfrage kann kann bei der initialen Konfiguration eingestellt werden.

    +

    + maximale Schritte + + diff --git a/res/module/am0c0/help/html/data/transformator.htm b/res/module/am0c0/help/html/data/transformator.htm new file mode 100644 index 0000000..e440f80 --- /dev/null +++ b/res/module/am0c0/help/html/data/transformator.htm @@ -0,0 +1,35 @@ + + + C0-Transformator + + + +

    C0-Transformator

    +

    Übersicht

    +

    Im Transformations-Fenster hat man nun die Möglichkeit das C0-Programm + in ein äquivalentes AM0-Programm zu transformieren. Im oberen linken Teil + ist der Code zu sehen, welcher vom Editor validiert wurde. Im Bereich oben + rechts ist die Symboltabelle zu finden. Es gilt zu beachten, dass die + Symboltabelle erst nach dem "blocktrans" erzeugt wird. Unten rechts wird + zur aktuell markierten Auswahl die Definition angezeigt und unten links ist + die Vorschau für die Regelanwendung auf die Auswahl zu sehen.

    +

    + Transformator +

    Transformationsschritt ausführen

    +

    Direkt unter dem Teil, des in der sich in der übersetzung befindenden Programmcodes, + sind 3 Buttons zu sehen. Mit einem Klick auf den Rückgängig-Button macht ihr + den zuletzt ausgeführten Transformationsschritt rückgängig. Der Anwenden-Button + wird erst aktiv, wenn ein noch zu transformierenden Block ausgewählt wurde. Dies + macht man, indem man einfach im oberen linken Teil des Fensters auf den + gewünschten Block klickt. Danach kann mit einem Klick auf den Anwenden-Button + oder einem weiteren Klick auf den Block der entsprechende Transformationsschritt + ausgeführt werden. Bei einem Klick auf den Fertig transformieren-Button werden + alle Schritte, welche nötig sind, um die Transformation abzuschließen, ausgeführt.

    +

    Möglichkeiten nach der Transformation

    +

    Nach komplett abgeschlossener Transformation wird der Simulieren-Button aktiv. + Mit einem Klick auf diesen kommt man direkt in das Simulations-Fenster, in dem das + erzeugte AM0-Programm simuliert werden kann. Desweiteren besteht mit dem Zurück zum + Editor-Button die Möglichkeit, dass AM0-Programm in den Editor zu übertragen.

    + Transformator nach Transformation + + diff --git a/res/module/am0c0/help/html/index.htm b/res/module/am0c0/help/html/index.htm new file mode 100644 index 0000000..136187d --- /dev/null +++ b/res/module/am0c0/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AM0/C0 Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/am0c0/help/html/top_frame.htm b/res/module/am0c0/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/am0c0/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/am0c0/help/jhelp/CVS/Entries b/res/module/am0c0/help/jhelp/CVS/Entries new file mode 100644 index 0000000..8864ea3 --- /dev/null +++ b/res/module/am0c0/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/am0c0Index.xml/1.1/Mon Aug 16 12:12:08 2010// +/am0c0Map.jhm/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/am0c0TOC.xml/1.1/Mon Aug 16 12:12:08 2010// +/am0c0_help.hs/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/res/module/am0c0/help/jhelp/CVS/Repository b/res/module/am0c0/help/jhelp/CVS/Repository new file mode 100644 index 0000000..6d5b712 --- /dev/null +++ b/res/module/am0c0/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help/jhelp diff --git a/res/module/am0c0/help/jhelp/CVS/Root b/res/module/am0c0/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..9fd0025 --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/DOCS.TAB/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/OFFSETS/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/POSITIONS/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/SCHEMA/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/TMAP/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/config.ini/1.1/Mon Aug 16 12:12:09 2010// diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..5425069 --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help/jhelp/JavaHelpSearch diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS b/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..0209b0d Binary files /dev/null and b/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..531ffba --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÝÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿ@þÿúªûû»¿¾ëªú﮾û¾ªªªªêªª¯¯êþº¯ª«ª®ªú®îº®ªúªªê®êªª»ªêªªª®ªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/am0c0/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..a7fedd8 Binary files /dev/null and b/res/module/am0c0/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/am0c0/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..4a6e7f5 Binary files /dev/null and b/res/module/am0c0/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/am0c0/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..2ac0b52 --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=297 id2=1 diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/TMAP b/res/module/am0c0/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..09b6e78 Binary files /dev/null and b/res/module/am0c0/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/am0c0/help/jhelp/JavaHelpSearch/config.ini b/res/module/am0c0/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/am0c0/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/am0c0/help/jhelp/am0c0Index.xml b/res/module/am0c0/help/jhelp/am0c0Index.xml new file mode 100644 index 0000000..e8e0098 --- /dev/null +++ b/res/module/am0c0/help/jhelp/am0c0Index.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/res/module/am0c0/help/jhelp/am0c0Map.jhm b/res/module/am0c0/help/jhelp/am0c0Map.jhm new file mode 100644 index 0000000..ba625c9 --- /dev/null +++ b/res/module/am0c0/help/jhelp/am0c0Map.jhm @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/am0c0/help/jhelp/am0c0TOC.xml b/res/module/am0c0/help/jhelp/am0c0TOC.xml new file mode 100644 index 0000000..d2adfc5 --- /dev/null +++ b/res/module/am0c0/help/jhelp/am0c0TOC.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/am0c0/help/jhelp/am0c0_help.hs b/res/module/am0c0/help/jhelp/am0c0_help.hs new file mode 100644 index 0000000..5df1025 --- /dev/null +++ b/res/module/am0c0/help/jhelp/am0c0_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum AM0/C0-Modul + + + + + am0c0 + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + am0c0TOC.xml + + + + Index + + javax.help.IndexView + am0c0Index.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/am0c0/help/pics/CVS/Entries b/res/module/am0c0/help/pics/CVS/Entries new file mode 100644 index 0000000..adbf1e7 --- /dev/null +++ b/res/module/am0c0/help/pics/CVS/Entries @@ -0,0 +1,10 @@ +/am0 simulator.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/back to editor after transformation.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/c0 transformator.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/editor.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/initial configuration.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/load_save.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/logo.gif/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/logo_help.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/presentation mode.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/step counter.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/res/module/am0c0/help/pics/CVS/Repository b/res/module/am0c0/help/pics/CVS/Repository new file mode 100644 index 0000000..319d26b --- /dev/null +++ b/res/module/am0c0/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am0c0/help/pics diff --git a/res/module/am0c0/help/pics/CVS/Root b/res/module/am0c0/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am0c0/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am0c0/help/pics/am0 simulator.jpg b/res/module/am0c0/help/pics/am0 simulator.jpg new file mode 100644 index 0000000..b9d855b Binary files /dev/null and b/res/module/am0c0/help/pics/am0 simulator.jpg differ diff --git a/res/module/am0c0/help/pics/back to editor after transformation.jpg b/res/module/am0c0/help/pics/back to editor after transformation.jpg new file mode 100644 index 0000000..e8c00ec Binary files /dev/null and b/res/module/am0c0/help/pics/back to editor after transformation.jpg differ diff --git a/res/module/am0c0/help/pics/c0 transformator.jpg b/res/module/am0c0/help/pics/c0 transformator.jpg new file mode 100644 index 0000000..0072431 Binary files /dev/null and b/res/module/am0c0/help/pics/c0 transformator.jpg differ diff --git a/res/module/am0c0/help/pics/editor.jpg b/res/module/am0c0/help/pics/editor.jpg new file mode 100644 index 0000000..34122e8 Binary files /dev/null and b/res/module/am0c0/help/pics/editor.jpg differ diff --git a/res/module/am0c0/help/pics/initial configuration.jpg b/res/module/am0c0/help/pics/initial configuration.jpg new file mode 100644 index 0000000..aeaf1d0 Binary files /dev/null and b/res/module/am0c0/help/pics/initial configuration.jpg differ diff --git a/res/module/am0c0/help/pics/load_save.jpg b/res/module/am0c0/help/pics/load_save.jpg new file mode 100644 index 0000000..f718bc8 Binary files /dev/null and b/res/module/am0c0/help/pics/load_save.jpg differ diff --git a/res/module/am0c0/help/pics/logo.gif b/res/module/am0c0/help/pics/logo.gif new file mode 100644 index 0000000..e2e5c88 Binary files /dev/null and b/res/module/am0c0/help/pics/logo.gif differ diff --git a/res/module/am0c0/help/pics/logo_help.png b/res/module/am0c0/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/module/am0c0/help/pics/logo_help.png differ diff --git a/res/module/am0c0/help/pics/presentation mode.jpg b/res/module/am0c0/help/pics/presentation mode.jpg new file mode 100644 index 0000000..dcf0f2f Binary files /dev/null and b/res/module/am0c0/help/pics/presentation mode.jpg differ diff --git a/res/module/am0c0/help/pics/step counter.jpg b/res/module/am0c0/help/pics/step counter.jpg new file mode 100644 index 0000000..2e93774 Binary files /dev/null and b/res/module/am0c0/help/pics/step counter.jpg differ diff --git a/res/module/am0c0/help/style.css b/res/module/am0c0/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/am0c0/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/am1simulator/CVS/Entries b/res/module/am1simulator/CVS/Entries new file mode 100644 index 0000000..98a0a5c --- /dev/null +++ b/res/module/am1simulator/CVS/Entries @@ -0,0 +1,2 @@ +D/am1simulator_pix//// +D/help//// diff --git a/res/module/am1simulator/CVS/Repository b/res/module/am1simulator/CVS/Repository new file mode 100644 index 0000000..1989e43 --- /dev/null +++ b/res/module/am1simulator/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator diff --git a/res/module/am1simulator/CVS/Root b/res/module/am1simulator/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/am1simulator_pix/CVS/Entries b/res/module/am1simulator/am1simulator_pix/CVS/Entries new file mode 100644 index 0000000..abe5ea5 --- /dev/null +++ b/res/module/am1simulator/am1simulator_pix/CVS/Entries @@ -0,0 +1,14 @@ +/back.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/bottom.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/clear.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/editor.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/file.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/forward.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/initial.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/logo.gif/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/onestep.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/open.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/run.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/save.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/stop.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/top.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ diff --git a/res/module/am1simulator/am1simulator_pix/CVS/Repository b/res/module/am1simulator/am1simulator_pix/CVS/Repository new file mode 100644 index 0000000..9ab7d98 --- /dev/null +++ b/res/module/am1simulator/am1simulator_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/am1simulator_pix diff --git a/res/module/am1simulator/am1simulator_pix/CVS/Root b/res/module/am1simulator/am1simulator_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/am1simulator_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/am1simulator_pix/back.png b/res/module/am1simulator/am1simulator_pix/back.png new file mode 100644 index 0000000..659cd90 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/back.png differ diff --git a/res/module/am1simulator/am1simulator_pix/bottom.png b/res/module/am1simulator/am1simulator_pix/bottom.png new file mode 100644 index 0000000..3dd7fcc Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/bottom.png differ diff --git a/res/module/am1simulator/am1simulator_pix/clear.png b/res/module/am1simulator/am1simulator_pix/clear.png new file mode 100644 index 0000000..9c15c09 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/clear.png differ diff --git a/res/module/am1simulator/am1simulator_pix/editor.png b/res/module/am1simulator/am1simulator_pix/editor.png new file mode 100644 index 0000000..188e1c1 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/editor.png differ diff --git a/res/module/am1simulator/am1simulator_pix/file.png b/res/module/am1simulator/am1simulator_pix/file.png new file mode 100644 index 0000000..2d7f2d6 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/file.png differ diff --git a/res/module/am1simulator/am1simulator_pix/forward.png b/res/module/am1simulator/am1simulator_pix/forward.png new file mode 100644 index 0000000..6ef8de7 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/forward.png differ diff --git a/res/module/am1simulator/am1simulator_pix/initial.png b/res/module/am1simulator/am1simulator_pix/initial.png new file mode 100644 index 0000000..ab0e8ea Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/initial.png differ diff --git a/res/module/am1simulator/am1simulator_pix/logo.gif b/res/module/am1simulator/am1simulator_pix/logo.gif new file mode 100644 index 0000000..68ff71b Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/logo.gif differ diff --git a/res/module/am1simulator/am1simulator_pix/onestep.png b/res/module/am1simulator/am1simulator_pix/onestep.png new file mode 100644 index 0000000..6e904ef Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/onestep.png differ diff --git a/res/module/am1simulator/am1simulator_pix/open.png b/res/module/am1simulator/am1simulator_pix/open.png new file mode 100644 index 0000000..ab94046 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/open.png differ diff --git a/res/module/am1simulator/am1simulator_pix/run.png b/res/module/am1simulator/am1simulator_pix/run.png new file mode 100644 index 0000000..d90ab66 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/run.png differ diff --git a/res/module/am1simulator/am1simulator_pix/save.png b/res/module/am1simulator/am1simulator_pix/save.png new file mode 100644 index 0000000..22ff495 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/save.png differ diff --git a/res/module/am1simulator/am1simulator_pix/stop.png b/res/module/am1simulator/am1simulator_pix/stop.png new file mode 100644 index 0000000..7be8a37 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/stop.png differ diff --git a/res/module/am1simulator/am1simulator_pix/top.png b/res/module/am1simulator/am1simulator_pix/top.png new file mode 100644 index 0000000..fa9a7d7 Binary files /dev/null and b/res/module/am1simulator/am1simulator_pix/top.png differ diff --git a/res/module/am1simulator/help/CVS/Entries b/res/module/am1simulator/help/CVS/Entries new file mode 100644 index 0000000..9cb36a8 --- /dev/null +++ b/res/module/am1simulator/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Mon Mar 7 19:57:19 2011/-kb/ diff --git a/res/module/am1simulator/help/CVS/Repository b/res/module/am1simulator/help/CVS/Repository new file mode 100644 index 0000000..232adfc --- /dev/null +++ b/res/module/am1simulator/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help diff --git a/res/module/am1simulator/help/CVS/Root b/res/module/am1simulator/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/html/CVS/Entries b/res/module/am1simulator/help/html/CVS/Entries new file mode 100644 index 0000000..da7980a --- /dev/null +++ b/res/module/am1simulator/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Mon Mar 7 19:57:18 2011// +D/data//// +/index.htm/1.1/Mon Mar 7 19:57:18 2011// +/top_frame.htm/1.1/Mon Mar 7 19:57:18 2011// diff --git a/res/module/am1simulator/help/html/CVS/Repository b/res/module/am1simulator/help/html/CVS/Repository new file mode 100644 index 0000000..6906237 --- /dev/null +++ b/res/module/am1simulator/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help/html diff --git a/res/module/am1simulator/help/html/CVS/Root b/res/module/am1simulator/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/html/contents.htm b/res/module/am1simulator/help/html/contents.htm new file mode 100644 index 0000000..dbe079a --- /dev/null +++ b/res/module/am1simulator/help/html/contents.htm @@ -0,0 +1,54 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul AM1-Simulator + +
    + + \ No newline at end of file diff --git a/res/module/am1simulator/help/html/data/CVS/Entries b/res/module/am1simulator/help/html/data/CVS/Entries new file mode 100644 index 0000000..7f07ae7 --- /dev/null +++ b/res/module/am1simulator/help/html/data/CVS/Entries @@ -0,0 +1,4 @@ +/editor.htm/1.1/Mon Mar 7 19:57:18 2011// +/overview.htm/1.1/Mon Mar 7 19:57:18 2011// +/presentation_mode.htm/1.1/Mon Mar 7 19:57:18 2011// +/simulation.htm/1.1/Mon Mar 7 19:57:18 2011// diff --git a/res/module/am1simulator/help/html/data/CVS/Repository b/res/module/am1simulator/help/html/data/CVS/Repository new file mode 100644 index 0000000..e18d3f9 --- /dev/null +++ b/res/module/am1simulator/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help/html/data diff --git a/res/module/am1simulator/help/html/data/CVS/Root b/res/module/am1simulator/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/html/data/editor.htm b/res/module/am1simulator/help/html/data/editor.htm new file mode 100644 index 0000000..522a85b --- /dev/null +++ b/res/module/am1simulator/help/html/data/editor.htm @@ -0,0 +1,30 @@ + + + Editor + + + +

    AM1-Editor

    +

    Übersicht

    +

    Hier hat man die Möglichkeit AM1 Programme zu schreiben oder + zu laden.

    +

    + Editor +

    Datei laden/speichern

    +

    Mit einem Klick auf den Laden-/ Speichernbutton kann nun + ein AM1-Programm geladen oder gespeichert werden. Falls Sie + bereits ein Programm geladen und modifiziert hatten, erfolgt + eine Nachfrage ob die Änderungen zwischengespeichert werden sollen.

    +

    + Laden/Speichern-Dialog +

    Programm validieren

    +

    Nachdem das Programm eingeben oder geladen wurde, kann es validiert werden. + Nun kann man mit einem Klick auf dem Parse-Button den Code überprüfen. Sollten Fehler aufgetreten sein, werden + diese nun unten links in der Konsole angezeigt. Andernfalls erhält man in der Konsole + eine Meldung, dass der Code syntaktisch korrekt ist.

    +

    Simulation starten

    +

    Um die Simulation zu starten, muss der Code zuvor + validiert werden. Nach der erfolgreichen Validierung + wird der Simulationsmodus aktiv.

    + + diff --git a/res/module/am1simulator/help/html/data/overview.htm b/res/module/am1simulator/help/html/data/overview.htm new file mode 100644 index 0000000..3fdf7fb --- /dev/null +++ b/res/module/am1simulator/help/html/data/overview.htm @@ -0,0 +1,31 @@ + + + Einleitung + + + + +

    Das Modul AM1-Simulator

    + +

    Einleitung

    + +

    Dieses Modul dient zur Verdeutlichung der AM1-Simulation. Orientiert wird sich hierbei + an der Vorlesung "Programmierung" von Prof. Vogler. + Der konkrete Algorithmus zur Simulation können im Vorlesungsskript nachgelesen werden.

    + + +

    Funktionsübersicht

    + +

    Das Modul AM1-Simulator realisiert folgende Funktionen: +

  • Parsen eines AM1-Programms
  • +
  • Editor zum eingeben von AM1-Programmen
  • +
  • Speichern und Laden von AM1-Programmen
  • +
  • Editor unterstützt Syntaxhervorhebung für AM1
  • +
  • Simulation eines AM1-Programms (in einem Schritt oder schrittweise)
  • +
  • Hervorhebung des nächsten auszuführenden Schritts im AM1-Programm
  • +
  • Anzeige der entsprechenden Definition bei jedem Schritt
  • +
  • Rückgängig machen/Wiederherstellen von Schritten
  • +

    + + + diff --git a/res/module/am1simulator/help/html/data/presentation_mode.htm b/res/module/am1simulator/help/html/data/presentation_mode.htm new file mode 100644 index 0000000..a82db00 --- /dev/null +++ b/res/module/am1simulator/help/html/data/presentation_mode.htm @@ -0,0 +1,15 @@ + + + Präsentations-Modus + + + +

    Präsentations-Modus

    +

    Um die Nutzung an einem Beamer zu vereinfachen, gibt es einen + Präsentations-Modus, welcher die Schriftgröße in allen Bereichen des Moduls + vergrößert. Dieser kann in jedem Bereich über das Menü, welches sich + am oberen Fensterrand befindet, aktiviert und auch wieder deaktiviert werden.

    +

    + Präsentations-Modus + + diff --git a/res/module/am1simulator/help/html/data/simulation.htm b/res/module/am1simulator/help/html/data/simulation.htm new file mode 100644 index 0000000..0c566da --- /dev/null +++ b/res/module/am1simulator/help/html/data/simulation.htm @@ -0,0 +1,42 @@ + + + Simulation + + + +

    Simulation

    +

    Übersicht

    +

    Hier hat man die Möglichkeit, ein zu zuvor geladenes oder eingegebenes Programm auf einer AM1 zu simulieren. + Das AM1-Programm ist im linken Teil des Fensters zu sehen. Hier wird der + nächste auszuführende Befehl markiert. Im unteren linken Teil ist die Befehlssemantik + für den markierten Befehl zu sehen. Im rechten Teil des Fensters ist die Tabelle zu + sehen, welche die Maschinenkonfiguration nach jedem ausgeführten Schritt dokumentiert. + Diese Tabelle ist in Seiten eingeteilt. Auf jeder Seite sind 50 Maschinenkonfigurationen + dokumentiert. Um die Seite zu wechseln gibt es über und unter dem vertikalen Scrollbalken + der Tabelle entsprechende Buttons. Desweiteren gibt es über der Tabelle einen Tabellenanfang- bzw. + einen Tabellenende-Button um auf die erste bzw. letzte Seite zu gelangen.

    +

    + AM1-Simulator +

    Initiale Konfiguration

    +

    Bevor eine Simulation gestartet werden kann muss eine Startkonfiguration angegeben + werden. Dies geschieht entweder mit einem Klick auf den Button Initiale Konfiguration + oder der Dialog wird automatisch eingeblendet, wenn beim Ausführen des ersten + Schritts noch keine Anfangskonfiguration existiert. Im Dialogfenster kann dann der + Befehlszähler, der Datenkeller, der Hauptspeicher, das Eingabeband, das Ausgabeband + und die Anzahl auszuführender Schritte bis zur Nachfrage zur Fortsetzung festgelegt werden.

    +

    + initiale Konfiguration +

    Simulationsschritt ausführen

    +

    Bevor der erste Schritt ausgeführt werden kann muss eine initiale + Konfiguration existieren. Danach kann mit jedem Klick auf den Weiter-Button der nächste + Befehl auf die aktuelle Maschinenkonfiguration angewendet werden. Sollte ein Befehl nicht + ausgeführt werden können (beispielsweise, wenn vom leeren Eingabeband gelesen werden + soll) wird eine entsprechende Fehlermeldung ausgegeben. Andernfalls wird der Schritt + ausgeführt und die Tabelle erweitert. Mit einem Klick auf den Button "Alles in einem Schritt" wird + das Programm bis zum Ende durchlaufen. Sollten dabei mehr als die eingestellte Anzahl von Schritten + durchlaufen werden erscheint eine Abfrage, ob weitere Schritte ausgeführt werden sollen. Die Anzahl + von Schritten bis zur Abfrage kann kann bei der initialen Konfiguration eingestellt werden.

    +

    + maximale Schritte + + diff --git a/res/module/am1simulator/help/html/index.htm b/res/module/am1simulator/help/html/index.htm new file mode 100644 index 0000000..577a3f5 --- /dev/null +++ b/res/module/am1simulator/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AM1-Simulator Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/am1simulator/help/html/top_frame.htm b/res/module/am1simulator/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/am1simulator/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/am1simulator/help/jhelp/CVS/Entries b/res/module/am1simulator/help/jhelp/CVS/Entries new file mode 100644 index 0000000..b13fb3b --- /dev/null +++ b/res/module/am1simulator/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/am1simulatorIndex.xml/1.1/Mon Mar 7 19:57:18 2011// +/am1simulatorMap.jhm/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/am1simulatorTOC.xml/1.1/Mon Mar 7 19:57:18 2011// +/am1simulator_help.hs/1.1/Mon Mar 7 19:57:18 2011/-kb/ diff --git a/res/module/am1simulator/help/jhelp/CVS/Repository b/res/module/am1simulator/help/jhelp/CVS/Repository new file mode 100644 index 0000000..2721435 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help/jhelp diff --git a/res/module/am1simulator/help/jhelp/CVS/Root b/res/module/am1simulator/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..0c6f5d5 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/DOCS.TAB/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/OFFSETS/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/POSITIONS/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/SCHEMA/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/TMAP/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/config.ini/1.1/Mon Mar 7 19:57:18 2011// diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..cbd19db --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help/jhelp/JavaHelpSearch diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS b/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..0209b0d Binary files /dev/null and b/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..531ffba --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÝÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿ@þÿúªûû»¿¾ëªú﮾û¾ªªªªêªª¯¯êþº¯ª«ª®ªú®îº®ªúªªê®êªª»ªêªªª®ªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/am1simulator/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..a7fedd8 Binary files /dev/null and b/res/module/am1simulator/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/am1simulator/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..4a6e7f5 Binary files /dev/null and b/res/module/am1simulator/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/am1simulator/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..2ac0b52 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=297 id2=1 diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/TMAP b/res/module/am1simulator/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..09b6e78 Binary files /dev/null and b/res/module/am1simulator/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/am1simulator/help/jhelp/JavaHelpSearch/config.ini b/res/module/am1simulator/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/am1simulator/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/am1simulator/help/jhelp/am1simulatorIndex.xml b/res/module/am1simulator/help/jhelp/am1simulatorIndex.xml new file mode 100644 index 0000000..3a2aada --- /dev/null +++ b/res/module/am1simulator/help/jhelp/am1simulatorIndex.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/res/module/am1simulator/help/jhelp/am1simulatorMap.jhm b/res/module/am1simulator/help/jhelp/am1simulatorMap.jhm new file mode 100644 index 0000000..61ee4e6 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/am1simulatorMap.jhm @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/am1simulator/help/jhelp/am1simulatorTOC.xml b/res/module/am1simulator/help/jhelp/am1simulatorTOC.xml new file mode 100644 index 0000000..bdbd605 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/am1simulatorTOC.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/am1simulator/help/jhelp/am1simulator_help.hs b/res/module/am1simulator/help/jhelp/am1simulator_help.hs new file mode 100644 index 0000000..42d6ce2 --- /dev/null +++ b/res/module/am1simulator/help/jhelp/am1simulator_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum AM1-Simulator Modul + + + + + am0c0 + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + am1simulatorTOC.xml + + + + Index + + javax.help.IndexView + am1simulatorIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/am1simulator/help/pics/CVS/Entries b/res/module/am1simulator/help/pics/CVS/Entries new file mode 100644 index 0000000..4ce5ab6 --- /dev/null +++ b/res/module/am1simulator/help/pics/CVS/Entries @@ -0,0 +1,7 @@ +/am1simulator.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/editor.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/initial_configuration.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/load_save.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/logo_help.png/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/presentation_mode.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/step_counter.jpg/1.1/Mon Mar 7 19:57:18 2011/-kb/ diff --git a/res/module/am1simulator/help/pics/CVS/Repository b/res/module/am1simulator/help/pics/CVS/Repository new file mode 100644 index 0000000..52f8861 --- /dev/null +++ b/res/module/am1simulator/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/am1simulator/help/pics diff --git a/res/module/am1simulator/help/pics/CVS/Root b/res/module/am1simulator/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/am1simulator/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/am1simulator/help/pics/am1simulator.jpg b/res/module/am1simulator/help/pics/am1simulator.jpg new file mode 100644 index 0000000..175b901 Binary files /dev/null and b/res/module/am1simulator/help/pics/am1simulator.jpg differ diff --git a/res/module/am1simulator/help/pics/editor.jpg b/res/module/am1simulator/help/pics/editor.jpg new file mode 100644 index 0000000..fe1e06a Binary files /dev/null and b/res/module/am1simulator/help/pics/editor.jpg differ diff --git a/res/module/am1simulator/help/pics/initial_configuration.jpg b/res/module/am1simulator/help/pics/initial_configuration.jpg new file mode 100644 index 0000000..c7940e4 Binary files /dev/null and b/res/module/am1simulator/help/pics/initial_configuration.jpg differ diff --git a/res/module/am1simulator/help/pics/load_save.jpg b/res/module/am1simulator/help/pics/load_save.jpg new file mode 100644 index 0000000..ee72bb6 Binary files /dev/null and b/res/module/am1simulator/help/pics/load_save.jpg differ diff --git a/res/module/am1simulator/help/pics/logo_help.png b/res/module/am1simulator/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/module/am1simulator/help/pics/logo_help.png differ diff --git a/res/module/am1simulator/help/pics/presentation_mode.jpg b/res/module/am1simulator/help/pics/presentation_mode.jpg new file mode 100644 index 0000000..68d1d86 Binary files /dev/null and b/res/module/am1simulator/help/pics/presentation_mode.jpg differ diff --git a/res/module/am1simulator/help/pics/step_counter.jpg b/res/module/am1simulator/help/pics/step_counter.jpg new file mode 100644 index 0000000..3b77b67 Binary files /dev/null and b/res/module/am1simulator/help/pics/step_counter.jpg differ diff --git a/res/module/am1simulator/help/style.css b/res/module/am1simulator/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/am1simulator/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/app/CVS/Entries b/res/module/app/CVS/Entries new file mode 100644 index 0000000..275c3d2 --- /dev/null +++ b/res/module/app/CVS/Entries @@ -0,0 +1,3 @@ +D/help//// +D/images//// +/style.css/1.1/Wed Oct 29 18:05:26 2008/-kb/ diff --git a/res/module/app/CVS/Repository b/res/module/app/CVS/Repository new file mode 100644 index 0000000..4a498b2 --- /dev/null +++ b/res/module/app/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app diff --git a/res/module/app/CVS/Root b/res/module/app/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/CVS/Entries b/res/module/app/help/CVS/Entries new file mode 100644 index 0000000..b931d74 --- /dev/null +++ b/res/module/app/help/CVS/Entries @@ -0,0 +1,3 @@ +D/html//// +D/jhelp//// +D/pics//// diff --git a/res/module/app/help/CVS/Repository b/res/module/app/help/CVS/Repository new file mode 100644 index 0000000..d0f16fc --- /dev/null +++ b/res/module/app/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help diff --git a/res/module/app/help/CVS/Root b/res/module/app/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/html/CVS/Entries b/res/module/app/help/html/CVS/Entries new file mode 100644 index 0000000..4c062d9 --- /dev/null +++ b/res/module/app/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Wed Oct 29 18:05:25 2008// +D/data//// +/index.htm/1.1/Wed Oct 29 18:05:25 2008// +/top_frame.htm/1.1/Wed Oct 29 18:05:25 2008// diff --git a/res/module/app/help/html/CVS/Repository b/res/module/app/help/html/CVS/Repository new file mode 100644 index 0000000..264dfba --- /dev/null +++ b/res/module/app/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help/html diff --git a/res/module/app/help/html/CVS/Root b/res/module/app/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/html/contents.htm b/res/module/app/help/html/contents.htm new file mode 100644 index 0000000..d50985c --- /dev/null +++ b/res/module/app/help/html/contents.htm @@ -0,0 +1,47 @@ + + + Inhaltsverzeichnis + + + + +
      +Das Modul Algebraisches Pfadproblem + +
    + + + \ No newline at end of file diff --git a/res/module/app/help/html/data/CVS/Entries b/res/module/app/help/html/data/CVS/Entries new file mode 100644 index 0000000..0b6f5f4 --- /dev/null +++ b/res/module/app/help/html/data/CVS/Entries @@ -0,0 +1,5 @@ +/example.htm/1.1/Wed Oct 29 18:05:25 2008// +/graphedit.htm/1.1/Wed Oct 29 18:05:25 2008// +/overview.htm/1.1/Wed Oct 29 18:05:25 2008// +/run.htm/1.1/Wed Oct 29 18:05:25 2008// +/semiring.htm/1.1/Wed Oct 29 18:05:25 2008// diff --git a/res/module/app/help/html/data/CVS/Repository b/res/module/app/help/html/data/CVS/Repository new file mode 100644 index 0000000..3db1d80 --- /dev/null +++ b/res/module/app/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help/html/data diff --git a/res/module/app/help/html/data/CVS/Root b/res/module/app/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/html/data/example.htm b/res/module/app/help/html/data/example.htm new file mode 100644 index 0000000..7b72c62 --- /dev/null +++ b/res/module/app/help/html/data/example.htm @@ -0,0 +1,81 @@ + + + Einleitung + + + + + + +

    Beispiel

    +

    + Dieser Abschnitt führt Schritt für Schritt in die Verwendung des APP-Moduls ein. + Dafür wird beispielhaft ein kürzestes Wege-Problem erstellt und die Berechnung durchgeführt. +

    + +

    Das kürzeste Wege-Problem

    + +

    + Wählen Sie als Semiring "Kürzestes Wege Problem" aus und klicken Sie auf die Schaltfläche "OK". + Die Programmoberfläche zum Eingeben des Graphen wird aktiviert. +

    +
    + +
    +Semiringauswahl +
    +
    + +

    Graph erstellen

    +

    + Klicken Sie auf die Zeichenfläche um neue Knoten zu erstellen. + Nach Auswahl des Kanten-Editier-Modus werden die Kanten vom Startknoten zum Endknoten gezogen. + Mit einem Doppelklick auf die Beschriftung kann diese geändert werden. +

    +
    + +
    +Knoten und Kanten erstellen +
    +
    + +

    Algorithmus durchführen

    +

    + Ist der Graph erstellt, wechseln Sie mit der "Durchführen"-Schaltfläche zum Algorithmus-Ablauf-Modus. +

    +
    + +
    +Umschalter für Bearbeiten- und Ablaufmodus +
    + +

    + Mit den Vor- und Zurück-Schaltflächen können Sie nun durch die einzelnen Schritte des Algorithmus navigieren. + Der Aho-Algorithmus wählt einen Zwischenknoten, der rot markiert wird. Dann wird eine neue Matrix berechnet, + indem je ein Knoten als Anfangs- bzw. Endknoten gewählt wird. +
    +

    + Graph und Matrix mit Färbung +
    +
    +

    + +

    Die Berechnung

    +

    + Die durch die Formel gezeigte Berechnung ermitteln nun, + ob es einen kürzeren Weg über den gewählten Zwischenknoten vom Anfangs- zum Endknoten gibt. +
    +

    + Formel +
    +
    + Ist das der Fall, wird die rechte Matrix mit dem neuen Wert an der Schwarz markierten Position aktualisiert. + Andernfalls wird der ursprüngliche Wert, der anfangs grau dargestellt wird, übernommen. +
    +
    + Eine Matrix stellt die Ergebnisse der Berechnungen für alle möglichen Kombinationen von Anfangs- und Endknoten für einen bestimmten Zwischenknoten dar. + Mit den Großen Schritten springt die Berechnung zum Anfang der nächsten oder der vorhergehenden bzw. aktuellen Matrix. +

    + + + \ No newline at end of file diff --git a/res/module/app/help/html/data/graphedit.htm b/res/module/app/help/html/data/graphedit.htm new file mode 100644 index 0000000..f76fcaf --- /dev/null +++ b/res/module/app/help/html/data/graphedit.htm @@ -0,0 +1,50 @@ + + + Grapherstellung + + + + + + +

    Graph erstellen

    +

    +Die Grapherstellung oder -bearbeitung erfolgt direkt über die Zeichenfläche oder mit Hilfe der Kantenliste. +

    + +

    Die Zeichenfläche

    +

    +Mit Klicken und Ziehen können auf der Zeichenfläche Knoten und Kanten hinzugefügt und Knoten verschoben werden. +Das Gewicht der Kanten lässt sich nach einem Doppelklick ändern. +Mit der Entfernen-Taste können Knoten und Kanten wieder entfernt werden.
    + +Die Werkzeugleiste stellt folgende Funktionen zur Verfügung.

    +

    + +
    +Werkzeugleiste +
    + +

    Die Kantenliste

    +

    +In die Kantenliste kann der Graph in seiner Tupelschreibweise eingegeben werden. +Ein Tupel besteht aus Anfangsknoten, Kantengewicht und Endknoten. Die Tupel werden mit Komma getrennt. +Solange die Eingabe nicht korrekt ist, wird sie rot unterstrichen und nicht akzeptiert.
    +

    + +
    +Werkzeugleiste +
    + +

    Algorithmus starten

    +

    +Der Ablauf des Algorithmus wird mit der Durchführen-Schaltfläche gestartet. +Natürlich ist danach mit der Betätigung der Bearbeiten-Schaltfläche ein Wechsel zurück zum Bearbeiten-Modus möglich. +

    + +
    +Umschalter für Bearbeiten- und Ablaufmodus +
    + + + \ No newline at end of file diff --git a/res/module/app/help/html/data/overview.htm b/res/module/app/help/html/data/overview.htm new file mode 100644 index 0000000..a83844a --- /dev/null +++ b/res/module/app/help/html/data/overview.htm @@ -0,0 +1,42 @@ + + + Einleitung + + + + + + +

    Das Modul Algebraisches Pfadproblem

    + +

    Einleitung

    +

    Das Modul ermöglicht es Ihnen sich intensiv mit algebraischen Pfadproblemen auseinanderzusetzen. + Es können fünf ausgewählte Pfadprobleme können mit dem Aho-Algorithmus gelöst werden. + Sie können einen Graphen selbst erstellen oder einen Beispielgraphen laden. + Dazu stehen die Beispiele aus dem Algorithmen und Datenstrukturen-Skript von Professor Vogler (WS2008/09) zur Verfügung. +

    + +

    Funktionsübersicht

    + +

    Folgende Funktionen werden vom Modul Algebraisches Pfadproblem realisiert:

    +
      +
    • +
      graphisches Erstellen / Bearbeiten eines Graphen
      +
    • +
      Speichern und Laden von Graphen
      +
    • +
      Visualisierung des Aho-Algorithmus
      +
    • +
    +
    + +

    Modul starten

    +

    Um das Modul zu starten, wählt man im Menü <Datei> +das Submenü +<Neu> und dann den Menübefehl +<Algebraisches Pfadproblem>. Im Hauptfenster erscheint nun die +Oberfläche des APP - Moduls im +Eingabe-Modus.

    + + + \ No newline at end of file diff --git a/res/module/app/help/html/data/run.htm b/res/module/app/help/html/data/run.htm new file mode 100644 index 0000000..62ce8a1 --- /dev/null +++ b/res/module/app/help/html/data/run.htm @@ -0,0 +1,58 @@ + + + Algorithmenablauf + + + + + + +

    Ablauf des Algorithmus

    + +

    Ablaufsteuerung

    +

    +Die Schritte des Algorithmus können einzeln oder gruppenweise ausgeführt werden. +Mit folgenden Aktionen kann der Ablauf des Algorithmus gesteuert werden: +

    +
    + + +
    +Schaltflächen zum Algorithmenablauf +
    +
    + +

    +Der Graph und die Berechnungsmatrizen werden nebeneinander dargestellt. +Ein kleiner Schritt ist hierbei die Berechnung einer Zelle in der Matrix, während in einem großem Schritt eine komplette Matrix berechnet wird. +Siehe Beispiel zur genaueren Beschreibung der einzelnen Schritte. +

    +
    + +
    +Schaltflächen zum Algorithmenablauf +
    +
    +

    +Mit der Schaltfläche "Beamer-Modus" werden die Schriften vergößert und die Darstelllung für die Anzeige mit einem Beamer optimiert. +Ein Klick auf die Lupe öffnet ein Fenster mit einer vergrößerten Darstellung der Formel. +

    + +

    Bedeutung der Farben

    + +

    +Zu jedem Schritt werden die zur Berechnung herangezogenen Werte und das Ergebnis im Graphen beziehungsweise der Matrix farbig hervorgehoben. +Die Farben haben dabei folgende Bedeutung: +

      +
    • Rot ist der aktuelle Zwischenknoten im Graphen.
    • +
    • Grün ist der Startknoten und der Weg vom Startknoten zum Zwischenknoten.
    • +
    • Blau ist der Endknoten und der Weg vom Zwischenkoten zum Endknoten.
    • +
    +

    +
    +Graph mit Färbung +
    + + + + \ No newline at end of file diff --git a/res/module/app/help/html/data/semiring.htm b/res/module/app/help/html/data/semiring.htm new file mode 100644 index 0000000..c7a5402 --- /dev/null +++ b/res/module/app/help/html/data/semiring.htm @@ -0,0 +1,24 @@ + + + Semiring + + + + + + +

    Semiring auswählen

    +
    +Aus dem Drop-Down-Menü kann der gewünschte Semiring ausgewählt werden. Die Auswahl wird mit der OK-Schaltfläche bestätigt.
    +
    +
    + +
    +Semiringauswahl +
    + +
    +Nach erfolgter Auswahl bestehen unterschiedliche Möglichkeiten den Graph einzugeben. +
    + + \ No newline at end of file diff --git a/res/module/app/help/html/index.htm b/res/module/app/help/html/index.htm new file mode 100644 index 0000000..1bb6a27 --- /dev/null +++ b/res/module/app/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum Algebraisches Pfadproblem Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/app/help/html/top_frame.htm b/res/module/app/help/html/top_frame.htm new file mode 100644 index 0000000..afd3315 --- /dev/null +++ b/res/module/app/help/html/top_frame.htm @@ -0,0 +1,12 @@ + + + oberer_frame + + + + + Logo + + + + \ No newline at end of file diff --git a/res/module/app/help/jhelp/CVS/Entries b/res/module/app/help/jhelp/CVS/Entries new file mode 100644 index 0000000..6672df8 --- /dev/null +++ b/res/module/app/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/appIndex.xml/1.1/Wed Oct 29 18:05:26 2008// +/appTOC.xml/1.1/Wed Oct 29 18:05:26 2008// +/app_help.hs/1.1/Wed Oct 29 18:05:26 2008/-kb/ +/map.jhm/1.1/Wed Oct 29 18:05:26 2008/-kb/ diff --git a/res/module/app/help/jhelp/CVS/Repository b/res/module/app/help/jhelp/CVS/Repository new file mode 100644 index 0000000..e3dce8d --- /dev/null +++ b/res/module/app/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help/jhelp diff --git a/res/module/app/help/jhelp/CVS/Root b/res/module/app/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..e8fd0fd --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/DOCS.TAB/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/OFFSETS/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/POSITIONS/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/SCHEMA/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/TMAP/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/config.ini/1.1/Wed Oct 29 18:05:25 2008// diff --git a/res/module/app/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..65bf2f0 --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help/jhelp/JavaHelpSearch diff --git a/res/module/app/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/jhelp/JavaHelpSearch/DOCS b/res/module/app/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..d52aeea Binary files /dev/null and b/res/module/app/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/app/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/app/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..e010f08 --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿý—ÿÿÿÿÿÿÿÿÿÿÿÝÿôz¿îî«î»®úîû¯îþú뾺ûïþÿªº»ªºªªêªêªêªªªªîªªªªêªªªªªªªªªª®ªªªªªªªªªªªªªªªªª˜ \ No newline at end of file diff --git a/res/module/app/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/app/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..e7f038e Binary files /dev/null and b/res/module/app/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/app/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/app/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..029fd44 Binary files /dev/null and b/res/module/app/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/app/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/app/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..7bcf862 --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=298 id2=1 diff --git a/res/module/app/help/jhelp/JavaHelpSearch/TMAP b/res/module/app/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..409ef4f Binary files /dev/null and b/res/module/app/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/app/help/jhelp/JavaHelpSearch/config.ini b/res/module/app/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/app/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/app/help/jhelp/appIndex.xml b/res/module/app/help/jhelp/appIndex.xml new file mode 100644 index 0000000..bb81ef2 --- /dev/null +++ b/res/module/app/help/jhelp/appIndex.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/app/help/jhelp/appTOC.xml b/res/module/app/help/jhelp/appTOC.xml new file mode 100644 index 0000000..73fe27a --- /dev/null +++ b/res/module/app/help/jhelp/appTOC.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/app/help/jhelp/app_help.hs b/res/module/app/help/jhelp/app_help.hs new file mode 100644 index 0000000..defdd62 --- /dev/null +++ b/res/module/app/help/jhelp/app_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum APP-Modul + + + + + app + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + appTOC.xml + + + + Index + + javax.help.IndexView + appIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/app/help/jhelp/map.jhm b/res/module/app/help/jhelp/map.jhm new file mode 100644 index 0000000..8e88bec --- /dev/null +++ b/res/module/app/help/jhelp/map.jhm @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/app/help/pics/BeamerModeButton.png b/res/module/app/help/pics/BeamerModeButton.png new file mode 100644 index 0000000..3a7228f Binary files /dev/null and b/res/module/app/help/pics/BeamerModeButton.png differ diff --git a/res/module/app/help/pics/CVS/Entries b/res/module/app/help/pics/CVS/Entries new file mode 100644 index 0000000..44ec189 --- /dev/null +++ b/res/module/app/help/pics/CVS/Entries @@ -0,0 +1,15 @@ +/BeamerModeButton.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/EdgeList.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/EditMode.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/EditToolbar.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/ModeSwitcher.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/RunMode.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/exampleedit.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/exampleformular.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/examplerun1.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/graph.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/logo_help.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/run.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/runbuttons.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/semiring.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/togglebutton.png/1.1/Wed Oct 29 18:05:24 2008/-kb/ diff --git a/res/module/app/help/pics/CVS/Repository b/res/module/app/help/pics/CVS/Repository new file mode 100644 index 0000000..ea9fbe9 --- /dev/null +++ b/res/module/app/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/help/pics diff --git a/res/module/app/help/pics/CVS/Root b/res/module/app/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/help/pics/EdgeList.png b/res/module/app/help/pics/EdgeList.png new file mode 100644 index 0000000..7f69d66 Binary files /dev/null and b/res/module/app/help/pics/EdgeList.png differ diff --git a/res/module/app/help/pics/EditMode.png b/res/module/app/help/pics/EditMode.png new file mode 100644 index 0000000..5f8899c Binary files /dev/null and b/res/module/app/help/pics/EditMode.png differ diff --git a/res/module/app/help/pics/EditToolbar.png b/res/module/app/help/pics/EditToolbar.png new file mode 100644 index 0000000..928f0d3 Binary files /dev/null and b/res/module/app/help/pics/EditToolbar.png differ diff --git a/res/module/app/help/pics/ModeSwitcher.png b/res/module/app/help/pics/ModeSwitcher.png new file mode 100644 index 0000000..17429c5 Binary files /dev/null and b/res/module/app/help/pics/ModeSwitcher.png differ diff --git a/res/module/app/help/pics/RunMode.png b/res/module/app/help/pics/RunMode.png new file mode 100644 index 0000000..28b77f2 Binary files /dev/null and b/res/module/app/help/pics/RunMode.png differ diff --git a/res/module/app/help/pics/exampleedit.png b/res/module/app/help/pics/exampleedit.png new file mode 100644 index 0000000..860d5df Binary files /dev/null and b/res/module/app/help/pics/exampleedit.png differ diff --git a/res/module/app/help/pics/exampleformular.png b/res/module/app/help/pics/exampleformular.png new file mode 100644 index 0000000..865e68c Binary files /dev/null and b/res/module/app/help/pics/exampleformular.png differ diff --git a/res/module/app/help/pics/examplerun1.png b/res/module/app/help/pics/examplerun1.png new file mode 100644 index 0000000..b0bdeb5 Binary files /dev/null and b/res/module/app/help/pics/examplerun1.png differ diff --git a/res/module/app/help/pics/graph.png b/res/module/app/help/pics/graph.png new file mode 100644 index 0000000..5ec78e9 Binary files /dev/null and b/res/module/app/help/pics/graph.png differ diff --git a/res/module/app/help/pics/logo_help.png b/res/module/app/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/module/app/help/pics/logo_help.png differ diff --git a/res/module/app/help/pics/run.png b/res/module/app/help/pics/run.png new file mode 100644 index 0000000..292adb6 Binary files /dev/null and b/res/module/app/help/pics/run.png differ diff --git a/res/module/app/help/pics/runbuttons.png b/res/module/app/help/pics/runbuttons.png new file mode 100644 index 0000000..4a2299e Binary files /dev/null and b/res/module/app/help/pics/runbuttons.png differ diff --git a/res/module/app/help/pics/semiring.png b/res/module/app/help/pics/semiring.png new file mode 100644 index 0000000..c311376 Binary files /dev/null and b/res/module/app/help/pics/semiring.png differ diff --git a/res/module/app/help/pics/togglebutton.png b/res/module/app/help/pics/togglebutton.png new file mode 100644 index 0000000..681bcc2 Binary files /dev/null and b/res/module/app/help/pics/togglebutton.png differ diff --git a/res/module/app/images/CVS/Entries b/res/module/app/images/CVS/Entries new file mode 100644 index 0000000..a5f5cd1 --- /dev/null +++ b/res/module/app/images/CVS/Entries @@ -0,0 +1,29 @@ +/animation_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/beamermode_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/edit_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/edit_button_s.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/edit_edges.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/edit_nodes.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/formula_component.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/go_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/go_button_s.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/graph_component_editmode.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/graph_component_runmode.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/groupstep_backward.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/groupstep_forward.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/logo.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/matrix1_component.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/matrix2_component.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/matrix_preview.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/minus_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/modifie_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/old_start_task.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/order_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/plus_button.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/redo.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/start_task.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/step_backward.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/step_forward.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/suspend.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/undo.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ +/zoom.gif/1.1/Wed Oct 29 18:05:24 2008/-kb/ diff --git a/res/module/app/images/CVS/Repository b/res/module/app/images/CVS/Repository new file mode 100644 index 0000000..b258e2e --- /dev/null +++ b/res/module/app/images/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/app/images diff --git a/res/module/app/images/CVS/Root b/res/module/app/images/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/app/images/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/app/images/animation_button.gif b/res/module/app/images/animation_button.gif new file mode 100644 index 0000000..d9e4737 Binary files /dev/null and b/res/module/app/images/animation_button.gif differ diff --git a/res/module/app/images/beamermode_button.gif b/res/module/app/images/beamermode_button.gif new file mode 100644 index 0000000..9d0bdfa Binary files /dev/null and b/res/module/app/images/beamermode_button.gif differ diff --git a/res/module/app/images/edit_button.gif b/res/module/app/images/edit_button.gif new file mode 100644 index 0000000..7b6406a Binary files /dev/null and b/res/module/app/images/edit_button.gif differ diff --git a/res/module/app/images/edit_button_s.gif b/res/module/app/images/edit_button_s.gif new file mode 100644 index 0000000..60357d2 Binary files /dev/null and b/res/module/app/images/edit_button_s.gif differ diff --git a/res/module/app/images/edit_edges.gif b/res/module/app/images/edit_edges.gif new file mode 100644 index 0000000..bd2a0eb Binary files /dev/null and b/res/module/app/images/edit_edges.gif differ diff --git a/res/module/app/images/edit_nodes.gif b/res/module/app/images/edit_nodes.gif new file mode 100644 index 0000000..dfca92b Binary files /dev/null and b/res/module/app/images/edit_nodes.gif differ diff --git a/res/module/app/images/formula_component.gif b/res/module/app/images/formula_component.gif new file mode 100644 index 0000000..b971301 Binary files /dev/null and b/res/module/app/images/formula_component.gif differ diff --git a/res/module/app/images/go_button.gif b/res/module/app/images/go_button.gif new file mode 100644 index 0000000..7f88774 Binary files /dev/null and b/res/module/app/images/go_button.gif differ diff --git a/res/module/app/images/go_button_s.gif b/res/module/app/images/go_button_s.gif new file mode 100644 index 0000000..b5792b1 Binary files /dev/null and b/res/module/app/images/go_button_s.gif differ diff --git a/res/module/app/images/graph_component_editmode.gif b/res/module/app/images/graph_component_editmode.gif new file mode 100644 index 0000000..e00d5ce Binary files /dev/null and b/res/module/app/images/graph_component_editmode.gif differ diff --git a/res/module/app/images/graph_component_runmode.gif b/res/module/app/images/graph_component_runmode.gif new file mode 100644 index 0000000..c2aa340 Binary files /dev/null and b/res/module/app/images/graph_component_runmode.gif differ diff --git a/res/module/app/images/groupstep_backward.gif b/res/module/app/images/groupstep_backward.gif new file mode 100644 index 0000000..a8ab64f Binary files /dev/null and b/res/module/app/images/groupstep_backward.gif differ diff --git a/res/module/app/images/groupstep_forward.gif b/res/module/app/images/groupstep_forward.gif new file mode 100644 index 0000000..57bcaea Binary files /dev/null and b/res/module/app/images/groupstep_forward.gif differ diff --git a/res/module/app/images/logo.gif b/res/module/app/images/logo.gif new file mode 100644 index 0000000..2a209a9 Binary files /dev/null and b/res/module/app/images/logo.gif differ diff --git a/res/module/app/images/matrix1_component.gif b/res/module/app/images/matrix1_component.gif new file mode 100644 index 0000000..951c493 Binary files /dev/null and b/res/module/app/images/matrix1_component.gif differ diff --git a/res/module/app/images/matrix2_component.gif b/res/module/app/images/matrix2_component.gif new file mode 100644 index 0000000..980303a Binary files /dev/null and b/res/module/app/images/matrix2_component.gif differ diff --git a/res/module/app/images/matrix_preview.gif b/res/module/app/images/matrix_preview.gif new file mode 100644 index 0000000..22d09a8 Binary files /dev/null and b/res/module/app/images/matrix_preview.gif differ diff --git a/res/module/app/images/minus_button.gif b/res/module/app/images/minus_button.gif new file mode 100644 index 0000000..e8ba108 Binary files /dev/null and b/res/module/app/images/minus_button.gif differ diff --git a/res/module/app/images/modifie_button.gif b/res/module/app/images/modifie_button.gif new file mode 100644 index 0000000..91d7a6d Binary files /dev/null and b/res/module/app/images/modifie_button.gif differ diff --git a/res/module/app/images/old_start_task.gif b/res/module/app/images/old_start_task.gif new file mode 100644 index 0000000..003d21e Binary files /dev/null and b/res/module/app/images/old_start_task.gif differ diff --git a/res/module/app/images/order_button.gif b/res/module/app/images/order_button.gif new file mode 100644 index 0000000..bcfb9dc Binary files /dev/null and b/res/module/app/images/order_button.gif differ diff --git a/res/module/app/images/plus_button.gif b/res/module/app/images/plus_button.gif new file mode 100644 index 0000000..da6b070 Binary files /dev/null and b/res/module/app/images/plus_button.gif differ diff --git a/res/module/app/images/redo.gif b/res/module/app/images/redo.gif new file mode 100644 index 0000000..c84e5b1 Binary files /dev/null and b/res/module/app/images/redo.gif differ diff --git a/res/module/app/images/start_task.gif b/res/module/app/images/start_task.gif new file mode 100644 index 0000000..c15fe39 Binary files /dev/null and b/res/module/app/images/start_task.gif differ diff --git a/res/module/app/images/step_backward.gif b/res/module/app/images/step_backward.gif new file mode 100644 index 0000000..4551e4f Binary files /dev/null and b/res/module/app/images/step_backward.gif differ diff --git a/res/module/app/images/step_forward.gif b/res/module/app/images/step_forward.gif new file mode 100644 index 0000000..b5ee47e Binary files /dev/null and b/res/module/app/images/step_forward.gif differ diff --git a/res/module/app/images/suspend.gif b/res/module/app/images/suspend.gif new file mode 100644 index 0000000..251f0ba Binary files /dev/null and b/res/module/app/images/suspend.gif differ diff --git a/res/module/app/images/undo.gif b/res/module/app/images/undo.gif new file mode 100644 index 0000000..eae118a Binary files /dev/null and b/res/module/app/images/undo.gif differ diff --git a/res/module/app/images/zoom.gif b/res/module/app/images/zoom.gif new file mode 100644 index 0000000..6af9d5e Binary files /dev/null and b/res/module/app/images/zoom.gif differ diff --git a/res/module/app/style.css b/res/module/app/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/app/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/avl/CVS/Entries b/res/module/avl/CVS/Entries new file mode 100644 index 0000000..100f5f0 --- /dev/null +++ b/res/module/avl/CVS/Entries @@ -0,0 +1,5 @@ +/avl.prefs/1.1/Fri Mar 24 16:02:44 2006/-kk/ +/avl_algdesc.de.xml/1.3/Mon Dec 19 19:15:01 2005// +/avl_algdesc.en.xml/1.2/Sat Mar 4 13:36:26 2006/-kk/ +D/avl_pix//// +D/help//// diff --git a/res/module/avl/CVS/Repository b/res/module/avl/CVS/Repository new file mode 100644 index 0000000..afbd6b9 --- /dev/null +++ b/res/module/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl diff --git a/res/module/avl/CVS/Root b/res/module/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/avl.prefs b/res/module/avl/avl.prefs new file mode 100644 index 0000000..bf0ba05 --- /dev/null +++ b/res/module/avl/avl.prefs @@ -0,0 +1,3 @@ +#j-Algo Default-Settings for AVL-Module +Version=1.0.1 +BeamerMode=false diff --git a/res/module/avl/avl_algdesc.de.xml b/res/module/avl/avl_algdesc.de.xml new file mode 100644 index 0000000..fafdb93 --- /dev/null +++ b/res/module/avl/avl_algdesc.de.xml @@ -0,0 +1,379 @@ + + !--> + + + + + +]> + + + + + search1 + + Schlüsselsuche im Suchbaum: + + a) Falls der Baum leer ist, dann "Schlüssel nicht im Baum vorhanden" + + b) Falls der Suchschlüssel gleich dem aktuellen Schlüssel ist, dann "Schlüssel gefunden" + + c) Falls der Suchschlüssel kleiner ist, als der aktuelle Schlüssel, + + wiederhole diesen Schritt im linken Teilbaum + + d) Falls der Suchschlüssel größer ist, als der aktuelle Schlüssel, + + wiederhole diesen Schritt im rechten Teilbaum + + + + + + search1newline + + + + + + insert1 + + 1. Suche Stelle zum Einfügen eines Schlüssels s: + + a) Falls der Baum leer ist, dann Einfügestelle gefunden, gehe zu Schritt 2 + + b) Falls der neue Schlüssel gleich dem aktuellen Schlüssel ist, + + dann Schlüssel schon vorhanden, Einfügen abbrechen + + c) Falls der neue Schlüssel kleiner ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im linken Teilbaum + + d) Falls der neue Schlüssel größer ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im rechten Teilbaum + + + + + + insert1newline + + + + + insert2 + + + 2. Knoten mit neuem Schlüssel an gefundene Stelle einfügen + + + + + insert2newline + + + + + + avlinsert1 + + 1. Suche Stelle zum Einfügen: + + a) Falls der Baum leer ist, dann Einfügestelle gefunden, gehe zu Schritt 2 + + b) Falls der neue Schlüssel gleich dem aktuellen Schlüssel ist, + + dann Schlüssel schon vorhanden, Einfügen abbrechen + + c) Falls der neue Schlüssel kleiner ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im linken Teilbaum + + d) Falls der neue Schlüssel größer ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im rechten Teilbaum + + + + + + avlinsert1newline + + + + + avlinsert2 + + + 2. neuen Knoten n an gefundene Stelle einfügen + + Balance von n aktualisieren (auf 0 setzen). + + n auf den Vorgängerknoten von n setzen, falls dieser existiert + + Sonst "fertig". + + + + + + avlinsert2newline + + + + + avlinsert3a + + + 3. Balancen aktualisieren am aktuellen Knoten n + + a) Falls neuer Schlüssel im linken Unterbaum von n eingefügt wurde: + + i) wenn n->balance==1, dann n->balance=0, Algorithmus beendet + + ii) wenn n->balance==0, dann n->balance=-1, wiederhole diesen Schritt + + mit dem Vorgängerknoten von n. Falls dieser nicht existiert, Algorithmus beendet + + iii) wenn n->balance==-1 und n->left->balance==-1, + + dann führe eine Rechtsrotation um n durch. + + iv) wenn n->balance==-1 und n->left->balance==1, + + dann führe Linksrotation um n->left und Rechtsrotation um n durch + + + + + + avlinsert3anewline + + + + + avlinsert3b + + + b) Falls neuer Schlüssel im rechten Unterbaum von n eingefügt wurde: + + i) wenn n->balance==-1, dann n->balance=0, Algorithmus beendet + + ii) wenn n->balance==0, dann n->balance=1, wiederhole diesen Schritt + + mit dem Vorgängerknoten von n. Falls dieser nicht existiert, gehe zu Algorithmus beendet + + iii) wenn n->balance==1 und n->right->balance==1, + + dann führe eine Linksrotation um n durch. + + iv) wenn n->balance==1 und n->right->balance==-1, + + dann führe Rechtsrotation um n->right und Linksrotation um n durch + + + + + + avlinsert3bnewline + + + + + remove1 + + 1. Schlüsselsuche: + + a) Falls der Baum leer ist, dann Löschen beendet (Schlüssel nicht vorhanden) + + b) Falls der neue Schlüssel gleich dem aktuellen Schlüssel ist, + + dann Schlüssel gefunden, gehe zu Schritt 2 + + c) Falls der neue Schlüssel kleiner ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im linken Teilbaum + + d) Falls der neue Schlüssel größer ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im rechten Teilbaum + + + + + + remove1newline + + + + + remove2 + + 2. Fallunterscheidung + + a) Falls zu löschender Knoten Blatt --> fertig + + b) Falls zu löschender Knoten keinen rechten Nachfolger hat, + + dann Knoten durch linken Teilbaum ersetzen + + c) sonst nächstgrößeren Schlüssel suchen (gehe zu Schritt 3) + + + + + + remove2newline + + + + + remove3 + + 3. Nächstgrößeren Schlüssel suchen + + Einmal nach rechts gehen und dann solange nach links, + + bis kein linker Nachfolger mehr da ist. + + + + + + remove3newline + + + + + remove4 + + 4. Schlüsselersetzen + + Ersetze zu löschenden Schlüssel durch nächstgrößeren Schlüssel. + + Dessen rechter Teilbaum wird dabei umgehangen. + + Algorithmus beendet + + + + + + remove4newline + + + + + avlremove1 + + 1. Schlüsselsuche: + + a) Falls der Baum leer ist, dann Löschen beendet (Schlüssel nicht vorhanden) + + b) Falls der neue Schlüssel gleich dem aktuellen Schlüssel ist, + + dann Schlüssel gefunden, gehe zu Schritt 2 + + c) Falls der neue Schlüssel kleiner ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im linken Teilbaum + + d) Falls der neue Schlüssel größer ist als der aktuelle Schlüssel, + + wiederhole diesen Schritt im rechten Teilbaum + + + + + + avlremove1newline + + + + + avlremove2 + + 2. Fallunterscheidung + + a) Falls zu löschender Knoten Blatt, gehe zu Schritt 5 mit Vaterknoten des zu löschenden. + + b) Falls zu löschender Knoten keinen rechten Nachfolger hat, + + dann Knoten durch linken Teilbaum ersetzen, gehe zu Schritt 5 + + c) sonst nächstgrößeren Schlüssel suchen (gehe zu Schritt 3) + + + + + + avlremove2newline + + + + + avlremove3 + + 3. Nächstgrößeren Schlüssel suchen + + Einmal nach rechts gehen und dann solange nach links, + + bis kein linker Nachfolger mehr da ist. + + + + + + avlremove3newline + + + + + avlremove4 + + 4. Schlüsselersetzen + + Ersetze zu löschenden Schlüssel durch nächstgrößeren Schlüssel. + + Dessen rechter Teilbaum wird dabei umgehangen, falls er existiert. + + Gehe zu Schritt 5 mit dem Vaterknoten des nächstgrößeren Schlüssels + + + + + + avlremove4newline + + + + + avlremove5 + + 5. Balancieren + + Berechne die Balance des aktuellen Knotens. Falls, + + a) Balance 2 und rechte Balance -1, dann Rechts-Links-Rotation + + b) Balance 2 und rechte Balance nicht -1, dann Links-Rotation + + c) Balance -2 und linke Balance 1, dann Links-Rechts-Rotation + + d) Balance -2 und linke Balance nicht 1, dann Rechts-Rotation + + e) sonst keine Rotation. + + Gehe zum Vaterknoten des aktuellen, falls er existiert, sonst Algorithmus beendet + + + + + + avlremove5newline + + + + diff --git a/res/module/avl/avl_algdesc.en.xml b/res/module/avl/avl_algdesc.en.xml new file mode 100644 index 0000000..e13876a --- /dev/null +++ b/res/module/avl/avl_algdesc.en.xml @@ -0,0 +1,379 @@ + + !--> + + + + + +]> + + + + + search1 + + Key search in search tree: + + a) If the tree is empty, then "The key is not in the tree" + + b) If the search key is equal to the current key, then "Key found" + + c) If the search key is less than the current key, + + repeat this step in the left subtree + + d) If the search key is greater than the current key, + + repeat this step in the right subtree + + + + + + search1newline + + + + + + insert1 + + 1. Search position for inserting the key k: + + a) If the tree is empty, position for inserting found, continue with step 2 + + b) If the new key is equal to the current key, + + then the key already exists, abort inserting + + c) If the new key is less than the current key, + + repeat this step in the left subtree + + d) If the new key is greater than the current key, + + repeat this step in the right subtree + + + + + + insert1newline + + + + + insert2 + + + 2. Insert node with the new key at the found position + + + + + insert2newline + + + + + + avlinsert1 + + 1. Search position for inserting the key k: + + a) If the tree is empty, position for inserting found, continue with step 2 + + b) If the new key is equal to the current key, + + then the key already exists, abort inserting + + c) If the new key is less than the current key, + + repeat this step in the left subtree + + d) If the new key is greater than the current key, + + repeat this step in the right subtree + + + + + + avlinsert1newline + + + + + avlinsert2 + + + 2. Insert node n at the found position. + + Update balance of n (set to 0). + + Set n to the parent of n, if it exists + + Else "finished". + + + + + + avlinsert2newline + + + + + avlinsert3a + + + 3. Update balances at the current node n + + a) If the new key was inserted in the left subtree of n: + + i) if n->balance==1, then n->balance=0, algorithm finished + + ii) if n->balance==0, then n->balance=-1, repeat this step + + with the parent of n. If this not exists, algorithm finished + + iii) if n->balance==-1 and n->left->balance==-1, + + then rotate right at n. + + iv) if n->balance==-1 and n->left->balance==1, + + then rotate left at n->left and rotate right at n + + + + + + avlinsert3anewline + + + + + avlinsert3b + + + b) If the new key was inserted in the right subtree of n: + + i) if n->balance==-1, then n->balance=0, algorithm finished + + ii) if n->balance==0, then n->balance=1, repeat this step + + with the parent of n. If this not exists, algorithm finished + + iii) if n->balance==1 and n->right->balance==1, + + then rotate left at n. + + iv) if n->balance==1 and n->right->balance==-1, + + then rotate right at n->right and rotate left at n + + + + + + avlinsert3bnewline + + + + + remove1 + + 1. Search for the key: + + a) If the tree is empty, then algorithm finished (the key not exists) + + b) If the new key is equal to the current key, + + then key found, continue with step 2 + + c) If the new key is less than the current key, + + repeat this step in the left subtree + + d) If the new key is greater than the current key, + + repeat this step in the right subtree + + + + + + remove1newline + + + + + remove2 + + 2. Case differentiation + + a) If the node to be deleted is leaf node --> finished + + b) If the node to be deleted has no right successor, + + then replace node with the left subtree + + c) else search direct successor (go to step 3) + + + + + + remove2newline + + + + + remove3 + + 3. Search symmetric order successor + + Go once to the right, and then to the left, until + + no left successor exists. + + + + + + remove3newline + + + + + remove4 + + 4. Replace the key + + Replace the key to be deleted with it's symmetric order successor. + + The subtree of this will be moved. + + Algorithm finished + + + + + + remove4newline + + + + + avlremove1 + + 1. Search for the key: + + a) If the tree is empty, then algorithm finished (the key not exists) + + b) If the new key is equal to the current key, + + then key found, continue with step 2 + + c) If the new key is less than the current key, + + repeat this step in the left subtree + + d) If the new key is greater than the current key, + + repeat this step in the right subtree + + + + + + avlremove1newline + + + + + avlremove2 + + 2. Case differentiation + + a) If the node to be deleted is leaf node, go to step 5 with it's parent node. + + b) If the node to be deleted has no right successor, + + then replace node with the left subtree, go to step 5 + + c) else search direct successor (go to step 3) + + + + + + avlremove2newline + + + + + avlremove3 + + 3. Search symmetric order successor + + Go once to the right, and then to the left, until + + no left successor exists. + + + + + + avlremove3newline + + + + + avlremove4 + + 4. Replace the key + + Replace the key to be deleted with it's symmetric order successor. + + The right subtree of this will be moved, if it exists. + + Go to step 5 with the parent node of the symmetric order successor. + + + + + + avlremove4newline + + + + + avlremove5 + + 5. Balance the tree + + Calculate the balance of the current node. If, + + a) balance 2 and right balance -1, then right-left-rotation + + b) balance 2 and right balance not -1, then left-rotation + + c) balance -2 and left balance 1, then left-right-rotation + + d) balance -2 and left balance not 1, then right-rotation + + e) else no rotation. + + Repeat this step with the parent of the current node, if it exists. Else algorithm finished + + + + + + avlremove5newline + + + + diff --git a/res/module/avl/avl_pix/CVS/Entries b/res/module/avl/avl_pix/CVS/Entries new file mode 100644 index 0000000..db2f712 --- /dev/null +++ b/res/module/avl/avl_pix/CVS/Entries @@ -0,0 +1,13 @@ +/logo.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_load.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_load_desc_de.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_load_desc_en.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_load_rollover.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_manual.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_manual_desc_de.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_manual_desc_en.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_manual_rollover.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_random.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ +/welcome_random_desc_de.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_random_desc_en.gif/1.2/Sat Mar 4 13:36:10 2006/-kb/ +/welcome_random_rollover.gif/1.1/Sun Jul 10 11:40:24 2005/-kb/ diff --git a/res/module/avl/avl_pix/CVS/Repository b/res/module/avl/avl_pix/CVS/Repository new file mode 100644 index 0000000..ee34f2d --- /dev/null +++ b/res/module/avl/avl_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/avl_pix diff --git a/res/module/avl/avl_pix/CVS/Root b/res/module/avl/avl_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/avl_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/avl_pix/logo.gif b/res/module/avl/avl_pix/logo.gif new file mode 100644 index 0000000..16fa4f8 Binary files /dev/null and b/res/module/avl/avl_pix/logo.gif differ diff --git a/res/module/avl/avl_pix/welcome_load.gif b/res/module/avl/avl_pix/welcome_load.gif new file mode 100644 index 0000000..fcb9730 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_load.gif differ diff --git a/res/module/avl/avl_pix/welcome_load_desc_de.gif b/res/module/avl/avl_pix/welcome_load_desc_de.gif new file mode 100644 index 0000000..d780c22 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_load_desc_de.gif differ diff --git a/res/module/avl/avl_pix/welcome_load_desc_en.gif b/res/module/avl/avl_pix/welcome_load_desc_en.gif new file mode 100644 index 0000000..597b0bf Binary files /dev/null and b/res/module/avl/avl_pix/welcome_load_desc_en.gif differ diff --git a/res/module/avl/avl_pix/welcome_load_rollover.gif b/res/module/avl/avl_pix/welcome_load_rollover.gif new file mode 100644 index 0000000..be1d746 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_load_rollover.gif differ diff --git a/res/module/avl/avl_pix/welcome_manual.gif b/res/module/avl/avl_pix/welcome_manual.gif new file mode 100644 index 0000000..54f620c Binary files /dev/null and b/res/module/avl/avl_pix/welcome_manual.gif differ diff --git a/res/module/avl/avl_pix/welcome_manual_desc_de.gif b/res/module/avl/avl_pix/welcome_manual_desc_de.gif new file mode 100644 index 0000000..fec6482 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_manual_desc_de.gif differ diff --git a/res/module/avl/avl_pix/welcome_manual_desc_en.gif b/res/module/avl/avl_pix/welcome_manual_desc_en.gif new file mode 100644 index 0000000..57b9c4b Binary files /dev/null and b/res/module/avl/avl_pix/welcome_manual_desc_en.gif differ diff --git a/res/module/avl/avl_pix/welcome_manual_rollover.gif b/res/module/avl/avl_pix/welcome_manual_rollover.gif new file mode 100644 index 0000000..1a39250 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_manual_rollover.gif differ diff --git a/res/module/avl/avl_pix/welcome_random.gif b/res/module/avl/avl_pix/welcome_random.gif new file mode 100644 index 0000000..961b4df Binary files /dev/null and b/res/module/avl/avl_pix/welcome_random.gif differ diff --git a/res/module/avl/avl_pix/welcome_random_desc_de.gif b/res/module/avl/avl_pix/welcome_random_desc_de.gif new file mode 100644 index 0000000..47fa846 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_random_desc_de.gif differ diff --git a/res/module/avl/avl_pix/welcome_random_desc_en.gif b/res/module/avl/avl_pix/welcome_random_desc_en.gif new file mode 100644 index 0000000..75d7882 Binary files /dev/null and b/res/module/avl/avl_pix/welcome_random_desc_en.gif differ diff --git a/res/module/avl/avl_pix/welcome_random_rollover.gif b/res/module/avl/avl_pix/welcome_random_rollover.gif new file mode 100644 index 0000000..93a90cc Binary files /dev/null and b/res/module/avl/avl_pix/welcome_random_rollover.gif differ diff --git a/res/module/avl/help/CVS/Entries b/res/module/avl/help/CVS/Entries new file mode 100644 index 0000000..15da81e --- /dev/null +++ b/res/module/avl/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Sun Mar 12 16:05:20 2006/-kb/ diff --git a/res/module/avl/help/CVS/Repository b/res/module/avl/help/CVS/Repository new file mode 100644 index 0000000..da680d8 --- /dev/null +++ b/res/module/avl/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help diff --git a/res/module/avl/help/CVS/Root b/res/module/avl/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/html/CVS/Entries b/res/module/avl/help/html/CVS/Entries new file mode 100644 index 0000000..8d7e8bc --- /dev/null +++ b/res/module/avl/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Sun Mar 12 16:04:34 2006// +D/data//// +/index.htm/1.1/Sun Mar 12 16:04:34 2006// +/top_frame.htm/1.1/Sun Mar 12 16:04:34 2006// diff --git a/res/module/avl/help/html/CVS/Repository b/res/module/avl/help/html/CVS/Repository new file mode 100644 index 0000000..c622f9b --- /dev/null +++ b/res/module/avl/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help/html diff --git a/res/module/avl/help/html/CVS/Root b/res/module/avl/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/html/contents.htm b/res/module/avl/help/html/contents.htm new file mode 100644 index 0000000..e69a59b --- /dev/null +++ b/res/module/avl/help/html/contents.htm @@ -0,0 +1,109 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul AVL + +
    + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/CVS/Entries b/res/module/avl/help/html/data/CVS/Entries new file mode 100644 index 0000000..cb21054 --- /dev/null +++ b/res/module/avl/help/html/data/CVS/Entries @@ -0,0 +1,7 @@ +/additionals.htm/1.2/Wed Mar 22 21:01:29 2006// +/documentation.htm/1.2/Wed Mar 22 21:01:29 2006// +/flowcontrol.htm/1.2/Wed Mar 22 21:01:29 2006// +/functions.htm/1.2/Wed Mar 22 21:01:29 2006// +/overview.htm/1.2/Wed Mar 22 21:01:29 2006// +/screen.htm/1.2/Wed Mar 22 21:01:29 2006// +/start.htm/1.2/Wed Mar 22 21:01:29 2006// diff --git a/res/module/avl/help/html/data/CVS/Repository b/res/module/avl/help/html/data/CVS/Repository new file mode 100644 index 0000000..ed7fdb5 --- /dev/null +++ b/res/module/avl/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help/html/data diff --git a/res/module/avl/help/html/data/CVS/Root b/res/module/avl/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/html/data/additionals.htm b/res/module/avl/help/html/data/additionals.htm new file mode 100644 index 0000000..d1efc63 --- /dev/null +++ b/res/module/avl/help/html/data/additionals.htm @@ -0,0 +1,60 @@ + + + Zusatzfunktionen und Hilfe + + + + +

    Zusatzfunktionen und Hilfe

    +

    Dieses Kapitel widmet sich den Eastereggs und der Hilfe des + Moduls AVL-Bäume.
    +

    +

    Navigator

    +

    Der Navigator ist eine kleine, versteckte Zusatzfunktion, die + die Arbeit mit großen Bäumen erheblich vereinfachen kann. Er stellt eine + willkommene Hilfe für das Scrollen der Zeichenfläche dar, ist aber nicht so + einfach zu finden.

    +
      +
    • + Wenn der Baum, der auf der Zeichenfläche angezeigt wird, zu groß für diese + wird, so erscheinen Schiebebalken, mit denen Sie den Bildausschnitt verschieben + können. +
    • + Klicken Sie nun auf das kleine Quadrat in der rechten unteren Ecke der + Zeichenfläche, genau zwischen den beiden Schiebebalken. Halten Sie dabei die + linke Maustaste gedrückt. +
    • + Eine kleine Übersichtskarte des Baumes mit einem Ausschnittfenster erscheint. + Verschieben Sie die Maus (mit gedrückter Taste) und das Ausschnittfenster, das + den Bildschirminhalt der Zeichenfläche repräsentiert, folgt Ihren Bewegungen.
    + + + + + + + + + +
                    
    +

    +   + Beamermodus

    + +

    Der Beamermodus ist in erster Linie für die Präsentation in + Vorlesungen oder ähnlichen Veranstaltungen gedacht. Ist dieser Modus aktiv, so + werden die Knoten des Baumes und die Einträge des Logbuches vergrößert + dargestellt. Der Algorithmustext aus dem Skript von Prof. Vogler bleibt dabei + unverändert, weil davon ausgegangen wird, dass die interessierten Studenten der + Vorlesung über ein (eventuell aktuelleres) Skript verfügen. Sie erreichen den + Beamermodus über den Menüpunkt <AVL-Bäume> => + <Beamermodus> . Ist der Modus + aktiv, so erscheint neben diesem Menüeintrag ein Häkchen. Um den Modus wieder + auszuschalten, entfernen Sie einfach den Haken per Klick.

    +

    +

    + +

    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/documentation.htm b/res/module/avl/help/html/data/documentation.htm new file mode 100644 index 0000000..02eee50 --- /dev/null +++ b/res/module/avl/help/html/data/documentation.htm @@ -0,0 +1,55 @@ + + + Dokumentation + + + + +

    Dokumentation

    +

    Da das Modul AVL-Bäume vor allem zu Lehr- und Lernzwecken + eingesetzt werden soll, ist eine detaillierte Dokumentation der Algorithmen + unumgänglich. Für die Einzelheiten des Algorithmustextes steht ein Auszug aus + dem Vorlesungsskript von Prof. Vogler zur Verfügung. Ein Logbuch in der rechten + unteren Ecke des Bildschirmes führt Protokoll über den Stand und die + Beschaffenheit des einzelnen Algorithmusteilschrittes. Zu guter Letzt wird ein + Infobereich angeboten, in dem wichtige Baumdaten zusammengefasst sind.
    +

    + +

    Skript

    +

    Der Dokumentationsbereich, der das Skript enthält, befindet sich + am unteren Bildschirmrand. Es handelt sich hierbei um einen Auszug des Skripts + zur Vorlesung "Algorithmen und Datenstrukturen" von Prof. Vogler (TU Dresden), + Version vom 2. Oktober 2003. Im Rahmen dieser Vorlesung soll das Modul + vorwiegend eingesetzt werden.
    + Bei dem jeweils aktuellen Algorithmustext handelt es sich um die Aktion, die + als nächstes im Ablauf des Algorithmus erfolgen wird. Sie wird rot markiert + angezeigt.
    + + +

    Logbuch

    + +

    Das Logbuch ist eine weitere Möglichkeit den Ablauf des + Algorithmus zu verfolgen. Es bezieht sich in erster Linie auf baumspezifische + Daten und verwendet zum Beispiel konkrete Schlüsselwerte, an Hand dessen die + Aktionen des Algorithmus besser verstanden werden sollen. Auch hier wird der + aktuelle Eintrag rot markiert dargestellt. Dieser bezieht sich aber auf die zu + letzt ausgeführte Aktion.
    +

    +

    Infobereich

    +

    Der Infobereich ist hauptsächlich dafür gedacht, Ihnen schnell + wichtige Daten des Baumes bereit zu stellen. Hier finden Sie folgende Punkte:

    +
      +
    • + Anzahl der Knoten
      + Dieser Punkt fasst für Sie die Anzahl der Knoten im Baum zusammen. +
    • + Baumhöhe
      + Hier finden Sie die Anzahl der Level des Baumes. +
    • + Durchschnittliche Suchtiefe
      + Dieser Wert berechnet sich, durch die Summe der Level aller Knoten durch die + Anzahl dieser. Der Wert ist ein Indiz dafür, wie gut der Baum ausbalanciert ist + bzw. wie groß der Suchaufwand im Durchschnitt ist.
    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/flowcontrol.htm b/res/module/avl/help/html/data/flowcontrol.htm new file mode 100644 index 0000000..72b8feb --- /dev/null +++ b/res/module/avl/help/html/data/flowcontrol.htm @@ -0,0 +1,76 @@ + + + Algorithmussteuerung + + + + +

    Algorithmussteuerung

    +

    Aufgabe des Moduls AVL-Bäume ist es, + Baumalgorithmen, wie das Einfügen und Löschen von Knoten, zu visualisieren. + Jeder Algorithmus ist in verschiedene Teilschritte unterteilt, die nacheinander + angezeigt werden. Das Visualisieren erfolgt dabei durch das Zeichnen des + Baumes, durch die Erklärung der Schritte im Dokumentationsbereich und im + Logbuch und durch die Neuberechnung der baumspezifischen Daten, die im + Infobereich präsentiert werden. Nachdem Sie einen Algorithmus gestartet haben, + verweilt er in einem Initialzustand und wartet auf Ihre Eingabe. Nun haben Sie + die Möglichkeit, den Algorithmus in kleinen oder groÿen Schritten zu + durchlaufen; Sie können ihn sofort beenden oder direkt abbrechen. Dafür bietet + die Algorithmussteuerung die entsprechenden Werkzeuge.

    + +

    Schritt-Pfeile

    +

    + Mittels der Schritt-Pfeile steuern Sie die Abfolge der Einzelschritte und + bekommen so eine detailierte Sicht auf die Arbeitsweise des Algorithmus. Das + Programm bietet Ihnen die Möglichkeit, einen Teilschritt rückgängig zu machen + und damit gewisse Abläufe zu wiederholen. Die Schritt-Pfeile, welche die + Rückgängigfunktion anbieten, weisen in ihrer Richtung nach links und sind + dadurch intuitiv von den Vorwärts-Pfeilen zu unterscheiden. Zusätzlich gibt es + für jede Richtung einen großen und einen kleinen Schritt, der per Knopfdruck + ausgeführt wird.

    +

    +

    + Kleine Schritte beim Einfügen eines Knoten stellen Schlüsselvergleiche, + Balancenberechnungen und Rotationen dar. Große Schritte hingegen sind zum + Beispiel das Suchen der Einfügestelle, das Einfügen an dieser und die gesamte + Balancenaktualisierung.

    +

    +

    + Einzel-Schritt-Pfeile
    + Ein Klick auf diese Buttons realisiert einen kleinen Algorithmusschritt zurück + bzw. nach vorn.

    +

    +

    + Block-Schritt-Pfeile
    + Ein Klick auf diese Button realisiert einen großen Schritt zurück bzw. nach + vorn. Sollte der Algorithmusablauf an eine Stelle geraten, an der es nur noch + einen kleinen Schritt nach vorn bzw. zurück gibt, so hat der Block-Schritt die + selbe Funktionalität wie ein Einzelschritt.

    + +

      + Abbruch und Beenden-Buttons

    + +

    Klicken Sie auf den Beenden-Button + um den laufenden Algorithmus bis zum Ende auszuführen. Klicken Sie auf den + Abbruch-Button um + den laufenden Algorithmus abzubrechen. Der Baum hat danach den gleichen Status + wie vor Beginn des Algorithmus. Ist ein Algorithmus beendet, so steht Ihnen + diese Option nicht mehr zur Verfügung, weil nur der laufende Algorithmus + abgebrochen werden kann.

    +

    +

    Animationsgeschwindigkeit

    +

    Beim Generieren eines Zufallsbaumes haben Sie die Option, den + Ablauf der Baumerzeugung als Animation ablaufen zu lassen. Starten Sie in + diesem Modus, so beginnt die Animation sofort und kann mit dem + Geschwindigkeitsregler schneller oder langsamer abgespielt werden. Zu Beginn + steht dieser auf der mittleren Position. Verschieben Sie den Regler nach links, + um die Animation zu verlangsamen bzw. nach rechts, um sie zu beschleunigen. + Eine Animation der anderen Algorithmenabläufe ist in dieser Version von + AVL-Bäume nicht integriert. +

    +

    +

    +

    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/functions.htm b/res/module/avl/help/html/data/functions.htm new file mode 100644 index 0000000..fbb096f --- /dev/null +++ b/res/module/avl/help/html/data/functions.htm @@ -0,0 +1,78 @@ + + + Modulfunktionen + + + + +

    Modulfunktionen

    +

    Alle Funktionen des Moduls AVL-Bäume lassen + sich über den Kontroll-Bereich der Arbeitsfläche bedienen. Sie stellen die + verschiedenen Baumalgorithmen dar, deren Visualisierung Aufgabe dieses Moduls + ist. Grundlegend läuft die Arbeit mit den Algorithmen immer nach dem gleichen + Schema ab:

    +
      +
    1. + Schlüsseleingabe +
    2. + Starten des Algorithmus per Klick auf den entsprechenden Button
    3. +
    +

    + Es gibt natürlich auch Algorithmen, wie der AVL-Test, die keinen Schlüssel + benötigen und ohne Schritt 1 auskommen.
    + Es folgen nun die einzelnen Funktionen im Detail.

    + +

    Schlüsseleingabe

    +

    Für die Eingabe der Schlüsselwerte steht ein Textfeld und ein + Button für zufällige Werte zur Verfügung. Es sind nur ganzzahlige + Schlüsselwerte von 1 bis 99 erlaubt.
    + Über dem Textfeld befindet sich eine Nachrichtenzeile, in welcher Sie auf + eventuelle Fehleingaben aufmerksam gemacht werden. Hier werden später ebenfalls + kurze Ergebnismeldungen zu den Algorithmen eingeblendet.

    + +

    Algorithmusfunktionen

    +

    + Knoten einfügen
    + Der eingegebene Wert wird als Schlüssel für einen neuen Knoten verwendet, der + in den Baum eingefügt werden soll. Ist bereits ein Knoten mit dem gleichen + Schlüssel im Baum enthalten, so bricht der Algorithmus erfolglos ab.
    + Knoten suchen
    + Nach dem Starten dieses Algorithmus beginnt die Suche nach dem eingegebenen + Schlüssel im Baum.
    + Knoten löschen
    + Nach dem eingegebenen Schlüssel wird gesucht und wenn ein entsprechender Knoten + gefunden wurde wird dieser aus der Baumstruktur entfernt.

    +

    +

    AVL-Modus

    +

    Ist dieses Kästchen aktiviert, werden die entsprechenden + Algorithmen so ausgeführt, dass die AVL-Eigenschaft gewahrt bleibt.
    + Achtung: Es ist keine Funktion implementiert, die an einem + beliebigen Suchbaum die AVL-Eigenschaft herstellt!
    + Ist das Kästchen deaktiviert, ist es daher nicht immer ohne weiteres wieder zu + aktivieren. Dazu muss zuerst getestet werden, ob der Baum die AVL-Eigenschaft + hat. Es ist jedoch jederzeit möglich, das Kästchen zu deaktivieren und einen + unbalancierten Baum zu erzeugen.

    + +

    Baum auf AVL-Eigenschaft testen

    +

    Wenn der AVL-Modus einmal deaktiviert sein sollte, so ermöglicht das Programm + einen Test des Baumes auf die AVL-Eigenschaft. Dabei erfolgt eine Berechnung + und Anzeige der Balancen aller Knoten und das eventuelle Markieren von Knoten, + deren Balance sich nicht mehr im Rahmen der AVL-Eigenschaft bewegt.
    + Es wird ein Hinweis-Dialog geöffnet, der Ihnen das Ergebnis des Tests + präsentiert. Sollte der Baum tatsächlich die AVL-Eigenschaft besitzen, so wird + Ihnen angeboten, direkt in den AVL-Modus zu wechseln.

    +

    +

    +
    + +

    Baum löschen

    +

    Mit einem Klick auf den Button + + in der Werkzeugleiste können Sie nach einer Sicherheitsabfrage die gesamte + Baumstruktur löschen und mit einer leeren Arbeitsfläche neu beginnen.

    +

    +

    +

    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/overview.htm b/res/module/avl/help/html/data/overview.htm new file mode 100644 index 0000000..532a6cb --- /dev/null +++ b/res/module/avl/help/html/data/overview.htm @@ -0,0 +1,37 @@ + + + Einleitung + + + + + +

    Das Modul AVL - Bäume

    +

    Einleitung

    +

    Das Modul AVL-Bäume realisiert die Darstellung + von binären Such- und AVL-Bäumen. Für eine detaillierte Beschreibung dieser + Baumtypen lesen Sie bitte nach im Vorlesungsskript von Prof. Vogler + "Algorithmen, Datenstrukturen und Programmierung". Eine mehr oder weniger kurze + Einführung in diese Thematik ist auch zu finden im Anhang des + j-Algo Handbuches.
    +

    +

    Funktionsübersicht

    +

    Das Modul AVL-Bäume realisiert folgende + Funktionen: +

    +
      +
    • + Visualisieren von binären Suchbäumen mit und ohne AVL-Eigenschaft +
    • + Einfügen, Suchen und Löschen von Baumknoten +
    • + Testen eines Baumes auf AVL-Eigenschaft +
    • + Generieren von zufälligen Suchbäumen +
    • + Speichern und Laden von Bäumen +
    • + Informationen zum Baum und zu den laufenden Algorithmen
    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/screen.htm b/res/module/avl/help/html/data/screen.htm new file mode 100644 index 0000000..2cfe3f2 --- /dev/null +++ b/res/module/avl/help/html/data/screen.htm @@ -0,0 +1,44 @@ + + + Die Arbeitsfläche + + + + +

    Die Arbeitsfläche

    +

    Die Arbeit mit AVL-Bäume spielt sich auf der + Arbeitsfläche ab. Sie bietet alle Funktionalitäten des Moduls und ist in fünf + wichtige Bereiche unterteilt.

    +
      +
    • + Zeichenfläche
      + Der Baum und alle Algorithmen werden hier visualisiert. +
    • + Infobereich
      + Wichtige Baumdaten wie Anzahl der Knoten, Baumhöhe und Suchtiefe sind hier zu + finden. +
    • + Kontroll-Bereich
      + In diesem Bereich erfolgt der Start und die Steuerung der Algorithmen. +
    • + Dokumentationsbereich
      + Hier läuft der Text zum jeweiligen Algorithmus mit. Der aktuelle Schritt wird + dabei farbig hervorgehoben. Der Text ist dem Skript "Algorithmen, + Datenstrukuren und Programmierung" von Prof.Vogler, Version vom 2. Oktober + 2003, entnommen. +
    • + Logbuch
      + Hier werden erfolgte Einzelaktionen protokolliert und dabei der jeweils + aktuelle Schritt farbig hervorgehoben.
    • +
    +

    Die Aufteilung zwischen dem unteren und dem oberen Bereich kann + mit dem Schiebebalken verändert werden. Per Klick auf die schwarzen Pfeile + können Sie den Textbereich wahlweise maximieren, um einen Überblick über den + Algorithmustext zu gewinnen, oder minimieren, um die Zeichenfläche zu + vergrössern. +

    +

    +

    + + + \ No newline at end of file diff --git a/res/module/avl/help/html/data/start.htm b/res/module/avl/help/html/data/start.htm new file mode 100644 index 0000000..2e79486 --- /dev/null +++ b/res/module/avl/help/html/data/start.htm @@ -0,0 +1,95 @@ + + + Programmstart - Der Willkommensbildschirm + + + + +

    Programmstart - Der Willkommensbildschirm

    +

    Nach Starten des Hauptprogramms j-Algo + können Sie über den Button <Neu> + oder mit dem Menüpunkt <Datei> => + <Neu> eine neue Instanz des Moduls AVL-Bäume + öffnen. Anschließend öffnet sich der Willkommensbildschirm des Moduls, der + Ihnen verschiedene Möglichkeiten eröffnet.

    + +

    +


    + + + +

    +   + Baum laden

    +

    Mit Klick auf das Ordner-Symbol öffnet sich ein Dialogfenster, + in dem Ihnen die Möglichkeit gegeben wird, eine "*.jalgo" - Datei auszuwählen, + in welcher ein Baum gespeichert wurde.
    + Im Prinzip ist die Bedeutung dieses Buttons die gleiche wie des <Öffnen> + - Buttons in der Werkzeugleiste. Der Unterschied besteht darin, dass + der Button in der Werkzeugleiste eine neue Modulinstanz öffnet, in welcher die + Datei geladen wird, der Button im Startbildschirm von AVL-Bäume + jedoch die Datei in die aktuell geöffnete Modulinstanz lädt.

    +

    +


    +  

    +

    +   + Baum von Hand erstellen

    +

    Mit Klick auf das Hand-Symbol gelangen Sie sofort zur leeren + Arbeitsfläche des Moduls AVL-Bäume. Sie können jetzt mit der + knotenweisen Generierung eines neuen Suchbaumes beginnen.
    +

    +

    +   + Zufallsbaum erstellen lassen

    +

    Mit Klick auf das Würfel-Symbol beginnen Sie die Generierung + eines zufällig erzeugten Suchbaumes. In dem folgenden Dialogfenster können Sie + verschiedene Daten zum Baum und die Art der Visualisierung festlegen.

    +
      +
    • + Anzahl der Knoten
      + Geben Sie hier die Anzahl der Knoten ein. Der entstehende Baum muss mindestens + einen Knoten enthalten, höchstens aber 99. +
    • + AVL-Eigenschaft
      + Aktivieren Sie dieses Kästchen, wenn der zu erstellende Baum die + AVL-Eigenschaft besitzen soll. +
    • + Visualisierung
      + Wählen Sie hier die Art der Visualisierung der Erstellung aus. +
        +
      • + Keine
        + Der Baum wird sofort erstellt. +
      • + Schrittweise
        + Jeder Algorithmusschritt kann von Ihnen per Hand bestätigt werden. +
      • + Automatisch
        + Lassen Sie die Erstellung des Baumes als Animation ablaufen, die + Geschwindigkeit ist dabei einstellbar.
      • +
      +

      + Haben Sie schrittweise oder automatische Visualisierung gewählt, können Sie den + Ablauf jederzeit abbrechen. Dabei wird das gerade aktive Knoteneinfügen + abgebrochen, und der Baum steht mit entsprechend weniger Knoten zur Verfügung.

      +
    • +
    +

    +

    + +

    + +   + Willkommensbildschirm anzeigen

    +

    Mit Klick auf diesen Button in der Werkzeugleiste des Modulbildschirms kann der + Willkommensbildschirm später jederzeit wieder angezeigt werden. Dabei werden + Sie evtl. gefragt, wie Sie mit Ihren Änderungen verfahren wollen. Sollten sie + Ihre Änderungen nicht verwerfen, so wird eine neue Instanz des Moduls geöffnet. +

    +

    +

    + +

    + + \ No newline at end of file diff --git a/res/module/avl/help/html/index.htm b/res/module/avl/help/html/index.htm new file mode 100644 index 0000000..079f448 --- /dev/null +++ b/res/module/avl/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AVL Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/avl/help/html/top_frame.htm b/res/module/avl/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/avl/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/avl/help/jhelp/CVS/Entries b/res/module/avl/help/jhelp/CVS/Entries new file mode 100644 index 0000000..40fea33 --- /dev/null +++ b/res/module/avl/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/avlIndex.xml/1.2/Wed Mar 22 11:52:27 2006// +/avlTOC.xml/1.1/Sun Mar 12 16:04:21 2006// +/avl_help.hs/1.2/Wed Mar 22 20:51:01 2006/-kb/ +/map.jhm/1.1/Sun Mar 12 16:04:21 2006/-kb/ diff --git a/res/module/avl/help/jhelp/CVS/Repository b/res/module/avl/help/jhelp/CVS/Repository new file mode 100644 index 0000000..baf402b --- /dev/null +++ b/res/module/avl/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help/jhelp diff --git a/res/module/avl/help/jhelp/CVS/Root b/res/module/avl/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..591ad64 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/DOCS.TAB/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/OFFSETS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/POSITIONS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/SCHEMA/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/TMAP/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/config.ini/1.1/Sun Mar 12 16:05:02 2006// diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..bb97f49 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help/jhelp/JavaHelpSearch diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/DOCS b/res/module/avl/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..be0db5f Binary files /dev/null and b/res/module/avl/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/avl/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..9e8d6d9 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,4 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿuÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ@k£ +2Šëúêû0³ +î³ ë®Œ*£ +ª«ªª«ã"ªÿ*®ë¨Âº«ú»ú««þûªºÿû®ú®¯¯ªþ«¯ººú¸Âª¿þîªë«ªïúªªêªªª«îªî¿«êªªú«ªîëÿªªª¯úꪺ껪몫«ºêªî¾«ªª®®ïꪪú¾ªºªªªªªªªªªªªªªªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/avl/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..47c3238 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ñîaÖ©Ê€0O—ƒ £÷˜¸÷Û7CØ`Ê¢ \ No newline at end of file diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/avl/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1aa79bf Binary files /dev/null and b/res/module/avl/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/avl/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..4a81846 --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=597 id2=1 diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/TMAP b/res/module/avl/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..e38ae3b Binary files /dev/null and b/res/module/avl/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/avl/help/jhelp/JavaHelpSearch/config.ini b/res/module/avl/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/avl/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/avl/help/jhelp/avlIndex.xml b/res/module/avl/help/jhelp/avlIndex.xml new file mode 100644 index 0000000..8e6c6e6 --- /dev/null +++ b/res/module/avl/help/jhelp/avlIndex.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/avl/help/jhelp/avlTOC.xml b/res/module/avl/help/jhelp/avlTOC.xml new file mode 100644 index 0000000..318c671 --- /dev/null +++ b/res/module/avl/help/jhelp/avlTOC.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/avl/help/jhelp/avl_help.hs b/res/module/avl/help/jhelp/avl_help.hs new file mode 100644 index 0000000..96a28e6 --- /dev/null +++ b/res/module/avl/help/jhelp/avl_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum AVL-Modul + + + + + avl + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + avlTOC.xml + + + + Index + + javax.help.IndexView + avlIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/avl/help/jhelp/map.jhm b/res/module/avl/help/jhelp/map.jhm new file mode 100644 index 0000000..6ee377d --- /dev/null +++ b/res/module/avl/help/jhelp/map.jhm @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/avl/help/pics/CVS/Entries b/res/module/avl/help/pics/CVS/Entries new file mode 100644 index 0000000..5526ee2 --- /dev/null +++ b/res/module/avl/help/pics/CVS/Entries @@ -0,0 +1,23 @@ +/animregler.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/avltest.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/beamermenu.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/button_dir.png/1.1/Sun Mar 12 16:04:25 2006/-kb/ +/button_hand.png/1.1/Sun Mar 12 16:04:25 2006/-kb/ +/button_wurfel.png/1.1/Sun Mar 12 16:04:25 2006/-kb/ +/clearmessage.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_abort.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_abort_and_finish.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_avl.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_beamer.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_clear.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_finish.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_steps.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/icon_stepsblock.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/loaddialog.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/logo_help.png/1.1/Sun Mar 12 16:04:25 2006/-kb/ +/navigator1.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/navigator2.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/prgmscreen.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/rgd.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/treedel.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ +/welcomscreen.png/1.3/Sun Mar 12 16:04:25 2006/-kb/ diff --git a/res/module/avl/help/pics/CVS/Repository b/res/module/avl/help/pics/CVS/Repository new file mode 100644 index 0000000..155d3ed --- /dev/null +++ b/res/module/avl/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/avl/help/pics diff --git a/res/module/avl/help/pics/CVS/Root b/res/module/avl/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/avl/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/avl/help/pics/animregler.png b/res/module/avl/help/pics/animregler.png new file mode 100644 index 0000000..aee6c64 Binary files /dev/null and b/res/module/avl/help/pics/animregler.png differ diff --git a/res/module/avl/help/pics/avltest.png b/res/module/avl/help/pics/avltest.png new file mode 100644 index 0000000..23f2843 Binary files /dev/null and b/res/module/avl/help/pics/avltest.png differ diff --git a/res/module/avl/help/pics/beamermenu.png b/res/module/avl/help/pics/beamermenu.png new file mode 100644 index 0000000..c3875af Binary files /dev/null and b/res/module/avl/help/pics/beamermenu.png differ diff --git a/res/module/avl/help/pics/button_dir.png b/res/module/avl/help/pics/button_dir.png new file mode 100644 index 0000000..531ec21 Binary files /dev/null and b/res/module/avl/help/pics/button_dir.png differ diff --git a/res/module/avl/help/pics/button_hand.png b/res/module/avl/help/pics/button_hand.png new file mode 100644 index 0000000..fc0832a Binary files /dev/null and b/res/module/avl/help/pics/button_hand.png differ diff --git a/res/module/avl/help/pics/button_wurfel.png b/res/module/avl/help/pics/button_wurfel.png new file mode 100644 index 0000000..bb5bdfe Binary files /dev/null and b/res/module/avl/help/pics/button_wurfel.png differ diff --git a/res/module/avl/help/pics/clearmessage.png b/res/module/avl/help/pics/clearmessage.png new file mode 100644 index 0000000..7f25a39 Binary files /dev/null and b/res/module/avl/help/pics/clearmessage.png differ diff --git a/res/module/avl/help/pics/icon_abort.png b/res/module/avl/help/pics/icon_abort.png new file mode 100644 index 0000000..d3268ce Binary files /dev/null and b/res/module/avl/help/pics/icon_abort.png differ diff --git a/res/module/avl/help/pics/icon_abort_and_finish.png b/res/module/avl/help/pics/icon_abort_and_finish.png new file mode 100644 index 0000000..0f06ebd Binary files /dev/null and b/res/module/avl/help/pics/icon_abort_and_finish.png differ diff --git a/res/module/avl/help/pics/icon_avl.png b/res/module/avl/help/pics/icon_avl.png new file mode 100644 index 0000000..b0a4602 Binary files /dev/null and b/res/module/avl/help/pics/icon_avl.png differ diff --git a/res/module/avl/help/pics/icon_beamer.png b/res/module/avl/help/pics/icon_beamer.png new file mode 100644 index 0000000..59e9788 Binary files /dev/null and b/res/module/avl/help/pics/icon_beamer.png differ diff --git a/res/module/avl/help/pics/icon_clear.png b/res/module/avl/help/pics/icon_clear.png new file mode 100644 index 0000000..5cd2c07 Binary files /dev/null and b/res/module/avl/help/pics/icon_clear.png differ diff --git a/res/module/avl/help/pics/icon_finish.png b/res/module/avl/help/pics/icon_finish.png new file mode 100644 index 0000000..2e63bdf Binary files /dev/null and b/res/module/avl/help/pics/icon_finish.png differ diff --git a/res/module/avl/help/pics/icon_steps.png b/res/module/avl/help/pics/icon_steps.png new file mode 100644 index 0000000..b5bd5e0 Binary files /dev/null and b/res/module/avl/help/pics/icon_steps.png differ diff --git a/res/module/avl/help/pics/icon_stepsblock.png b/res/module/avl/help/pics/icon_stepsblock.png new file mode 100644 index 0000000..14baad6 Binary files /dev/null and b/res/module/avl/help/pics/icon_stepsblock.png differ diff --git a/res/module/avl/help/pics/loaddialog.png b/res/module/avl/help/pics/loaddialog.png new file mode 100644 index 0000000..3460f9d Binary files /dev/null and b/res/module/avl/help/pics/loaddialog.png differ diff --git a/res/module/avl/help/pics/logo_help.png b/res/module/avl/help/pics/logo_help.png new file mode 100644 index 0000000..97560c8 Binary files /dev/null and b/res/module/avl/help/pics/logo_help.png differ diff --git a/res/module/avl/help/pics/navigator1.png b/res/module/avl/help/pics/navigator1.png new file mode 100644 index 0000000..9a75486 Binary files /dev/null and b/res/module/avl/help/pics/navigator1.png differ diff --git a/res/module/avl/help/pics/navigator2.png b/res/module/avl/help/pics/navigator2.png new file mode 100644 index 0000000..bfb4a46 Binary files /dev/null and b/res/module/avl/help/pics/navigator2.png differ diff --git a/res/module/avl/help/pics/prgmscreen.png b/res/module/avl/help/pics/prgmscreen.png new file mode 100644 index 0000000..8126128 Binary files /dev/null and b/res/module/avl/help/pics/prgmscreen.png differ diff --git a/res/module/avl/help/pics/rgd.png b/res/module/avl/help/pics/rgd.png new file mode 100644 index 0000000..3a748be Binary files /dev/null and b/res/module/avl/help/pics/rgd.png differ diff --git a/res/module/avl/help/pics/treedel.png b/res/module/avl/help/pics/treedel.png new file mode 100644 index 0000000..e711aff Binary files /dev/null and b/res/module/avl/help/pics/treedel.png differ diff --git a/res/module/avl/help/pics/welcomscreen.png b/res/module/avl/help/pics/welcomscreen.png new file mode 100644 index 0000000..ea98e5d Binary files /dev/null and b/res/module/avl/help/pics/welcomscreen.png differ diff --git a/res/module/avl/help/style.css b/res/module/avl/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/avl/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/bfsdfs/CVS/Entries b/res/module/bfsdfs/CVS/Entries new file mode 100644 index 0000000..b6194f4 --- /dev/null +++ b/res/module/bfsdfs/CVS/Entries @@ -0,0 +1,2 @@ +D/bfsdfs_pix//// +D/help//// diff --git a/res/module/bfsdfs/CVS/Repository b/res/module/bfsdfs/CVS/Repository new file mode 100644 index 0000000..20ef548 --- /dev/null +++ b/res/module/bfsdfs/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs diff --git a/res/module/bfsdfs/CVS/Root b/res/module/bfsdfs/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/bfsdfs_pix/CVS/Entries b/res/module/bfsdfs/bfsdfs_pix/CVS/Entries new file mode 100644 index 0000000..67828eb --- /dev/null +++ b/res/module/bfsdfs/bfsdfs_pix/CVS/Entries @@ -0,0 +1,20 @@ +/beamermode_button.gif/1.1/Wed Dec 8 13:47:53 2010// +/edit_double_edges.png/1.1/Wed Dec 8 13:47:53 2010// +/edit_edges.png/1.1/Wed Dec 8 13:47:53 2010// +/edit_nodes.png/1.1/Wed Dec 8 13:47:53 2010// +/logo.png/1.1/Wed Dec 8 13:47:53 2010// +/tab_bfs.png/1.1/Wed Dec 8 13:47:53 2010// +/tab_design.png/1.1/Wed Dec 8 13:47:53 2010// +/tab_dfs.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_last.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_last_descr_de.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_last_descr_en.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_last_over.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_load.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_load_descr_de.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_load_descr_en.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_load_over.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_new.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_new_descr_de.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_new_descr_en.png/1.1/Wed Dec 8 13:47:53 2010// +/ws_new_over.png/1.1/Wed Dec 8 13:47:53 2010// diff --git a/res/module/bfsdfs/bfsdfs_pix/CVS/Repository b/res/module/bfsdfs/bfsdfs_pix/CVS/Repository new file mode 100644 index 0000000..a926656 --- /dev/null +++ b/res/module/bfsdfs/bfsdfs_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/bfsdfs_pix diff --git a/res/module/bfsdfs/bfsdfs_pix/CVS/Root b/res/module/bfsdfs/bfsdfs_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/bfsdfs_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/bfsdfs_pix/beamermode_button.gif b/res/module/bfsdfs/bfsdfs_pix/beamermode_button.gif new file mode 100644 index 0000000..3be7a76 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/beamermode_button.gif differ diff --git a/res/module/bfsdfs/bfsdfs_pix/edit_double_edges.png b/res/module/bfsdfs/bfsdfs_pix/edit_double_edges.png new file mode 100644 index 0000000..a1c66fc Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/edit_double_edges.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/edit_edges.png b/res/module/bfsdfs/bfsdfs_pix/edit_edges.png new file mode 100644 index 0000000..2a64b0f Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/edit_edges.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/edit_nodes.png b/res/module/bfsdfs/bfsdfs_pix/edit_nodes.png new file mode 100644 index 0000000..cc85bf7 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/edit_nodes.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/logo.png b/res/module/bfsdfs/bfsdfs_pix/logo.png new file mode 100644 index 0000000..0b63381 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/logo.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/tab_bfs.png b/res/module/bfsdfs/bfsdfs_pix/tab_bfs.png new file mode 100644 index 0000000..3515fa5 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/tab_bfs.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/tab_design.png b/res/module/bfsdfs/bfsdfs_pix/tab_design.png new file mode 100644 index 0000000..5983b1e Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/tab_design.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/tab_dfs.png b/res/module/bfsdfs/bfsdfs_pix/tab_dfs.png new file mode 100644 index 0000000..afb12da Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/tab_dfs.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_last.png b/res/module/bfsdfs/bfsdfs_pix/ws_last.png new file mode 100644 index 0000000..451939e Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_last.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_de.png b/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_de.png new file mode 100644 index 0000000..57ac6e2 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_de.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_en.png b/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_en.png new file mode 100644 index 0000000..16e4b2a Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_last_descr_en.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_last_over.png b/res/module/bfsdfs/bfsdfs_pix/ws_last_over.png new file mode 100644 index 0000000..23f9c2e Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_last_over.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_load.png b/res/module/bfsdfs/bfsdfs_pix/ws_load.png new file mode 100644 index 0000000..dba8a55 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_load.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_de.png b/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_de.png new file mode 100644 index 0000000..2e7cd94 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_de.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_en.png b/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_en.png new file mode 100644 index 0000000..8ebc744 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_load_descr_en.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_load_over.png b/res/module/bfsdfs/bfsdfs_pix/ws_load_over.png new file mode 100644 index 0000000..f7752ff Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_load_over.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_new.png b/res/module/bfsdfs/bfsdfs_pix/ws_new.png new file mode 100644 index 0000000..d62450a Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_new.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_de.png b/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_de.png new file mode 100644 index 0000000..4e55716 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_de.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_en.png b/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_en.png new file mode 100644 index 0000000..6474198 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_new_descr_en.png differ diff --git a/res/module/bfsdfs/bfsdfs_pix/ws_new_over.png b/res/module/bfsdfs/bfsdfs_pix/ws_new_over.png new file mode 100644 index 0000000..94e47a6 Binary files /dev/null and b/res/module/bfsdfs/bfsdfs_pix/ws_new_over.png differ diff --git a/res/module/bfsdfs/help/CVS/Entries b/res/module/bfsdfs/help/CVS/Entries new file mode 100644 index 0000000..2062d57 --- /dev/null +++ b/res/module/bfsdfs/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Wed Dec 8 13:47:53 2010// diff --git a/res/module/bfsdfs/help/CVS/Repository b/res/module/bfsdfs/help/CVS/Repository new file mode 100644 index 0000000..2c5378b --- /dev/null +++ b/res/module/bfsdfs/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help diff --git a/res/module/bfsdfs/help/CVS/Root b/res/module/bfsdfs/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/html/CVS/Entries b/res/module/bfsdfs/help/html/CVS/Entries new file mode 100644 index 0000000..204b095 --- /dev/null +++ b/res/module/bfsdfs/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Wed Dec 8 13:47:53 2010// +D/data//// +/index.htm/1.1/Wed Dec 8 13:47:53 2010// +/top_frame.htm/1.1/Wed Dec 8 13:47:53 2010// diff --git a/res/module/bfsdfs/help/html/CVS/Repository b/res/module/bfsdfs/help/html/CVS/Repository new file mode 100644 index 0000000..53bc4e9 --- /dev/null +++ b/res/module/bfsdfs/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help/html diff --git a/res/module/bfsdfs/help/html/CVS/Root b/res/module/bfsdfs/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/html/contents.htm b/res/module/bfsdfs/help/html/contents.htm new file mode 100644 index 0000000..dbaa941 --- /dev/null +++ b/res/module/bfsdfs/help/html/contents.htm @@ -0,0 +1,58 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul BFS/DFS + +
    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/CVS/Entries b/res/module/bfsdfs/help/html/data/CVS/Entries new file mode 100644 index 0000000..3c87368 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/CVS/Entries @@ -0,0 +1,7 @@ +/algorithmcontrol.htm/1.1/Wed Dec 8 13:47:53 2010// +/bfstab.htm/1.1/Wed Dec 8 13:47:53 2010// +/designtab.htm/1.1/Wed Dec 8 13:47:53 2010// +/dfstab.htm/1.1/Wed Dec 8 13:47:53 2010// +/otherfunction.htm/1.1/Wed Dec 8 13:47:53 2010// +/overview.htm/1.1/Wed Dec 8 13:47:53 2010// +/welcomescreen.htm/1.1/Wed Dec 8 13:47:53 2010// diff --git a/res/module/bfsdfs/help/html/data/CVS/Repository b/res/module/bfsdfs/help/html/data/CVS/Repository new file mode 100644 index 0000000..371531f --- /dev/null +++ b/res/module/bfsdfs/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help/html/data diff --git a/res/module/bfsdfs/help/html/data/CVS/Root b/res/module/bfsdfs/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/html/data/algorithmcontrol.htm b/res/module/bfsdfs/help/html/data/algorithmcontrol.htm new file mode 100644 index 0000000..95afa75 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/algorithmcontrol.htm @@ -0,0 +1,64 @@ + + + Der Bereich der Algorithmensteuerung + + + + + +

    Der Bereich der Algorithmensteuerung

    + +

    +

    +

    +
    +
    + +

    Startknoten wählen

    + +

    + Wählt den Knoten, mit dem der Algorithmus beginnen soll. +

    + +

    Zufall verwenden

    + +

    + Durch Aktivieren dieser Option wird der Baum zufällig durchlaufen. Das kann dazu verwendet werden, unterschiedliche Ergebnisbäume zu erzeugen. +

    + +

    Nachfolger wählen

    + +

    + Bestimmt in welcher Reihenfolge die Nachfolger des aktuellen Knotens durchlaufen werden. Zum Verändern der Reihenfolge ziehen Sie die Knoten mit der Maus an eine andere Position. +

    + +

    Ablauf

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Setzt den Algorithmus zurück.
    Geht einen Schritt im Algorithmus zurück.
    Geht einen Schritt im Algorithmus vor.
    Durchläuft den Algorithmus automatisch bis zum Ende.
    Stoppt das automatische Durchlaufen des Algorithmus.
    + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/bfstab.htm b/res/module/bfsdfs/help/html/data/bfstab.htm new file mode 100644 index 0000000..85b9d81 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/bfstab.htm @@ -0,0 +1,23 @@ + + + Breitensuche-Tab + + + + +

    Der Breitensuche-Tab

    + +

    + Der Breitensuche-Tab zeigt +

    +
      +
    • den Suchbaum: Der Algorithmus zeichnet den Suchbaum und die Distanz der Knoten zum Startknoten über den Graphen
    • +
    • die Warteschlange: Liste von Knoten, die der Algorithmus noch bearbeitet
    • +
    • den Steuerbereich: sh. Algorithmensteuerung
    • +
    +
    +

    +

    +

    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/designtab.htm b/res/module/bfsdfs/help/html/data/designtab.htm new file mode 100644 index 0000000..2f8a48f --- /dev/null +++ b/res/module/bfsdfs/help/html/data/designtab.htm @@ -0,0 +1,60 @@ + + + Design-Tab + + + + +

    Der Design-Tab

    + +

    + Der Design Tab gliedert sich in zwei Bereiche: Die Zeichenfläche und die Leiste mit den Buttons für die im folgenden erläuterten Aktionen. +

    +
    +

    +

    +

    +
    +
    + +

    +     Rückgängig / Wiederholen der letzten Aktion. +

    + +

    + Macht einen Schritt rückgängig / wiederholt ihn. +

    + +

    +    Knoten hinzufügen oder Knoten verschieben. +

    + +

    + Aktiviert den Hinzufügen-Modus für Knoten: Sie können jetzt neue Knoten auf die Zeichenfläche setzen oder vorhandene Knoten verschieben. +

    + +

    +    Gerichtete Kante hinzufügen. +

    + +

    + Aktiviert den Hinzufügen-Modus für gerichtete Kanten. Sie können jetzt gerichtete Kanten hinzufügen. Klicken Sie dazu hintereinander auf zwei Knoten oder ziehen Sie eine Kante mit der Maus. Mit zwei Klicks auf einen Knoten erstellen Sie eine Schleife. +

    + +

    +    Ungerichtete Kante hinzufügen. +

    + +

    + Aktiviert den Hinzufügen-Modus für ungerichtete Kanten. Sie können jetzt ungerichtete Kanten hinzufügen. Es funktioniert wie mit gerichten Kanten. +

    + +

    +    Löschen von Elementen. +

    + +

    + Aktiviert den Löschen-Modus. Sie können jetzt mit einem Klick Knoten oder Kanten von der Zeichenfläche entfernen. +

    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/dfstab.htm b/res/module/bfsdfs/help/html/data/dfstab.htm new file mode 100644 index 0000000..4955303 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/dfstab.htm @@ -0,0 +1,21 @@ + + + Tiefensuche-Tab + + + + +

    Der Tiefensuche-Tab

    +

    + Der Tiefensuche-Tab zeigt

    +
      +
    • den Suchbaum: Der Algorithmus zeichnet den Suchbaum und die Distanz der Knoten zum Startknoten über den Graphen
    • +
    • den Laufzeitkeller: Knoten mit ihren Nachfolgern, die der Algorithmus noch bearbeitet
    • +
    • den Steuerbereich: sh. Algorithmensteuerung
    • +
    +
    +

    +

    +

    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/otherfunction.htm b/res/module/bfsdfs/help/html/data/otherfunction.htm new file mode 100644 index 0000000..28fd8d9 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/otherfunction.htm @@ -0,0 +1,21 @@ + + + Weitere Funktionalität + + + + +

    Weitere Funktionalität

    + + + + + + + + + +
    Vergrößerte Darstellung zur Vorführung über einen Beamer.
    Schaltet Animationen an bzw. ab.
    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/overview.htm b/res/module/bfsdfs/help/html/data/overview.htm new file mode 100644 index 0000000..6b16ddc --- /dev/null +++ b/res/module/bfsdfs/help/html/data/overview.htm @@ -0,0 +1,41 @@ + + + Einleitung + + + + +

    Das Modul BFS / DFS

    + +

    Einleitung

    +

    + Das Modul BFS / DFS visualisiert Algorithmen zur Tiefensuche und Breitensuche in Graphen. Es richtet sich nach dem + Vorlesungsskript Algorithmen, Datenstrukturen und Programmierung + von Univ.-Prof. Dr.-Ing. habil. Heiko Vogler (6. Auflage, 21.09.2007, + Seite 135-140). +

    + +

    Funktions-Übersicht

    +
      +
    • Erstellen von Graphen.
    • +
    • Steuerung und Durchführung des jeweiligen Algorithmus.
    • +
    • Speichern und Laden von Graphen.
    • +
    + +

    Übersicht über die Modulfenster

    +
      +
    • Willkommensbildschirm
    • +
    • Design-Tab
    • +
    • Breitensuche-Tab
    • +
    • Tiefensuche-Tab
    • +
    +

    + Das Verwenden der Buttons in den Tabs für Design, Breitensuche und Tiefensuche ist gleichbedeutend mit der Verwendung der Elemente in der Symbolleiste von j-Algo. +

    +

    Informationen zu den einzelnen Tabs finden Sie unter den dazugehörigen Unterpunkten.

    + +

    Instanzenverwaltung

    +

    Eine weitere Besonderheit unseres Moduls ist, das es mehrere Instanzen gleichzeitig verwalten kann.

    + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/data/welcomescreen.htm b/res/module/bfsdfs/help/html/data/welcomescreen.htm new file mode 100644 index 0000000..c9297e3 --- /dev/null +++ b/res/module/bfsdfs/help/html/data/welcomescreen.htm @@ -0,0 +1,29 @@ + + + Willkommensbildschirm + + + + +

    Der Willkommensbildschirm

    + +

    +

    +



    + +

    + + Startet das Modul mit einem neuen Graphen. +

    + +

    + + Lädt einen gespeicherten Graphen aus einer Datei. +

    + +

    + + Lädt den Graphen aus der zuletzt geladenen Datei. +

    + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/index.htm b/res/module/bfsdfs/help/html/index.htm new file mode 100644 index 0000000..0ec1ee2 --- /dev/null +++ b/res/module/bfsdfs/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum BFS/DFS Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/html/top_frame.htm b/res/module/bfsdfs/help/html/top_frame.htm new file mode 100644 index 0000000..9350624 --- /dev/null +++ b/res/module/bfsdfs/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + +
    Logo
    + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/CVS/Entries b/res/module/bfsdfs/help/jhelp/CVS/Entries new file mode 100644 index 0000000..3635627 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/bfsdfsIndex.xml/1.1/Wed Dec 8 13:47:53 2010// +/bfsdfsTOC.xml/1.1/Wed Dec 8 13:47:53 2010// +/bfsdfs_help.hs/1.1/Wed Dec 8 13:47:53 2010// +/map.jhm/1.1/Wed Dec 8 13:47:53 2010// diff --git a/res/module/bfsdfs/help/jhelp/CVS/Repository b/res/module/bfsdfs/help/jhelp/CVS/Repository new file mode 100644 index 0000000..5053945 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help/jhelp diff --git a/res/module/bfsdfs/help/jhelp/CVS/Root b/res/module/bfsdfs/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..a176482 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Wed Dec 8 13:47:53 2010// +/DOCS.TAB/1.1/Wed Dec 8 13:47:53 2010// +/OFFSETS/1.1/Wed Dec 8 13:47:53 2010// +/POSITIONS/1.1/Wed Dec 8 13:47:53 2010// +/SCHEMA/1.1/Wed Dec 8 13:47:54 2010// +/TMAP/1.1/Wed Dec 8 13:47:54 2010// +/config.ini/1.1/Wed Dec 8 13:47:54 2010// diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..4c05fe8 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help/jhelp/JavaHelpSearch diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..400f900 Binary files /dev/null and b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..d7f521e --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÝ}×ÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿô8³ró•“/Ì/ÿóh¿Ì/Ì/6/4³*‹ÿÍ¢ÿüÊ»Ë̪¢ó üÈ¿ÿÿÿÿÿÿÌ/0¿üÂó ó ó ÿÌ/ÿÿÿÿÿÿÿüÂÿÿÿÿÿÿÿý€ \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..1fabe1d Binary files /dev/null and b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..2967e70 Binary files /dev/null and b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..0c42a65 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=234 id2=1 diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/TMAP b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..2a9c0df Binary files /dev/null and b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/bfsdfs/help/jhelp/JavaHelpSearch/config.ini b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/bfsdfsIndex.xml b/res/module/bfsdfs/help/jhelp/bfsdfsIndex.xml new file mode 100644 index 0000000..a47b6f9 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/bfsdfsIndex.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/bfsdfsTOC.xml b/res/module/bfsdfs/help/jhelp/bfsdfsTOC.xml new file mode 100644 index 0000000..1e97705 --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/bfsdfsTOC.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/bfsdfs_help.hs b/res/module/bfsdfs/help/jhelp/bfsdfs_help.hs new file mode 100644 index 0000000..a91a49e --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/bfsdfs_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum BFS/DFS Modul + + + + + bfsdfs + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + bfsdfsTOC.xml + + + + Index + + javax.help.IndexView + bfsdfsIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/jhelp/map.jhm b/res/module/bfsdfs/help/jhelp/map.jhm new file mode 100644 index 0000000..34c772b --- /dev/null +++ b/res/module/bfsdfs/help/jhelp/map.jhm @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/bfsdfs/help/pics/CVS/Entries b/res/module/bfsdfs/help/pics/CVS/Entries new file mode 100644 index 0000000..c4e5692 --- /dev/null +++ b/res/module/bfsdfs/help/pics/CVS/Entries @@ -0,0 +1,28 @@ +/abortAlg.gif/1.1/Wed Dec 8 13:47:54 2010// +/animation.png/1.1/Wed Dec 8 13:47:54 2010// +/beamermode_button.gif/1.1/Wed Dec 8 13:47:54 2010// +/bfstab.png/1.1/Wed Dec 8 13:47:54 2010// +/chance.png/1.1/Wed Dec 8 13:47:54 2010// +/clear.gif/1.1/Wed Dec 8 13:47:54 2010// +/controlpanel.png/1.1/Wed Dec 8 13:47:54 2010// +/designtab.png/1.1/Wed Dec 8 13:47:54 2010// +/dfstab.png/1.1/Wed Dec 8 13:47:54 2010// +/edit_double_edges.png/1.1/Wed Dec 8 13:47:54 2010// +/edit_edges.png/1.1/Wed Dec 8 13:47:54 2010// +/edit_nodes.png/1.1/Wed Dec 8 13:47:54 2010// +/logo.png/1.1/Wed Dec 8 13:47:54 2010// +/performAll.gif/1.1/Wed Dec 8 13:47:54 2010// +/performStep.gif/1.1/Wed Dec 8 13:47:54 2010// +/permutation.png/1.1/Wed Dec 8 13:47:54 2010// +/redo.gif/1.1/Wed Dec 8 13:47:54 2010// +/startnodechooser.png/1.1/Wed Dec 8 13:47:54 2010// +/tab_bfs.png/1.1/Wed Dec 8 13:47:54 2010// +/tab_design.png/1.1/Wed Dec 8 13:47:54 2010// +/tab_dfs.png/1.1/Wed Dec 8 13:47:54 2010// +/undo.gif/1.1/Wed Dec 8 13:47:54 2010// +/undoAll.gif/1.1/Wed Dec 8 13:47:54 2010// +/undoStep.gif/1.1/Wed Dec 8 13:47:54 2010// +/welcomescreen.png/1.1/Wed Dec 8 13:47:54 2010// +/ws_last.png/1.1/Wed Dec 8 13:47:54 2010// +/ws_load.png/1.1/Wed Dec 8 13:47:54 2010// +/ws_new.png/1.1/Wed Dec 8 13:47:54 2010// diff --git a/res/module/bfsdfs/help/pics/CVS/Repository b/res/module/bfsdfs/help/pics/CVS/Repository new file mode 100644 index 0000000..ab141d5 --- /dev/null +++ b/res/module/bfsdfs/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/bfsdfs/help/pics diff --git a/res/module/bfsdfs/help/pics/CVS/Root b/res/module/bfsdfs/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/bfsdfs/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/bfsdfs/help/pics/abortAlg.gif b/res/module/bfsdfs/help/pics/abortAlg.gif new file mode 100644 index 0000000..06949a6 Binary files /dev/null and b/res/module/bfsdfs/help/pics/abortAlg.gif differ diff --git a/res/module/bfsdfs/help/pics/animation.png b/res/module/bfsdfs/help/pics/animation.png new file mode 100644 index 0000000..167027c Binary files /dev/null and b/res/module/bfsdfs/help/pics/animation.png differ diff --git a/res/module/bfsdfs/help/pics/beamermode_button.gif b/res/module/bfsdfs/help/pics/beamermode_button.gif new file mode 100644 index 0000000..3be7a76 Binary files /dev/null and b/res/module/bfsdfs/help/pics/beamermode_button.gif differ diff --git a/res/module/bfsdfs/help/pics/bfstab.png b/res/module/bfsdfs/help/pics/bfstab.png new file mode 100644 index 0000000..546e34d Binary files /dev/null and b/res/module/bfsdfs/help/pics/bfstab.png differ diff --git a/res/module/bfsdfs/help/pics/chance.png b/res/module/bfsdfs/help/pics/chance.png new file mode 100644 index 0000000..ba895c5 Binary files /dev/null and b/res/module/bfsdfs/help/pics/chance.png differ diff --git a/res/module/bfsdfs/help/pics/clear.gif b/res/module/bfsdfs/help/pics/clear.gif new file mode 100644 index 0000000..468b7bd Binary files /dev/null and b/res/module/bfsdfs/help/pics/clear.gif differ diff --git a/res/module/bfsdfs/help/pics/controlpanel.png b/res/module/bfsdfs/help/pics/controlpanel.png new file mode 100644 index 0000000..eb01e0a Binary files /dev/null and b/res/module/bfsdfs/help/pics/controlpanel.png differ diff --git a/res/module/bfsdfs/help/pics/designtab.png b/res/module/bfsdfs/help/pics/designtab.png new file mode 100644 index 0000000..4156c10 Binary files /dev/null and b/res/module/bfsdfs/help/pics/designtab.png differ diff --git a/res/module/bfsdfs/help/pics/dfstab.png b/res/module/bfsdfs/help/pics/dfstab.png new file mode 100644 index 0000000..792d640 Binary files /dev/null and b/res/module/bfsdfs/help/pics/dfstab.png differ diff --git a/res/module/bfsdfs/help/pics/edit_double_edges.png b/res/module/bfsdfs/help/pics/edit_double_edges.png new file mode 100644 index 0000000..a1c66fc Binary files /dev/null and b/res/module/bfsdfs/help/pics/edit_double_edges.png differ diff --git a/res/module/bfsdfs/help/pics/edit_edges.png b/res/module/bfsdfs/help/pics/edit_edges.png new file mode 100644 index 0000000..2a64b0f Binary files /dev/null and b/res/module/bfsdfs/help/pics/edit_edges.png differ diff --git a/res/module/bfsdfs/help/pics/edit_nodes.png b/res/module/bfsdfs/help/pics/edit_nodes.png new file mode 100644 index 0000000..cc85bf7 Binary files /dev/null and b/res/module/bfsdfs/help/pics/edit_nodes.png differ diff --git a/res/module/bfsdfs/help/pics/logo.png b/res/module/bfsdfs/help/pics/logo.png new file mode 100644 index 0000000..0b63381 Binary files /dev/null and b/res/module/bfsdfs/help/pics/logo.png differ diff --git a/res/module/bfsdfs/help/pics/performAll.gif b/res/module/bfsdfs/help/pics/performAll.gif new file mode 100644 index 0000000..923ccee Binary files /dev/null and b/res/module/bfsdfs/help/pics/performAll.gif differ diff --git a/res/module/bfsdfs/help/pics/performStep.gif b/res/module/bfsdfs/help/pics/performStep.gif new file mode 100644 index 0000000..b917be6 Binary files /dev/null and b/res/module/bfsdfs/help/pics/performStep.gif differ diff --git a/res/module/bfsdfs/help/pics/permutation.png b/res/module/bfsdfs/help/pics/permutation.png new file mode 100644 index 0000000..8e7aba3 Binary files /dev/null and b/res/module/bfsdfs/help/pics/permutation.png differ diff --git a/res/module/bfsdfs/help/pics/redo.gif b/res/module/bfsdfs/help/pics/redo.gif new file mode 100644 index 0000000..9ff244f Binary files /dev/null and b/res/module/bfsdfs/help/pics/redo.gif differ diff --git a/res/module/bfsdfs/help/pics/startnodechooser.png b/res/module/bfsdfs/help/pics/startnodechooser.png new file mode 100644 index 0000000..960d03c Binary files /dev/null and b/res/module/bfsdfs/help/pics/startnodechooser.png differ diff --git a/res/module/bfsdfs/help/pics/tab_bfs.png b/res/module/bfsdfs/help/pics/tab_bfs.png new file mode 100644 index 0000000..3515fa5 Binary files /dev/null and b/res/module/bfsdfs/help/pics/tab_bfs.png differ diff --git a/res/module/bfsdfs/help/pics/tab_design.png b/res/module/bfsdfs/help/pics/tab_design.png new file mode 100644 index 0000000..5983b1e Binary files /dev/null and b/res/module/bfsdfs/help/pics/tab_design.png differ diff --git a/res/module/bfsdfs/help/pics/tab_dfs.png b/res/module/bfsdfs/help/pics/tab_dfs.png new file mode 100644 index 0000000..afb12da Binary files /dev/null and b/res/module/bfsdfs/help/pics/tab_dfs.png differ diff --git a/res/module/bfsdfs/help/pics/undo.gif b/res/module/bfsdfs/help/pics/undo.gif new file mode 100644 index 0000000..f367948 Binary files /dev/null and b/res/module/bfsdfs/help/pics/undo.gif differ diff --git a/res/module/bfsdfs/help/pics/undoAll.gif b/res/module/bfsdfs/help/pics/undoAll.gif new file mode 100644 index 0000000..7e52e8d Binary files /dev/null and b/res/module/bfsdfs/help/pics/undoAll.gif differ diff --git a/res/module/bfsdfs/help/pics/undoStep.gif b/res/module/bfsdfs/help/pics/undoStep.gif new file mode 100644 index 0000000..facdc36 Binary files /dev/null and b/res/module/bfsdfs/help/pics/undoStep.gif differ diff --git a/res/module/bfsdfs/help/pics/welcomescreen.png b/res/module/bfsdfs/help/pics/welcomescreen.png new file mode 100644 index 0000000..1e81751 Binary files /dev/null and b/res/module/bfsdfs/help/pics/welcomescreen.png differ diff --git a/res/module/bfsdfs/help/pics/ws_last.png b/res/module/bfsdfs/help/pics/ws_last.png new file mode 100644 index 0000000..451939e Binary files /dev/null and b/res/module/bfsdfs/help/pics/ws_last.png differ diff --git a/res/module/bfsdfs/help/pics/ws_load.png b/res/module/bfsdfs/help/pics/ws_load.png new file mode 100644 index 0000000..dba8a55 Binary files /dev/null and b/res/module/bfsdfs/help/pics/ws_load.png differ diff --git a/res/module/bfsdfs/help/pics/ws_new.png b/res/module/bfsdfs/help/pics/ws_new.png new file mode 100644 index 0000000..d62450a Binary files /dev/null and b/res/module/bfsdfs/help/pics/ws_new.png differ diff --git a/res/module/bfsdfs/help/style.css b/res/module/bfsdfs/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/bfsdfs/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/c0h0/CVS/Entries b/res/module/c0h0/CVS/Entries new file mode 100644 index 0000000..e31e7a4 --- /dev/null +++ b/res/module/c0h0/CVS/Entries @@ -0,0 +1,3 @@ +/c0h0.prefs/1.1/Sat Mar 5 14:12:05 2011// +D/c0h0_pix//// +D/help//// diff --git a/res/module/c0h0/CVS/Repository b/res/module/c0h0/CVS/Repository new file mode 100644 index 0000000..1a98a64 --- /dev/null +++ b/res/module/c0h0/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0 diff --git a/res/module/c0h0/CVS/Root b/res/module/c0h0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/c0h0.prefs b/res/module/c0h0/c0h0.prefs new file mode 100644 index 0000000..8798b3c --- /dev/null +++ b/res/module/c0h0/c0h0.prefs @@ -0,0 +1,3 @@ +#j-Algo Default-Settings for C0H0-Modul +Version 0.5 +BeamerMode=true diff --git a/res/module/c0h0/c0h0_pix/CVS/Entries b/res/module/c0h0/c0h0_pix/CVS/Entries new file mode 100644 index 0000000..e8e8098 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/CVS/Entries @@ -0,0 +1,44 @@ +/drive-harddisk.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/drive-harddisk16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/exampleButtonIcon-original.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/exampleButtonIcon-original16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/exampleButtonIcon.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/exampleButtonIcon16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/loadButtonIcon-original.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/loadButtonIcon-original16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/loadButtonIcon.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/loadButtonIcon16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/logo.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/logo16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/makepng.sh/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/newButtonIcon.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/newButtonIcon16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/performAll.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/performAll16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/performStep.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/performStep16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/process-stop.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/process-stop16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/run.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/run16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +D/svg//// +/system-lock-screen.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/system-lock-screen16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/text-x-csharp.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/text-x-csharp16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/transviewOff.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/transviewOff16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/transviewOn.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/transviewOn16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/undoAll.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/undoAll16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/undoStep.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/undoStep16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstate.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstate16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateC0Flow.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateC0Flow16.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateC0H0.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateC0H016.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateFlowH0.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/viewstateFlowH016.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ diff --git a/res/module/c0h0/c0h0_pix/CVS/Repository b/res/module/c0h0/c0h0_pix/CVS/Repository new file mode 100644 index 0000000..a73d87f --- /dev/null +++ b/res/module/c0h0/c0h0_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/c0h0_pix diff --git a/res/module/c0h0/c0h0_pix/CVS/Root b/res/module/c0h0/c0h0_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/c0h0_pix/drive-harddisk.png b/res/module/c0h0/c0h0_pix/drive-harddisk.png new file mode 100644 index 0000000..fb3f7bf Binary files /dev/null and b/res/module/c0h0/c0h0_pix/drive-harddisk.png differ diff --git a/res/module/c0h0/c0h0_pix/drive-harddisk16.png b/res/module/c0h0/c0h0_pix/drive-harddisk16.png new file mode 100644 index 0000000..bf64803 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/drive-harddisk16.png differ diff --git a/res/module/c0h0/c0h0_pix/exampleButtonIcon-original.png b/res/module/c0h0/c0h0_pix/exampleButtonIcon-original.png new file mode 100644 index 0000000..cfce957 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/exampleButtonIcon-original.png differ diff --git a/res/module/c0h0/c0h0_pix/exampleButtonIcon-original16.png b/res/module/c0h0/c0h0_pix/exampleButtonIcon-original16.png new file mode 100644 index 0000000..a492cb1 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/exampleButtonIcon-original16.png differ diff --git a/res/module/c0h0/c0h0_pix/exampleButtonIcon.png b/res/module/c0h0/c0h0_pix/exampleButtonIcon.png new file mode 100644 index 0000000..37a1df3 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/exampleButtonIcon.png differ diff --git a/res/module/c0h0/c0h0_pix/exampleButtonIcon16.png b/res/module/c0h0/c0h0_pix/exampleButtonIcon16.png new file mode 100644 index 0000000..03c121a Binary files /dev/null and b/res/module/c0h0/c0h0_pix/exampleButtonIcon16.png differ diff --git a/res/module/c0h0/c0h0_pix/loadButtonIcon-original.png b/res/module/c0h0/c0h0_pix/loadButtonIcon-original.png new file mode 100644 index 0000000..1293c75 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/loadButtonIcon-original.png differ diff --git a/res/module/c0h0/c0h0_pix/loadButtonIcon-original16.png b/res/module/c0h0/c0h0_pix/loadButtonIcon-original16.png new file mode 100644 index 0000000..09d387c Binary files /dev/null and b/res/module/c0h0/c0h0_pix/loadButtonIcon-original16.png differ diff --git a/res/module/c0h0/c0h0_pix/loadButtonIcon.png b/res/module/c0h0/c0h0_pix/loadButtonIcon.png new file mode 100644 index 0000000..fdb3662 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/loadButtonIcon.png differ diff --git a/res/module/c0h0/c0h0_pix/loadButtonIcon16.png b/res/module/c0h0/c0h0_pix/loadButtonIcon16.png new file mode 100644 index 0000000..aaf897c Binary files /dev/null and b/res/module/c0h0/c0h0_pix/loadButtonIcon16.png differ diff --git a/res/module/c0h0/c0h0_pix/logo.png b/res/module/c0h0/c0h0_pix/logo.png new file mode 100644 index 0000000..ab6c774 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/logo.png differ diff --git a/res/module/c0h0/c0h0_pix/logo16.png b/res/module/c0h0/c0h0_pix/logo16.png new file mode 100644 index 0000000..28007ec Binary files /dev/null and b/res/module/c0h0/c0h0_pix/logo16.png differ diff --git a/res/module/c0h0/c0h0_pix/makepng.sh b/res/module/c0h0/c0h0_pix/makepng.sh new file mode 100644 index 0000000..7da96a7 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/makepng.sh @@ -0,0 +1,7 @@ +#!/bin/bash +find ./svg -iname "*.svg" | while read file; + do + inkscape -f $file -e ${file%%.svg}.png; + inkscape -f $file -e ${file%%.svg}16.png -h 16; + mv ./svg/*.png .; + done; diff --git a/res/module/c0h0/c0h0_pix/newButtonIcon.png b/res/module/c0h0/c0h0_pix/newButtonIcon.png new file mode 100644 index 0000000..3f0d8e3 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/newButtonIcon.png differ diff --git a/res/module/c0h0/c0h0_pix/newButtonIcon16.png b/res/module/c0h0/c0h0_pix/newButtonIcon16.png new file mode 100644 index 0000000..1db37dd Binary files /dev/null and b/res/module/c0h0/c0h0_pix/newButtonIcon16.png differ diff --git a/res/module/c0h0/c0h0_pix/performAll.png b/res/module/c0h0/c0h0_pix/performAll.png new file mode 100644 index 0000000..45802ee Binary files /dev/null and b/res/module/c0h0/c0h0_pix/performAll.png differ diff --git a/res/module/c0h0/c0h0_pix/performAll16.png b/res/module/c0h0/c0h0_pix/performAll16.png new file mode 100644 index 0000000..a81608c Binary files /dev/null and b/res/module/c0h0/c0h0_pix/performAll16.png differ diff --git a/res/module/c0h0/c0h0_pix/performStep.png b/res/module/c0h0/c0h0_pix/performStep.png new file mode 100644 index 0000000..8bfad60 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/performStep.png differ diff --git a/res/module/c0h0/c0h0_pix/performStep16.png b/res/module/c0h0/c0h0_pix/performStep16.png new file mode 100644 index 0000000..c924286 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/performStep16.png differ diff --git a/res/module/c0h0/c0h0_pix/process-stop.png b/res/module/c0h0/c0h0_pix/process-stop.png new file mode 100644 index 0000000..0f7c3f7 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/process-stop.png differ diff --git a/res/module/c0h0/c0h0_pix/process-stop16.png b/res/module/c0h0/c0h0_pix/process-stop16.png new file mode 100644 index 0000000..dd2e2a8 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/process-stop16.png differ diff --git a/res/module/c0h0/c0h0_pix/run.png b/res/module/c0h0/c0h0_pix/run.png new file mode 100644 index 0000000..0aac28c Binary files /dev/null and b/res/module/c0h0/c0h0_pix/run.png differ diff --git a/res/module/c0h0/c0h0_pix/run16.png b/res/module/c0h0/c0h0_pix/run16.png new file mode 100644 index 0000000..f4d88d8 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/run16.png differ diff --git a/res/module/c0h0/c0h0_pix/svg/CVS/Entries b/res/module/c0h0/c0h0_pix/svg/CVS/Entries new file mode 100644 index 0000000..060ce10 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/CVS/Entries @@ -0,0 +1,21 @@ +/drive-harddisk.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/exampleButtonIcon-original.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/exampleButtonIcon.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/loadButtonIcon-original.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/loadButtonIcon.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/logo.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/newButtonIcon.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/performAll.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/performStep.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/process-stop.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/run.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/system-lock-screen.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/text-x-csharp.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/transviewOff.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/transviewOn.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/undoAll.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/undoStep.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/viewstate.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/viewstateC0Flow.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/viewstateC0H0.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ +/viewstateFlowH0.svg/1.1/Sat Mar 5 14:12:04 2011/-kb/ diff --git a/res/module/c0h0/c0h0_pix/svg/CVS/Repository b/res/module/c0h0/c0h0_pix/svg/CVS/Repository new file mode 100644 index 0000000..c5a03d7 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/c0h0_pix/svg diff --git a/res/module/c0h0/c0h0_pix/svg/CVS/Root b/res/module/c0h0/c0h0_pix/svg/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/c0h0_pix/svg/drive-harddisk.svg b/res/module/c0h0/c0h0_pix/svg/drive-harddisk.svg new file mode 100644 index 0000000..2bc71e9 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/drive-harddisk.svg @@ -0,0 +1,1114 @@ + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon-original.svg b/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon-original.svg new file mode 100644 index 0000000..35c3538 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon-original.svg @@ -0,0 +1,552 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon.svg b/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon.svg new file mode 100644 index 0000000..7356a52 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/exampleButtonIcon.svg @@ -0,0 +1,3131 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/loadButtonIcon-original.svg b/res/module/c0h0/c0h0_pix/svg/loadButtonIcon-original.svg new file mode 100644 index 0000000..88e1baa --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/loadButtonIcon-original.svg @@ -0,0 +1,279 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/loadButtonIcon.svg b/res/module/c0h0/c0h0_pix/svg/loadButtonIcon.svg new file mode 100644 index 0000000..cd97740 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/loadButtonIcon.svg @@ -0,0 +1,2670 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/logo.svg b/res/module/c0h0/c0h0_pix/svg/logo.svg new file mode 100644 index 0000000..1077896 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/logo.svg @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + then + + + + else + + + if + + diff --git a/res/module/c0h0/c0h0_pix/svg/newButtonIcon.svg b/res/module/c0h0/c0h0_pix/svg/newButtonIcon.svg new file mode 100644 index 0000000..e4d5369 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/newButtonIcon.svg @@ -0,0 +1,1291 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/performAll.svg b/res/module/c0h0/c0h0_pix/svg/performAll.svg new file mode 100644 index 0000000..d0a30ec --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/performAll.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/performStep.svg b/res/module/c0h0/c0h0_pix/svg/performStep.svg new file mode 100644 index 0000000..ea20f21 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/performStep.svg @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/process-stop.svg b/res/module/c0h0/c0h0_pix/svg/process-stop.svg new file mode 100644 index 0000000..148b46e --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/process-stop.svg @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/run.svg b/res/module/c0h0/c0h0_pix/svg/run.svg new file mode 100644 index 0000000..eef5f81 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/run.svg @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/system-lock-screen.svg b/res/module/c0h0/c0h0_pix/svg/system-lock-screen.svg new file mode 100644 index 0000000..257794a --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/system-lock-screen.svg @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/text-x-csharp.svg b/res/module/c0h0/c0h0_pix/svg/text-x-csharp.svg new file mode 100644 index 0000000..442ac63 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/text-x-csharp.svg @@ -0,0 +1,521 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/transviewOff.svg b/res/module/c0h0/c0h0_pix/svg/transviewOff.svg new file mode 100644 index 0000000..c892054 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/transviewOff.svg @@ -0,0 +1,454 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/transviewOn.svg b/res/module/c0h0/c0h0_pix/svg/transviewOn.svg new file mode 100644 index 0000000..739cbe0 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/transviewOn.svg @@ -0,0 +1,463 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/undoAll.svg b/res/module/c0h0/c0h0_pix/svg/undoAll.svg new file mode 100644 index 0000000..4c3b764 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/undoAll.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/undoStep.svg b/res/module/c0h0/c0h0_pix/svg/undoStep.svg new file mode 100644 index 0000000..7301f48 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/undoStep.svg @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/c0h0_pix/svg/viewstate.svg b/res/module/c0h0/c0h0_pix/svg/viewstate.svg new file mode 100644 index 0000000..211f798 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/viewstate.svg @@ -0,0 +1,770 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + h0 + + + + + + + then + + + + else + + + if + + + + c0 + h0 + + + + + + + + + then + + + + else + + + if + + c0 + + diff --git a/res/module/c0h0/c0h0_pix/svg/viewstateC0Flow.svg b/res/module/c0h0/c0h0_pix/svg/viewstateC0Flow.svg new file mode 100644 index 0000000..eb11380 --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/viewstateC0Flow.svg @@ -0,0 +1,778 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + h0 + + + + + + + then + + + + else + + + if + + + + c0 + h0 + + + + + + + + + then + + + + else + + + if + + c0 + + diff --git a/res/module/c0h0/c0h0_pix/svg/viewstateC0H0.svg b/res/module/c0h0/c0h0_pix/svg/viewstateC0H0.svg new file mode 100644 index 0000000..b70b9af --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/viewstateC0H0.svg @@ -0,0 +1,778 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + h0 + + + + + + + then + + + + else + + + if + + + + c0 + h0 + + + + + + + + + then + + + + else + + + if + + c0 + + diff --git a/res/module/c0h0/c0h0_pix/svg/viewstateFlowH0.svg b/res/module/c0h0/c0h0_pix/svg/viewstateFlowH0.svg new file mode 100644 index 0000000..11916aa --- /dev/null +++ b/res/module/c0h0/c0h0_pix/svg/viewstateFlowH0.svg @@ -0,0 +1,778 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + h0 + + + + + + + then + + + + else + + + if + + + + c0 + h0 + + + + + + + + + then + + + + else + + + if + + c0 + + diff --git a/res/module/c0h0/c0h0_pix/system-lock-screen.png b/res/module/c0h0/c0h0_pix/system-lock-screen.png new file mode 100644 index 0000000..14f8893 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/system-lock-screen.png differ diff --git a/res/module/c0h0/c0h0_pix/system-lock-screen16.png b/res/module/c0h0/c0h0_pix/system-lock-screen16.png new file mode 100644 index 0000000..e9bcfc7 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/system-lock-screen16.png differ diff --git a/res/module/c0h0/c0h0_pix/text-x-csharp.png b/res/module/c0h0/c0h0_pix/text-x-csharp.png new file mode 100644 index 0000000..f900b32 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/text-x-csharp.png differ diff --git a/res/module/c0h0/c0h0_pix/text-x-csharp16.png b/res/module/c0h0/c0h0_pix/text-x-csharp16.png new file mode 100644 index 0000000..22d1a23 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/text-x-csharp16.png differ diff --git a/res/module/c0h0/c0h0_pix/transviewOff.png b/res/module/c0h0/c0h0_pix/transviewOff.png new file mode 100644 index 0000000..66f6cfd Binary files /dev/null and b/res/module/c0h0/c0h0_pix/transviewOff.png differ diff --git a/res/module/c0h0/c0h0_pix/transviewOff16.png b/res/module/c0h0/c0h0_pix/transviewOff16.png new file mode 100644 index 0000000..3ffcc33 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/transviewOff16.png differ diff --git a/res/module/c0h0/c0h0_pix/transviewOn.png b/res/module/c0h0/c0h0_pix/transviewOn.png new file mode 100644 index 0000000..a4937fd Binary files /dev/null and b/res/module/c0h0/c0h0_pix/transviewOn.png differ diff --git a/res/module/c0h0/c0h0_pix/transviewOn16.png b/res/module/c0h0/c0h0_pix/transviewOn16.png new file mode 100644 index 0000000..ee7fc14 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/transviewOn16.png differ diff --git a/res/module/c0h0/c0h0_pix/undoAll.png b/res/module/c0h0/c0h0_pix/undoAll.png new file mode 100644 index 0000000..2023a83 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/undoAll.png differ diff --git a/res/module/c0h0/c0h0_pix/undoAll16.png b/res/module/c0h0/c0h0_pix/undoAll16.png new file mode 100644 index 0000000..42e755c Binary files /dev/null and b/res/module/c0h0/c0h0_pix/undoAll16.png differ diff --git a/res/module/c0h0/c0h0_pix/undoStep.png b/res/module/c0h0/c0h0_pix/undoStep.png new file mode 100644 index 0000000..1ac6908 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/undoStep.png differ diff --git a/res/module/c0h0/c0h0_pix/undoStep16.png b/res/module/c0h0/c0h0_pix/undoStep16.png new file mode 100644 index 0000000..6450571 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/undoStep16.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstate.png b/res/module/c0h0/c0h0_pix/viewstate.png new file mode 100644 index 0000000..7136d1f Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstate.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstate16.png b/res/module/c0h0/c0h0_pix/viewstate16.png new file mode 100644 index 0000000..2f989df Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstate16.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateC0Flow.png b/res/module/c0h0/c0h0_pix/viewstateC0Flow.png new file mode 100644 index 0000000..dfa5c68 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateC0Flow.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateC0Flow16.png b/res/module/c0h0/c0h0_pix/viewstateC0Flow16.png new file mode 100644 index 0000000..dfa5c68 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateC0Flow16.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateC0H0.png b/res/module/c0h0/c0h0_pix/viewstateC0H0.png new file mode 100644 index 0000000..57ebadc Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateC0H0.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateC0H016.png b/res/module/c0h0/c0h0_pix/viewstateC0H016.png new file mode 100644 index 0000000..57ebadc Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateC0H016.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateFlowH0.png b/res/module/c0h0/c0h0_pix/viewstateFlowH0.png new file mode 100644 index 0000000..d27d869 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateFlowH0.png differ diff --git a/res/module/c0h0/c0h0_pix/viewstateFlowH016.png b/res/module/c0h0/c0h0_pix/viewstateFlowH016.png new file mode 100644 index 0000000..d27d869 Binary files /dev/null and b/res/module/c0h0/c0h0_pix/viewstateFlowH016.png differ diff --git a/res/module/c0h0/help/CVS/Entries b/res/module/c0h0/help/CVS/Entries new file mode 100644 index 0000000..f10c378 --- /dev/null +++ b/res/module/c0h0/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Sat Mar 5 14:12:06 2011/-kb/ diff --git a/res/module/c0h0/help/CVS/Repository b/res/module/c0h0/help/CVS/Repository new file mode 100644 index 0000000..654a23b --- /dev/null +++ b/res/module/c0h0/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help diff --git a/res/module/c0h0/help/CVS/Root b/res/module/c0h0/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/html/CVS/Entries b/res/module/c0h0/help/html/CVS/Entries new file mode 100644 index 0000000..5bd9d53 --- /dev/null +++ b/res/module/c0h0/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Sat Mar 5 14:12:05 2011// +D/data//// +/index.htm/1.1/Sat Mar 5 14:12:05 2011// +/top_frame.htm/1.1/Sat Mar 5 14:12:05 2011// diff --git a/res/module/c0h0/help/html/CVS/Repository b/res/module/c0h0/help/html/CVS/Repository new file mode 100644 index 0000000..10de65b --- /dev/null +++ b/res/module/c0h0/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help/html diff --git a/res/module/c0h0/help/html/CVS/Root b/res/module/c0h0/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/html/contents.htm b/res/module/c0h0/help/html/contents.htm new file mode 100644 index 0000000..894d089 --- /dev/null +++ b/res/module/c0h0/help/html/contents.htm @@ -0,0 +1,61 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul C0H0 + +
    + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/1_start.htm b/res/module/c0h0/help/html/data/1_start.htm new file mode 100644 index 0000000..8ce4dc7 --- /dev/null +++ b/res/module/c0h0/help/html/data/1_start.htm @@ -0,0 +1,24 @@ + + + Der Willkommensbildschirm + + + +

    Der Willkommensbildschirm

    + Willkommensbildschirm +

    Laden von Beispieldateien

    +

    + Dem C0H0-Modul liegen zahlreiche Beispieldateien bei. + Der Benutzer kan eine Übersicht über Klicken auf das rechte Symbol aufrufen. + Die Beispieldatei wird dabei in den C0-Quelltexteditor geladen und kann anschließend verwendet werden. +

    +

    Laden von C0-Quelltextdateien

    +

    + Über einen Klick auf das mittlere Symbol kann der Benutzer C0-Quelltexte laden und anschließend verwenden. +

    +

    Neuen C0-Quelltext erstellen

    +

    + Über eine Klick auf das linke Symbol beginnt man mit einem leeren Quelltexteditor. +

    + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/2_toolbar.htm b/res/module/c0h0/help/html/data/2_toolbar.htm new file mode 100644 index 0000000..8033a3b --- /dev/null +++ b/res/module/c0h0/help/html/data/2_toolbar.htm @@ -0,0 +1,37 @@ + + + Die Werkzeugleiste + + + +

    Die Werkzeugleiste

    + Werkzeugleiste +

    Neuen C0-Quelltext erstellen

    +

    Mit der linken Schaltfläche kann der Benutzer einen neuen C0-Quelltext erstellen. +

    +

    C0-Quelltextdatei laden

    +

    Mit der 2. Schaltfläche kann eine C0-Quelltextdatei geladen werden. +

    +

    Beartbeiten, Simulation

    +

    Mit dieser Schaltfläche kann zwischen dem Bearbeitungsmodus und dem Simulationsmodus umgeschalten werden. +

    +

    Navigation bei der Transformation

    +

    Die 4 Schaltflächen mit den Pfeilsymbolen ermöglichen es dem Benutzer während der + Simulation die Transformation in einzelnen Schritten durchzuführen. Außerdem ist es möglich + eine kompletten Transformationsabschnitt sofort fertigzustellen um schnell zur gewünschten + Position zu navigieren. +

    +

    Ansichtswechsel

    +

    Das C0H0-Modul erlaubt es dem Benutzer den C0-Quelltext verschiedenartig darzustellen. + Dabei werden folgende Kombination angeboten: +

    +
      +
    • C0-Quelltext und Flussdiagramm
    • +
    • Flussdiagramm und H0-Quelltext
    • +
    • C0- und H0-Quelltext
    • +
    +

    Ãœbersetzungsregeln anzeigen

    +

    Diese Schaltfläche blendet Anzeige der sttrans-Regeln ein- bzw. aus. +

    + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/3_c0h0menu.htm b/res/module/c0h0/help/html/data/3_c0h0menu.htm new file mode 100644 index 0000000..3d3e8e0 --- /dev/null +++ b/res/module/c0h0/help/html/data/3_c0h0menu.htm @@ -0,0 +1,28 @@ + + + Das Menü "C0H0" + + + +

    Das Menü "C0H0"

    + Menu +

    Neuer c0-Code

    +

    Mit dieser Funktion kann der Benutzer einen neuen C0-Quelltext erstellen. +

    +

    Öffnen eines c0-Quelltexts

    +

    Mit dieser Funktion kann der Benutzer eine C0-Quelltextdatei öffnen. +

    +

    Laden von C0-Beispielen

    +

    Diese Funktion lädt eines der C0-Quelltext-Beispiele. +

    +

    Speichern des aktuellen C0-Quelltexts

    +

    Mit diesen Funktionen kann der Benutzer den aktuellen C0-Quelltext abspeichern. +

    +

    Speichern von H0-Quelltexten

    +

    Diese Funktion speichert den H0-Quelltext ab. +

    +

    Beamermodus

    +

    Mit dieser Funktion kann zwischen der normalen Ansicht und einer vergrößerten Beamer-Ansicht gewechselt werden. +

    + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/4_c0edit.htm b/res/module/c0h0/help/html/data/4_c0edit.htm new file mode 100644 index 0000000..3cac8f4 --- /dev/null +++ b/res/module/c0h0/help/html/data/4_c0edit.htm @@ -0,0 +1,24 @@ + + + Der C0-Quelltexteditor + + + +

    Der C0-Quelltexteditor

    +

    Der m-k-i-Codegenerator

    + m-k-i-Generator +

    Mit dem m-k-i-Codegenerator kann der Rumpf eines C0-Quelltexts erstellt werden. + Dabei werden die Anzahl der Variable "m", die Anzahl der Eingaben "k" und die Nummer der Variable, welche zum Schluss ausgegeben werden soll "i" angegeben. + Der Generator erzeugt danach dem Rumpf des C0-Quelltexts. +

    +

    Der Quelltexteditor

    + Editorbereich +

    Auf der linken Seite befindet sich der C0-Quelltexteditor. + Dieser untersützt bei Eingaben durch Syntaxhervorhebung und automatisches Einrücken des Quelltexts. +

    +

    Der Syntaxcheck

    + Syntaxcheck +

    Im unteren Bereich werden bei Syntaxfehlern Hinweise angezeigt. +

    + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/5_transform.htm b/res/module/c0h0/help/html/data/5_transform.htm new file mode 100644 index 0000000..37f99ac --- /dev/null +++ b/res/module/c0h0/help/html/data/5_transform.htm @@ -0,0 +1,30 @@ + + + Die Transformation + + + +

    Die Transformation

    +

    Erzeugung der Baumstrukturierten Adressen

    + m-k-i-Generator +

    Zunächst werden in Einzelschritten die baumstrukturierten Adressen erzeugt um am +C0-Quelltext vermerkt. Wie überall im Programm kann zu jedem Zeitpunkt vor- und +zurückgeschalten werden +

    +

    Darstellung als Flussdiagramm

    + Flussdiagramm +

    Sobald die baumstrukturierten Adressen vollständig erzeugt wurden wird das Flussdiagramm +schrittweise eingeblendet. Dabei werden die entsprechenden Elemente im +C0-Quelltext hervorgehoben, sodass der Benutzer sehen kann, welcher Teil des C0- +Quelltextes zu welchem Teil des Fludiagramms gehört. Das Aufdecken des Flussiagramms +erfolgt ebenfalls wieder in einzelnen Schritten. +

    +

    Umwandlung in H0-Quelltext

    + Umwandlung zu H0-Quelltext +

    Sobald das Flussdiagramm vollständig aufgedeckt wurde, werden Flussiagramm und +der, noch leere, H0-Quelltext eingeblendet. In Einzelschritten wird das Flussdiagram +abgearbeitet und der zugehörige H0-Quelltext erzeugt. +

    + + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/CVS/Entries b/res/module/c0h0/help/html/data/CVS/Entries new file mode 100644 index 0000000..d776ee5 --- /dev/null +++ b/res/module/c0h0/help/html/data/CVS/Entries @@ -0,0 +1,7 @@ +/1_start.htm/1.1/Sat Mar 5 14:12:06 2011// +/2_toolbar.htm/1.1/Sat Mar 5 14:12:06 2011// +/3_c0h0menu.htm/1.1/Sat Mar 5 14:12:06 2011// +/4_c0edit.htm/1.1/Sat Mar 5 14:12:06 2011// +/5_transform.htm/1.1/Sat Mar 5 14:12:06 2011// +/overview.htm/1.1/Sat Mar 5 14:12:06 2011// +/titlepage.html/1.1/Sat Mar 5 14:12:06 2011// diff --git a/res/module/c0h0/help/html/data/CVS/Repository b/res/module/c0h0/help/html/data/CVS/Repository new file mode 100644 index 0000000..53f3738 --- /dev/null +++ b/res/module/c0h0/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help/html/data diff --git a/res/module/c0h0/help/html/data/CVS/Root b/res/module/c0h0/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/html/data/overview.htm b/res/module/c0h0/help/html/data/overview.htm new file mode 100644 index 0000000..a61c9c7 --- /dev/null +++ b/res/module/c0h0/help/html/data/overview.htm @@ -0,0 +1,29 @@ + + + +Einleitung + + + + + +

    Dies ist die Hilfe des C0H0-Moduls

    +

    Einleitung

    +

    Es wird anschaulich erklärt, wie ein C00-Programm in ein äquivalentes H0-Programm konvertiert wird. + Der Nutzer kann dazu ein C00-Programm laden oder selbst schreiben. + Anschließend wird der Umwandlungsvorgang in mehreren Schritten durchgeführt. + Zunächst werden sogenannte baumstrukturierte Adressen anschaulich erzeugt. + Der C00-Quelltext wird ein einem Flussdiagramm dargestellt und mit den erzeugten baumstrukturierten Adressen versehen. + Anschließend wird das Flussdiagramm durchlaufen und mit den einzelnen Umwandlungsregeln entsprechend der H0-Quelltext erzeugt.

    +

    Funktionsübersicht

    +

    +

      +
    • - Laden, Speichern und Bearbeiten eines C00-Programms
    • +
    • - Parsen eines C00-Programms
    • +
    • - Erzeugen vom baumstrukturierten Adressen
    • +
    • - Erzeuges eines Flussdiagramms aus einem C00-Programm
    • +
    • - Erzeugen eines H0-Programms aus einem Flussdiagramm und baumstrukturiertenAdressen
    • +
    • - Verweis auf die angewendete sttrans-Regel
    • +
    +

    + \ No newline at end of file diff --git a/res/module/c0h0/help/html/data/titlepage.html b/res/module/c0h0/help/html/data/titlepage.html new file mode 100644 index 0000000..f960d26 --- /dev/null +++ b/res/module/c0h0/help/html/data/titlepage.html @@ -0,0 +1,14 @@ + + + + +Das Modul C0/H0 + +
    +
    +

    Das Modul C0/H0

    +

    Anwenderdokumentation

    +
    + + + diff --git a/res/module/c0h0/help/html/index.htm b/res/module/c0h0/help/html/index.htm new file mode 100644 index 0000000..3d8eaa0 --- /dev/null +++ b/res/module/c0h0/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum C0H0-Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/c0h0/help/html/top_frame.htm b/res/module/c0h0/help/html/top_frame.htm new file mode 100644 index 0000000..533bbe6 --- /dev/null +++ b/res/module/c0h0/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/c0h0/help/jhelp/CVS/Entries b/res/module/c0h0/help/jhelp/CVS/Entries new file mode 100644 index 0000000..624da62 --- /dev/null +++ b/res/module/c0h0/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/c0h0Index.xml/1.1/Sat Mar 5 14:12:05 2011// +/c0h0TOC.xml/1.1/Sat Mar 5 14:12:05 2011// +/c0h0_help.hs/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/c0h0map.jhm/1.1/Sat Mar 5 14:12:05 2011/-kb/ diff --git a/res/module/c0h0/help/jhelp/CVS/Repository b/res/module/c0h0/help/jhelp/CVS/Repository new file mode 100644 index 0000000..a75a53f --- /dev/null +++ b/res/module/c0h0/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help/jhelp diff --git a/res/module/c0h0/help/jhelp/CVS/Root b/res/module/c0h0/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..cd36694 --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/DOCS.TAB/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/OFFSETS/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/POSITIONS/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/SCHEMA/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/TMAP/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/config.ini/1.1/Sat Mar 5 14:12:06 2011// diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..536696a --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help/jhelp/JavaHelpSearch diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS b/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..1b6626b Binary files /dev/null and b/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..44b0ded Binary files /dev/null and b/res/module/c0h0/help/jhelp/JavaHelpSearch/DOCS.TAB differ diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/c0h0/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..87d8c31 --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +…Ÿ%¦fA†a@€Ws—+VŸE]Î\­Zt§Ùóe1zÒ}Ÿ6S­€ \ No newline at end of file diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/c0h0/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..8329c49 Binary files /dev/null and b/res/module/c0h0/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/c0h0/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..3841983 --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=242 id2=1 diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/TMAP b/res/module/c0h0/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..b0d55e4 Binary files /dev/null and b/res/module/c0h0/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/c0h0/help/jhelp/JavaHelpSearch/config.ini b/res/module/c0h0/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/c0h0/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/c0h0/help/jhelp/c0h0Index.xml b/res/module/c0h0/help/jhelp/c0h0Index.xml new file mode 100644 index 0000000..a1db78e --- /dev/null +++ b/res/module/c0h0/help/jhelp/c0h0Index.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/help/jhelp/c0h0TOC.xml b/res/module/c0h0/help/jhelp/c0h0TOC.xml new file mode 100644 index 0000000..bf77245 --- /dev/null +++ b/res/module/c0h0/help/jhelp/c0h0TOC.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/help/jhelp/c0h0_help.hs b/res/module/c0h0/help/jhelp/c0h0_help.hs new file mode 100644 index 0000000..9d465e0 --- /dev/null +++ b/res/module/c0h0/help/jhelp/c0h0_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Modul C0/H0 + + + + + c0h0_home + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + c0h0TOC.xml + + + + Index + + javax.help.IndexView + c0h0Index.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/c0h0/help/jhelp/c0h0map.jhm b/res/module/c0h0/help/jhelp/c0h0map.jhm new file mode 100644 index 0000000..7afeec3 --- /dev/null +++ b/res/module/c0h0/help/jhelp/c0h0map.jhm @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/c0h0/help/pics/0_welcomescreen.png b/res/module/c0h0/help/pics/0_welcomescreen.png new file mode 100644 index 0000000..fc1ea41 Binary files /dev/null and b/res/module/c0h0/help/pics/0_welcomescreen.png differ diff --git a/res/module/c0h0/help/pics/10_toggle_views.png b/res/module/c0h0/help/pics/10_toggle_views.png new file mode 100644 index 0000000..fdb5b0b Binary files /dev/null and b/res/module/c0h0/help/pics/10_toggle_views.png differ diff --git a/res/module/c0h0/help/pics/11_actions.png b/res/module/c0h0/help/pics/11_actions.png new file mode 100644 index 0000000..ad123bb Binary files /dev/null and b/res/module/c0h0/help/pics/11_actions.png differ diff --git a/res/module/c0h0/help/pics/12_mark_code_lines.png b/res/module/c0h0/help/pics/12_mark_code_lines.png new file mode 100644 index 0000000..029e0b0 Binary files /dev/null and b/res/module/c0h0/help/pics/12_mark_code_lines.png differ diff --git a/res/module/c0h0/help/pics/13_toolbar.png b/res/module/c0h0/help/pics/13_toolbar.png new file mode 100644 index 0000000..0967fea Binary files /dev/null and b/res/module/c0h0/help/pics/13_toolbar.png differ diff --git a/res/module/c0h0/help/pics/14_menu.png b/res/module/c0h0/help/pics/14_menu.png new file mode 100644 index 0000000..5cfaf2a Binary files /dev/null and b/res/module/c0h0/help/pics/14_menu.png differ diff --git a/res/module/c0h0/help/pics/1_example.png b/res/module/c0h0/help/pics/1_example.png new file mode 100644 index 0000000..1928809 Binary files /dev/null and b/res/module/c0h0/help/pics/1_example.png differ diff --git a/res/module/c0h0/help/pics/2_newfile.png b/res/module/c0h0/help/pics/2_newfile.png new file mode 100644 index 0000000..2ba4ea5 Binary files /dev/null and b/res/module/c0h0/help/pics/2_newfile.png differ diff --git a/res/module/c0h0/help/pics/3_m-k-i-generator.png b/res/module/c0h0/help/pics/3_m-k-i-generator.png new file mode 100644 index 0000000..6f4303c Binary files /dev/null and b/res/module/c0h0/help/pics/3_m-k-i-generator.png differ diff --git a/res/module/c0h0/help/pics/4_editor.png b/res/module/c0h0/help/pics/4_editor.png new file mode 100644 index 0000000..2b28d40 Binary files /dev/null and b/res/module/c0h0/help/pics/4_editor.png differ diff --git a/res/module/c0h0/help/pics/5_checking.png b/res/module/c0h0/help/pics/5_checking.png new file mode 100644 index 0000000..bdc0e6e Binary files /dev/null and b/res/module/c0h0/help/pics/5_checking.png differ diff --git a/res/module/c0h0/help/pics/6_syntaxhighlighting.png b/res/module/c0h0/help/pics/6_syntaxhighlighting.png new file mode 100644 index 0000000..22234c8 Binary files /dev/null and b/res/module/c0h0/help/pics/6_syntaxhighlighting.png differ diff --git a/res/module/c0h0/help/pics/7_create_tsa.png b/res/module/c0h0/help/pics/7_create_tsa.png new file mode 100644 index 0000000..2d34241 Binary files /dev/null and b/res/module/c0h0/help/pics/7_create_tsa.png differ diff --git a/res/module/c0h0/help/pics/8_trace_flowchart.png b/res/module/c0h0/help/pics/8_trace_flowchart.png new file mode 100644 index 0000000..c48277c Binary files /dev/null and b/res/module/c0h0/help/pics/8_trace_flowchart.png differ diff --git a/res/module/c0h0/help/pics/9_create_h0code.png b/res/module/c0h0/help/pics/9_create_h0code.png new file mode 100644 index 0000000..31a9289 Binary files /dev/null and b/res/module/c0h0/help/pics/9_create_h0code.png differ diff --git a/res/module/c0h0/help/pics/CVS/Entries b/res/module/c0h0/help/pics/CVS/Entries new file mode 100644 index 0000000..7a5d082 --- /dev/null +++ b/res/module/c0h0/help/pics/CVS/Entries @@ -0,0 +1,15 @@ +/0_welcomescreen.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/10_toggle_views.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/11_actions.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/12_mark_code_lines.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/13_toolbar.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/14_menu.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/1_example.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/2_newfile.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/3_m-k-i-generator.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/4_editor.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/5_checking.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/6_syntaxhighlighting.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/7_create_tsa.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/8_trace_flowchart.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ +/9_create_h0code.png/1.1/Sat Mar 5 14:12:05 2011/-kb/ diff --git a/res/module/c0h0/help/pics/CVS/Repository b/res/module/c0h0/help/pics/CVS/Repository new file mode 100644 index 0000000..a8ba084 --- /dev/null +++ b/res/module/c0h0/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/c0h0/help/pics diff --git a/res/module/c0h0/help/pics/CVS/Root b/res/module/c0h0/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/c0h0/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/c0h0/help/style.css b/res/module/c0h0/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/c0h0/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/dijkstra/CVS/Entries b/res/module/dijkstra/CVS/Entries new file mode 100644 index 0000000..d9d43de --- /dev/null +++ b/res/module/dijkstra/CVS/Entries @@ -0,0 +1,2 @@ +D/dijkstra_pix//// +D/help//// diff --git a/res/module/dijkstra/CVS/Repository b/res/module/dijkstra/CVS/Repository new file mode 100644 index 0000000..366539a --- /dev/null +++ b/res/module/dijkstra/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra diff --git a/res/module/dijkstra/CVS/Root b/res/module/dijkstra/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/dijkstra_pix/CVS/Entries b/res/module/dijkstra/dijkstra_pix/CVS/Entries new file mode 100644 index 0000000..0e2120b --- /dev/null +++ b/res/module/dijkstra/dijkstra_pix/CVS/Entries @@ -0,0 +1 @@ +/logo.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ diff --git a/res/module/dijkstra/dijkstra_pix/CVS/Repository b/res/module/dijkstra/dijkstra_pix/CVS/Repository new file mode 100644 index 0000000..89feabe --- /dev/null +++ b/res/module/dijkstra/dijkstra_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/dijkstra_pix diff --git a/res/module/dijkstra/dijkstra_pix/CVS/Root b/res/module/dijkstra/dijkstra_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/dijkstra_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/dijkstra_pix/logo.gif b/res/module/dijkstra/dijkstra_pix/logo.gif new file mode 100644 index 0000000..38baebf Binary files /dev/null and b/res/module/dijkstra/dijkstra_pix/logo.gif differ diff --git a/res/module/dijkstra/help/CVS/Entries b/res/module/dijkstra/help/CVS/Entries new file mode 100644 index 0000000..6cbdb7c --- /dev/null +++ b/res/module/dijkstra/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Sun Mar 12 16:04:47 2006/-kb/ diff --git a/res/module/dijkstra/help/CVS/Repository b/res/module/dijkstra/help/CVS/Repository new file mode 100644 index 0000000..c20b724 --- /dev/null +++ b/res/module/dijkstra/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help diff --git a/res/module/dijkstra/help/CVS/Root b/res/module/dijkstra/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/html/CVS/Entries b/res/module/dijkstra/help/html/CVS/Entries new file mode 100644 index 0000000..da9d528 --- /dev/null +++ b/res/module/dijkstra/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Sun Mar 12 16:05:40 2006// +D/data//// +/index.htm/1.1/Sun Mar 12 16:05:40 2006// +/top_frame.htm/1.1/Sun Mar 12 16:05:40 2006// diff --git a/res/module/dijkstra/help/html/CVS/Repository b/res/module/dijkstra/help/html/CVS/Repository new file mode 100644 index 0000000..f7dc7df --- /dev/null +++ b/res/module/dijkstra/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help/html diff --git a/res/module/dijkstra/help/html/CVS/Root b/res/module/dijkstra/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/html/contents.htm b/res/module/dijkstra/help/html/contents.htm new file mode 100644 index 0000000..ec5d119 --- /dev/null +++ b/res/module/dijkstra/help/html/contents.htm @@ -0,0 +1,54 @@ + + + Inhaltsverzeichnis + + + + +
      + Das Modul Dijkstra + +
    + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/html/data/CVS/Entries b/res/module/dijkstra/help/html/data/CVS/Entries new file mode 100644 index 0000000..b724c3a --- /dev/null +++ b/res/module/dijkstra/help/html/data/CVS/Entries @@ -0,0 +1,3 @@ +/edit.htm/1.2/Wed Mar 22 21:01:26 2006// +/overview.htm/1.2/Wed Mar 22 21:01:26 2006// +/run.htm/1.2/Wed Mar 22 21:01:26 2006// diff --git a/res/module/dijkstra/help/html/data/CVS/Repository b/res/module/dijkstra/help/html/data/CVS/Repository new file mode 100644 index 0000000..1bb7a66 --- /dev/null +++ b/res/module/dijkstra/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help/html/data diff --git a/res/module/dijkstra/help/html/data/CVS/Root b/res/module/dijkstra/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/html/data/edit.htm b/res/module/dijkstra/help/html/data/edit.htm new file mode 100644 index 0000000..fe8d218 --- /dev/null +++ b/res/module/dijkstra/help/html/data/edit.htm @@ -0,0 +1,83 @@ + + + Einleitung + + + + + + +

    Graph erstellen

    +

    Nach dem Start des Moduls wird die Oberfläche für das Erstellen + eines Graphen angezeigt. Sie ist in die Bereiche +

      +
    1. + "Werkzeuge" +
    2. + "Graph" +
    3. + "Knotenliste" +
    4. + "Kantenliste" +
    5. + "Distanzmatrix"
    + aufgeteilt.

    + +

    Graphische Eingabe / Erstellen eines Graphen per Maus

    +

    Das Erstellen eines Graphen per Maus wird durch die Werkzeuge +

      +
    1. +
      "Knoten hinzufügen/verschieben" -- Durch Klicken auf die + Zeichenfläche wird ein neuer Knoten erzeugt. Ein bestehender Knoten kann durch + Ziehen mit der Maus bewegt werden. +
      +
    2. +
      "Kante hinzufügen/bewerten" -- Indem man die Maus von einem + Knoten zu einem anderen zieht, entsteht zwischen ihnen eine neue Kante. Die + Kantenbewertung wird geändert, wenn man sie herauf- bzw. hinunterzieht. +
      +
    3. +
      "Knoten löschen" -- Ein angeklickter Knoten wird + gelöscht. +
      +
    4. +
      "Kante löschen" -- Eine angeklickte Kante wird gelöscht.
      +
    5. +
    + unterstützt.

    +

    +

    Dabei geht man wie folgt vor: Nach der Auswahl des Werkzeugs + "Knoten hinzufügen / verschieben" kann man durch einfaches Klicken auf die + weiße Zeichenfläche Knoten erstellen. Vorhandene Knoten können mit + Drag&Drop verschoben werden. Nachdem man alle Knoten angelegt hat, kann man + nach Auswahl des Werkzeugs "Kante hinzufügen / bewerten" den Graphen + vervollständigen. Um eine Kante zu erstellen, klickt man erst den "Startknoten" + und dann den "Endknoten" der Kante an. Es erscheint eine Kante zwischen den + Knoten mit der Bewertung "fünf". Diese Bewertung (auch Kantengewicht) kann + verändert werden, indem man das Kantengewicht mit der Maus "festhält" und nach + oben (das Gewicht wird größer) oder unten (das Gewicht wird kleiner) zieht.

    +

    +

    + +

    Die Knotenliste

    +

    Die Knotenliste zeigt die Indizes aller Knoten durch Kommata + getrennt. Durch Hinzufügen von Indizes werden auch neue Knoten erzeugt. + Änderungen in der Knotenliste werden nach Betätigen der Schaltfläche "Anwenden" + übernommen.

    + +

    Die Kantenliste

    +

    Die Kantenliste zeigt alle Kanten des Graphen im Format ( VON, + WEG, ZU ). Durch Editieren dieser Liste können bestehende Kanten geändert und + neue hinzufügt werden. Auch hier ist zu beachten, dass Änderungen erst durch + Klicken von "Anwenden" übernommen werden.

    + +

    Die Adjazenzmatrix

    +

    Die Adjazenzrelation des Graphen ist in dieser Matrix + dargestellt. Kanten und Knoten können in jener durch einfaches Eingeben einer + Kantenbewertung erzeugt werden. Dabei muss nicht beachtet werden, daß die + Matrix symmetrisch bleibt, da dies automatisch gewährleistet wird. Nach dem + Bearbeiten der Matrix darf nicht vergessen werden, den "Anwenden" - Button zu + betätigen, damit die Änderungen übernommen werden.

    + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/html/data/overview.htm b/res/module/dijkstra/help/html/data/overview.htm new file mode 100644 index 0000000..414a4de --- /dev/null +++ b/res/module/dijkstra/help/html/data/overview.htm @@ -0,0 +1,51 @@ + + + Einleitung + + + + + + +

    Das Modul Dijkstra

    +

    Einleitung

    +

    Das Modul Dijkstra visualisiert den bekannten + Algorithmus von E. W. Dijkstra zum Finden der kürzesten Wege von einem + Startknoten in einem Distanzgraphen. Der Algorithmus selbst ist unter anderem + im Vorlesungsskript von Prof. Vogler "Algorithmen, Datenstrukturen und + Programmierung" zu finden. Aber auch im Internet existieren zahlreiche Quellen + dazu. Soweit es möglich gewesen ist, wurde beim Design des Moduls darauf + geachtet, es weitgehend intuitiv und selbst-dokumentierend zu gestalten. + Nichtsdestotrotz findet sich hier eine kurze Einführung in das Dijkstra + - Modul.
    +

    +

    Funktionsübersicht

    +

    Das Modul Dijkstra realisiert folgende + Funktionen:

    +
      +
    • +
      graphisches Erstellen / Bearbeiten eines Distanzgraphen
      +
    • +
      Erstellen / Bearbeiten eines Graphen mittels Kanten- / + Knotenliste oder Adjazenzmatrix
      +
    • +
      Speichern und Laden von Graphen
      +
    • +
      Visualisierung des Dijkstra-Algorithmus
      +
    • +
    +
    +

    Modul starten

    +

    Um das Modul zu starten, wählt man im Menü <Datei> + das Submenü + <Neu> und dann den Menübefehl + <Dijkstra>. Im Hauptfenster erscheint nun die + Oberfläche des Dijkstra - Moduls im +Eingabe-Modus.

    +

    Symbolleiste

    +

    Die Symbolleiste stellt die Funktionen <Speichern>, + <Speichern unter>, <Rückgängig> und + <Wiederherstellen> bereit.

    + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/html/data/run.htm b/res/module/dijkstra/help/html/data/run.htm new file mode 100644 index 0000000..62406ff --- /dev/null +++ b/res/module/dijkstra/help/html/data/run.htm @@ -0,0 +1,26 @@ + + + Einleitung + + + + + + +

    Ablauf des Algorithmus

    +

    +

    +

    Ist man mit dem Aussehen seines Graphen zufrieden, wird durch + Auswählen des "Algorithmus starten" - Buttons in den Algorithmus-Modus des + Moduls gewechselt.
    + Der Graph erscheint nun zuerst grau und ändert sich farblich im weiteren + Verlauf, um die verschiedenen Zustände des Dijkstra - Algorithmus darzustellen. + Um die einzelnen Schritte des Algorithmus abzuarbeiten, kann man man mit den + "<"- und ">"-Buttons zum vorherigen bzw. nächsten Schritt springen. + "<<" und ">>" überspringen gleich mehrere Schritte.
    + Falls man sich entschließt, einen anderen Graphen untersuchen zu wollen, kann + mit "Graph bearbeiten" in den Editiermodus zurückgekehrt werden. "Algorithmus + neu starten" springt zurück an den Anfang des Algorithmus.

    + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/html/index.htm b/res/module/dijkstra/help/html/index.htm new file mode 100644 index 0000000..38c0e10 --- /dev/null +++ b/res/module/dijkstra/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum Dijkstra Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/html/top_frame.htm b/res/module/dijkstra/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/dijkstra/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/jhelp/CVS/Entries b/res/module/dijkstra/help/jhelp/CVS/Entries new file mode 100644 index 0000000..26c39f8 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/dijkstraIndex.xml/1.2/Wed Mar 22 11:52:27 2006// +/dijkstraTOC.xml/1.1/Sun Mar 12 16:04:52 2006// +/dijkstra_help.hs/1.2/Wed Mar 22 20:51:05 2006/-kb/ +/map.jhm/1.1/Sun Mar 12 16:04:52 2006/-kb/ diff --git a/res/module/dijkstra/help/jhelp/CVS/Repository b/res/module/dijkstra/help/jhelp/CVS/Repository new file mode 100644 index 0000000..6cf56da --- /dev/null +++ b/res/module/dijkstra/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help/jhelp diff --git a/res/module/dijkstra/help/jhelp/CVS/Root b/res/module/dijkstra/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..9ba772c --- /dev/null +++ b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Sun Mar 12 16:04:17 2006/-kb/ +/DOCS.TAB/1.1/Sun Mar 12 16:04:17 2006/-kb/ +/OFFSETS/1.1/Sun Mar 12 16:04:17 2006/-kb/ +/POSITIONS/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/SCHEMA/1.1/Sun Mar 12 16:04:17 2006/-kb/ +/TMAP/1.2/Wed Mar 22 11:52:27 2006/-kb/ +/config.ini/1.1/Sun Mar 12 16:04:17 2006// diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..1a02cfc --- /dev/null +++ b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help/jhelp/JavaHelpSearch diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS b/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..8d7bf32 Binary files /dev/null and b/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..e282970 Binary files /dev/null and b/res/module/dijkstra/help/jhelp/JavaHelpSearch/DOCS.TAB differ diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/dijkstra/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..cfc7656 Binary files /dev/null and b/res/module/dijkstra/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/dijkstra/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..c925e14 Binary files /dev/null and b/res/module/dijkstra/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/dijkstra/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..0c42a65 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=234 id2=1 diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/TMAP b/res/module/dijkstra/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..8db7e2b Binary files /dev/null and b/res/module/dijkstra/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/dijkstra/help/jhelp/JavaHelpSearch/config.ini b/res/module/dijkstra/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/dijkstra/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/dijkstra/help/jhelp/dijkstraIndex.xml b/res/module/dijkstra/help/jhelp/dijkstraIndex.xml new file mode 100644 index 0000000..1cbd8a4 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/dijkstraIndex.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/dijkstra/help/jhelp/dijkstraTOC.xml b/res/module/dijkstra/help/jhelp/dijkstraTOC.xml new file mode 100644 index 0000000..084d166 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/dijkstraTOC.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/jhelp/dijkstra_help.hs b/res/module/dijkstra/help/jhelp/dijkstra_help.hs new file mode 100644 index 0000000..311a813 --- /dev/null +++ b/res/module/dijkstra/help/jhelp/dijkstra_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Dijkstra-Modul + + + + + dijkstra + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + dijkstraTOC.xml + + + + Index + + javax.help.IndexView + dijkstraIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/jhelp/map.jhm b/res/module/dijkstra/help/jhelp/map.jhm new file mode 100644 index 0000000..e3d56ab --- /dev/null +++ b/res/module/dijkstra/help/jhelp/map.jhm @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/dijkstra/help/pics/CVS/Entries b/res/module/dijkstra/help/pics/CVS/Entries new file mode 100644 index 0000000..8f84aa9 --- /dev/null +++ b/res/module/dijkstra/help/pics/CVS/Entries @@ -0,0 +1,3 @@ +/edit.png/1.1/Sun Mar 12 16:05:13 2006/-kb/ +/logo_help.png/1.1/Sun Mar 12 16:05:13 2006/-kb/ +/run.png/1.1/Sun Mar 12 16:05:13 2006/-kb/ diff --git a/res/module/dijkstra/help/pics/CVS/Repository b/res/module/dijkstra/help/pics/CVS/Repository new file mode 100644 index 0000000..5b73d8c --- /dev/null +++ b/res/module/dijkstra/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/dijkstra/help/pics diff --git a/res/module/dijkstra/help/pics/CVS/Root b/res/module/dijkstra/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/dijkstra/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/dijkstra/help/pics/edit.png b/res/module/dijkstra/help/pics/edit.png new file mode 100644 index 0000000..fdbb5c9 Binary files /dev/null and b/res/module/dijkstra/help/pics/edit.png differ diff --git a/res/module/dijkstra/help/pics/logo_help.png b/res/module/dijkstra/help/pics/logo_help.png new file mode 100644 index 0000000..1ac8c4b Binary files /dev/null and b/res/module/dijkstra/help/pics/logo_help.png differ diff --git a/res/module/dijkstra/help/pics/run.png b/res/module/dijkstra/help/pics/run.png new file mode 100644 index 0000000..08b5f69 Binary files /dev/null and b/res/module/dijkstra/help/pics/run.png differ diff --git a/res/module/dijkstra/help/style.css b/res/module/dijkstra/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/dijkstra/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/ebnf/CVS/Entries b/res/module/ebnf/CVS/Entries new file mode 100644 index 0000000..a9583a6 --- /dev/null +++ b/res/module/ebnf/CVS/Entries @@ -0,0 +1,3 @@ +D/ebnf_pix//// +D/font//// +D/help//// diff --git a/res/module/ebnf/CVS/Repository b/res/module/ebnf/CVS/Repository new file mode 100644 index 0000000..cc7b27a --- /dev/null +++ b/res/module/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf diff --git a/res/module/ebnf/CVS/Root b/res/module/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/ebnf_pix/CVS/Entries b/res/module/ebnf/ebnf_pix/CVS/Entries new file mode 100644 index 0000000..0e2516d --- /dev/null +++ b/res/module/ebnf/ebnf_pix/CVS/Entries @@ -0,0 +1,25 @@ +/addBranch.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/addRepetition.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/addTerminal.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/addVariable.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +D/button//// +D/cursor//// +/edit.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/light_green.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/light_green.png/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/light_red.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/light_red.png/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/logo.gif/1.3/Sat Aug 12 19:57:13 2006/-kb/ +/rubber.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_ebnf.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_ebnf_desc_de.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_ebnf_desc_en.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_ebnf_rollover.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_load.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_load_desc_de.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_load_desc_en.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_load_rollover.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_syndia.gif/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/start_syndia_desc_de.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_syndia_desc_en.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/start_syndia_rollover.gif/1.1/Sat Aug 12 19:57:14 2006/-kb/ diff --git a/res/module/ebnf/ebnf_pix/CVS/Repository b/res/module/ebnf/ebnf_pix/CVS/Repository new file mode 100644 index 0000000..b22ec88 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/ebnf_pix diff --git a/res/module/ebnf/ebnf_pix/CVS/Root b/res/module/ebnf/ebnf_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/ebnf_pix/addBranch.gif b/res/module/ebnf/ebnf_pix/addBranch.gif new file mode 100644 index 0000000..fda0b52 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/addBranch.gif differ diff --git a/res/module/ebnf/ebnf_pix/addRepetition.gif b/res/module/ebnf/ebnf_pix/addRepetition.gif new file mode 100644 index 0000000..19b2712 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/addRepetition.gif differ diff --git a/res/module/ebnf/ebnf_pix/addTerminal.gif b/res/module/ebnf/ebnf_pix/addTerminal.gif new file mode 100644 index 0000000..a5e4ae8 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/addTerminal.gif differ diff --git a/res/module/ebnf/ebnf_pix/addVariable.gif b/res/module/ebnf/ebnf_pix/addVariable.gif new file mode 100644 index 0000000..434de31 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/addVariable.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/CVS/Entries b/res/module/ebnf/ebnf_pix/button/CVS/Entries new file mode 100644 index 0000000..7e3b0c3 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/button/CVS/Entries @@ -0,0 +1,18 @@ +/addBranch.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/addDiagram.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/addRepetition.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/addTerminal.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/addVariable.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/edit.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/fittosize.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/fittowidth.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/nostairs.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rubber.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_addBranch.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_addRepetition.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_addTerminal.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_addVariable.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_edit.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/selected_rubber.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/stairs.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/zoomer.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ diff --git a/res/module/ebnf/ebnf_pix/button/CVS/Repository b/res/module/ebnf/ebnf_pix/button/CVS/Repository new file mode 100644 index 0000000..6fecd75 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/button/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/ebnf_pix/button diff --git a/res/module/ebnf/ebnf_pix/button/CVS/Root b/res/module/ebnf/ebnf_pix/button/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/button/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/ebnf_pix/button/addBranch.gif b/res/module/ebnf/ebnf_pix/button/addBranch.gif new file mode 100644 index 0000000..b9d8943 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/addBranch.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/addDiagram.gif b/res/module/ebnf/ebnf_pix/button/addDiagram.gif new file mode 100644 index 0000000..bb9fe41 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/addDiagram.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/addRepetition.gif b/res/module/ebnf/ebnf_pix/button/addRepetition.gif new file mode 100644 index 0000000..a4b88ad Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/addRepetition.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/addTerminal.gif b/res/module/ebnf/ebnf_pix/button/addTerminal.gif new file mode 100644 index 0000000..6e0a574 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/addTerminal.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/addVariable.gif b/res/module/ebnf/ebnf_pix/button/addVariable.gif new file mode 100644 index 0000000..7282f62 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/addVariable.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/edit.gif b/res/module/ebnf/ebnf_pix/button/edit.gif new file mode 100644 index 0000000..cffc914 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/edit.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/fittosize.gif b/res/module/ebnf/ebnf_pix/button/fittosize.gif new file mode 100644 index 0000000..b732114 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/fittosize.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/fittowidth.gif b/res/module/ebnf/ebnf_pix/button/fittowidth.gif new file mode 100644 index 0000000..73ec225 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/fittowidth.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/nostairs.gif b/res/module/ebnf/ebnf_pix/button/nostairs.gif new file mode 100644 index 0000000..515f79e Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/nostairs.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/rubber.gif b/res/module/ebnf/ebnf_pix/button/rubber.gif new file mode 100644 index 0000000..0f84f5e Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/rubber.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_addBranch.gif b/res/module/ebnf/ebnf_pix/button/selected_addBranch.gif new file mode 100644 index 0000000..9ad2dba Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_addBranch.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_addRepetition.gif b/res/module/ebnf/ebnf_pix/button/selected_addRepetition.gif new file mode 100644 index 0000000..c1f5412 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_addRepetition.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_addTerminal.gif b/res/module/ebnf/ebnf_pix/button/selected_addTerminal.gif new file mode 100644 index 0000000..b993747 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_addTerminal.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_addVariable.gif b/res/module/ebnf/ebnf_pix/button/selected_addVariable.gif new file mode 100644 index 0000000..2b53f8f Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_addVariable.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_edit.gif b/res/module/ebnf/ebnf_pix/button/selected_edit.gif new file mode 100644 index 0000000..ff377e6 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_edit.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/selected_rubber.gif b/res/module/ebnf/ebnf_pix/button/selected_rubber.gif new file mode 100644 index 0000000..e7b7075 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/selected_rubber.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/stairs.gif b/res/module/ebnf/ebnf_pix/button/stairs.gif new file mode 100644 index 0000000..b1a98d3 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/stairs.gif differ diff --git a/res/module/ebnf/ebnf_pix/button/zoomer.gif b/res/module/ebnf/ebnf_pix/button/zoomer.gif new file mode 100644 index 0000000..51caf78 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/button/zoomer.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/CVS/Entries b/res/module/ebnf/ebnf_pix/cursor/CVS/Entries new file mode 100644 index 0000000..712a1dc --- /dev/null +++ b/res/module/ebnf/ebnf_pix/cursor/CVS/Entries @@ -0,0 +1,8 @@ +/branch.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/branch_right.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/edit.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/repetition.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/repetition_right.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/rubber.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/terminal.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ +/variable.gif/1.1/Sat Aug 12 19:57:11 2006/-kb/ diff --git a/res/module/ebnf/ebnf_pix/cursor/CVS/Repository b/res/module/ebnf/ebnf_pix/cursor/CVS/Repository new file mode 100644 index 0000000..56bcb5a --- /dev/null +++ b/res/module/ebnf/ebnf_pix/cursor/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/ebnf_pix/cursor diff --git a/res/module/ebnf/ebnf_pix/cursor/CVS/Root b/res/module/ebnf/ebnf_pix/cursor/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/ebnf_pix/cursor/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/ebnf_pix/cursor/branch.gif b/res/module/ebnf/ebnf_pix/cursor/branch.gif new file mode 100644 index 0000000..f368856 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/branch.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/branch_right.gif b/res/module/ebnf/ebnf_pix/cursor/branch_right.gif new file mode 100644 index 0000000..feeb0ad Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/branch_right.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/edit.gif b/res/module/ebnf/ebnf_pix/cursor/edit.gif new file mode 100644 index 0000000..ab2b097 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/edit.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/repetition.gif b/res/module/ebnf/ebnf_pix/cursor/repetition.gif new file mode 100644 index 0000000..f34a3cc Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/repetition.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/repetition_right.gif b/res/module/ebnf/ebnf_pix/cursor/repetition_right.gif new file mode 100644 index 0000000..b65f384 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/repetition_right.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/rubber.gif b/res/module/ebnf/ebnf_pix/cursor/rubber.gif new file mode 100644 index 0000000..45610f3 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/rubber.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/terminal.gif b/res/module/ebnf/ebnf_pix/cursor/terminal.gif new file mode 100644 index 0000000..ca7e444 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/terminal.gif differ diff --git a/res/module/ebnf/ebnf_pix/cursor/variable.gif b/res/module/ebnf/ebnf_pix/cursor/variable.gif new file mode 100644 index 0000000..f64d269 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/cursor/variable.gif differ diff --git a/res/module/ebnf/ebnf_pix/edit.gif b/res/module/ebnf/ebnf_pix/edit.gif new file mode 100644 index 0000000..80af8f7 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/edit.gif differ diff --git a/res/module/ebnf/ebnf_pix/light_green.gif b/res/module/ebnf/ebnf_pix/light_green.gif new file mode 100644 index 0000000..91789e4 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/light_green.gif differ diff --git a/res/module/ebnf/ebnf_pix/light_green.png b/res/module/ebnf/ebnf_pix/light_green.png new file mode 100644 index 0000000..8ae0ca7 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/light_green.png differ diff --git a/res/module/ebnf/ebnf_pix/light_red.gif b/res/module/ebnf/ebnf_pix/light_red.gif new file mode 100644 index 0000000..28057c8 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/light_red.gif differ diff --git a/res/module/ebnf/ebnf_pix/light_red.png b/res/module/ebnf/ebnf_pix/light_red.png new file mode 100644 index 0000000..74b8678 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/light_red.png differ diff --git a/res/module/ebnf/ebnf_pix/logo.gif b/res/module/ebnf/ebnf_pix/logo.gif new file mode 100644 index 0000000..46777a3 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/logo.gif differ diff --git a/res/module/ebnf/ebnf_pix/rubber.gif b/res/module/ebnf/ebnf_pix/rubber.gif new file mode 100644 index 0000000..a9dc81a Binary files /dev/null and b/res/module/ebnf/ebnf_pix/rubber.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_ebnf.gif b/res/module/ebnf/ebnf_pix/start_ebnf.gif new file mode 100644 index 0000000..a2bf27f Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_ebnf.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_ebnf_desc_de.gif b/res/module/ebnf/ebnf_pix/start_ebnf_desc_de.gif new file mode 100644 index 0000000..e7fec9b Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_ebnf_desc_de.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_ebnf_desc_en.gif b/res/module/ebnf/ebnf_pix/start_ebnf_desc_en.gif new file mode 100644 index 0000000..e2348ed Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_ebnf_desc_en.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_ebnf_rollover.gif b/res/module/ebnf/ebnf_pix/start_ebnf_rollover.gif new file mode 100644 index 0000000..dd58aee Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_ebnf_rollover.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_load.gif b/res/module/ebnf/ebnf_pix/start_load.gif new file mode 100644 index 0000000..bcd69af Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_load.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_load_desc_de.gif b/res/module/ebnf/ebnf_pix/start_load_desc_de.gif new file mode 100644 index 0000000..9809d7b Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_load_desc_de.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_load_desc_en.gif b/res/module/ebnf/ebnf_pix/start_load_desc_en.gif new file mode 100644 index 0000000..704bb80 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_load_desc_en.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_load_rollover.gif b/res/module/ebnf/ebnf_pix/start_load_rollover.gif new file mode 100644 index 0000000..275dd8c Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_load_rollover.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_syndia.gif b/res/module/ebnf/ebnf_pix/start_syndia.gif new file mode 100644 index 0000000..78f7f60 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_syndia.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_syndia_desc_de.gif b/res/module/ebnf/ebnf_pix/start_syndia_desc_de.gif new file mode 100644 index 0000000..1c15369 Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_syndia_desc_de.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_syndia_desc_en.gif b/res/module/ebnf/ebnf_pix/start_syndia_desc_en.gif new file mode 100644 index 0000000..278cedb Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_syndia_desc_en.gif differ diff --git a/res/module/ebnf/ebnf_pix/start_syndia_rollover.gif b/res/module/ebnf/ebnf_pix/start_syndia_rollover.gif new file mode 100644 index 0000000..90b201f Binary files /dev/null and b/res/module/ebnf/ebnf_pix/start_syndia_rollover.gif differ diff --git a/res/module/ebnf/font/CVS/Entries b/res/module/ebnf/font/CVS/Entries new file mode 100644 index 0000000..ab080a6 --- /dev/null +++ b/res/module/ebnf/font/CVS/Entries @@ -0,0 +1 @@ +/EbnfSans.ttf/1.1/Sat Aug 12 19:57:15 2006/-kb/ diff --git a/res/module/ebnf/font/CVS/Repository b/res/module/ebnf/font/CVS/Repository new file mode 100644 index 0000000..181cb7e --- /dev/null +++ b/res/module/ebnf/font/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/font diff --git a/res/module/ebnf/font/CVS/Root b/res/module/ebnf/font/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/font/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/font/EbnfSans.ttf b/res/module/ebnf/font/EbnfSans.ttf new file mode 100644 index 0000000..7989b0f Binary files /dev/null and b/res/module/ebnf/font/EbnfSans.ttf differ diff --git a/res/module/ebnf/help/CVS/Entries b/res/module/ebnf/help/CVS/Entries new file mode 100644 index 0000000..04a287e --- /dev/null +++ b/res/module/ebnf/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Sat Aug 12 19:57:15 2006/-kb/ diff --git a/res/module/ebnf/help/CVS/Repository b/res/module/ebnf/help/CVS/Repository new file mode 100644 index 0000000..0739448 --- /dev/null +++ b/res/module/ebnf/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help diff --git a/res/module/ebnf/help/CVS/Root b/res/module/ebnf/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/CVS/Entries b/res/module/ebnf/help/html/CVS/Entries new file mode 100644 index 0000000..fa2c96a --- /dev/null +++ b/res/module/ebnf/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Sat Aug 12 19:57:14 2006// +D/data//// +/index.htm/1.1/Sat Aug 12 19:57:14 2006// +/top_frame.htm/1.1/Sat Aug 12 19:57:14 2006// diff --git a/res/module/ebnf/help/html/CVS/Repository b/res/module/ebnf/help/html/CVS/Repository new file mode 100644 index 0000000..4dc892b --- /dev/null +++ b/res/module/ebnf/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html diff --git a/res/module/ebnf/help/html/CVS/Root b/res/module/ebnf/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/contents.htm b/res/module/ebnf/help/html/contents.htm new file mode 100644 index 0000000..e69a59b --- /dev/null +++ b/res/module/ebnf/help/html/contents.htm @@ -0,0 +1,109 @@ + + + Inhaltsverzeichnis + + + +
      + Das Modul AVL + +
    + + \ No newline at end of file diff --git a/res/module/ebnf/help/html/data/CVS/Entries b/res/module/ebnf/help/html/data/CVS/Entries new file mode 100644 index 0000000..59064cd --- /dev/null +++ b/res/module/ebnf/help/html/data/CVS/Entries @@ -0,0 +1,7 @@ +D/ebnf-definition//// +/intro.htm/1.1/Sat Aug 12 19:57:15 2006// +/overview.htm/1.1/Sat Aug 12 19:57:15 2006// +D/rs//// +D/start//// +D/syndia//// +D/trans//// diff --git a/res/module/ebnf/help/html/data/CVS/Repository b/res/module/ebnf/help/html/data/CVS/Repository new file mode 100644 index 0000000..92c2ea3 --- /dev/null +++ b/res/module/ebnf/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data diff --git a/res/module/ebnf/help/html/data/CVS/Root b/res/module/ebnf/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/ebnf-definition/CVS/Entries b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Entries new file mode 100644 index 0000000..bd2b1ec --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Entries @@ -0,0 +1,3 @@ +D/ebnfdisplay//// +D/ebnfinput//// +/saveebnf.htm/1.1/Sat Aug 12 19:57:14 2006// diff --git a/res/module/ebnf/help/html/data/ebnf-definition/CVS/Repository b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Repository new file mode 100644 index 0000000..018ff75 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/ebnf-definition diff --git a/res/module/ebnf/help/html/data/ebnf-definition/CVS/Root b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Entries b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Entries new file mode 100644 index 0000000..047e22f --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Entries @@ -0,0 +1,4 @@ +/binarydef.htm/1.1/Sat Aug 12 19:57:13 2006// +/ebnfdisplay.htm/1.1/Sat Aug 12 19:57:13 2006// +/keepbinarydef.htm/1.1/Sat Aug 12 19:57:13 2006// +/switchtotrans.htm/1.1/Sat Aug 12 19:57:13 2006// diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Repository b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Repository new file mode 100644 index 0000000..674bc3e --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Root b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/binarydef.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/binarydef.htm new file mode 100644 index 0000000..4e51f84 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/binarydef.htm @@ -0,0 +1,19 @@ + + + Setzen der Startvariable + + + + + +

    Definition binär klammern

    +

    Um in den trans()-Algorithmus wechseln zu können muss die Definition binär geklammert sein. Nach strenger Auslegung der Definition existieren nur binäre Alternativen in der EBNF: +


    +nicht binär geklammert: (a|b|c)
    +korrekt geklammert: (a|(b|c))

    +


    + Der Lesbarkeit halber ermöglicht das Programm eine Eingabe von nicht binär geklammerten Alternativen. Ob die Definition noch nicht korrekt geklammerte Terme enthält wird durch eine entsprechende Meldung angezigt.
    + Um eine Definition binär zu klammern muss der “Definition binär klammern”-Button genutzt werden. Dadurch werden die noch fehlenden Klammern hinzugefügt und rot hervorgehoben. Damit ist der Wechsel zum trans()-Algorithmus ermöglicht.

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/ebnfdisplay.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/ebnfdisplay.htm new file mode 100644 index 0000000..4a61ed0 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/ebnfdisplay.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    EBNF-Anzeige

    +
    • Die EBNF-Anzeige kann nur erreicht werden, wenn die Definition korrekt und vollständig ist. Eine Überprüfung dessen findet durch die vorausgegangene Nutzung des “Eingabe beenden”-Buttons bzw. Beim Laden einer Datei statt. +
    • Hintergrund der EBNF-Anzeige ist die übersichtliche Anzeige einer EBNF-Definition, ohne die Eingabemaske. Außerdem besteht hier die Möglichkeit zum trans()-Algorithmus zu wechseln um dieEBNF-Definition in ein Syntaxdiagramm umzuwandeln. +
    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/keepbinarydef.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/keepbinarydef.htm new file mode 100644 index 0000000..6d9ffe4 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/keepbinarydef.htm @@ -0,0 +1,14 @@ + + + Setzen der Startvariable + + + + + +

    Beibehalten der binären Klammerung

    + +

    Falls in der EBNF-Anzeige nachträglich eine binäre Klammerung vorgenommen wurde, so wird beim Wechsel zur EBNF-Eingabe (mittels “Definition überarbeiten”-Button) und beim Speichern aus der EBNF-Anzeige heraus nachgefragt, ob diese in der Definition beibehalten werden soll.

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/switchtotrans.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/switchtotrans.htm new file mode 100644 index 0000000..6dfd8ed --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfdisplay/switchtotrans.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    zum trans()-Algorithmus wechseln

    + +

    +Wenn die Definition binär geklammert ist, kann man in den trans()-Algorithmus durch Anklicken des “zum trans()-Algorithmus wechseln”-Buttons wechseln

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Entries b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Entries new file mode 100644 index 0000000..30df0cf --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Entries @@ -0,0 +1,7 @@ +/canvas.htm/1.1/Sat Aug 12 19:57:14 2006// +/checkdef.htm/1.1/Sat Aug 12 19:57:14 2006// +/editdef.htm/1.1/Sat Aug 12 19:57:14 2006// +/finishinput.htm/1.1/Sat Aug 12 19:57:14 2006// +/input.htm/1.1/Sat Aug 12 19:57:14 2006// +/intro.htm/1.1/Sat Aug 12 19:57:14 2006// +/setstartvar.htm/1.1/Sat Aug 12 19:57:14 2006// diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Repository b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Repository new file mode 100644 index 0000000..373c511 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Root b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/canvas.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/canvas.htm new file mode 100644 index 0000000..e884e69 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/canvas.htm @@ -0,0 +1,14 @@ + + + Setzen der Startvariable + + + + + +

    Die Arbeitsfläche

    +

    Die Arbeitsfläche der EBNF-Eingabe teilt sich in eine obere und eine untere Hälfte. Die obere Hälfte dient der Eingabe der Definition, die untere der Ansicht. +Ein nachträgliches Bearbeiten der Definition wird durch die Interaktivität der Definition im unteren Bereich ermöglicht.

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/checkdef.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/checkdef.htm new file mode 100644 index 0000000..474e61b --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/checkdef.htm @@ -0,0 +1,23 @@ + + + Setzen der Startvariable + + + + + +

    Überprüfen einer Definition

    +

    +Um eine Definition zu überprüfen kann der Button “Definition überprüfen” genutzt werden. Die Definition wird dann auf folgende Fehler und mögliche Probleme überprüft: +

    • Das Vorhandensein einer Startvariable (--> Fehlermeldung) +
    • Das Vorhandensein einer Regel für jede Variable (--> Fehlermeldung) +
    • Die Nutzung aller Variablen der Variablenmenge (--> Warnung) + +
    • Die Nutzung aller Terminalsymbole der Terminalsymbolmenge (--> Warnung) +
    • Die Erreichbarkeit aller Regeln von der Startvariablen aus (--> Warnung) +
    +Wird mind. ein Fehler gefunden, so werden Warnungen ignoriert und nicht angezeigt um die Übersicht zu wahren. +

    + + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/editdef.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/editdef.htm new file mode 100644 index 0000000..4a80f5b --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/editdef.htm @@ -0,0 +1,39 @@ + + + Setzen der Startvariable + + + + + +

    Bearbeiten der Definition

    +

    Möchte man an einer bereits eingegebenen Definition Änderungen vornehmen, zum Beispiel eine Regel löschen oder ein Terminalsymbol umbenennen, so kann dies über das Kontextmenü in der Ansicht geschehen.

    +

    Löschen

    +

    Löschen von Variablen und Terminalsymbolen

    +
    • Ein Symbol kann nur dann gelöscht werden, wenn es in keiner Regel mehr vorkommt. +
    • Wenn dies dies der Fall ist, kann man im Kontextmenü des Symbols in der Variablen- oder Terminalsymbolmenge die Funktion löschen auswählen. +
    +


    bzw.

    +

    +

    Löschen von Regeln

    +
    • Regeln können über das Kontextmenü in der Regel-Ansicht gelöscht werden.
    • +


    +

    Bearbeiten

    +

    Bearbeiten von Variablen und Terminalsymbolen.

    +
    • Symbole können über ihr Kontextmenü umbenannt werden. Dabei gelten für die Namensänderung die gleichen Regeln wie für die Eingabe. + +
    • Wählt man im Kontextmenü eines Symbols “Bearbeiten” aus, so erscheint in der entsprechenden Eingabemaske das Symbol, der Hinzufügen-Button ändert sich in einen “Ändern”-Button und es erscheint zusätzlich ein “Abbrechen”-Button. Im Textfeld kann man den Symbolnamen ändern und anschließend durch die Auswahl von “Ändern” übernehmen. Möchte man die Änderung abbrechen, so kann man dies über den entsprechenden Button vornehmen. +


    +

    bzw.

    +


    +
      +
    • Grundsätzlich kann man immer nur eine Variable und ein Terminalsymbol gleichzeitig bearbeiten; im Moment bearbeitete Symbole werden in der Ansicht gelb hervorgehoben.
    • +

    +

    Bearbeiten von Regeln

    +
    • Regeln können über ihr Kontextmenü bearbeitet werden. +
    • Wählt man im Kontextmenü einer Regel “Bearbeiten” aus, so erscheint in der Regel-Eingabemaske die Regel, der Hinzufügen-Button ändert sich in einen “Ändern”-Button und es erscheint zusätzlich ein “Abbrechen”-Button. Im Textfeld kann man den Term bearbeiten und anschließend durch die Auswahl von “Ändern” übernehmen. Das Ändern der Variablen der Regel ist nicht möglich. Möchte man die Änderung abbrechen, so kann man dies über den entsprechenden Button vornehmen. +
    • Grundsätzlich kann man immer nur eine Regel bearbeiten; die im Moment bearbeitete Regel wird in der Ansicht gelb hervorgehoben. +

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/finishinput.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/finishinput.htm new file mode 100644 index 0000000..a47c0a4 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/finishinput.htm @@ -0,0 +1,13 @@ + + + Setzen der Startvariable + + + + + +

    Beenden der Eingabe

    + +

    Durch das Aktivieren des “Eingabe beenden”-Buttons wird die Definition überprüft. Wird dabei mind. ein Fehler gefunden, so kann der Wechsel zur EBNF-Anzeige nicht stattfinden. Wenn kein Fehler auftritt (Warnungen können vorkommen, werden aber nicht angezeigt) geschieht ein Wechsel zur EBNF-Anzeige, in welcher die Eingabemaske nicht mehr zu sehen ist.

    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/input.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/input.htm new file mode 100644 index 0000000..9e04856 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/input.htm @@ -0,0 +1,38 @@ + + + Einleitung + + + + + +

    Eingabe der Definition

    +

    Die Definition wird im oberen Bilschirmbereich eingegeben. Es stehen Steuerelemente für die Eingabe von Variablen, Terminalsymbolen sowie Regeln zur Verfügung. +

    +

    Eingabe von Variablen und Terminalsymbolen

    +

     

    +

    Zugelassene Symbole

    Grundsätzlich sind alle Symbole zugelassen, die die folgenden Bedingungen erfüllen: +
    • Ein Symbol darf nicht der Anfang eines anderen Terminalsymbols oder einer anderen Variable sein +
    • Ein Symbol darf nicht mit Leerzeichen beginnen oder enden +
    • Ein Symbol darf nicht leer sein +
    • Ein Symbol darf keine Metasymbole enthalten +

    Hinzufügen von Terminalsymbolen und Variablen zur EBNF-Definition

    +

    Das hinzuzufügende Symbol muss in das entsprechende Textfeld geschrieben werden und kann dann mit der Eingabetaste oder Klick auf Hinzufügen zur Definition hinzugefügt werden. Falls das Symbol nicht hinzugefügt werden kann, wird eine entsprechende Fehlermeldung angezeigt. +

    +


    +

    bzw.

    +


    +

    Eingabe von Regeln

    +

    Mit einer EBNF-Regel wird einer Variablen ein EBNF-Term zugeordnet. Die Variable kann aus der Drop-Down-Liste ausgewählt werden. Da es zu jeder Variablen nur eine Regel geben darf, werden nur diejenigen Variablen angezeigt, zu denen es noch keine Regel gibt.
    +Für einen korrekten EBNF-Term gelten folgende Regeln:

    +
    • Ein EBNF-Term besteht aus Variablen, Terminalsymbolen und Metasymbolen +
    • Die Metasymbole müssen korrekt geklammert sein +
    • Der EBNF-Term darf nicht leer sein +
    +

    Eine neue Regel kann mit der Eingabetaste oder Klick auf Hinzufügen zur Definition hinzugefügt werden. Falls die Regel nicht hinzugefügt werden kann, wird eine entsprechende Fehlermeldung angezeigt.

    +


    +


    + Kommt in der Regel ein unbekanntes Symbol vor, so wird ein Dialogfenster angezeigt, welches die Möglichkeit bietet, das neue Symbol der Menge der Variablen oder Terminalsymbole hinzuzufügen. Man kann auch Teile des nicht erkannten Textes als Symbol hinzufügen, indem man den Text im Dialog bearbeitet. In diesem Fall ist es möglich, dass weitere unbekannte Symbole gefunden werden. Wählt man in diesem Dialog “Abbrechen”, so schlägt das Hinzufügen der Regel fehl.

    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/intro.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/intro.htm new file mode 100644 index 0000000..0b8eca4 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/intro.htm @@ -0,0 +1,43 @@ + + + Einleitung + + + + + +

    Eingabe einer Definition

    + +

    Die Definition wird im oberen Bilschirmbereich eingegeben. + Es stehen Steuerelemente für die Eingabe von Variablen, Terminalsymbolen sowie Regeln zur Verfügung. + +

    Eingabe von Variablen und Terminalsymbolen

    +

    Das Modul AVL-Bäume realisiert die Darstellung + von binären Such- und AVL-Bäumen. Für eine detaillierte Beschreibung dieser + Baumtypen lesen Sie bitte nach im Vorlesungsskript von Prof. Vogler + "Algorithmen, Datenstrukturen und Programmierung". Eine mehr oder weniger kurze + Einführung in diese Thematik ist auch zu finden im Anhang des + j-Algo Handbuches.
    +

    + +

    Funktionsübersicht

    +

    Das Modul AVL-Bäume realisiert folgende + Funktionen: +

    +
      +
    • + Visualisieren von binären Suchbäumen mit und ohne AVL-Eigenschaft +
    • + Einfügen, Suchen und Löschen von Baumknoten +
    • + + Testen eines Baumes auf AVL-Eigenschaft +
    • + Generieren von zufälligen Suchbäumen +
    • + Speichern und Laden von Bäumen +
    • + Informationen zum Baum und zu den laufenden Algorithmen
    + + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/setstartvar.htm b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/setstartvar.htm new file mode 100644 index 0000000..3a80498 --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/ebnfinput/setstartvar.htm @@ -0,0 +1,16 @@ + + + Setzen der Startvariable + + + + + +

    Setzen der Startvariable

    + +

    Eine Definition besitzt genau dann eine Startvariable, wenn sie mindestens eine Variable enthält. Beim Hinzufügen der ersten Variablen wird diese automatisch zur Startvariable.


    +

    Die Startvariable kann geändert werden, indem man eine Variable aus der entsprechenden Drop-Down-Liste auswählt. Außerdem kann man eine Variable über ihr Kontextmenü in der Anzeige der Variablenmenge als Startvariable setzen.

    +


    +


    + + diff --git a/res/module/ebnf/help/html/data/ebnf-definition/saveebnf.htm b/res/module/ebnf/help/html/data/ebnf-definition/saveebnf.htm new file mode 100644 index 0000000..ca7869e --- /dev/null +++ b/res/module/ebnf/help/html/data/ebnf-definition/saveebnf.htm @@ -0,0 +1,21 @@ + + + Setzen der Startvariable + + + + + +

    Speichern von EBNF-Definitionen

    +

    +Man kann grundsätzlich Definitionen zu jedem Zeitpunkt in der EBNF-Eingabe speichern. +

    +Dies geschieht entweder über das Menü “Datei” oder die ensprechenden Symole in der Werkzeugleiste .

    +


    +

    Außerdem wird gefragt, ob die Definition gespeichert werden soll, sobald man das Modul verlassen möchte und nicht gesicherte Veränderungen vorgenommen hat.

    +


    +


    + Falls in der EBNF-Anzeige nachträglich eine binäre Klammerung vorgenommen wurde, so wird beim Speichern aus der EBNF-Anzeige heraus nachgefragt, ob diese in der Definition beibehalten werden soll.

    +


    + + diff --git a/res/module/ebnf/help/html/data/intro.htm b/res/module/ebnf/help/html/data/intro.htm new file mode 100644 index 0000000..6f3bf95 --- /dev/null +++ b/res/module/ebnf/help/html/data/intro.htm @@ -0,0 +1,12 @@ + + + Einleitung + + + +

    Einleitung

    +

    Das j-Algo Modul Ebnf und Syntaxdiagramme erweitert j-Algo um die Möglichkeit, EBNF Definitionen und Syntaxdiagramme zu erzeugen und bearbeiten.

    +Darüberhinaus stellt das Modul die Möglichkeit bereit, EBNF-Definitionen in Syntaxdiagramme zu überführen; dies geschieht mit dem trans()-Algorithmus, der im Modul schrittweise nachvollzogen werden kann.

    +Außerdem wird eine graphische Darstellung des Rücksprungalgorithmus zur Verfügung gestellt, mit deren Hilfe der Benutzer Worte der von einem Syntaxdiagramm definierten Sprache erzeugen kann.

    + + \ No newline at end of file diff --git a/res/module/ebnf/help/html/data/overview.htm b/res/module/ebnf/help/html/data/overview.htm new file mode 100644 index 0000000..3684d4c --- /dev/null +++ b/res/module/ebnf/help/html/data/overview.htm @@ -0,0 +1,12 @@ + + + Setzen der Startvariable + + + + + +

    Funktionsübersicht

    +

    Das Modul "EBNF / Syntaxdiagramme" erlaubt es dem Nutzer eigene EBNF-Definition einzugeben, zu überprüfen, diese mittels des trans()-Algorithmus' in ein Syntaxdiaramm umzuwandeln und von da an als Syntaxdiagramm zu behandeln. Es ist selbstverständlich auch möglich eigene Syntaxdiagramme zu erstellen und diese (sowie die aus dem trans()-Algorithmus kommenden) im Rücksprung-Algorithmus zu durchlaufen.

    + + diff --git a/res/module/ebnf/help/html/data/rs/CVS/Entries b/res/module/ebnf/help/html/data/rs/CVS/Entries new file mode 100644 index 0000000..10c3b31 --- /dev/null +++ b/res/module/ebnf/help/html/data/rs/CVS/Entries @@ -0,0 +1,2 @@ +/canvas.htm/1.1/Sat Aug 12 19:57:15 2006// +/control.htm/1.1/Sat Aug 12 19:57:15 2006// diff --git a/res/module/ebnf/help/html/data/rs/CVS/Repository b/res/module/ebnf/help/html/data/rs/CVS/Repository new file mode 100644 index 0000000..6cac626 --- /dev/null +++ b/res/module/ebnf/help/html/data/rs/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/rs diff --git a/res/module/ebnf/help/html/data/rs/CVS/Root b/res/module/ebnf/help/html/data/rs/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/rs/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/rs/canvas.htm b/res/module/ebnf/help/html/data/rs/canvas.htm new file mode 100644 index 0000000..916539e --- /dev/null +++ b/res/module/ebnf/help/html/data/rs/canvas.htm @@ -0,0 +1,21 @@ + + + Setzen der Startvariable + + + + + +

    Die Arbeitsfläche

    +

    Die Arbeitsfläche des Rücksprungalgorithmus ist in vier Bereiche aufgeteilt.

    +

    Syntaxdiagramm-Ansicht

    +

    Die Syntaxdiagramme wird hier grafisch dargestellt. Darüber hinaus erfolgt die Steuerung während des Algorithmus’ durch Anklicken der Diagramme in dieser Ansicht.

    +

    Keller

    +

    Hier werden alle Rücksprungadressen dargestellt, die während des Algorithmus’ auf den Keller gelegt werden.

    +

    Kontrollbereich

    +

    Hier wird das Wort ausgegeben, das während des Algorithmus’ erzeugt wurde. Darüber hinaus kann hier ein Wort eingegeben werden, das erzeugt werden soll, der Algorithmus wird von hier gestartet. Zusätzlich bietet der Kontrollbereich die Möglichkeit, die Darstellung der Syntaxdiagramme in der Syntaxdiagramm-Ansicht anzupassen.

    +

    Erklärungsbereich

    +

    Hier werden während des Ablaufes des Algorithmus’ Erklärungen zu den einzelnen Algorithmusschritten ausgegeben.

    +




    + + diff --git a/res/module/ebnf/help/html/data/rs/control.htm b/res/module/ebnf/help/html/data/rs/control.htm new file mode 100644 index 0000000..8384f27 --- /dev/null +++ b/res/module/ebnf/help/html/data/rs/control.htm @@ -0,0 +1,63 @@ + + + Setzen der Startvariable + + + + + +

    Seuerung des Algorithmus

    +

    Aufgabe des Bereichs ‚Rücksprungalgorithmus’ ist es, den Algorithmus der Worterzeugung zu visualisieren. Er repräsentiert den Ablauf eines Weges durch ein Syntaxdiagramm-System und erzeugt während des Ablaufes ein Wort, das sich aus den passierten Terminalsymbolen zusammensetzt. Das Modul ist dabei nicht in der Lage, Entscheidungen über die Wegewahl bezüglich der Erzeugung eines Wortes selbst zu treffen. Vielmehr soll er dem Nutzer helfen, eigene Durchläufe und Sprünge zwischen den einzelnen Diagrammen zu überprüfen.

    +Im Folgenden wird die Steuerung des Algorithmus’ erläutert:

    +

    Eingabe eines Wortes

    +

    Bevor der Algorithmus gestartet wird, besteht die Möglichkeit, im Kontrollbereich ein Wort einzugeben, welches während des Algorithmus erzeugt werden soll. Dieses kann einfach in das Textfeld eingegeben werden, welches mit ‚Zu erzeugendes Wort’ bezeichnet ist. Die Eingabe eines Wortes, welches erzeugt werden soll, ist optional. Es ist genauso möglich, kein Wort einzugeben und die Generierung von Wörtern so zu testen, oder den Button 'Wort erzeugen' im Kontrollbereich zu klicken, der automatisch ein Wort - welches auch mit dem Algorithmus erzeugt werden kann - generiert (Dabei kann es sich aber auch um das leere Wort handeln, falls das Syntax-Diagramm-System dieses ermöglicht).

    +

    Start des Algorithmus

    +

    Nach der (optionalen) Eingabe eines Wortes kann der Algorithmus gestartet werden. Dies ist über einen Klick auf den Button ‚Algorithmus starten’ im Kontrollbereich, oder über das Menü Rücksprung-Algorithmus-> Algorithmus starten möglich.

    +Anmerkung: Besteht das zuvor eingegebene Wort nicht ausschließlich aus in den Syntax-Diagrammen vorhandenen Terminalsymbolen, so ist die Erzeugung eines solchen Wortes prinzipiell nicht möglich. Der Algorithmus wird ein solches Wort zurückweisen und den Algorithmus nicht starten.
    +
    + Ist der Algorithmus gestartet, so wird die aktuelle Position in einem der gegebenen Programme durch einen roten Punkt gekennzeichnet.

    +




    +

    Zu Beginn des Algorithmus wird dieser Punkt am Anfang des Startdiagrammes stehen.

    +

    Wählen eines Weges durch ein Syntax-Diagramm

    +

    Um einen Weg durch ein Syntax-Diagramm zu wählen, können einzelne Elemente des Diagrammes in der Syntax-Diagramm-Anzeige direkt angeklickt werden. Folgende Elemente können angeklickt werden: Erreichbare Terminalsymbole, erreichbare Variablen. Erreichbare, leere Verzweigungen, erreichbare Ausgänge von Syntax-Diagrammen.

    +

    Passieren eines Terminalsymboles

    +

    Um ein Terminalsymbol zu passieren, kann dieses einfach angeklickt werden. Dies ist nur möglich, wenn das entsprechende Terminalsymbol von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist ein Terminalsymbol zu erreichen, so wird es blau hervorgehoben, sobald man mit der Maus über das Symbol fährt.

    +




    +

    Passierte Terminalsymbole werden an das Ende des erzeugten Wortes im Kontrollbereich angehängt.

    +

    Passieren einer Variable

    +

    Um eine Variable zu passieren, kann diese einfach angeklickt werden. Dies ist nur möglich, wenn die entsprechende Variable von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist eine Variable zu erreichen, so wird sie blau hervorgehoben, sobald man mit der Maus über die Variable fährt.

    +




    +

    Wird eine Variable passiert, so wird ihre Rücksprungadresse auf den Keller gelegt. Dem Passieren einer Variable folgt stets ein Sprung in ein Syntax-Diagramm.

    +

    Sprung in ein Syntax-Diagramm

    +

    Dem Sprung in ein Syntax-Diagramm geht stets das Passieren einer Variable voraus. Um in ein Syntax-Diagramm zu springen, muss einfach mit der Maus über das entsprechende Syntax-Diagramm in der Syntaxdiagramm-Ansicht gefahren werden, dieses wird dann mit einem blauen Rahmen umrandet.

    +




    +

    Durch den Klick auf das Diagramm wird der Sprung ins Diagramm durchgeführt. Ein Sprung ist nur möglich, wenn der Name des Diagrammes, mit dem Inhalt der zuvor passierten Variable übereinstimmt. Andernfalls wird der Algorithmus den Sprung zurückweisen.

    +

    Passieren einer leeren Verzweigung

    +

    Um eine leere Verzweigung zu passieren, kann diese einfach angeklickt werden. Dies ist nur möglich, wenn die entsprechende Verzweigung von der aktuellen Position im Syntax-Diagramm zu erreichen ist. Ist eine leere Verzweigung zu erreichen, so wird sie blau hervorgehoben, sobald man mit der Maus über die Variable fährt.

    +




    +

    Beim Klick auf eine leere Verzweigung wird das erzeugte Wort nicht verändert. Es ändert sich lediglich die Position im Syntax-Diagramm.

    +

    Verlassen eines Syntax-Diagrammes

    +

    Ist nach dem passieren eines Terminalsymboles, einer Variable, oder leeren Verzweigung, sowie dem Rücksprung in ein Syntax-Diagramm nur noch der Ausgang des Diagrammes zu erreichen, so wird der Algorithmus das Diagramm automatisch verlassen. Doch nicht immer ist der Weg zum Ausgang die einzige Möglichkeit. In solchen Situationen muss man selbst entscheiden, ob das Diagramm verlassen werden soll.

    Um das Diagramm zu verlassen, muss einfach in der Syntaxdiagramm-Anzeige auf den Ausgang des Diagrammes geklickt werden. Das Verlassen des Diagrammes wird nur durchgeführt, wenn der Ausgang des Diagrammes von der aktuellen Position im Diagramm erreicht werden kann. Der Ausgang des Diagrammes wird dann beim Fahren mit der Maus über den Ausgang blau hervorgehoben.

    +




    +

    + Dem Verlassen des Diagrammes folgt entweder der Rücksprung in ein Diagramm, oder das Ende des Algorithmus.

    +

    Rücksprung in ein Syntax-Diagramm

    +

    Wurde ein Syntax-Diagramm verlassen, so kann ein Rücksprung in ein Diagramm folgen. Der Rücksprung folgt immer dann, wenn noch Rücksprungadressen auf dem Keller liegen.

    +




    +

    Um einen Rücksprung durchzuführen muss einfach in der Syntaxdiagramm-Anzeige die Rücksprungmarke einer Variable in einem Diagramm angeklickt werden. Diese werden, falls ein Rücksprung möglich ist, beim Fahren mit der Maus über die Marke blau hervorgehoben.

    +




    +

    Ein Rücksprung wird nur durchgeführt, wenn die Nummer der angeklickten Rücksprungmarke mit der obersten Adresse auf dem Keller übereinstimmt. Die oberste Adresse wird dann vom Keller gelöscht, der Weg kann hinter der Variable fortgesetzt werden, zu der zurückgesprungen wurde. Stimmen Rücksprungmarke und oberste Adresse auf dem Keller nicht überein, so wird der Rücksprung vom Algorithmus zurückgewiesen.

    +

    Ende des Rücksprungalgorithmus

    +

    Wird ein Syntax-Diagramm verlassen und es befindet sich keine Rücksprung-Adresse mehr auf dem Keller, so endet der Algorithmus. Er endet jedoch nur dann erfolgreich, wenn das Ende des Startdiagrammes erreicht wurde, und das vor Beginn des Algorithmus eingegebene Wort erzeugt wurde. Andernfalls wird der Algorithmus mit einer Fehlermeldung enden.

    +

    Fehler während des Algorithmusdurchlaufes

    +

    Nicht immer werdeb Fehler während des Laufens durch ein Syntax-Diagramm sofort erkannt und vom Algorithmus zurückgewiesen. So kann es z.B. passieren, dass das eingegebene Wort komplett erzeugt, der Ausgang des Startdiagrammes aber noch nicht erreicht wurde. Genauso kann ein anderes Wort als die Eingabe erzeugt worden sein. In einem solchen Fall wird der Algorithmus die Weiterarbeit verweigern. Es bestehen die Möglichkeiten, einzelne, falsche Schritte rückgängig zu machen, oder den Algorithmus komplett zurück zu setzen.

    +

    Schritte rückgängig machen

    +

    Um einen Schritt im Algorithmus rückgängig zu machen, gibt es zwei Möglichkeiten. Zum einen den Klick auf das entsprechende Symbol in der Toolbar am oberen Fensterrand, oder die Auswahl über das Menü Rücksprung-Algorithms -> Schritt rückgängig.

    +

    Schritte wiederherstellen

    +

    Um einen Schritt im Algorithmus wiederherzustellen, gibt es zwei Möglichkeiten. Zum einen den Klick auf das entsprechende Symbol in der Toolbar am oberen Fensterrand, oder die Auswahl über das Menü Rücksprung-Algorithms -> Schritt wiederherstellen.

    +

    Den Rücksprungalgorithmus zurücksetzen

    +

    Der Klick auf den Button ‚Algorithmus zurücksetzen’ im Kontrollbereich ermöglicht das Zurücksetzen des Algorithmus in die Ausgangsposition. Einzelne Schritte können von hier aus wieder hergestellt werden. Es kann aber auch ein neues Wort eingegeben und der Algorithmus neu gestartet werden.

    +

    Verlassen der Rücksprungalgorithmus-Bereiches.

    +

    Der Rücksprungalgorithmus-Bereich kann über den Button ‚Zur Syntaxdiagrammanzeige wechseln’ im Kontrollbereich verlassen werden. Das Programm kehrt dann in die Syntaxdiagramm-Anzeige zurück. Die gleiche Funktionalität bietet die Auswahl im Menü Rücksprung-Algorithmus -> Algorithmus verlassen.

    + + diff --git a/res/module/ebnf/help/html/data/start/CVS/Entries b/res/module/ebnf/help/html/data/start/CVS/Entries new file mode 100644 index 0000000..e62faeb --- /dev/null +++ b/res/module/ebnf/help/html/data/start/CVS/Entries @@ -0,0 +1,4 @@ +/ebnf.htm/1.1/Sat Aug 12 19:57:15 2006// +/load.htm/1.1/Sat Aug 12 19:57:15 2006// +/show.htm/1.1/Sat Aug 12 19:57:15 2006// +/syndia.htm/1.1/Sat Aug 12 19:57:15 2006// diff --git a/res/module/ebnf/help/html/data/start/CVS/Repository b/res/module/ebnf/help/html/data/start/CVS/Repository new file mode 100644 index 0000000..802d842 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/start diff --git a/res/module/ebnf/help/html/data/start/CVS/Root b/res/module/ebnf/help/html/data/start/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/start/ebnf.htm b/res/module/ebnf/help/html/data/start/ebnf.htm new file mode 100644 index 0000000..9000526 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/ebnf.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    EBNF-Definition manuell erstellen

    +


    +
    +Mit diesem Button ist es möglich manuell eine neue EBNF-Definition zu erstellen. Sie gelangen hiermit zum EBNF-Editor.

    + + + diff --git a/res/module/ebnf/help/html/data/start/load.htm b/res/module/ebnf/help/html/data/start/load.htm new file mode 100644 index 0000000..9939149 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/load.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    EBNF / Syntaxdiagramm laden

    +



    +Mit diesem Button ist es möglich eine EBNF-Definition bzw. ein Syntax-Diagramm aus einer *.jalgo-Datei zu laden. Das entsprechende "Untermodul" wird dann automatisch gestartet. +

    + + + diff --git a/res/module/ebnf/help/html/data/start/show.htm b/res/module/ebnf/help/html/data/start/show.htm new file mode 100644 index 0000000..c6cc871 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/show.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    Willkommensbildschirm anzeigen

    +


    +
    +Mit diesem Button ist es möglich aus jedem Modulteil zum Startbildschirm zurück zu kehren. Es wird, sofern nötig, gefragt ob Änderungen gespeichert werden sollen.

    + + + diff --git a/res/module/ebnf/help/html/data/start/syndia.htm b/res/module/ebnf/help/html/data/start/syndia.htm new file mode 100644 index 0000000..8a14f97 --- /dev/null +++ b/res/module/ebnf/help/html/data/start/syndia.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    EBNF-Definition manuell erstellen

    +


    +
    +Mit diesem Button ist es möglich manuell ein neues Syntax-Diagramm zu erstellen. Sie gelangen hiermit zum Syntax-Diagramm-Editor.

    + + + diff --git a/res/module/ebnf/help/html/data/syndia/CVS/Entries b/res/module/ebnf/help/html/data/syndia/CVS/Entries new file mode 100644 index 0000000..bc5cc0c --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/CVS/Entries @@ -0,0 +1,5 @@ +/add.htm/1.1/Sat Aug 12 19:57:15 2006// +/canvas.htm/1.1/Sat Aug 12 19:57:15 2006// +/display.htm/1.1/Sat Aug 12 19:57:15 2006// +/edit.htm/1.1/Sat Aug 12 19:57:15 2006// +/load.htm/1.1/Sat Aug 12 19:57:15 2006// diff --git a/res/module/ebnf/help/html/data/syndia/CVS/Repository b/res/module/ebnf/help/html/data/syndia/CVS/Repository new file mode 100644 index 0000000..2ab71d5 --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/syndia diff --git a/res/module/ebnf/help/html/data/syndia/CVS/Root b/res/module/ebnf/help/html/data/syndia/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/syndia/add.htm b/res/module/ebnf/help/html/data/syndia/add.htm new file mode 100644 index 0000000..d822253 --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/add.htm @@ -0,0 +1,53 @@ + + + Setzen der Startvariable + + + + + +

    Hinzufügen von Elementen

    + +

    Um einem Syntaxdiagrammsystem Elemente hinzufügen zu können, muss man sich in einem entsprechenden Modus befinden. Einzig das Hinzufügen neuer Syntaxdiagramme geschieht ohne Moduswechsel.

    +
    +

    Syntaxdiagramme

    +

    Um ein neues Syntaxdiagramm einzufügen genügt ein einfacher Klick auf das Symbol im Kontrollbereich. In der Syntaxdiagramm-Anzeige erscheint ein Popupfenster, in dem sich u.a. ein Texteingabefeld befindet. In diesem bereits fokusiertem Eingabefeld können Sie nun den gewünschten Namen ihres neuen Syntaxdiagramms angeben. Ihre Eingabe beenden Sie entweder mit OK-Button rechts des Eingabefeldes oder über ENTER.
    +
    Falls der von Ihnen gewählte Name schon für ein anderes Diagramm vergeben ist, werden Sie im Rahmentext des Popupfensters darauf hingewiesen. Sie müssen einen anderen Namen wählen.

    + Unterhalb des Eingabefeldes befindet sich eine weitere Zeile:

    +

    +

    Indem Sie die Checkbox auswählen, können Sie ihr neues Diagramm als Startdiagramm einfügen. Es ist immer nur ein Startdiagramm zulässig, d.h. das alte Startdiagramm verliert dieses "Privileg" an das neue Syntaxdiagramm.
    +
    + Sie können die Eingabe jederzeit mit ESCAPE abbrechen. Die Eingabe eines leeren Diagrammnamens bewirkt ebenfalls einen Abbruch. Es wird kein Syntaxdiagramm hinzugefügt.

    +

    Über die Einfüge-Modi

    +

    Um Elemente einfügen zu können, müssen Sie in den Modus " einfügen" wechseln. Dieses Beispiel demonstriert dies für Terminalsymbole. Den Moduswechsel erreichen Sie auf zwei verschiedenen Wegen: entweder wählen Sie im Kontrollbereich den Button

    +

    +

    aus oder Sie bewegen Ihre Maus in die Syntaxdiagramm-Anzeige. Dort können Sie jederzeit mit einem Rechtsklick ein Kontextmenü öffnen, in dem Sie ebenfalls den Modus "Terminalsymbole einfügen" anwählen können.

    +

    +


    + Ist dieser Modus gewählt, wird der zugehörige Button im Kontrollbereich ausgraut. Auch ändert sich der Mauszeiger, wenn Sie über den Arbeitsbereich fahren. Somit wissen Sie immer, in welchem Modus Sie sich gerade befinden.

    +

    Über die Rhomben

    +

    Im Editiermodus bekommen die Syntaxdiagramme neue Elemente - die Rhomben. Sie sind Pseudoelemente, die das Einfügen von Elementen erleichtern bzw. erst ermöglichen. In ihrem Grundzustand sind die Rhomben grau. Befindet man sich in einem Einfügemodus, so leuchten sie grün auf, falls an dieser Stelle ein Hinzufügen möglich ist. Leuchten sie dagegen rot auf (dies geschieht beim Einsetzen des Endes von Verzweigungen und Wiederholungen [siehe dort]), kann das Element an dieser Stelle nicht eingefügt werden.

    Hat man etwas eingefügt, erscheinen vor und hinter diesem Element neue Rhomben, an denen erneut hinzugefügt werden kann. In Wiederholungen und Verzweigungen erscheinen zudem in den Elementen neue Rhomben - schließlich soll man auch hier Einfügen können.

    +

    Terminalsymbole und Variablen

    +

    Wechseln Sie als erstes in den Modus "Terminalsymbole einfügen" oder "Variablen einfügen".

    +

    oder
    +bzw.
    + oder

    +

    In der Arbeitsfläche können Sie nun mit der Maus über jeden beliebigen Rhombus fahren - er leuchtet grün auf. Mit einem Linksklick fügen Sie das Terminalsymbol / die Variable an dem aktuell grün leuchtenden Rhobus ein.
    +
    + Es erscheint ein Textfeld, in dem Sie einen Namen für das Element eingeben müssen. Als Standard erscheint ausgewählt "a" / "A".
    +
    + Zum Bestätigen einer Eingabe drücken Sie entweder auf den OK-Button oder ENTER. Falls Sie das Erstellen abbrechen möchten, drücken Sie ESACAPE oder geben einen leeren Namen ein.

    +

    Verzweigungen und Wiederholungen

    +

    Wechseln Sie als erstes in den Modus "Verzweigungen einfügen" / "Wiederholungen einfügen".

    +

    oder
    +bzw.
    + oder

    +

    In der Arbeitsfläche können Sie nun mit der Maus über jeden beliebigen Rhombus fahren - er leuchtet grün auf. Mit einem Linksklick fügen Sie den Anfang der Verzweigung / Wiederholung ein. Daraufhin erscheint grau gepunktet eine neue Verzweigung / Wiederholung. Diese zeigt, von von wo bis wo eingefügt werden kann. Anfangs ist sie auf den angeklickten Rhombus beschränkt.
    +
    + Sie können diese "unfertige" Verzweigung / Wiederholung nun sowohl nach links als auch nach rechts in die Breite ziehen. Fahren Sie dazu mit der Maus über andere Rhomben. Leuchtet ein Rhombus grün auf, so kann bis zu dieser Stelle eingefügt werden. Dies wird durch die veränderte grau gepunktete Verzweigunng / Wiederholung angezeigt. Dabei können auch schon vorhandene Elemente eingeschlossen werden.
    +
    + Leuchtet ein Rhombus dagegen rot auf, so darf an dieser Stelle nicht eingefügt werden. Dies ist der Fall, wenn das Ende nicht auf der gleichen Linie liegt wie der Startpunkt. Auch dürfen sich Linien nicht kreuzen, so dass das Einfügen eines Endes in das Innere einer anderen Verzweigung / Wiederholung ebenfalls nicht erlaubt ist.
    +
    + Haben Sie den Mauszeiger über ein grün leuchtendes Ende gefahren, so können Sie nun mit einem weiteren Linksklick Einfügen. Die grau gepunktete Verzweigung / Wiederholung verschwindet und ein vollständig neues Element erscheint.

    + + diff --git a/res/module/ebnf/help/html/data/syndia/canvas.htm b/res/module/ebnf/help/html/data/syndia/canvas.htm new file mode 100644 index 0000000..42f4ecb --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/canvas.htm @@ -0,0 +1,13 @@ + + + Setzen der Startvariable + + + + + +

    Die Arbeitsfläche

    +

    Die Arbeitsfläche des Syntaxdiagramm-Editors ist zweigeteilt: Im oberen Abschnitt befindet sich der Kontrollbereich, über den alle Aktionen, die für das Erstellen und Editieren von Syntaxdiagrammen nötig sind, anwählbar sind. Darunter befindet sich die Anzeige für Syntaxdiagramme - die Arbeitsfläche, auf der an den Diagrammen gearbeitet wird.

    +


    + + diff --git a/res/module/ebnf/help/html/data/syndia/display.htm b/res/module/ebnf/help/html/data/syndia/display.htm new file mode 100644 index 0000000..b77c5ac --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/display.htm @@ -0,0 +1,23 @@ + + + Setzen der Startvariable + + + + + +

    Die Syntaxdiagramm-Anzeige

    + +

    +

    Anzeigebereich

    +

    Hier werden die Syntaxdiagramme visualisiert.

    +

    Kontrollbereich

    +

    Im Kontrollbereich hat man die Möglichkeit, die Syntaxdiagramme grafisch zu verändern. Die Möglichkeiten beschränken sich auf das Skalieren der Diagramme, das automatische Anpassen der Größe an das Fenster, sowie das Entfernen von Treppenstrukturen. Auf der rechten Seite befinden sich zudem noch Navigationsbuttons.

    +: Hier haben Sie die Möglichkeit, das Diagramm selbst zu vergrößern und zu verkleinern
    + + + + : Hier kann man einstellen, ob sich die Größe der Diagramme automatisch dem Fensterrahmen anpassen soll oder nicht.
    + : Bei Aktivierung dieses Knopfes, während Treppenstrukturen in den Diagrammen entfernt.

    + + diff --git a/res/module/ebnf/help/html/data/syndia/edit.htm b/res/module/ebnf/help/html/data/syndia/edit.htm new file mode 100644 index 0000000..cbc409c --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/edit.htm @@ -0,0 +1,30 @@ + + + Setzen der Startvariable + + + + + +

    Bearbeiten und Löschen von Elementen

    +

    Editieren

    +

    Im Editiermodus ist es möglich, Terminalsymbol-, Variablen- und Syntaxdiagrammnamen zu ändern.

    Wechseln Sie dazu zuerst in diesen Modus.

    +

    bzw.

    +


    + Fahren Sie nun mit der Maus über Terminalsymbole oder Variablen, so leuchten diese blau auf. Mit einem Linksklick auf diese Elemente erscheint ein Textfeld mit dessen Name. Sie können den Namen nun beliebig ändern. Mit dem OK-Button oder ENTER schließen Sie die Änderung ab. Mit ESCAPE oder der Eingabe eines leeren Namens brechen Sie den Editiervorgang ab.
    +
    + Fahren Sie mit der Maus über den Namen eines Syntaxdiagramms, so erscheint dieser fett. Mit einem Linksklick können Sie nun den Namen des Diagramms ändern. Dazu erscheint der Dialog, der auch zum Einfügen neuer Elemente angezeigt wird. Einziger Unterschied ist, dass, falls Sie das Startdiagramm editieren, Sie diesem Diagramm diesen Status nicht nehmen können - die entsprechende Chackbox ist ausgegraut.

    +
    +

    Löschen

    +

    Im Löschmodus ist es möglich, sowohl alle Syntaxdiagrammelemente als auch leere Diagramme zu löschen.

    + Wechseln Sie dazu zuerst in diesen Modus.

    +

    bzw.

    +


    + Fahren Sie nun mit der Maus über Terminalsymbole oder Variablen, so leuchten diese rot auf. Mit einem Linksklick werden diese gelöscht. Nachfolgende Elemente rücken nach links.
    +
    + Verzweigungen und Wiederholungen können ebenfalls gelöscht werden. Bewegen Sie dazu den Mauszeiger auf die obere oder untere Linie eines dieser Elemente. Die Linie und alle darauf liegenden Elemente leuchten rot auf. Mit einem Linksklick bestätigen Sie den Löschvorgang.
    + War die untere Linie markiert, so werden Elemente der oberen Linie beibehalten. Löschen Sie die obere Linie einer Verzweigung, so werden die Elemente der unteren Linie - sofern vorhanden - auf die obere Linie eingefügt. Die untere Linie verschwindet. Dies geschieht auch beim Löschen des unteren Teils einer Wiederholung; nur werden hier die Elemente in umgekehrter Reihenfolge oben eingefügt (d.h. ihre "Leserichtung" bleibt erhalten).
    +
    + Befinden Sie sich mit dem Mauszeiger über einem leeren Syntaxdiagramm (d.h. nur ein Rhombus befindet sich in diesem Diagramm), so erscheint um dieses ein roter Rahmen. Bestätigen Sie mit einem Linksklick, wird das Diagramm gelöscht. Handelt es sich dabei um das Startdiagramm, so erscheint ein Hinweis, dass das Löschen des Startdiagramms nicht möglich ist.

    + + diff --git a/res/module/ebnf/help/html/data/syndia/load.htm b/res/module/ebnf/help/html/data/syndia/load.htm new file mode 100644 index 0000000..6135b76 --- /dev/null +++ b/res/module/ebnf/help/html/data/syndia/load.htm @@ -0,0 +1,15 @@ + + + Setzen der Startvariable + + + + + +

    Laden und Speichern von Syntaxdiagrammen

    +

    Speichern von Syntaxdiagrammen

    +

    Natürlich haben Sie auch die Möglichkeit, Syntaxdiagramme zu speichern.
    Dies ist möglich in der Syntaxdiagramm-Anzeige sowie im Syntaxdiagramm-Editor. Das Speichern ist nur mit der Endung *.jalgo möglich. Das Programm erkennt jedoch automatisch, dass es sich um ein Syntaxdiagramm handelt.

    Hinweis! Speichern sie die Diagramme in einem eindeutigen Ordner oder geben Sie dem Diagramm einen geeigneten Namen, da die Speicherendungen im gesamten jAlgo *.jalgo sind.

    +

    Laden von Syntaxdiagrammen

    +

    Beim Laden von Syntaxdiagrammen unterscheidet das Modul, ob sie vollständig sind oder nicht. Vollständig bedeutet, dass zu jeder Variable im Diagramm ein Diagramm mit diesem Namen existiert. Ist es vollständig, befinden Sie sich nach dem Laden in der Syntaxdiagrammanzeige. Ist es nicht vollständig wird der Editor geöffnet und das Diagramm kann bearbeitet werden.

    + + diff --git a/res/module/ebnf/help/html/data/trans/CVS/Entries b/res/module/ebnf/help/html/data/trans/CVS/Entries new file mode 100644 index 0000000..22a4ed0 --- /dev/null +++ b/res/module/ebnf/help/html/data/trans/CVS/Entries @@ -0,0 +1,2 @@ +/canvas.htm/1.1/Sat Aug 12 19:57:14 2006// +/control.htm/1.1/Sat Aug 12 19:57:14 2006// diff --git a/res/module/ebnf/help/html/data/trans/CVS/Repository b/res/module/ebnf/help/html/data/trans/CVS/Repository new file mode 100644 index 0000000..59e4838 --- /dev/null +++ b/res/module/ebnf/help/html/data/trans/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/html/data/trans diff --git a/res/module/ebnf/help/html/data/trans/CVS/Root b/res/module/ebnf/help/html/data/trans/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/html/data/trans/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/html/data/trans/canvas.htm b/res/module/ebnf/help/html/data/trans/canvas.htm new file mode 100644 index 0000000..12050f9 --- /dev/null +++ b/res/module/ebnf/help/html/data/trans/canvas.htm @@ -0,0 +1,35 @@ + + + Setzen der Startvariable + + + + + +

    Die Arbeitsfläche

    +



    +

    Anzeigebereich

    +

    Hier werden die Syntaxdiagramme visualisiert, vollständig, sowie auch während des Algorithmus. Neben den Syntaxdiagrammelementen existieren hier zusätzlich noch die hinterlegten trans()-Elemente. Fährt man mit der Maus darüber, werden die zu trennenden Elemente farblich hervorgehoben und im Erklärungsbereich wird der dazugehörige Schritt angezeigt. Bei Klick, wird dieser Schritt ausgeführt.

    +

    Kontrollbereich

    +

    Im Kontrollbereich hat man die Möglichkeit, die Syntaxdiagramme grafisch zu verändern. Die Möglichkeiten beschränken sich auf das Skalieren der Diagramme, das automatische Anpassen der Größe an das Fenster, sowie die Entfernung von Treppenstrukturen. Auf der rechten Seite befinden sich zudem noch Navigationsbuttons.
    +

    +

    : Hier haben Sie die Möglichkeit, das Diagramm selbst zu vergrößern und zu verkleinern
    + : Hier kann man einstellen, ob sich die Größe der Diagramme automatisch dem Fensterrahmen anpassen soll oder nicht.
    + : Bei Aktivierung dieses Knopfes, während Treppenstrukturen in den Diagrammen entfernt.

    +

    ACHTUNG!!! Ein Wechsel in die Syntaxdiagramm-Anzeige ist nur nach Beendigen des Algorithmus möglich und man kommt zudem nicht wieder zurück! Wechselt man in die Ebnf-Ansicht und lässt die Ebnf-Definition unverändert, fährt man bei Rückkehr in den trans()-Algorithmus fort, ändert man die Ebnf-Defintion, wird der Algorithmus neu gestartet

    +

    Steuerbereich

    +

    Hier kann man neben dem direkten Arbeiten in der Anzeige noch über Buttons den Algorithmus steuern.
    +

    +

    : Macht alle bisher ausgeführten Schritte rückgängig
    +

    +

    : Macht den letzten ausgeführten Schritt rückgängig
    +

    +

    : Bei Aktivierung dieses Buttons wird permanent der nächste Schritt hervorgehoben
    +

    +

    : Führt den nächsten automatisch gewählten Schritt aus
    +

    +

    : Führt den Algorithmus bis zum Ende aus

    +

    Erklärungsbereich

    +

    Hier werden die Erklärungen zu den einzelnen Schritten angezeigt oder es werden Nutzer Hinweise angezeigt.

    + + diff --git a/res/module/ebnf/help/html/data/trans/control.htm b/res/module/ebnf/help/html/data/trans/control.htm new file mode 100644 index 0000000..29f227b --- /dev/null +++ b/res/module/ebnf/help/html/data/trans/control.htm @@ -0,0 +1,19 @@ + + + Setzen der Startvariable + + + + + +

    Seuerung des Algorithmus

    +

    Es existieren zwei Möglichkeiten, den Algorithmus zu steuern. Zum einen

    +

    Im Anzeigebereich

    +

    Hier kann man direkt mit den farblich hinterlegten trans()-Elementen arbeiten. Befindet sich die Maus darüber, werden die zu trennenden Teilstücke hervorgehoben sowie der zugehörige Algorithmusschritt im Erklärungsberiech angezeigt. Klickt man darauf, wird dieser Schritt ausgeführt und das Element umgeformt. +

    +Sowie über die

    +

    Die Steuerbuttons

    +

    Die Erklärung zu den Steuerbuttons befindet sich im Bereich Arbeitsflaeche. +

    + + diff --git a/res/module/ebnf/help/html/index.htm b/res/module/ebnf/help/html/index.htm new file mode 100644 index 0000000..079f448 --- /dev/null +++ b/res/module/ebnf/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AVL Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/ebnf/help/html/top_frame.htm b/res/module/ebnf/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/ebnf/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/CVS/Entries b/res/module/ebnf/help/jhelp/CVS/Entries new file mode 100644 index 0000000..9f39ff9 --- /dev/null +++ b/res/module/ebnf/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/ebnfIndex.xml/1.1/Sat Aug 12 19:57:14 2006// +/ebnfTOC.xml/1.1/Sat Aug 12 19:57:14 2006// +/ebnf_help.hs/1.1/Sat Aug 12 19:57:14 2006/-kb/ +/map.jhm/1.1/Sat Aug 12 19:57:14 2006/-kb/ diff --git a/res/module/ebnf/help/jhelp/CVS/Repository b/res/module/ebnf/help/jhelp/CVS/Repository new file mode 100644 index 0000000..a918127 --- /dev/null +++ b/res/module/ebnf/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/jhelp diff --git a/res/module/ebnf/help/jhelp/CVS/Root b/res/module/ebnf/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..59645c0 --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/DOCS.TAB/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/OFFSETS/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/POSITIONS/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/SCHEMA/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/TMAP/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/config.ini/1.1/Sat Aug 12 19:57:13 2006// diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..7df0d27 --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/jhelp/JavaHelpSearch diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS b/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..26b0d1c Binary files /dev/null and b/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..40ea4fa --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,6 @@ +eÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿý—ÿÿÿeeÿÿý—ÿÿÿÿÿÿÙÿÿÿÿÿÿÿÿÿÿÿÿý—ÿö_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÙý—ÿÿÿeÿÿÿÿÙÿö_ÿÿÿÿÿö_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÙ}•—ÿÚ_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿö_ÿÙÿÿÿÿeÿÿÿÿÿÿÿÿý—ÿÿÿeÿÿÿÿÿÿÿö_ÿ@4¸íxº0¸Âë£&(Ò¬hYJŽ,dJ2Ê0±3J¬`R‹¨Ì¼ÂΊ8³ Í/0¾0¼ê,Ò/£ +0¯3¢®üÒŽ.0¸Â¿Ž*û³"d(Ê(ÂŒ*ìÂ.üÈ£ 2Š»Ì*£ +*0«4¨ÒÌ‹9 +3+¬ÂêîŒ*Œ*¼Â¾³ Œ(£Š£b³”ºŽ*0ªŽ*ªªªªîŒ*êªê*þ0º¿êŽ+ª¨Âª¬Âú+ªÌ(¬̿4»0¯Ì+ªªª¨Âª£ +*ª«ªªªªªª³ +Œ*èªóKŒ*ªªî4¨Â¨Èªª¨ÒŒ*ªêº¨Ò®ª«ª0¯ŒŠª®0ºêÿÿÿüÂóKÿÿÿ0¿ÿÿüÂÿÿÿÿÿÿÿÿÿÿÿÿÿÿ0¿ÿÿÿÿÿÿÿÿÿÿÍ/ÿÿó ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý€ \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/ebnf/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..41aa4c1 --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ƒºås®ù”ÂVI¡Re³dAaÉ„bÈUlÔ0 €÷η¡´á4ÒL5Ò¤U|yrÙÐÖ@ê; áäDBþ<2ž6Ôꪀ0Ü.€0кªªª` \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/ebnf/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1729a5d Binary files /dev/null and b/res/module/ebnf/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/ebnf/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..28a98ba --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=862 id2=1 diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/TMAP b/res/module/ebnf/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..a43a5e9 Binary files /dev/null and b/res/module/ebnf/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/ebnf/help/jhelp/JavaHelpSearch/config.ini b/res/module/ebnf/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/ebnf/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/ebnfIndex.xml b/res/module/ebnf/help/jhelp/ebnfIndex.xml new file mode 100644 index 0000000..0944bef --- /dev/null +++ b/res/module/ebnf/help/jhelp/ebnfIndex.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/ebnf/help/jhelp/ebnfTOC.xml b/res/module/ebnf/help/jhelp/ebnfTOC.xml new file mode 100644 index 0000000..cbfcbc8 --- /dev/null +++ b/res/module/ebnf/help/jhelp/ebnfTOC.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/ebnf_help.hs b/res/module/ebnf/help/jhelp/ebnf_help.hs new file mode 100644 index 0000000..c6f5bad --- /dev/null +++ b/res/module/ebnf/help/jhelp/ebnf_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Modul EBNF / Syntaxdiagramme + + + + + ebnf + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + ebnfTOC.xml + + + + Index + + javax.help.IndexView + ebnfIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/ebnf/help/jhelp/map.jhm b/res/module/ebnf/help/jhelp/map.jhm new file mode 100644 index 0000000..ac46c08 --- /dev/null +++ b/res/module/ebnf/help/jhelp/map.jhm @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/ebnf/help/pics/CVS/Entries b/res/module/ebnf/help/pics/CVS/Entries new file mode 100644 index 0000000..65101fc --- /dev/null +++ b/res/module/ebnf/help/pics/CVS/Entries @@ -0,0 +1,67 @@ +/ebnfdisplay_full.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfdisplay_keepbinary.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfdisplay_makebinary.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfdisplay_transbutton.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_addrule.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_addterminal.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_addvariable.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_buttons.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_delrule.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_delterminal.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_delvariable.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_editrule.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_editterminal.png/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/ebnfinput_editvar.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_full.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_popup_startvar.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_setstartvar.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/ebnfinput_unknownsymbol.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/editebnf.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/editsyndia.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/load.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/logo.gif/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/redo.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_dot.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_frame.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_full.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_keller.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_mouseoverexit.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_mouseoverline.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_terminal.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_variable.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/rs_variable_keller.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/savebuttons.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/savedialog.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/savemenu.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Button_OK.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Edit.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_NeuesDiagramm.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Radiergummi.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Terminal.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Variable.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Verzweigung.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Leiste_Wiederholung.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Edit.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Radiergummi.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Terminal.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Variable.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Verzweigung.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_Popup_Wiederholung.png/1.1/Sat Aug 12 19:57:13 2006/-kb/ +/syndia_aufteilung.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_display.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_display_autosize.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_display_resize.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_display_stairs.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_startdiagramm.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/syndia_view.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_finish.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_fit.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_gui.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_info.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_last.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_next.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_reset.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_resize.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/trans_stairs.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/undo.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ +/welcome.png/1.1/Sat Aug 12 19:57:12 2006/-kb/ diff --git a/res/module/ebnf/help/pics/CVS/Repository b/res/module/ebnf/help/pics/CVS/Repository new file mode 100644 index 0000000..489d863 --- /dev/null +++ b/res/module/ebnf/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/ebnf/help/pics diff --git a/res/module/ebnf/help/pics/CVS/Root b/res/module/ebnf/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/ebnf/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/ebnf/help/pics/ebnfdisplay_full.png b/res/module/ebnf/help/pics/ebnfdisplay_full.png new file mode 100644 index 0000000..859c5c9 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfdisplay_full.png differ diff --git a/res/module/ebnf/help/pics/ebnfdisplay_keepbinary.png b/res/module/ebnf/help/pics/ebnfdisplay_keepbinary.png new file mode 100644 index 0000000..8c74a44 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfdisplay_keepbinary.png differ diff --git a/res/module/ebnf/help/pics/ebnfdisplay_makebinary.png b/res/module/ebnf/help/pics/ebnfdisplay_makebinary.png new file mode 100644 index 0000000..45723e0 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfdisplay_makebinary.png differ diff --git a/res/module/ebnf/help/pics/ebnfdisplay_transbutton.png b/res/module/ebnf/help/pics/ebnfdisplay_transbutton.png new file mode 100644 index 0000000..bfd8bde Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfdisplay_transbutton.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_addrule.png b/res/module/ebnf/help/pics/ebnfinput_addrule.png new file mode 100644 index 0000000..ffefd95 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_addrule.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_addterminal.png b/res/module/ebnf/help/pics/ebnfinput_addterminal.png new file mode 100644 index 0000000..32b5404 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_addterminal.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_addvariable.png b/res/module/ebnf/help/pics/ebnfinput_addvariable.png new file mode 100644 index 0000000..7b71403 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_addvariable.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_buttons.png b/res/module/ebnf/help/pics/ebnfinput_buttons.png new file mode 100644 index 0000000..c48c86d Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_buttons.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_delrule.png b/res/module/ebnf/help/pics/ebnfinput_delrule.png new file mode 100644 index 0000000..b050754 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_delrule.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_delterminal.png b/res/module/ebnf/help/pics/ebnfinput_delterminal.png new file mode 100644 index 0000000..9290f98 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_delterminal.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_delvariable.png b/res/module/ebnf/help/pics/ebnfinput_delvariable.png new file mode 100644 index 0000000..ecd42c7 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_delvariable.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_editrule.png b/res/module/ebnf/help/pics/ebnfinput_editrule.png new file mode 100644 index 0000000..33179fc Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_editrule.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_editterminal.png b/res/module/ebnf/help/pics/ebnfinput_editterminal.png new file mode 100644 index 0000000..4cc14e4 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_editterminal.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_editvar.png b/res/module/ebnf/help/pics/ebnfinput_editvar.png new file mode 100644 index 0000000..67053d2 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_editvar.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_full.png b/res/module/ebnf/help/pics/ebnfinput_full.png new file mode 100644 index 0000000..ae120b1 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_full.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_popup_startvar.png b/res/module/ebnf/help/pics/ebnfinput_popup_startvar.png new file mode 100644 index 0000000..256b295 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_popup_startvar.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_setstartvar.png b/res/module/ebnf/help/pics/ebnfinput_setstartvar.png new file mode 100644 index 0000000..a0b4cb5 Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_setstartvar.png differ diff --git a/res/module/ebnf/help/pics/ebnfinput_unknownsymbol.png b/res/module/ebnf/help/pics/ebnfinput_unknownsymbol.png new file mode 100644 index 0000000..cadb60c Binary files /dev/null and b/res/module/ebnf/help/pics/ebnfinput_unknownsymbol.png differ diff --git a/res/module/ebnf/help/pics/editebnf.png b/res/module/ebnf/help/pics/editebnf.png new file mode 100644 index 0000000..89a2d2b Binary files /dev/null and b/res/module/ebnf/help/pics/editebnf.png differ diff --git a/res/module/ebnf/help/pics/editsyndia.png b/res/module/ebnf/help/pics/editsyndia.png new file mode 100644 index 0000000..e0d2b48 Binary files /dev/null and b/res/module/ebnf/help/pics/editsyndia.png differ diff --git a/res/module/ebnf/help/pics/load.png b/res/module/ebnf/help/pics/load.png new file mode 100644 index 0000000..46a021e Binary files /dev/null and b/res/module/ebnf/help/pics/load.png differ diff --git a/res/module/ebnf/help/pics/logo.gif b/res/module/ebnf/help/pics/logo.gif new file mode 100644 index 0000000..46777a3 Binary files /dev/null and b/res/module/ebnf/help/pics/logo.gif differ diff --git a/res/module/ebnf/help/pics/redo.png b/res/module/ebnf/help/pics/redo.png new file mode 100644 index 0000000..cad5710 Binary files /dev/null and b/res/module/ebnf/help/pics/redo.png differ diff --git a/res/module/ebnf/help/pics/rs_dot.png b/res/module/ebnf/help/pics/rs_dot.png new file mode 100644 index 0000000..63a95d8 Binary files /dev/null and b/res/module/ebnf/help/pics/rs_dot.png differ diff --git a/res/module/ebnf/help/pics/rs_frame.png b/res/module/ebnf/help/pics/rs_frame.png new file mode 100644 index 0000000..ec87dfe Binary files /dev/null and b/res/module/ebnf/help/pics/rs_frame.png differ diff --git a/res/module/ebnf/help/pics/rs_full.png b/res/module/ebnf/help/pics/rs_full.png new file mode 100644 index 0000000..1bd343e Binary files /dev/null and b/res/module/ebnf/help/pics/rs_full.png differ diff --git a/res/module/ebnf/help/pics/rs_keller.png b/res/module/ebnf/help/pics/rs_keller.png new file mode 100644 index 0000000..21c8678 Binary files /dev/null and b/res/module/ebnf/help/pics/rs_keller.png differ diff --git a/res/module/ebnf/help/pics/rs_mouseoverexit.png b/res/module/ebnf/help/pics/rs_mouseoverexit.png new file mode 100644 index 0000000..a6275a9 Binary files /dev/null and b/res/module/ebnf/help/pics/rs_mouseoverexit.png differ diff --git a/res/module/ebnf/help/pics/rs_mouseoverline.png b/res/module/ebnf/help/pics/rs_mouseoverline.png new file mode 100644 index 0000000..8a889ea Binary files /dev/null and b/res/module/ebnf/help/pics/rs_mouseoverline.png differ diff --git a/res/module/ebnf/help/pics/rs_terminal.png b/res/module/ebnf/help/pics/rs_terminal.png new file mode 100644 index 0000000..e4c1ee4 Binary files /dev/null and b/res/module/ebnf/help/pics/rs_terminal.png differ diff --git a/res/module/ebnf/help/pics/rs_variable.png b/res/module/ebnf/help/pics/rs_variable.png new file mode 100644 index 0000000..369880a Binary files /dev/null and b/res/module/ebnf/help/pics/rs_variable.png differ diff --git a/res/module/ebnf/help/pics/rs_variable_keller.png b/res/module/ebnf/help/pics/rs_variable_keller.png new file mode 100644 index 0000000..e6a65a9 Binary files /dev/null and b/res/module/ebnf/help/pics/rs_variable_keller.png differ diff --git a/res/module/ebnf/help/pics/savebuttons.png b/res/module/ebnf/help/pics/savebuttons.png new file mode 100644 index 0000000..d3186a9 Binary files /dev/null and b/res/module/ebnf/help/pics/savebuttons.png differ diff --git a/res/module/ebnf/help/pics/savedialog.png b/res/module/ebnf/help/pics/savedialog.png new file mode 100644 index 0000000..c959684 Binary files /dev/null and b/res/module/ebnf/help/pics/savedialog.png differ diff --git a/res/module/ebnf/help/pics/savemenu.png b/res/module/ebnf/help/pics/savemenu.png new file mode 100644 index 0000000..b401304 Binary files /dev/null and b/res/module/ebnf/help/pics/savemenu.png differ diff --git a/res/module/ebnf/help/pics/syndia_Button_OK.png b/res/module/ebnf/help/pics/syndia_Button_OK.png new file mode 100644 index 0000000..21b6ea3 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Button_OK.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Edit.png b/res/module/ebnf/help/pics/syndia_Leiste_Edit.png new file mode 100644 index 0000000..64e5a9c Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Edit.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_NeuesDiagramm.png b/res/module/ebnf/help/pics/syndia_Leiste_NeuesDiagramm.png new file mode 100644 index 0000000..4617dca Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_NeuesDiagramm.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Radiergummi.png b/res/module/ebnf/help/pics/syndia_Leiste_Radiergummi.png new file mode 100644 index 0000000..4d7c05c Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Radiergummi.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Terminal.png b/res/module/ebnf/help/pics/syndia_Leiste_Terminal.png new file mode 100644 index 0000000..3474e03 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Terminal.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Variable.png b/res/module/ebnf/help/pics/syndia_Leiste_Variable.png new file mode 100644 index 0000000..e3e5727 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Variable.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Verzweigung.png b/res/module/ebnf/help/pics/syndia_Leiste_Verzweigung.png new file mode 100644 index 0000000..5cdadb2 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Verzweigung.png differ diff --git a/res/module/ebnf/help/pics/syndia_Leiste_Wiederholung.png b/res/module/ebnf/help/pics/syndia_Leiste_Wiederholung.png new file mode 100644 index 0000000..bb4a7e4 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Leiste_Wiederholung.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Edit.png b/res/module/ebnf/help/pics/syndia_Popup_Edit.png new file mode 100644 index 0000000..6123b47 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Edit.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Radiergummi.png b/res/module/ebnf/help/pics/syndia_Popup_Radiergummi.png new file mode 100644 index 0000000..1aca702 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Radiergummi.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Terminal.png b/res/module/ebnf/help/pics/syndia_Popup_Terminal.png new file mode 100644 index 0000000..64c6abc Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Terminal.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Variable.png b/res/module/ebnf/help/pics/syndia_Popup_Variable.png new file mode 100644 index 0000000..c22b544 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Variable.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Verzweigung.png b/res/module/ebnf/help/pics/syndia_Popup_Verzweigung.png new file mode 100644 index 0000000..34c7924 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Verzweigung.png differ diff --git a/res/module/ebnf/help/pics/syndia_Popup_Wiederholung.png b/res/module/ebnf/help/pics/syndia_Popup_Wiederholung.png new file mode 100644 index 0000000..d547aa8 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_Popup_Wiederholung.png differ diff --git a/res/module/ebnf/help/pics/syndia_aufteilung.png b/res/module/ebnf/help/pics/syndia_aufteilung.png new file mode 100644 index 0000000..7e8ee11 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_aufteilung.png differ diff --git a/res/module/ebnf/help/pics/syndia_display.png b/res/module/ebnf/help/pics/syndia_display.png new file mode 100644 index 0000000..d176812 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_display.png differ diff --git a/res/module/ebnf/help/pics/syndia_display_autosize.png b/res/module/ebnf/help/pics/syndia_display_autosize.png new file mode 100644 index 0000000..cd6e206 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_display_autosize.png differ diff --git a/res/module/ebnf/help/pics/syndia_display_resize.png b/res/module/ebnf/help/pics/syndia_display_resize.png new file mode 100644 index 0000000..24dd727 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_display_resize.png differ diff --git a/res/module/ebnf/help/pics/syndia_display_stairs.png b/res/module/ebnf/help/pics/syndia_display_stairs.png new file mode 100644 index 0000000..b534ded Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_display_stairs.png differ diff --git a/res/module/ebnf/help/pics/syndia_startdiagramm.png b/res/module/ebnf/help/pics/syndia_startdiagramm.png new file mode 100644 index 0000000..1a46879 Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_startdiagramm.png differ diff --git a/res/module/ebnf/help/pics/syndia_view.png b/res/module/ebnf/help/pics/syndia_view.png new file mode 100644 index 0000000..d052a6d Binary files /dev/null and b/res/module/ebnf/help/pics/syndia_view.png differ diff --git a/res/module/ebnf/help/pics/trans_finish.png b/res/module/ebnf/help/pics/trans_finish.png new file mode 100644 index 0000000..7225b1c Binary files /dev/null and b/res/module/ebnf/help/pics/trans_finish.png differ diff --git a/res/module/ebnf/help/pics/trans_fit.png b/res/module/ebnf/help/pics/trans_fit.png new file mode 100644 index 0000000..6909be3 Binary files /dev/null and b/res/module/ebnf/help/pics/trans_fit.png differ diff --git a/res/module/ebnf/help/pics/trans_gui.png b/res/module/ebnf/help/pics/trans_gui.png new file mode 100644 index 0000000..29c437f Binary files /dev/null and b/res/module/ebnf/help/pics/trans_gui.png differ diff --git a/res/module/ebnf/help/pics/trans_info.png b/res/module/ebnf/help/pics/trans_info.png new file mode 100644 index 0000000..d58a8d2 Binary files /dev/null and b/res/module/ebnf/help/pics/trans_info.png differ diff --git a/res/module/ebnf/help/pics/trans_last.png b/res/module/ebnf/help/pics/trans_last.png new file mode 100644 index 0000000..0386234 Binary files /dev/null and b/res/module/ebnf/help/pics/trans_last.png differ diff --git a/res/module/ebnf/help/pics/trans_next.png b/res/module/ebnf/help/pics/trans_next.png new file mode 100644 index 0000000..8960b75 Binary files /dev/null and b/res/module/ebnf/help/pics/trans_next.png differ diff --git a/res/module/ebnf/help/pics/trans_reset.png b/res/module/ebnf/help/pics/trans_reset.png new file mode 100644 index 0000000..aac9caa Binary files /dev/null and b/res/module/ebnf/help/pics/trans_reset.png differ diff --git a/res/module/ebnf/help/pics/trans_resize.png b/res/module/ebnf/help/pics/trans_resize.png new file mode 100644 index 0000000..2c3ecbf Binary files /dev/null and b/res/module/ebnf/help/pics/trans_resize.png differ diff --git a/res/module/ebnf/help/pics/trans_stairs.png b/res/module/ebnf/help/pics/trans_stairs.png new file mode 100644 index 0000000..784c899 Binary files /dev/null and b/res/module/ebnf/help/pics/trans_stairs.png differ diff --git a/res/module/ebnf/help/pics/undo.png b/res/module/ebnf/help/pics/undo.png new file mode 100644 index 0000000..0fcefa7 Binary files /dev/null and b/res/module/ebnf/help/pics/undo.png differ diff --git a/res/module/ebnf/help/pics/welcome.png b/res/module/ebnf/help/pics/welcome.png new file mode 100644 index 0000000..32165f6 Binary files /dev/null and b/res/module/ebnf/help/pics/welcome.png differ diff --git a/res/module/ebnf/help/style.css b/res/module/ebnf/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/ebnf/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/em/CVS/Entries b/res/module/em/CVS/Entries new file mode 100644 index 0000000..f856085 --- /dev/null +++ b/res/module/em/CVS/Entries @@ -0,0 +1,6 @@ +/clear.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +D/help//// +/last.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/next.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +D/pics//// +/previous.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ diff --git a/res/module/em/CVS/Repository b/res/module/em/CVS/Repository new file mode 100644 index 0000000..eb87b7e --- /dev/null +++ b/res/module/em/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em diff --git a/res/module/em/CVS/Root b/res/module/em/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/clear.png b/res/module/em/clear.png new file mode 100644 index 0000000..9c15c09 Binary files /dev/null and b/res/module/em/clear.png differ diff --git a/res/module/em/help/CVS/Entries b/res/module/em/help/CVS/Entries new file mode 100644 index 0000000..c5bf138 --- /dev/null +++ b/res/module/em/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Mon Jan 30 18:56:51 2012// diff --git a/res/module/em/help/CVS/Repository b/res/module/em/help/CVS/Repository new file mode 100644 index 0000000..fa2ec5c --- /dev/null +++ b/res/module/em/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help diff --git a/res/module/em/help/CVS/Root b/res/module/em/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/html/CVS/Entries b/res/module/em/help/html/CVS/Entries new file mode 100644 index 0000000..a1a785b --- /dev/null +++ b/res/module/em/help/html/CVS/Entries @@ -0,0 +1,3 @@ +D/data//// +/index.htm/1.1/Mon Jan 30 18:56:52 2012// +/top_frame.htm/1.1/Mon Jan 30 18:56:52 2012// diff --git a/res/module/em/help/html/CVS/Repository b/res/module/em/help/html/CVS/Repository new file mode 100644 index 0000000..d1ba301 --- /dev/null +++ b/res/module/em/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help/html diff --git a/res/module/em/help/html/CVS/Root b/res/module/em/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/html/data/CVS/Entries b/res/module/em/help/html/data/CVS/Entries new file mode 100644 index 0000000..f2d2fbc --- /dev/null +++ b/res/module/em/help/html/data/CVS/Entries @@ -0,0 +1,5 @@ +/input.htm/1.1/Mon Jan 30 18:56:52 2012// +/io.htm/1.1/Mon Jan 30 18:56:52 2012// +/output.htm/1.1/Mon Jan 30 18:56:52 2012// +/overview.htm/1.1/Mon Jan 30 18:56:52 2012// +/praesentation.htm/1.1/Mon Jan 30 18:56:52 2012// diff --git a/res/module/em/help/html/data/CVS/Repository b/res/module/em/help/html/data/CVS/Repository new file mode 100644 index 0000000..08cca90 --- /dev/null +++ b/res/module/em/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help/html/data diff --git a/res/module/em/help/html/data/CVS/Root b/res/module/em/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/html/data/input.htm b/res/module/em/help/html/data/input.htm new file mode 100644 index 0000000..7bcf51e --- /dev/null +++ b/res/module/em/help/html/data/input.htm @@ -0,0 +1,113 @@ + + + Neues Experiment + + + +

    Neues Experiment

    +

    Übersicht

    +

    Nach dem Start des Moduls wird zuerst eine Startansicht angezeigt, in der der Benutzer + aus zwei Optionen wählen kann: +

      +
    • erstellen eines neuen Experiments
    • +
    • laden eines gespeicherten Experiments
    • +
    + Dieses Kapitel beschreibt, wie eine neues Experiment erstellt werden kann. +

    +

    + Startansicht + +

    Angabe der Objekte

    +

    Nach der Wahl des Menüpunktes neues Experiment aus in der Startansicht öffnet + sich ein Fenster zur Angabe der Objekte, aus denen das Experiment bestehen soll. Hier können + nun beliebige Objekte dem Experiment hinzugefügt werden.
    + Für die beiden im Alltag gebräuchlichen Objekte Würfel und Münze + gibt es bereits spezielle Tasten, die direkt das spezifizierte Objekt dem Experiment hinzufügen. + Des Weiteren können Objekte mit beliebiger, positiver Seitenzahl angegeben werden. Dies erfolgt + über das Eingabefeld und anschließendes bestätigen per Eingabetaste oder durch Klick + auf die entsprechende Taste. Die Tasten zum Hinzufügen von neuen Objekten sind mit einem grü + Pluszeichen gekennzeichnet.
    + Über die Rückgängig-Taste kann das zuletzt angegebene Objekt wieder entfernt + werden. Die Rückgängig-Taste ist durch ein rotes Minuszeichen gekennzeichnet.
    + Nach Eingabe der gewünschten Objekte (mindestens einem) kann per Klick auf die Weiter-Taste + fortgefahren werden. Die Weiter-Taste ist mit einem grünen Pfeil nach rechts gekennzeichnet. +

    +

    + Angabe der Objekte + +

    Festlegen der Beobachtungen

    +

    Bei der Festlegung der Beobachtungen wird die Menge der Ereignisse des Experiments partitioniert. Fü + diese Partitionierung stehen verschiedene vorgefertigte Wahlmöglichkeiten zu Verfügung.

    +

    + Standardeinstellung der Partitionierung
    + +

    In der Listenansicht sind sowohl der Name als auch die Elemente der Klasse in mathematischer + Schreibweise dargestellt, sodass für den Benutzer die Einteilung der Beobachtungen + stets einsichtig ist. Des Weiteren kann der Benutzer per Doppelklick auf einen + Listeneintrag den Namen der Klasse anpassen. +

    +

    + + Umbenennen einer Klasse
    + +
      +
    • Gleiche Seite: Die Ereignismenge wird in zwei Klassen geteilt, wobei eine Klasse alle + Tupel enthält, deren Elemente gleich sind, die andere die restlichen Ereignisse.
    • +
    • Anzahl Seite: Über das Auswahlfeld kann gewählt werden, welche Seite + gezählt werden soll (z.B. enthält das Tupel (1,4) 0-mal Seite 2, die Tupel (2,1) + und (1,2) jeweils 1-mal Seite 2 und (2,2) 2-mal Seite 2). Bei dieser Einstellung variiert + die Anzahl der verschiedenen Klassen.
    • +
    • Ein Objekt hat eine Eigenschaft: Diese Einstellungsmöglichkeit eignet sich für + die Einteilung in zwei Klassen, wobei zur Einteilung nur ein bestimmtes Objekt auf + eine bestimmte Eigenschaft hin überprüft wird (z.B. könnte gefragt sein, wie oft + mit der ersten Münze Kopf geworfen wurde).
    • +
    • Summe der Seiten: Diese Option teilt die Ereignisse nach der Summe der Seiten ein, + wobei die Summe sich aus den Elementen des Tupel berechnet (z.B. hat (1,3) die Summe + 4, (2,4) die Summe 6, usw.). Für Münzen wird Zahl=1 und Kopf=2 gesetzt.
    • +
    • Eigene Partitionierung: Mit der eigenen Partitionierung kann der Benutzer + selbst frei wählen, wie die Ereignisse in Klassen eingeteilt werden sollen. Über eine + Tabelle kann durch Klicken oder Ziehen von „Rahmen“ die Menge der Ereignisse + der Klasse festelegt werden. Dabei ist ausgeschlossen, dass ein Ereignis zwei oder mehr + Klassen gleichzeitig zugewiesen wird. Weiterhin kann der Benutzer erst fortfahren, wenn + alle Ereignisse partitioniert wurden. Bereits hinzugefügte Klassen können über die + Entfernen-Taste auch wieder entfernt werden. Zur einfachen Vervollständigung + der Beobachtung gibt es eine Auffüll-Taste, die aus den noch nicht partitionierten + Ereignissen eine neue „Restklasse“ erstellt.

      + Anlegen einer eigenen Partitionierung +
    • +
    + +

    Eingeben der Beobachtungshäufigkeiten

    +

    Für die Berechnungen des EM-Algorithmus ist die Angabe der Häufigkeiten der Beobachtungen von Nöten. + Diese Häufigkeiten müssen in die rechte Spalte der Tabelle eingetragen werden, wobei es ausreicht, + dass eine Beobachtung häufiger als 0-mal auftritt. Jede Häufigkeit muss eine reelle Zahl ≥0 sein. +
    + Zur Vermeidung von Fehleingaben werden Fehlermeldungen angezeigt. Des Weiteren ist die Taste zum + Fortfahren nur dann aktiviert, wenn die Eingabe korrekt ist.
    + Akzeptierte Fomate für die Eingabe sind von der Form: +

      +
    • 1.5 – Eingabe nach amerikanischem Format (Punkt als Trennzeichen).
    • +
    • 1,5 – Eingabe nach europäischem Format (Komma als Trennzeichen).
    • +
    • 3/2 – Eingabe als Dezimalbruch
    • +
    +

    +

    + Eingabe der Häufigkeiten + +

    Startwahrscheinlichkeiten

    +

    Der letzte Schritt zur vollständigen Eingabe der benötigten Parameter ist die Angabe mindestens einer + Startwahrscheinlichkeit für die Objekte des Experiments. Für eine korrekte Startwahrscheinlichkeit + für ein Objekt muss die Summe der Wahrscheinlichkeiten der Seiten 1 sein. Weiterhin darf es keine + negativen Wahrscheinlichkeiten geben.
    + Zur vereinfachten Eingabe der Wahrscheinlichkeiten gibt es zwei Tasten zum auffüllen einer + angewählten Spalte. Zum Einen kann eine Spalte gleichverteilt aufgefüllt werden (Schild-Symbol), + zum Anderen kann sie zufällig aufgefüllt werden (Fragezeichen-Symbol). Als dritte + Möglichkeit steht dem Benutzer die freie Eingabe zur Verfügung. Für alle drei Varianten findet + sich ein Beispiel in der Abbildung.
    + Bereits eingegebene Startwahrscheinlichkeiten können mit der Entfernen-Taste wieder entfernt + werden. Die Entfernen-Taste ist mit einem roten Minuszeichen gekennzeichnet. +

    +

    + Startwahrscheinlichkeiten + + diff --git a/res/module/em/help/html/data/io.htm b/res/module/em/help/html/data/io.htm new file mode 100644 index 0000000..e9af8e3 --- /dev/null +++ b/res/module/em/help/html/data/io.htm @@ -0,0 +1,35 @@ + + + Laden/Speichern + + + +

    Laden/Speichern

    +

    Übersicht

    +

    Das Modul EM-Algorithmus bietet die Möglichkeit, gespeicherte Experimente zu Laden und selbst erstellte + Experiemtne zu Speichern. +

    +

    Laden

    +

    Mit dem Modul werden Beispieldateien mit Experimenten zur Verfügung gestellt. Diese orientieren sich + an den Beispielen aus der Vorlesung von Prof. Vogler und an den zugehörigen Übungsaufgaben.
    + In der Startansicht gibt es die Auswahlmöglichkeit, eine gespeichertes Experiment zu Laden. Des + Weiteren ist es immer möglich, über das Laden-Icon in der Toolbar ein Experiment zu laden. +
    Nach Klicken auf eines der Laden-Icons öffnet sich ein Dialog, in dem der Nutzer die zu + öffnende Datei auswählen kann. Diese muss die Dateiendung .em haben, um korrekt geladen werden + zu können. Ist die Auswahl korrekt, wird das Experiment geladen. +
    Nach dem Laden können die Parameter des Experiments noch verändert oder erweitert werden.

    +

    + Öffnen-Dialog + +

    Speichern

    +

    Nachdem ein Experiment vollständig initialisiert wurde bietet das Modul dem Nutzer die Möglichkeit, + das Experiment zu speichern. Dazu steht in der Toolbar ein Speichern-Icon zur Verfügung, das mit + einer Diskette gekennzeichnet ist.
    + Beim Klicken auf dieses Icon wird ein Dialog geöffnet, in dem der Nutzer dazu aufgefordert wird, den + Dateipfad und -namen anzugeben, unter dem das Experiment gespeichert werden soll. Dabei kann wahlweise + eine neue Datei erzeugt werden oder eine vorhandene Datei überschrieben werden.
    + Die Dateiendung .em wird automatisch an den Dateinamen angehängt. +

    + Speichern-Dialog + + diff --git a/res/module/em/help/html/data/output.htm b/res/module/em/help/html/data/output.htm new file mode 100644 index 0000000..b48e9ef --- /dev/null +++ b/res/module/em/help/html/data/output.htm @@ -0,0 +1,113 @@ + + + Visualisierung + + + +

    Visualisierung

    +

    Übersicht

    +

    Nach korrekter Initialisierung oder Laden eines Experiments wird der EM-Algorithmus schrittweise + visualisiert. Der Nutzer hat dabei die volle Kontrolle über die Navigation durch Schritte des + Algorithmus. Weiterhin stehen verschiedene Modi zur Anzeige der Berechnungen zur Verfügung. + Standardmäßig wird nach Beenden der Eingabe die Hybridansicht geöffnet. +
    Die Umschaltung zwischen den einzelnen Ansichten erfolgt über das Dropdown-Menü des Moduls. + Zusätzlich besteht die Möglichkeit, die Likelihood logarithmisch darzustellen. Dies bietet sich an, + da die Likelihood schnell sehr klein wird. Durch die logarithmische Darstellung werden Änderungen + dann deutlicher sichtbar. +
    Die verschiedenen Startwahrscheinlichkeiten sind durch unterschiedliche Farben gekennzeichnet. + Die Zuordnung kann der Legende am unteren Rand des Diagramms entnommen werden. +
    Falls während der Visualisierung wieder in die Eingabe geschaltet werden soll, um beispielsweise + Änderungen am Experiment vorzunehmen, kann dies durch Klick auf das Symbol getan werden.
    +
    Standardansicht nach der Eingabe
    +

    + +

    Diagrammansicht

    +

    In der Diagrammansicht werden die durch den Algorithmus berechneten Werte grafisch als + Liniendiagramme dargestellt. Durch Klicken auf die Tasten am oberen Rand kann zwischen den + zu betrachtenden Werten gewechselt werden. Die genaue Bedeutung der einzelnen Werte kann + im Skript zur Vorlesung nachgelesen werden. Durch Ziehen eines Rahmens kann in die + Liniendiagramme hineingezoomt werden. Durch Klicken der Standardzoom-Taste + wird die Ansicht wieder zurückgesetzt.
    + Liniendiagramm der Likelihood
    + Besteht das Experiment aus genau zwei Münzen steht zusätzlich eine 3D-Visualisierung der + Likelihood zur Verfügung. Diese kann durch Klicken und Ziehen der Maus gedreht werden. + Beim Navigieren durch die Schritte bleibt die eingestellte Ansicht erhalten.
    +
    3D-Ansicht
    +

    + +

    Tabellenansicht

    +

    Die Tabellenansicht bietet eine genaue Übersicht über berechneten Werte. Durch die + absoluten Zahlenwerte kann der Nutzer eigene Berechnungen nachprüfen oder exakte Aussagen + über die Entwicklung der Werte machen.
    + Die Tabelle scrollt automatisch mit den Schritten des Algorithmus mit, wobei immer drei + Berechnungschritte zu einem Zeitpunkt sichtbar sind.
    + Des Weiteren kann die Tabelle eingeklappt werden, um die Darstellung übersichtlicher + zu machen. Im eingeklappten Zustand sind nur die Zeilen mit den Likelihood-Werten der einzelnen + Startwahrscheinlichkeiten zu sehen, wohingegen im ausgeklappten Zustand alle Informationen + angezeigt werden.
    + Um die Tabelle ein- bzw. auszuklappen muss auf eine der Likelihood-Zeilen geklickt werden. Wichtig + ist, dass jeweils auf eine Kopfzeile geklickt wird. Bei erneutem Klick auf die Kopfzeile wird die + Tabelle entsprechend weiter ein- bzw. ausgeklappt.
    +
    Tabellenansicht
    +

    + +

    Hybridansicht

    +

    Die Hybridansicht kombiniert die Diagrammansicht mit der + Tabellenansicht und bietet so einen umfassenen Überblick. Die + Funktionen der einzelnen Ansichten bleiben dabei uneingeschränkt erhalten, so kann + beispielsweise weiterhin in die Diagramme hineingezoomt werde. Des Weiteren bietet + sich dem Nutzer auf diese Weise die Möglichkeit, sich die Entwicklung der Werte mit + Hilfe des Diagramms zu veranschaulichen und gleichzeitig die absolute Veränderung der + Werte beobachten zu können.
    + Über die Leiste zwischen den Ansichten kann die Größe der einzelnen Ansichsteile frei angepasst + werden. Insbesondere kann dadurch die Hybridansicht in die Diagrammansicht + oder die Tabellenansicht überführt werden.
    +
    Hybridansicht
    +

    + +

    Navigation

    +

    Zur Navigation durch die Berechnungschritte stehen in der Toolbar des Moduls vier Tasten zur + Verfügung, die mit grünen Pfeilen gekennzeichnet sind. Die Funktionen der Tasten + sind im Detail: +

      +
    •   Schritt vor:
      + Es werden drei Einzelschritte auf einmal berechnet. Diese Option bietet + sich an, wenn es hauptsächlich um die Entwicklung der Werte (vor allem der + Likelihood) geht. +
    • +
    •   Einzelschritt vor:
      + Es wird nur der nächste Wert berechnet. Diese Option ist hilfreich, um die + Berechnungen des Algorithmus nachzuvollziehen. Die genauen Auswirkungen eines + Einzelschritts sind nur in der Tabellenansicht + nachvollziehbar. +
    • +
    •   Schritt zurück:
      + Äquivalent zur Option Schritt vor werden die letzten drei berechneten + (Einzel-)Werte aus der Darstellung entfernt. Der Startwert der Berechnung + kann nicht entfernt werden. +
    • +
    •   Einzelschritt zurück:
      + Äquivalent zur Option Einzeschritt vor wird der letzte berechnete + Wert aus der Darstellung entfernt. Auch hier kann der Startwert nicht + entfernt werden. Die Änderungen durch Einzelschritte sind nur in der + Tabellenansicht nachvollziehbar. +
    • +
    •   Berechnung bis Grenze:
      + Diese Option bietet dem Nutzer die Möglichkeit, die Berechnung des EM-Algorithmus + bis zu einer bestimmten Grenze automatisch auszuführen. Der sich öffnende Dialog + fordert eine Eingabe in Prozen (%) und bezeichnet die Differenz zwischen zwei + aufeinanderfolgenden Likelihoods Ln-1 und Ln. Die Berechnung wird + gestoppt, sobald die Veränderung zwischen allen Likelihoods unterhalb der angegebenen + Grenze liegt. Sowohl die Tabelle als auch das Diagramm werden auf die Berechung angepasst + und zeigen das Ergebnis der Berechnung an. +
    • +
    •   Zurück zur Eingabe:
      + Um von der Visualisierung zurück zur Eingabe zu gelangen genügt ein Klick auf das + Home-Icon. Dies zeigt das Eingabefenster für die + Startwahrscheinlichkeiten an, + von dem aus die komplette Eingabe verändert werden kann. +
    • +
        +

        + + diff --git a/res/module/em/help/html/data/overview.htm b/res/module/em/help/html/data/overview.htm new file mode 100644 index 0000000..bff806e --- /dev/null +++ b/res/module/em/help/html/data/overview.htm @@ -0,0 +1,37 @@ + + + Einleitung + + + + +

        Das Modul zum EM-Algorithmus

        + +

        Einleitung

        + +

        Dieses Modul dient zur Verdeutlichung der Berechnungen des EM-Algorithmus, wie + er in der Vorlesung "Programmierung" von Prof. Vogler. + Die konkreten Arbeitsschritte des Algorithmus können im Skript zur Vorlesung + nachgelesen werden.

        + + +

        Funktionsübersicht

        + +

        Die Funktionen des Moduls können grundlegend in zwei Teile getrennt werden - zum einen + die Eingabe oder das Laden eines neuen Experiments, zum anderen die Visualisierung der + Berechnngen des EM-Algorithmus.

        +

        Das Modul zum EM-Algorithmus ermöglicht das Erstellen eines neuen Experiments, die Visualisierung + der Berechnungen sowie das Laden und Speichern von Experimenten durch:

        + +
      • Angabe der zugrunde liegenden Objekte
      • +
      • Festlegen von Beobachtungen
      • +
      • Bestimmen der Häufigkeit des Auftretens + der Beobachtung
      • +
      • Angabe einer oder mehrerer Annahmen + über die Wahrscheinlichkeiten der verschiedenen Objekte des Experiments
      • +
      • Grafische Darstellung in der Diagramm-Ansicht
      • +
      • Tabellarische Darstellung der Werte
      • +
      • Kombination der Ansichten in der Hybrid-Ansicht
      • +
      • Laden von Experimenten
      • + + diff --git a/res/module/em/help/html/data/praesentation.htm b/res/module/em/help/html/data/praesentation.htm new file mode 100644 index 0000000..0622e7c --- /dev/null +++ b/res/module/em/help/html/data/praesentation.htm @@ -0,0 +1,25 @@ + + + Präsentations-Modus + + + +

        Präsentations-Modus

        +

        Um die Nutzung an einem Beamer zu vereinfachen, gibt es einen + Präsentations-Modus, welcher die Schriftgröße in allen Bereichen des Moduls + vergrößert. Dieser kann in jedem Bereich über das Menü, welches sich + am oberen Fensterrand befindet, aktiviert und auch wieder deaktiviert werden. Zusätzlich + werden die Icons der Benutzeroberfläche vergrößert.

        +

        + Präsentations-Modus +

        Alternativ kann der Präsentationsmodus über das Icon in der Toolbar (de-)aktiviert werden. Wenn + der Präsentationsmodus aktiviert ist, ist das Icon grün hinterlegt. +

          +
        • – Präsentationsmodus ist deaktiviert, + durch Klicken aktivieren. +
        • +
        • – Präsentationsmodus ist aktiviert, + Klicken zum deaktivieren. +
        + + diff --git a/res/module/em/help/html/index.htm b/res/module/em/help/html/index.htm new file mode 100644 index 0000000..3508493 --- /dev/null +++ b/res/module/em/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum EM-Algorithmus Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + diff --git a/res/module/em/help/html/top_frame.htm b/res/module/em/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/em/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/em/help/jhelp/CVS/Entries b/res/module/em/help/jhelp/CVS/Entries new file mode 100644 index 0000000..f0b93a2 --- /dev/null +++ b/res/module/em/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/emIndex.xml/1.1/Mon Jan 30 18:56:52 2012// +/emMap.jhm/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/emTOC.xml/1.1/Mon Jan 30 18:56:52 2012// +/em_help.hs/1.1/Mon Jan 30 18:56:52 2012// diff --git a/res/module/em/help/jhelp/CVS/Repository b/res/module/em/help/jhelp/CVS/Repository new file mode 100644 index 0000000..c28393f --- /dev/null +++ b/res/module/em/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help/jhelp diff --git a/res/module/em/help/jhelp/CVS/Root b/res/module/em/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..ecc0c7e --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/DOCS.TAB/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/OFFSETS/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/POSITIONS/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/SCHEMA/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/TMAP/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/config.ini/1.1/Mon Jan 30 18:56:52 2012// diff --git a/res/module/em/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..8e062cc --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help/jhelp/JavaHelpSearch diff --git a/res/module/em/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/jhelp/JavaHelpSearch/DOCS b/res/module/em/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..0209b0d Binary files /dev/null and b/res/module/em/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/em/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/em/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..531ffba --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÝÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿ@þÿúªûû»¿¾ëªú﮾û¾ªªªªêªª¯¯êþº¯ª«ª®ªú®îº®ªúªªê®êªª»ªêªªª®ªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/em/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/em/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..a7fedd8 Binary files /dev/null and b/res/module/em/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/em/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/em/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..4a6e7f5 Binary files /dev/null and b/res/module/em/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/em/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/em/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..2ac0b52 --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=297 id2=1 diff --git a/res/module/em/help/jhelp/JavaHelpSearch/TMAP b/res/module/em/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..09b6e78 Binary files /dev/null and b/res/module/em/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/em/help/jhelp/JavaHelpSearch/config.ini b/res/module/em/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/em/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/em/help/jhelp/emIndex.xml b/res/module/em/help/jhelp/emIndex.xml new file mode 100644 index 0000000..d03f2fc --- /dev/null +++ b/res/module/em/help/jhelp/emIndex.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/res/module/em/help/jhelp/emMap.jhm b/res/module/em/help/jhelp/emMap.jhm new file mode 100644 index 0000000..81cb620 --- /dev/null +++ b/res/module/em/help/jhelp/emMap.jhm @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/em/help/jhelp/emTOC.xml b/res/module/em/help/jhelp/emTOC.xml new file mode 100644 index 0000000..7128b1f --- /dev/null +++ b/res/module/em/help/jhelp/emTOC.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/em/help/jhelp/em_help.hs b/res/module/em/help/jhelp/em_help.hs new file mode 100644 index 0000000..c86f4d2 --- /dev/null +++ b/res/module/em/help/jhelp/em_help.hs @@ -0,0 +1,60 @@ + + + + + + + Hilfe zum Modul zum EM-Algorithmus + + + + em + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + TOC + + javax.help.TOCView + emTOC.xml + + + + Index + + javax.help.IndexView + emIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/em/help/pics/3D.png b/res/module/em/help/pics/3D.png new file mode 100644 index 0000000..86a5d69 Binary files /dev/null and b/res/module/em/help/pics/3D.png differ diff --git a/res/module/em/help/pics/CVS/Entries b/res/module/em/help/pics/CVS/Entries new file mode 100644 index 0000000..c14c788 --- /dev/null +++ b/res/module/em/help/pics/CVS/Entries @@ -0,0 +1,26 @@ +/3D.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/beamerOff.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/beamerOn.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/clear.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/diagramm.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/eigene_partitionierung.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/haeufigkeiten.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/home.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/hybrid.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/hybrid_default.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/klasse_benennen.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/last.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/load.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/logo_help.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/next.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/objektangabe.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/oeffnen.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/partitionierung.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/presentation_mode.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/previous.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/run.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/save.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/speichern.png/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/start.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/tabelle.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/wahrscheinlichkeiten.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ diff --git a/res/module/em/help/pics/CVS/Repository b/res/module/em/help/pics/CVS/Repository new file mode 100644 index 0000000..b3399ef --- /dev/null +++ b/res/module/em/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/help/pics diff --git a/res/module/em/help/pics/CVS/Root b/res/module/em/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/help/pics/beamerOff.png b/res/module/em/help/pics/beamerOff.png new file mode 100644 index 0000000..5b59847 Binary files /dev/null and b/res/module/em/help/pics/beamerOff.png differ diff --git a/res/module/em/help/pics/beamerOn.png b/res/module/em/help/pics/beamerOn.png new file mode 100644 index 0000000..6ab41ee Binary files /dev/null and b/res/module/em/help/pics/beamerOn.png differ diff --git a/res/module/em/help/pics/clear.png b/res/module/em/help/pics/clear.png new file mode 100644 index 0000000..9c15c09 Binary files /dev/null and b/res/module/em/help/pics/clear.png differ diff --git a/res/module/em/help/pics/diagramm.png b/res/module/em/help/pics/diagramm.png new file mode 100644 index 0000000..0aa7177 Binary files /dev/null and b/res/module/em/help/pics/diagramm.png differ diff --git a/res/module/em/help/pics/eigene_partitionierung.png b/res/module/em/help/pics/eigene_partitionierung.png new file mode 100644 index 0000000..faedddb Binary files /dev/null and b/res/module/em/help/pics/eigene_partitionierung.png differ diff --git a/res/module/em/help/pics/haeufigkeiten.png b/res/module/em/help/pics/haeufigkeiten.png new file mode 100644 index 0000000..48d983c Binary files /dev/null and b/res/module/em/help/pics/haeufigkeiten.png differ diff --git a/res/module/em/help/pics/home.png b/res/module/em/help/pics/home.png new file mode 100644 index 0000000..9ea0675 Binary files /dev/null and b/res/module/em/help/pics/home.png differ diff --git a/res/module/em/help/pics/hybrid.png b/res/module/em/help/pics/hybrid.png new file mode 100644 index 0000000..bd9b990 Binary files /dev/null and b/res/module/em/help/pics/hybrid.png differ diff --git a/res/module/em/help/pics/hybrid_default.png b/res/module/em/help/pics/hybrid_default.png new file mode 100644 index 0000000..1e7c8b6 Binary files /dev/null and b/res/module/em/help/pics/hybrid_default.png differ diff --git a/res/module/em/help/pics/klasse_benennen.png b/res/module/em/help/pics/klasse_benennen.png new file mode 100644 index 0000000..43352fe Binary files /dev/null and b/res/module/em/help/pics/klasse_benennen.png differ diff --git a/res/module/em/help/pics/last.png b/res/module/em/help/pics/last.png new file mode 100644 index 0000000..6e904ef Binary files /dev/null and b/res/module/em/help/pics/last.png differ diff --git a/res/module/em/help/pics/load.png b/res/module/em/help/pics/load.png new file mode 100644 index 0000000..c2d72e6 Binary files /dev/null and b/res/module/em/help/pics/load.png differ diff --git a/res/module/em/help/pics/logo_help.png b/res/module/em/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/module/em/help/pics/logo_help.png differ diff --git a/res/module/em/help/pics/next.png b/res/module/em/help/pics/next.png new file mode 100644 index 0000000..6ef8de7 Binary files /dev/null and b/res/module/em/help/pics/next.png differ diff --git a/res/module/em/help/pics/objektangabe.png b/res/module/em/help/pics/objektangabe.png new file mode 100644 index 0000000..e0368dc Binary files /dev/null and b/res/module/em/help/pics/objektangabe.png differ diff --git a/res/module/em/help/pics/oeffnen.png b/res/module/em/help/pics/oeffnen.png new file mode 100644 index 0000000..9f4a8e5 Binary files /dev/null and b/res/module/em/help/pics/oeffnen.png differ diff --git a/res/module/em/help/pics/partitionierung.png b/res/module/em/help/pics/partitionierung.png new file mode 100644 index 0000000..128b4bc Binary files /dev/null and b/res/module/em/help/pics/partitionierung.png differ diff --git a/res/module/em/help/pics/presentation_mode.png b/res/module/em/help/pics/presentation_mode.png new file mode 100644 index 0000000..1179590 Binary files /dev/null and b/res/module/em/help/pics/presentation_mode.png differ diff --git a/res/module/em/help/pics/previous.png b/res/module/em/help/pics/previous.png new file mode 100644 index 0000000..659cd90 Binary files /dev/null and b/res/module/em/help/pics/previous.png differ diff --git a/res/module/em/help/pics/run.png b/res/module/em/help/pics/run.png new file mode 100644 index 0000000..feb13a9 Binary files /dev/null and b/res/module/em/help/pics/run.png differ diff --git a/res/module/em/help/pics/save.png b/res/module/em/help/pics/save.png new file mode 100644 index 0000000..c477790 Binary files /dev/null and b/res/module/em/help/pics/save.png differ diff --git a/res/module/em/help/pics/speichern.png b/res/module/em/help/pics/speichern.png new file mode 100644 index 0000000..777f66f Binary files /dev/null and b/res/module/em/help/pics/speichern.png differ diff --git a/res/module/em/help/pics/start.png b/res/module/em/help/pics/start.png new file mode 100644 index 0000000..f6cb36e Binary files /dev/null and b/res/module/em/help/pics/start.png differ diff --git a/res/module/em/help/pics/tabelle.png b/res/module/em/help/pics/tabelle.png new file mode 100644 index 0000000..5bf9e24 Binary files /dev/null and b/res/module/em/help/pics/tabelle.png differ diff --git a/res/module/em/help/pics/wahrscheinlichkeiten.png b/res/module/em/help/pics/wahrscheinlichkeiten.png new file mode 100644 index 0000000..afda6b0 Binary files /dev/null and b/res/module/em/help/pics/wahrscheinlichkeiten.png differ diff --git a/res/module/em/help/style.css b/res/module/em/help/style.css new file mode 100644 index 0000000..6236a76 --- /dev/null +++ b/res/module/em/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/em/last.png b/res/module/em/last.png new file mode 100644 index 0000000..6e904ef Binary files /dev/null and b/res/module/em/last.png differ diff --git a/res/module/em/next.png b/res/module/em/next.png new file mode 100644 index 0000000..6ef8de7 Binary files /dev/null and b/res/module/em/next.png differ diff --git a/res/module/em/pics/2.png b/res/module/em/pics/2.png new file mode 100644 index 0000000..75848da Binary files /dev/null and b/res/module/em/pics/2.png differ diff --git a/res/module/em/pics/6.png b/res/module/em/pics/6.png new file mode 100644 index 0000000..7e2a98f Binary files /dev/null and b/res/module/em/pics/6.png differ diff --git a/res/module/em/pics/CVS/Entries b/res/module/em/pics/CVS/Entries new file mode 100644 index 0000000..930e8be --- /dev/null +++ b/res/module/em/pics/CVS/Entries @@ -0,0 +1,24 @@ +/2.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/6.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/addCoin.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/addDice.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/addN.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/backFrame.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/beamerOff.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/beamerOn.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/fillUp.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/home.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/load.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/logo.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/logo_small.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/new.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/nextFrame.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/random.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/remove.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/run.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/save.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +D/small//// +/start.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/start_load.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/start_load_rollover.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/start_rollover.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ diff --git a/res/module/em/pics/CVS/Repository b/res/module/em/pics/CVS/Repository new file mode 100644 index 0000000..1b9d3da --- /dev/null +++ b/res/module/em/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/pics diff --git a/res/module/em/pics/CVS/Root b/res/module/em/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/pics/addCoin.png b/res/module/em/pics/addCoin.png new file mode 100644 index 0000000..9b13f06 Binary files /dev/null and b/res/module/em/pics/addCoin.png differ diff --git a/res/module/em/pics/addDice.png b/res/module/em/pics/addDice.png new file mode 100644 index 0000000..f349b1d Binary files /dev/null and b/res/module/em/pics/addDice.png differ diff --git a/res/module/em/pics/addN.png b/res/module/em/pics/addN.png new file mode 100644 index 0000000..f6db75a Binary files /dev/null and b/res/module/em/pics/addN.png differ diff --git a/res/module/em/pics/backFrame.png b/res/module/em/pics/backFrame.png new file mode 100644 index 0000000..8da04a3 Binary files /dev/null and b/res/module/em/pics/backFrame.png differ diff --git a/res/module/em/pics/beamerOff.png b/res/module/em/pics/beamerOff.png new file mode 100644 index 0000000..5b59847 Binary files /dev/null and b/res/module/em/pics/beamerOff.png differ diff --git a/res/module/em/pics/beamerOn.png b/res/module/em/pics/beamerOn.png new file mode 100644 index 0000000..6ab41ee Binary files /dev/null and b/res/module/em/pics/beamerOn.png differ diff --git a/res/module/em/pics/fillUp.png b/res/module/em/pics/fillUp.png new file mode 100644 index 0000000..24dcbee Binary files /dev/null and b/res/module/em/pics/fillUp.png differ diff --git a/res/module/em/pics/home.png b/res/module/em/pics/home.png new file mode 100644 index 0000000..9ea0675 Binary files /dev/null and b/res/module/em/pics/home.png differ diff --git a/res/module/em/pics/load.png b/res/module/em/pics/load.png new file mode 100644 index 0000000..c2d72e6 Binary files /dev/null and b/res/module/em/pics/load.png differ diff --git a/res/module/em/pics/logo.png b/res/module/em/pics/logo.png new file mode 100644 index 0000000..7e3bace Binary files /dev/null and b/res/module/em/pics/logo.png differ diff --git a/res/module/em/pics/logo_small.png b/res/module/em/pics/logo_small.png new file mode 100644 index 0000000..1de9da9 Binary files /dev/null and b/res/module/em/pics/logo_small.png differ diff --git a/res/module/em/pics/new.png b/res/module/em/pics/new.png new file mode 100644 index 0000000..dbb1e94 Binary files /dev/null and b/res/module/em/pics/new.png differ diff --git a/res/module/em/pics/nextFrame.png b/res/module/em/pics/nextFrame.png new file mode 100644 index 0000000..a814ae9 Binary files /dev/null and b/res/module/em/pics/nextFrame.png differ diff --git a/res/module/em/pics/random.png b/res/module/em/pics/random.png new file mode 100644 index 0000000..9593005 Binary files /dev/null and b/res/module/em/pics/random.png differ diff --git a/res/module/em/pics/remove.png b/res/module/em/pics/remove.png new file mode 100644 index 0000000..a223997 Binary files /dev/null and b/res/module/em/pics/remove.png differ diff --git a/res/module/em/pics/run.png b/res/module/em/pics/run.png new file mode 100644 index 0000000..feb13a9 Binary files /dev/null and b/res/module/em/pics/run.png differ diff --git a/res/module/em/pics/save.png b/res/module/em/pics/save.png new file mode 100644 index 0000000..c477790 Binary files /dev/null and b/res/module/em/pics/save.png differ diff --git a/res/module/em/pics/small/CVS/Entries b/res/module/em/pics/small/CVS/Entries new file mode 100644 index 0000000..d922b27 --- /dev/null +++ b/res/module/em/pics/small/CVS/Entries @@ -0,0 +1,9 @@ +/addCoin.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/addDice.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/addN.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/backFrame.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/fillUp.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/new.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/nextFrame.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/random.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ +/remove.png/1.1/Mon Jan 30 18:56:51 2012/-kb/ diff --git a/res/module/em/pics/small/CVS/Repository b/res/module/em/pics/small/CVS/Repository new file mode 100644 index 0000000..9c5d0d3 --- /dev/null +++ b/res/module/em/pics/small/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/em/pics/small diff --git a/res/module/em/pics/small/CVS/Root b/res/module/em/pics/small/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/em/pics/small/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/em/pics/small/addCoin.png b/res/module/em/pics/small/addCoin.png new file mode 100644 index 0000000..7735733 Binary files /dev/null and b/res/module/em/pics/small/addCoin.png differ diff --git a/res/module/em/pics/small/addDice.png b/res/module/em/pics/small/addDice.png new file mode 100644 index 0000000..a7e2e5b Binary files /dev/null and b/res/module/em/pics/small/addDice.png differ diff --git a/res/module/em/pics/small/addN.png b/res/module/em/pics/small/addN.png new file mode 100644 index 0000000..3bf3c59 Binary files /dev/null and b/res/module/em/pics/small/addN.png differ diff --git a/res/module/em/pics/small/backFrame.png b/res/module/em/pics/small/backFrame.png new file mode 100644 index 0000000..df0ab1f Binary files /dev/null and b/res/module/em/pics/small/backFrame.png differ diff --git a/res/module/em/pics/small/fillUp.png b/res/module/em/pics/small/fillUp.png new file mode 100644 index 0000000..2e1246f Binary files /dev/null and b/res/module/em/pics/small/fillUp.png differ diff --git a/res/module/em/pics/small/new.png b/res/module/em/pics/small/new.png new file mode 100644 index 0000000..3e5e93c Binary files /dev/null and b/res/module/em/pics/small/new.png differ diff --git a/res/module/em/pics/small/nextFrame.png b/res/module/em/pics/small/nextFrame.png new file mode 100644 index 0000000..3230f6c Binary files /dev/null and b/res/module/em/pics/small/nextFrame.png differ diff --git a/res/module/em/pics/small/random.png b/res/module/em/pics/small/random.png new file mode 100644 index 0000000..32618b4 Binary files /dev/null and b/res/module/em/pics/small/random.png differ diff --git a/res/module/em/pics/small/remove.png b/res/module/em/pics/small/remove.png new file mode 100644 index 0000000..b87b339 Binary files /dev/null and b/res/module/em/pics/small/remove.png differ diff --git a/res/module/em/pics/start.png b/res/module/em/pics/start.png new file mode 100644 index 0000000..764c5e0 Binary files /dev/null and b/res/module/em/pics/start.png differ diff --git a/res/module/em/pics/start_load.png b/res/module/em/pics/start_load.png new file mode 100644 index 0000000..0daaae6 Binary files /dev/null and b/res/module/em/pics/start_load.png differ diff --git a/res/module/em/pics/start_load_rollover.png b/res/module/em/pics/start_load_rollover.png new file mode 100644 index 0000000..98bba57 Binary files /dev/null and b/res/module/em/pics/start_load_rollover.png differ diff --git a/res/module/em/pics/start_rollover.png b/res/module/em/pics/start_rollover.png new file mode 100644 index 0000000..c2897b1 Binary files /dev/null and b/res/module/em/pics/start_rollover.png differ diff --git a/res/module/em/previous.png b/res/module/em/previous.png new file mode 100644 index 0000000..659cd90 Binary files /dev/null and b/res/module/em/previous.png differ diff --git a/res/module/heapsort/CVS/Entries b/res/module/heapsort/CVS/Entries new file mode 100644 index 0000000..075c9e3 --- /dev/null +++ b/res/module/heapsort/CVS/Entries @@ -0,0 +1,2 @@ +D/heapsort_pix//// +D/help//// diff --git a/res/module/heapsort/CVS/Repository b/res/module/heapsort/CVS/Repository new file mode 100644 index 0000000..cc41457 --- /dev/null +++ b/res/module/heapsort/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort diff --git a/res/module/heapsort/CVS/Root b/res/module/heapsort/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/heapsort_pix/CVS/Entries b/res/module/heapsort/heapsort_pix/CVS/Entries new file mode 100644 index 0000000..c8975bd --- /dev/null +++ b/res/module/heapsort/heapsort_pix/CVS/Entries @@ -0,0 +1,2 @@ +/logo.gif/1.1/Mon Jan 28 17:39:15 2008/-kb/ +/suspend.gif/1.1/Mon Jan 28 17:39:15 2008/-kb/ diff --git a/res/module/heapsort/heapsort_pix/CVS/Repository b/res/module/heapsort/heapsort_pix/CVS/Repository new file mode 100644 index 0000000..e42729a --- /dev/null +++ b/res/module/heapsort/heapsort_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort/heapsort_pix diff --git a/res/module/heapsort/heapsort_pix/CVS/Root b/res/module/heapsort/heapsort_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/heapsort_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/heapsort_pix/logo.gif b/res/module/heapsort/heapsort_pix/logo.gif new file mode 100644 index 0000000..3e29b44 Binary files /dev/null and b/res/module/heapsort/heapsort_pix/logo.gif differ diff --git a/res/module/heapsort/heapsort_pix/suspend.gif b/res/module/heapsort/heapsort_pix/suspend.gif new file mode 100644 index 0000000..ecb9710 Binary files /dev/null and b/res/module/heapsort/heapsort_pix/suspend.gif differ diff --git a/res/module/heapsort/help/CVS/Entries b/res/module/heapsort/help/CVS/Entries new file mode 100644 index 0000000..91a3eb9 --- /dev/null +++ b/res/module/heapsort/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Wed Jan 30 14:32:18 2008/-kb/ diff --git a/res/module/heapsort/help/CVS/Repository b/res/module/heapsort/help/CVS/Repository new file mode 100644 index 0000000..cb8669b --- /dev/null +++ b/res/module/heapsort/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort/help diff --git a/res/module/heapsort/help/CVS/Root b/res/module/heapsort/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/help/html/CVS/Entries b/res/module/heapsort/help/html/CVS/Entries new file mode 100644 index 0000000..f0b49c9 --- /dev/null +++ b/res/module/heapsort/help/html/CVS/Entries @@ -0,0 +1 @@ +/overview.htm/1.1/Wed Jan 30 14:32:17 2008// diff --git a/res/module/heapsort/help/html/CVS/Repository b/res/module/heapsort/help/html/CVS/Repository new file mode 100644 index 0000000..397cdfa --- /dev/null +++ b/res/module/heapsort/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort/help/html diff --git a/res/module/heapsort/help/html/CVS/Root b/res/module/heapsort/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/help/html/overview.htm b/res/module/heapsort/help/html/overview.htm new file mode 100644 index 0000000..f2a7fb2 --- /dev/null +++ b/res/module/heapsort/help/html/overview.htm @@ -0,0 +1,60 @@ + + + Hilfe zum Modul Heapsort + + + + + + +

        j-Algo-Modul Heapsort

        + +

        Einführung

        + +

        Dieses Modul verbildlicht den Ablauf des Sortieralgorithmus Heapsort, wie er in der Vorlesung Algorithmen und Datenstrukturen von Prof. Heiko Vogler an der TU Dresden vorgestellt wird. Dafür können bis zu 31 paarweise verschiedene natürliche Zahlen von 1 bis 99 eingegeben werden, die die zu sortierende Eingabefolge bilden. Danach ist es möglich, den Algorithmus schrittweise ablaufen zu lassen, wobei unterschieden wird zwischen dem Vorlesungsmodus und dem Selbststudium.

        + +

        Im Folgenden wird zunächst kurz der Algorithmus mit seiner Darstellung in diesem Modul vorgestellt, bevor die Bedienung des Moduls im Einzelnen erläutert wird.

        + + +

        Algorithmus

        + +

        Hinweis: Diese Erklärungen sind kurz gehalten. Im Zweifelsfall ist grundsätzlich das Vorlesungsskript heranzuziehen.

        + +

        Vorbereitungsphase

        + +

        Für die Beschreibung von Heapsort ist es vorteilhaft, sich die Eingabefolge als Binärbaum vorzustellen. Beginnend mit der Wurzel wird jede Ebene des Binärbaums von links nach rechts mit den verbleibenden Gliedern der Folge aufgefüllt. Dieser Prozeß wird von diesem Modul schrittweise animiert.

        + +

        Bild 1: Der Binärbaum zur Eingabefolge
        +

        + +

        Phase 1

        + +

        In der ersten Phase wird in dem Binärbaum die Heapeigenschaft hergestellt, die besagt, daß die Beschriftung eines Knotens nicht kleiner sein darf als die Beschriftung an den direkten Nachfolgern. Dies wird in der ersten Phase geprüft und gegebenenfalls korrigiert, indem Knotenbeschriftungen vertauscht werden.

        + +

        Man beginnt diesen Prozeß an der größten Position "li", die noch Nachfolger hat, und setzt ihn in Richtung Wurzel fort, bis man jene ebenfalls bearbeitet hat. Wenn die Heapeigenschaft an einem Knoten verletzt ist, wird die Knotenbeschriftung so lange sinkengelassen, bis alle Nachfolger (so vorhanden) mit einer kleineren Zahl beschriftet sind.

        + +

        In diesem Modul wird die aktuelle Position des Zeigers "li" durch einen horizontalen Pfeil dargestellt. Die aktuell betrachteten Knoten beim Sinkenlassen sind gelb hervorgehoben.

        + +

        Bild 2: Phase 1. Zu erkennen sind der Zeiger "li" und die hervorgehobenen Knoten.
        +

        + +

        Phase 2

        + +

        In der zweiten Phase gibt Heapsort die sortierte Folge aus. Dabei wird die Folge in einen unsortierten und einen sortierten Bereich geteilt, wobei am Anfang die gesamte Folge als unsortiert angesehen wird. Aufgrund der Heapeigenschaft befindet sich an der Wurzel des Baumes die größte Zahl. Diese wird mit der letzten Zahl im unsortierten Bereich vertauscht, wodurch die nun letzte Zahl vom unsortierten an den sortierten Bereich übergeht.

        + +

        Durch das Vertauschen wird in der Regel die Heapeigenschaft verletzt, so daß auf dem neuen Wurzelknoten die Funktion sinkenlassen aufgerufen wird. Dabei wird allerdings nur der unsortierte Bereich der Folge betrachtet. Diese Vorgehensweise wird wiederholt, bis nur noch der Wurzelknoten zum unsortierten Bereich gehört.

        + +

        Die beiden Bereiche werden durch den Zeiger "re" abgegrenzt, welcher die letzte Position im unsortierten Bereich angibt; die folgenden Positionen sind sortiert. Der sortierte Bereich wird in diesem Modul grau unterlegt dargestellt.

        + +

        Bild 3: Phase 2. Zu erkennen: Der grau unterlegte sortierte Bereich.
        +

        + +

        Vorgehensweise

        + +

        Nach dem Öffnen des Moduls befindet sich am rechten Rand des Fensters das Eingabefeld. Geben Sie die Zahlen der Eingabefolge eine nach der anderen ein und bestätigen Sie jeweils mit Enter. Wenn Sie fertig sind, können Sie durch Drücken von Enter im leeren Eingabefeld oder durch Betätigen des entsprechenden Knopfes den Algorithmus starten.

        + +

        Nun erscheinen in der Toolbar Buttons, die die Steuerung des Algorithmus ermöglichen. Dabei haben Sie die Wahl, einen Schritt vorwärts oder rückwärts zu gehen, einen Makroschritt vorwärts oder rückwärts zu gehen, ganz an den Anfang zurück zu kehren oder den gesamten Ablauf des Algorithmus animieren zu lassen. Makroschritte fassen Schritte zu logisch zusammenhängenden Einheiten zusammen.

        + +

        Wenn der Vorlesungsmodus deaktiviert ist, befindet sich am rechten Bildschirmrand eine Leiste, welche die Schritte des Sinkenlassens protokolliert.

        + + diff --git a/res/module/heapsort/help/jhelp/CVS/Entries b/res/module/heapsort/help/jhelp/CVS/Entries new file mode 100644 index 0000000..b323c0c --- /dev/null +++ b/res/module/heapsort/help/jhelp/CVS/Entries @@ -0,0 +1,4 @@ +/heapsortIndex.xml/1.1/Wed Jan 30 14:32:17 2008// +/heapsortTOC.xml/1.1/Wed Jan 30 14:32:17 2008// +/heapsort_help.hs/1.1/Wed Jan 30 14:32:17 2008/-kb/ +/map.jhm/1.1/Wed Jan 30 14:32:17 2008/-kb/ diff --git a/res/module/heapsort/help/jhelp/CVS/Repository b/res/module/heapsort/help/jhelp/CVS/Repository new file mode 100644 index 0000000..d6f19c2 --- /dev/null +++ b/res/module/heapsort/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort/help/jhelp diff --git a/res/module/heapsort/help/jhelp/CVS/Root b/res/module/heapsort/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/help/jhelp/heapsortIndex.xml b/res/module/heapsort/help/jhelp/heapsortIndex.xml new file mode 100644 index 0000000..133e7cc --- /dev/null +++ b/res/module/heapsort/help/jhelp/heapsortIndex.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + diff --git a/res/module/heapsort/help/jhelp/heapsortTOC.xml b/res/module/heapsort/help/jhelp/heapsortTOC.xml new file mode 100644 index 0000000..378bbd5 --- /dev/null +++ b/res/module/heapsort/help/jhelp/heapsortTOC.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/res/module/heapsort/help/jhelp/heapsort_help.hs b/res/module/heapsort/help/jhelp/heapsort_help.hs new file mode 100644 index 0000000..dbcd7ed --- /dev/null +++ b/res/module/heapsort/help/jhelp/heapsort_help.hs @@ -0,0 +1,66 @@ + + + + + + + + Hilfe zum Modul Heapsort + + + + + heapsort + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + heapsortTOC.xml + + + + Index + + javax.help.IndexView + heapsortIndex.xml + + + + + diff --git a/res/module/heapsort/help/jhelp/map.jhm b/res/module/heapsort/help/jhelp/map.jhm new file mode 100644 index 0000000..237b7a5 --- /dev/null +++ b/res/module/heapsort/help/jhelp/map.jhm @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/res/module/heapsort/help/pics/CVS/Entries b/res/module/heapsort/help/pics/CVS/Entries new file mode 100644 index 0000000..64426c0 --- /dev/null +++ b/res/module/heapsort/help/pics/CVS/Entries @@ -0,0 +1,3 @@ +/pic01.png/1.1/Wed Jan 30 14:32:17 2008/-kb/ +/pic02.png/1.1/Wed Jan 30 14:32:17 2008/-kb/ +/pic03.png/1.1/Wed Jan 30 14:32:17 2008/-kb/ diff --git a/res/module/heapsort/help/pics/CVS/Repository b/res/module/heapsort/help/pics/CVS/Repository new file mode 100644 index 0000000..f1decef --- /dev/null +++ b/res/module/heapsort/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/heapsort/help/pics diff --git a/res/module/heapsort/help/pics/CVS/Root b/res/module/heapsort/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/heapsort/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/heapsort/help/pics/pic01.png b/res/module/heapsort/help/pics/pic01.png new file mode 100644 index 0000000..d3bba49 Binary files /dev/null and b/res/module/heapsort/help/pics/pic01.png differ diff --git a/res/module/heapsort/help/pics/pic02.png b/res/module/heapsort/help/pics/pic02.png new file mode 100644 index 0000000..dece2db Binary files /dev/null and b/res/module/heapsort/help/pics/pic02.png differ diff --git a/res/module/heapsort/help/pics/pic03.png b/res/module/heapsort/help/pics/pic03.png new file mode 100644 index 0000000..217cab6 Binary files /dev/null and b/res/module/heapsort/help/pics/pic03.png differ diff --git a/res/module/heapsort/help/style.css b/res/module/heapsort/help/style.css new file mode 100644 index 0000000..4a7d5dd --- /dev/null +++ b/res/module/heapsort/help/style.css @@ -0,0 +1,41 @@ +body { + font-size:12pt; + /*font-family:arial,sans-serif;*/ + margin-left:5; + margin-right:5; + color:black; +} + +p { + font-size:small; + font-weight:normal; + margin-top:10; + margin-bottom:10; +} + +h1 { + font-size:x-large; + /*font-family:times new roman, serif*/ + font-family:arial,sans-serif; + font-weight:bold; + margin-top:20; + margin-bottom:15; +} + +h2 { + font-size:large; + font-family:arial,sans-serif; + font-weight:bold; + margin-top:20; + margin-bottom:15; +} + + +h3 { + font-size:medium; + font-family:arial,sans-serif; + font-weight:bold; + margin-top:15; + margin-bottom:10; +} + diff --git a/res/module/hoare/CVS/Entries b/res/module/hoare/CVS/Entries new file mode 100644 index 0000000..eae2217 --- /dev/null +++ b/res/module/hoare/CVS/Entries @@ -0,0 +1,5 @@ +D/help//// +/hoare.prefs/1.1/Wed Aug 27 13:00:57 2008// +D/hoare_font//// +D/hoare_pix//// +D/hoare_res//// diff --git a/res/module/hoare/CVS/Repository b/res/module/hoare/CVS/Repository new file mode 100644 index 0000000..2164207 --- /dev/null +++ b/res/module/hoare/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare diff --git a/res/module/hoare/CVS/Root b/res/module/hoare/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/CVS/Entries b/res/module/hoare/help/CVS/Entries new file mode 100644 index 0000000..0973316 --- /dev/null +++ b/res/module/hoare/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Mon Jan 14 22:16:25 2008/-kb/ diff --git a/res/module/hoare/help/CVS/Repository b/res/module/hoare/help/CVS/Repository new file mode 100644 index 0000000..f5e7915 --- /dev/null +++ b/res/module/hoare/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help diff --git a/res/module/hoare/help/CVS/Root b/res/module/hoare/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/html/CVS/Entries b/res/module/hoare/help/html/CVS/Entries new file mode 100644 index 0000000..046e7d2 --- /dev/null +++ b/res/module/hoare/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.2/Wed Aug 27 13:02:56 2008// +D/data//// +/index.htm/1.1/Mon Jan 14 22:16:24 2008// +/top_frame.htm/1.1/Mon Jan 14 22:16:24 2008// diff --git a/res/module/hoare/help/html/CVS/Repository b/res/module/hoare/help/html/CVS/Repository new file mode 100644 index 0000000..61962ca --- /dev/null +++ b/res/module/hoare/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help/html diff --git a/res/module/hoare/help/html/CVS/Root b/res/module/hoare/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/html/contents.htm b/res/module/hoare/help/html/contents.htm new file mode 100644 index 0000000..98eaef9 --- /dev/null +++ b/res/module/hoare/help/html/contents.htm @@ -0,0 +1,79 @@ + + + Inhaltsverzeichnis + + + +
          +

          Das Modul Hoare

          + + + +
      + + + diff --git a/res/module/hoare/help/html/data/CVS/Entries b/res/module/hoare/help/html/data/CVS/Entries new file mode 100644 index 0000000..059c3c7 --- /dev/null +++ b/res/module/hoare/help/html/data/CVS/Entries @@ -0,0 +1,6 @@ +/aufbau.htm/1.1/Wed Aug 27 13:02:38 2008// +/formula_editor.htm/1.1/Wed Aug 27 13:02:40 2008// +/overview.htm/1.2/Wed Aug 27 13:02:38 2008// +/screen.htm/1.2/Wed Aug 27 13:02:37 2008// +/sourcecode_editor.htm/1.1/Wed Aug 27 13:02:39 2008// +/usage.htm/1.1/Wed Aug 27 13:02:40 2008// diff --git a/res/module/hoare/help/html/data/CVS/Repository b/res/module/hoare/help/html/data/CVS/Repository new file mode 100644 index 0000000..d6a231f --- /dev/null +++ b/res/module/hoare/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help/html/data diff --git a/res/module/hoare/help/html/data/CVS/Root b/res/module/hoare/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/html/data/aufbau.htm b/res/module/hoare/help/html/data/aufbau.htm new file mode 100644 index 0000000..3267f00 --- /dev/null +++ b/res/module/hoare/help/html/data/aufbau.htm @@ -0,0 +1,38 @@ + + + Aufbau + + + +

      Aufbau des Beweisbaums

      +

      Kanten und normale Knoten

      +

      Knoten

      + Knoten +

      Ein normaler Knoten zeigt einen Ausschnitt des Quelltexts, der zu diesem Knoten gehört und davor den Variablennamen der Vor- und dahinter den der Nachbedingung.

      +

      aufgeklappter Knoten

      + aufgeklappter Knoten +

      Aufgeklappt zeigt ein Knoten den vollen zum Knoten gehörenden Quelltext und den Inhalt der Vor- und Nachbedingungsvariablen oder nur den Variablennamen, wenn die Variable noch nicht gefüllt ist. Die Vorbedingung ist grün und oberhalb des Quelltexts dargestellt, während die Nachbedingung unterhalb des Quelltexts und rot ist.

      +

      Kanten

      + Knoten mit Kanten +

      An den Kanten steht eine Abkürzung der Regel, die angewendet wurde. Außerdem sieht man durch sie, welcher Knoten sich aus welchen anderen Knoten ergibt.

      +

      Implikationsknoten

      + Implikationsknoten +

      Wie man schon daran sieht, dass sie eckig sind, sind Implikationsknoten etwas besonderes.
      + Besonders an ihnen ist, dass die darin dargestellte Implikation bei Änderung der Vor- oder Nachbedingung evaluiert, d.h. auf Gültigkeit geprüft wird. + Während der Überprüfung wird der Knoten gelb gefärbt, was bei komplexen Berechnungen und vielen Variablen etwas länger dauern kann. +

      + +

      Farbgebung

      +

      + Die Knoten im Baum können vier Farben annehmen: + + + + + + +
      FarbeBedeutung
      rotDer Knoten muss noch bearbeitet werden. Es fehlt entweder noch Vor- oder Nachbedingung oder es muss noch eine Regel angewendet werden
      Zusätzlich werden Implikationsknoten und Zuweisungsknoten rot, wenn die Implikation falsch ist/die Zuweisung nicht stimmt. Als weiterer Spezialfall wird ein Iterationsknoten rot, wenn die Nachbedingung nicht von der Form P∧¬Π ist.
      grauDer Knoten muss nicht mehr bearbeitet werden, aber weiter oben im Baum sind noch rote Knoten.
      grünDer Knoten und alle im Baum darüberliegenden müssen nicht mehr bearbeitet werden.
      gelbDer Knoten wird gerade evaluiert. Nur bei Implikationsknoten vorhanden.
      +

      + + + diff --git a/res/module/hoare/help/html/data/formula_editor.htm b/res/module/hoare/help/html/data/formula_editor.htm new file mode 100644 index 0000000..a456f30 --- /dev/null +++ b/res/module/hoare/help/html/data/formula_editor.htm @@ -0,0 +1,52 @@ + + + Editoren + + + + + +

      Formeleditor

      +

      +Im Formeleditor kann der Wert einer Variable geändert werden. +

      +

      Formeleditor

      +

      +Die Formel wird im Textfeld in der Mitte bearbeitet, wobei Sonderzeichen und +speziellen Funktionen durch festgelegte Kodierungen eingegeben werden. +Durch einen Klick auf die entsprechende Schaltfläche in der oberen Leiste wird die Kodierung +automatisch eingefügt.
      +Mit Klick auf die Schaltfläche "OK" rechts unten wird die eingegebene Formel als neuer Wert +für die Variable übernommen.
      +Achtung: Schließt man den Formeleditor ohne Klick auf den "OK"-Button, so werden die Änderungen +an der Variable verworfen.

      +

      +Unter dem Textfeld ist eine Vorschau, die angezeigt, wie die Formel später in der Variablenliste und im +Baum aussehen wird.
      +Ist der im Textfeld eingegebene Text keine zulässige Formel, wird der Hintergrund der +Vorschau rot und der "OK"-Button kann nicht geklickt werden, das heißt der neue Wert kann +nicht übernommen werden.

      + +

      Bemerkung zur Klammernsetzung: In der Vorschau werden manchmal eingegebene Klammern, die überflüssig sind, nicht +angezeigt. Die Klammerung ist dann implizit durch die Priorität der Operatoren bzw. Funktionen +gegeben.

      + +

      Kodierungen der Sonderzeichen

      +

      Kursiver Text steht für Argumente, die an dieser Stelle eingetragen werden.

      + + + + + + + + + + + + + +
      SonderzeichenKodierung
      ∧ (logisches und)&&
      ∨ (logisches oder)||
      ¬ (logisches nicht)!
      ≤ (kleiner gleich)<=
      ≥ (größer gleich)>=
      ≠ (ungleich)!=
      Σ (Summe)Sum(expr, var, start, end)
      Π (Produkt)Product(expr, var, start, end)
      exp (Exponentialfunktion)exp(x)
      ln (natürlicher Logarithmus)ln(x)
      √ (Quadratwurzel)sqrt(x)
      + + + diff --git a/res/module/hoare/help/html/data/overview.htm b/res/module/hoare/help/html/data/overview.htm new file mode 100644 index 0000000..fe210ea --- /dev/null +++ b/res/module/hoare/help/html/data/overview.htm @@ -0,0 +1,38 @@ + + + Einleitung + + + + +

      Das Modul Hoare-Kalkül

      + +

      Einleitung

      + +

      Dieses Modul verbildlicht den Ablauf des Hoare-Kalküls von + C. A. R. Hoare, mit dem es möglich ist, Eigenschaften imperativer + Computerprogramme mittels logischer Regeln zu beweisen.
      + Der Kalkül orientiert sich dabei an der Vorlesung + Programmierung, die von Prof. Heiko Vogler + an der TU Dresden gehalten wird. Überdies sind im Internet + zahlreiche Beschreibungen des Kalküls zu finden, so auch in der freien + Enzyklopädie Wikipedia.

      + + +

      Funktionsübersicht

      + +

      Das Modul Hoare-Kalkül realisiert folgende Funktionen: +

    • Parsen eines C0-Quelltextes
    • +
    • Auswahl von Knoten und Anwendung erlaubter Regeln darauf
    • +
    • variable Zusicherungen, die auch nach Regelanwendung noch verändert werden dürfen
    • +
    • automatisches Überprüfen der eingegebenen Implikationen durch beschränktes Testen
    • +
    • Löschen von Teilbäumen (auch einzelner Knoten)
    • +
    • Rückgängig machen/Wiederherstellen von Bearbeitungsschritten
    • +
    • grafische Darstellung des Beweisbaumes
    • +
    • Zoomen im Beweisbaum
    • +
    • Hervorhebung des aktuellen Bereiches im Quelltext und der Zusicherungen des aktuellen Knotens
    • +
    • Speichern und Laden von Beweisbäumen
    • +

      + + + diff --git a/res/module/hoare/help/html/data/screen.htm b/res/module/hoare/help/html/data/screen.htm new file mode 100644 index 0000000..d3c985c --- /dev/null +++ b/res/module/hoare/help/html/data/screen.htm @@ -0,0 +1,70 @@ + + + Die Arbeitsfläche + + +

      Der Arbeitsbereich

      + +

      Der Startbildschrim

      +
        der Startbildschrim +

        +
          + + + + +
          open c0Hiermit öffnet man ein neues c0 Programm, welches direkt mit dem ersten Knoten initialisiert wird.
          new c0Hiermit öffnet man den Arbeitsbildschirm und kann dort ein neues c0 Programm eingeben.
          openHiermit öffnet man eine .jalgo Datei, welche initialisiert wird.
          +
        +
      +
      +

      Anzeigeoptionen in der Toolbar

      +
        der Startbildschrim +

        +
          + + + + + + + + + + + + + + + +
          neu neues Modul öffnen
          öffnen jalgo Datei laden
          speichern jalgo Datei speichern
          speichern als jalgo Datei speichern als
          rückgängig Letzten Vorgang rückgängig machen
          wiederholen rückgängig gemachte Vorgänge wiederholen
          neu initialisieren Hoare Modul neu initialisieren
          c0 laden c0 Programm laden
          teilbaum löschen Teilbaum löschen
          zoom zurücksetzen Zoomwert auf Standart Wert zurücksetzen
          vergrößern Graph Ansicht vergrößern (mit Punktwahl)
          verkleinern Graph Ansicht verkleinern (mit Punktwahl)
          zoom Modus verlassen Zoom Modus nach Vergrößern/Verkleinern wieder verlassen
          seitenleiste wegklappen den Graph alleine zeigen, bzw. Seitenmenüs wieder einblenden
          +
        +
      +
      +

      Anzeigeoptionen in des Menüs

      +
        der Startbildschrim +

        +
          + + + + + + +
          neu initialisieren Hoare Modul neu initialisieren
          c0 laden c0 Programm laden
          rückgängig Letzten Vorgang rückgängig machen
          wiederholen rückgängig gemachte Vorgänge wiederholen
          wiederholen In den Beamer Modus schalten (Schrift und Ansichtselemente werden größer, um das Programm auf einem Beamer zu verwenden)
          +
        +
      +
      +

      Tastenkombinationen

      +
        +
          + + + + + + +
          Entfernen (ENTF)bei selektierter Zelle, Teilbaum löschen
          Backspace (‹--)bei selektierter Zelle, Teilbaum löschen
          Alt + Mausradschneller Zoom des Graphes in beide Richtungen
          Steuerung(Strg/Ctrl) + EnterOK Button im Formeleditor
          rechter Mausklick im Zoom ModusZoom Modus nach Vergrößern/Verkleinern wieder verlassen
          +
        +
      + + diff --git a/res/module/hoare/help/html/data/sourcecode_editor.htm b/res/module/hoare/help/html/data/sourcecode_editor.htm new file mode 100644 index 0000000..03c51ab --- /dev/null +++ b/res/module/hoare/help/html/data/sourcecode_editor.htm @@ -0,0 +1,26 @@ + + + Editoren + + + + + +

      Quelltexteditor

      +

      +Im Quelltexteditor hat man die Möglichkeit einen Quelltext einzugeben oder den aktuellen Quelltext zu bearbeiten. +

      +

      +Quelltexteditor +Wenn ein Quelltext geparst wurde, wird der Quelltexteditor gesperrt, da eine Veränderung und das neue Parsen den aktuellen Fortschritt des Beweises löscht. Er kann aber wieder über den Button "Bearbeiten" zum Bearbeiten freigeschaltet werden. Die Änderung kann über den Button "Wiederherstellen" rückgängig gemacht werden.
      +Außerdem wird bei markierter Zelle im Beweisbaum, der zugehörige Quelltext im Quelltexteditor markiert dargestellt.

      +

      +Er beinhaltet drei Buttons: + + + + +
      ParsenParst den aktuellen Quelltext und generiert den neuen Wurzelknoten des Beweisbaums. Dabei wird der aktuelle Fortschritt gelöscht.
      BearbeitenSchaltet den Quelltexteditor zum Bearbeiten frei.
      WiederherstellenStellt den Zustand des Quelltexts vor dem Bearbeiten wieder her.
      +

      + + diff --git a/res/module/hoare/help/html/data/usage.htm b/res/module/hoare/help/html/data/usage.htm new file mode 100644 index 0000000..1c08b95 --- /dev/null +++ b/res/module/hoare/help/html/data/usage.htm @@ -0,0 +1,135 @@ + + + Algorithmussteuerung + + + +

      Erstellen eines Beweisbaums

      + +

      Anhand des folgenden Beispiels soll betrachtet werden, wie mit dem Modul ein Beweisbaum für ein +C0-Programm erstellt werden kann:

      + +

      +while (x>0) x=x-1; +

      + +

      Dieses Programm zählt einfach nur x auf 0 herunter, falls vor der Ausführung x>0.

      + +

      Der fertige Beweisbaum für dieses Beispiel ist auch unter dem Ordner examples vorhanden.

      + +

      Quelltext laden/eingeben und parsen

      +

      Um den Quelltext eines Programms aus einer Datei zu laden, hat man die Möglichkeit + über die Toolbar, über das Menü + oder über den Startbildschirm zu gehen. Es erscheint jeweils ein + Dateiauswahldialog, in dem man die zu ladende Datei, die den Quelltext enthält, auswählen kann.
      +Der Quelltext wird dann auch gleich geparst.

      +

      Weiterhin hat man die Möglichkeit über den Quelltexteditor einen + Quelltext einzugeben und mit dem Druck auf den Button "Parsen", diesen auszuwerten und den Wurzelknoten + des Beweisbaums anzuzeigen.

      + +

         C0-Programm im Quelltexteditor eingeben und auf Parsen klicken +   +geparsetes C0-Programm

      + +

      Regel anwenden

      +

      Der Beweisbaum besteht besteht nach dem Parsen zunächst nur aus einem Knoten.

      +

         Wurzelknoten

      +

      Um eine Regel auf einen Knoten anzuwenden, muss man ihn zunächst durch +einen Klick auswählen. Der Knoten bekommt dann einen farbigen Rahmen. +

      +

         ausgewählter Wurzelknoten

      +

      +Danach klickt man auf der Liste rechts neben dem Graphen auf die gewünschte +Regel.

      +

         Iteration anklicken

      +

      +Bei erfolgreicher Anwendung werden dann im Baum für den ausgewählten Knoten je nach Regel +ein oder zwei neue Knoten erstellt. Bei manchen Regeln wird außerdem eine +zusätzliche Variable erstellt, siehe auch Vor- und Nachbedingungen +eingeben.

      +

         Schwächere Nachbedingung angewendet

      +

      +Kommt es zu einem Fehler, z.B. weil schon eine Regel angewendet wurde, oder die +Regel nicht anwendbar ist, dann passiert nichts und es erscheint eine entsprechende +Fehlermeldung in dem Feld rechts oben.

      +

         Beispiel für Fehlermeldung

      +

      +Eine Vorschau für die Regeln wird automatisch angezeigt, wenn man mit der Maus +über der jeweiligen Schaltfläche ist. Für die Iterationsregel, die auf eine while-Schleife +angewendet werden muss, sieht sie z. B. so aus:

      +

      +

         Vorschau der Iterationsregel

      +

      Weitere Informationen: Aufbau eines Beweisbaums

      +

      Vor- und Nachbedingungen eingeben

      +

      Zu jedem Knoten gehört eine Vor- und eine Nachbedingung.
      +Diese besteht entweder nur aus einer Variablen (bezeichnet mit P, z.B. P1) oder aus der Konjunktion einer Variablen +mit einer oder mehreren Konstanten (bezeichnet mit Π, z.B. Π1).
      +Die Konstanten ergeben sich direkt aus vorherigen +Regelanwendungen und können im Gegensatz zu Variablen nicht geändert werden.
      +Siehe auch Aufbau eines Beweisbaumes.

      +

      + +

      Das Bearbeiten der Variable geschieht mit dem Formeleditor.
      +Es gibt verschiedene Möglichkeiten den Formeleditor für eine Variable zu öffnen: +

        +
      • Klick auf die Variable in der Variablenliste rechts +

           Klick auf P1 in der Variablenliste

        +
      • +
      • Klick auf die Variable bei den "Variablen Vor- und Nachbedingung" unter der Variablenliste, +falls der entsprechende Knoten ausgewählt wurde (*) +

           Klick auf P1 bei den Variablen der Vor- und Nachbedingung

        +
      • +
      • Zweifachen Klick auf einen Knoten, so dass er vergrößert dargestellt wird und dann Klick +auf die Variable +

           Klick auf P1 im vergrößerten Knoten

        +
      • +
      • Rechtsklick auf einen Knoten und dann Auswahl der Variable im Popupmenü +

           Klick auf P1 im Popupmenü

        +
      • +
      +

      + +

      * Ist ein Knoten durch einen Klick ausgewählt worden, so werden die beiden Variablen, die in +der Vor- bzw. Nachbedingung vorkommen unter der Variablenliste angezeigt und außerdem farblich +hervorgehoben.

      + +

      Beispielbeweisbaum

      + +

      Das Parsen des C0-Programms liefert uns den Wurzelknoten.

      +

         Wurzelknoten

      +

      Wir wollen beweisen, dass wenn vorher x≥0, dann ist nach dem Ausführung x=0. +Das heißt wir tragen mit dem Formeleditor für die Vorbedingung +P1 den Wert x≥0 und für die Nachbedingung P2 den Wert x=0 ein.

      +

         Wurzelknoten

      +

      Da der Quelltext im Knoten die Form while (Π) {...}, müssen wir für den Beweis die Iterationsregel +anwenden. Die Vorschau sagt uns, dass dafür die Nachbedingung von der Form P∧¬Π sein +muss, wobei P die Vorbedingung und gleichzeitig die Schleifeninvariante ist.

      +

         Vorschau der Iterationsregel

      +

      Für unseren Fall heißt das, die Nachbedingung muss den Wert x≥0∧¬x<0 haben. +Das erreichen wir mit Hilfe der Regel Schwächere Nachbedingung, die für die Nachbedingung eine neue Variable P3 einführt.

      +

         Anwendung der Regel Schwächere Nachbedingung

      +

      Der Wurzelknoten färbt sich jetzt grau, da an ihm nichts mehr getan werden muss.

      +

      Den Wert für P3 setzen wir jetzt auf den Wert x≥0∧¬x<0, den wir uns vorher überlegt haben.

      +

         Eingeben der neuen Nachbedingung

      +

      Da die Implikation P3=>P2, die bei der Regel Schwächere Nachbedingung überprüft werden muss wahr ist (aus x≥0∧¬x<0 folgt x=0), +färbt sich der Implikationsknoten grün. Wäre die Implikation nicht wahr, würde er sich rot färben +und P2 oder P3 müssten geändert werden, damit sie stimmt.

      +

      Vor- und Nachbedingung haben jetzt die richtige Form, so dass wir die Iterationsregel anwenden können.

      +

         Anwendung der Iterationsregel

      +

      Nun müssen wir den Teilbaum für den Schleifenrumpf erstellen. In unserem Fall besteht er nur +aus einer einfachen Zuweisung. Das heißt wir müssen das Zuweisungsaxiom anwenden. Wie die Vorschau zeigt, +muss dafür die Vorbedingung gleich der Nachbedingung sein, wobei jedes Vorkommen von x durch x-1 +erstetzt wird.

      +

         Vorschau des Zuweisungsaxioms

      +

      In unserem Beispiel muss also die Vorbedingung den Wert x-1≥0 haben. Das erreichen wir durch +die Anwendung der Regel Stärkere Vorbedingung, die es uns erlaubt die Vorbedingung zu ändern.

      +

         Anwendung der Regel Stärkere Vorbedingung

      +

      Für die neue Vorbedingung P4 geben wir x-1≥0 ein.

      +

         Eingeben der neuen Vorbedingung

      +

      Der Implikationsknoten färbt sich wieder grün, denn aus x>0 folgt x-1≥0.

      +

      Wir können jetzt das Zuweisungsaxiom anwenden.

      +

         Anwendung des Zuweisungsaxiom

      +

      Der Beweis ist vollständig und korrekt und der komplette Baum färbt sich grün.

      + + + diff --git a/res/module/hoare/help/html/index.htm b/res/module/hoare/help/html/index.htm new file mode 100644 index 0000000..9264b67 --- /dev/null +++ b/res/module/hoare/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum Hoare Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + diff --git a/res/module/hoare/help/html/top_frame.htm b/res/module/hoare/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/hoare/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/hoare/help/jhelp/CVS/Entries b/res/module/hoare/help/jhelp/CVS/Entries new file mode 100644 index 0000000..4fc755a --- /dev/null +++ b/res/module/hoare/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/hoareIndex.xml/1.2/Wed Aug 27 13:02:24 2008// +/hoareMap.jhm/1.2/Wed Aug 27 13:02:25 2008/-kb/ +/hoareTOC.xml/1.2/Wed Aug 27 13:02:25 2008// +/hoare_help.hs/1.2/Wed Aug 27 13:02:25 2008/-kb/ diff --git a/res/module/hoare/help/jhelp/CVS/Repository b/res/module/hoare/help/jhelp/CVS/Repository new file mode 100644 index 0000000..fb4943a --- /dev/null +++ b/res/module/hoare/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help/jhelp diff --git a/res/module/hoare/help/jhelp/CVS/Root b/res/module/hoare/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..7765d76 --- /dev/null +++ b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.2/Wed Aug 27 13:02:44 2008/-kb/ +/DOCS.TAB/1.2/Wed Aug 27 13:02:45 2008/-kb/ +/OFFSETS/1.2/Wed Aug 27 13:02:45 2008/-kb/ +/POSITIONS/1.2/Wed Aug 27 13:02:45 2008/-kb/ +/SCHEMA/1.2/Wed Aug 27 13:02:45 2008/-kb/ +/TMAP/1.2/Wed Aug 27 13:02:45 2008/-kb/ +/config.ini/1.1/Mon Jan 14 22:16:22 2008// diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..c4d244b --- /dev/null +++ b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help/jhelp/JavaHelpSearch diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS b/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..8ce5660 Binary files /dev/null and b/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..97d3c58 Binary files /dev/null and b/res/module/hoare/help/jhelp/JavaHelpSearch/DOCS.TAB differ diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/hoare/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..9590369 Binary files /dev/null and b/res/module/hoare/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/hoare/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..08d1486 Binary files /dev/null and b/res/module/hoare/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/hoare/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..836930f --- /dev/null +++ b/res/module/hoare/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=594 id2=1 diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/TMAP b/res/module/hoare/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..9c8eb02 Binary files /dev/null and b/res/module/hoare/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/hoare/help/jhelp/JavaHelpSearch/config.ini b/res/module/hoare/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/hoare/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/hoare/help/jhelp/hoareIndex.xml b/res/module/hoare/help/jhelp/hoareIndex.xml new file mode 100644 index 0000000..b5736ad --- /dev/null +++ b/res/module/hoare/help/jhelp/hoareIndex.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + diff --git a/res/module/hoare/help/jhelp/hoareMap.jhm b/res/module/hoare/help/jhelp/hoareMap.jhm new file mode 100644 index 0000000..2bb1f46 --- /dev/null +++ b/res/module/hoare/help/jhelp/hoareMap.jhm @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/hoare/help/jhelp/hoareTOC.xml b/res/module/hoare/help/jhelp/hoareTOC.xml new file mode 100644 index 0000000..d499508 --- /dev/null +++ b/res/module/hoare/help/jhelp/hoareTOC.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/hoare/help/jhelp/hoare_help.hs b/res/module/hoare/help/jhelp/hoare_help.hs new file mode 100644 index 0000000..a3f9fd6 --- /dev/null +++ b/res/module/hoare/help/jhelp/hoare_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Hoare-Modul + + + + + hoare + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + hoareTOC.xml + + + + Index + + javax.help.IndexView + hoareIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + diff --git a/res/module/hoare/help/pics/CNull.gif b/res/module/hoare/help/pics/CNull.gif new file mode 100644 index 0000000..87b684d Binary files /dev/null and b/res/module/hoare/help/pics/CNull.gif differ diff --git a/res/module/hoare/help/pics/CVS/Entries b/res/module/hoare/help/pics/CVS/Entries new file mode 100644 index 0000000..6fed191 --- /dev/null +++ b/res/module/hoare/help/pics/CVS/Entries @@ -0,0 +1,48 @@ +/CNull.gif/1.1/Wed Aug 27 13:01:14 2008/-kb/ +/Fehler bei Regelanwendung.png/1.1/Wed Aug 27 13:01:11 2008/-kb/ +/Formeleditor mit Inhalt.png/1.1/Wed Aug 27 13:01:00 2008/-kb/ +/Implication.jpg/1.1/Wed Aug 27 13:01:28 2008/-kb/ +/Iterationsregel-Vorschau mit Regeln mit Maus.png/1.1/Wed Aug 27 13:01:24 2008/-kb/ +/Iterationsregel-Vorschau.png/1.1/Wed Aug 27 13:01:18 2008/-kb/ +/Popupmenu mit Maus.png/1.1/Wed Aug 27 13:01:20 2008/-kb/ +/Quelltexteditor.jpg/1.1/Wed Aug 27 13:01:10 2008/-kb/ +/Quelltexteingabe mit Maus.png/1.1/Wed Aug 27 13:01:15 2008/-kb/ +/Quelltexteingabe2.png/1.1/Wed Aug 27 13:01:16 2008/-kb/ +/Regelbuttons (SN) mit Maus.png/1.1/Wed Aug 27 13:01:12 2008/-kb/ +/Startknoten gross mit Maus.png/1.1/Wed Aug 27 13:01:26 2008/-kb/ +/Startknoten mit Vor- und Nachbedingung gross.png/1.1/Wed Aug 27 13:01:27 2008/-kb/ +/Startknoten.png/1.1/Wed Aug 27 13:01:21 2008/-kb/ +/Variablen Vor- und Nachbedingung leer mit Maus.png/1.1/Wed Aug 27 13:01:29 2008/-kb/ +/Variablenliste leer mit Maus.png/1.1/Wed Aug 27 13:01:16 2008/-kb/ +/Zuweisungsaxiom angewendet Baum gr_n.png/1.1/Wed Aug 27 13:01:21 2008/-kb/ +/Zuweisungsaxiom-Vorschau.png/1.1/Wed Aug 27 13:01:00 2008/-kb/ +/ausgewaehlter Startknoten.png/1.1/Wed Aug 27 13:01:16 2008/-kb/ +/beamer.gif/1.1/Wed Aug 27 13:01:12 2008/-kb/ +/delnode.gif/1.1/Wed Aug 27 13:01:09 2008/-kb/ +/dritte Regelanwendung (SV) grosser Knoten Vorbedingung eingetragen.png/1.1/Wed Aug 27 13:01:20 2008/-kb/ +/dritte Regelanwendung (SV) grosser Knoten.png/1.1/Wed Aug 27 13:01:13 2008/-kb/ +/erste Regelanwendung (SN) grosser Knoten Nachbedingung eingetragen.png/1.1/Wed Aug 27 13:01:19 2008/-kb/ +/erste Regelanwendung (SN) grosser Knoten.png/1.1/Wed Aug 27 13:01:27 2008/-kb/ +/erste Regelanwendung (SN).png/1.1/Wed Aug 27 13:01:18 2008/-kb/ +/log.png/1.1/Mon Jan 14 22:16:22 2008/-kb/ +/logo.gif/1.2/Wed Aug 27 13:01:10 2008/-kb/ +/logo_help.png/1.1/Mon Jan 14 22:16:22 2008/-kb/ +/menu.gif/1.1/Wed Aug 27 13:01:02 2008/-kb/ +/new.gif/1.1/Wed Aug 27 13:01:19 2008/-kb/ +/new_welcome_0.gif/1.1/Wed Aug 27 13:01:26 2008/-kb/ +/normalMouse.gif/1.1/Wed Aug 27 13:01:29 2008/-kb/ +/open.gif/1.1/Wed Aug 27 13:01:14 2008/-kb/ +/open_welcome_0.gif/1.1/Wed Aug 27 13:01:26 2008/-kb/ +/openc0_welcome_0.gif/1.1/Wed Aug 27 13:01:26 2008/-kb/ +/redo.gif/1.1/Wed Aug 27 13:01:19 2008/-kb/ +/reinit.gif/1.1/Wed Aug 27 13:00:58 2008/-kb/ +/resetZoom.gif/1.1/Wed Aug 27 13:01:03 2008/-kb/ +/save.gif/1.1/Wed Aug 27 13:01:29 2008/-kb/ +/save_as.gif/1.1/Wed Aug 27 13:00:59 2008/-kb/ +/toggleSplitter.gif/1.1/Wed Aug 27 13:01:01 2008/-kb/ +/tool.gif/1.1/Wed Aug 27 13:01:21 2008/-kb/ +/undo.gif/1.1/Wed Aug 27 13:01:01 2008/-kb/ +/welcome.gif/1.1/Wed Aug 27 13:01:07 2008/-kb/ +/zoomIn.gif/1.1/Wed Aug 27 13:01:23 2008/-kb/ +/zoomOut.gif/1.1/Wed Aug 27 13:01:29 2008/-kb/ +/zweite Regelanwendung (Iter) Knoten gross.png/1.1/Wed Aug 27 13:01:18 2008/-kb/ diff --git a/res/module/hoare/help/pics/CVS/Repository b/res/module/hoare/help/pics/CVS/Repository new file mode 100644 index 0000000..4275dcd --- /dev/null +++ b/res/module/hoare/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/help/pics diff --git a/res/module/hoare/help/pics/CVS/Root b/res/module/hoare/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/help/pics/Fehler bei Regelanwendung.png b/res/module/hoare/help/pics/Fehler bei Regelanwendung.png new file mode 100644 index 0000000..1c226e5 Binary files /dev/null and b/res/module/hoare/help/pics/Fehler bei Regelanwendung.png differ diff --git a/res/module/hoare/help/pics/Formeleditor mit Inhalt.png b/res/module/hoare/help/pics/Formeleditor mit Inhalt.png new file mode 100644 index 0000000..0df1f62 Binary files /dev/null and b/res/module/hoare/help/pics/Formeleditor mit Inhalt.png differ diff --git a/res/module/hoare/help/pics/Implication.jpg b/res/module/hoare/help/pics/Implication.jpg new file mode 100644 index 0000000..5d5ba3b Binary files /dev/null and b/res/module/hoare/help/pics/Implication.jpg differ diff --git a/res/module/hoare/help/pics/Iterationsregel-Vorschau mit Regeln mit Maus.png b/res/module/hoare/help/pics/Iterationsregel-Vorschau mit Regeln mit Maus.png new file mode 100644 index 0000000..afa1dc0 Binary files /dev/null and b/res/module/hoare/help/pics/Iterationsregel-Vorschau mit Regeln mit Maus.png differ diff --git a/res/module/hoare/help/pics/Iterationsregel-Vorschau.png b/res/module/hoare/help/pics/Iterationsregel-Vorschau.png new file mode 100644 index 0000000..14e6c5e Binary files /dev/null and b/res/module/hoare/help/pics/Iterationsregel-Vorschau.png differ diff --git a/res/module/hoare/help/pics/Popupmenu mit Maus.png b/res/module/hoare/help/pics/Popupmenu mit Maus.png new file mode 100644 index 0000000..72691c8 Binary files /dev/null and b/res/module/hoare/help/pics/Popupmenu mit Maus.png differ diff --git a/res/module/hoare/help/pics/Quelltexteditor.jpg b/res/module/hoare/help/pics/Quelltexteditor.jpg new file mode 100644 index 0000000..68db61e Binary files /dev/null and b/res/module/hoare/help/pics/Quelltexteditor.jpg differ diff --git a/res/module/hoare/help/pics/Quelltexteingabe mit Maus.png b/res/module/hoare/help/pics/Quelltexteingabe mit Maus.png new file mode 100644 index 0000000..7fa8d8e Binary files /dev/null and b/res/module/hoare/help/pics/Quelltexteingabe mit Maus.png differ diff --git a/res/module/hoare/help/pics/Quelltexteingabe2.png b/res/module/hoare/help/pics/Quelltexteingabe2.png new file mode 100644 index 0000000..b5e7996 Binary files /dev/null and b/res/module/hoare/help/pics/Quelltexteingabe2.png differ diff --git a/res/module/hoare/help/pics/Regelbuttons (SN) mit Maus.png b/res/module/hoare/help/pics/Regelbuttons (SN) mit Maus.png new file mode 100644 index 0000000..668297a Binary files /dev/null and b/res/module/hoare/help/pics/Regelbuttons (SN) mit Maus.png differ diff --git a/res/module/hoare/help/pics/Startknoten gross mit Maus.png b/res/module/hoare/help/pics/Startknoten gross mit Maus.png new file mode 100644 index 0000000..77411a7 Binary files /dev/null and b/res/module/hoare/help/pics/Startknoten gross mit Maus.png differ diff --git a/res/module/hoare/help/pics/Startknoten mit Vor- und Nachbedingung gross.png b/res/module/hoare/help/pics/Startknoten mit Vor- und Nachbedingung gross.png new file mode 100644 index 0000000..0f60abc Binary files /dev/null and b/res/module/hoare/help/pics/Startknoten mit Vor- und Nachbedingung gross.png differ diff --git a/res/module/hoare/help/pics/Startknoten.png b/res/module/hoare/help/pics/Startknoten.png new file mode 100644 index 0000000..d8460c0 Binary files /dev/null and b/res/module/hoare/help/pics/Startknoten.png differ diff --git a/res/module/hoare/help/pics/Variablen Vor- und Nachbedingung leer mit Maus.png b/res/module/hoare/help/pics/Variablen Vor- und Nachbedingung leer mit Maus.png new file mode 100644 index 0000000..51bc06a Binary files /dev/null and b/res/module/hoare/help/pics/Variablen Vor- und Nachbedingung leer mit Maus.png differ diff --git a/res/module/hoare/help/pics/Variablenliste leer mit Maus.png b/res/module/hoare/help/pics/Variablenliste leer mit Maus.png new file mode 100644 index 0000000..fe5ca98 Binary files /dev/null and b/res/module/hoare/help/pics/Variablenliste leer mit Maus.png differ diff --git a/res/module/hoare/help/pics/Zuweisungsaxiom angewendet Baum gr_n.png b/res/module/hoare/help/pics/Zuweisungsaxiom angewendet Baum gr_n.png new file mode 100644 index 0000000..0a3472e Binary files /dev/null and b/res/module/hoare/help/pics/Zuweisungsaxiom angewendet Baum gr_n.png differ diff --git a/res/module/hoare/help/pics/Zuweisungsaxiom-Vorschau.png b/res/module/hoare/help/pics/Zuweisungsaxiom-Vorschau.png new file mode 100644 index 0000000..30bbcb5 Binary files /dev/null and b/res/module/hoare/help/pics/Zuweisungsaxiom-Vorschau.png differ diff --git a/res/module/hoare/help/pics/ausgewaehlter Startknoten.png b/res/module/hoare/help/pics/ausgewaehlter Startknoten.png new file mode 100644 index 0000000..1b3229a Binary files /dev/null and b/res/module/hoare/help/pics/ausgewaehlter Startknoten.png differ diff --git a/res/module/hoare/help/pics/beamer.gif b/res/module/hoare/help/pics/beamer.gif new file mode 100644 index 0000000..9507c3c Binary files /dev/null and b/res/module/hoare/help/pics/beamer.gif differ diff --git a/res/module/hoare/help/pics/delnode.gif b/res/module/hoare/help/pics/delnode.gif new file mode 100644 index 0000000..e116647 Binary files /dev/null and b/res/module/hoare/help/pics/delnode.gif differ diff --git a/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten Vorbedingung eingetragen.png b/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten Vorbedingung eingetragen.png new file mode 100644 index 0000000..b4b0028 Binary files /dev/null and b/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten Vorbedingung eingetragen.png differ diff --git a/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten.png b/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten.png new file mode 100644 index 0000000..ca7d55f Binary files /dev/null and b/res/module/hoare/help/pics/dritte Regelanwendung (SV) grosser Knoten.png differ diff --git a/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten Nachbedingung eingetragen.png b/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten Nachbedingung eingetragen.png new file mode 100644 index 0000000..81bfa9e Binary files /dev/null and b/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten Nachbedingung eingetragen.png differ diff --git a/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten.png b/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten.png new file mode 100644 index 0000000..684e57e Binary files /dev/null and b/res/module/hoare/help/pics/erste Regelanwendung (SN) grosser Knoten.png differ diff --git a/res/module/hoare/help/pics/erste Regelanwendung (SN).png b/res/module/hoare/help/pics/erste Regelanwendung (SN).png new file mode 100644 index 0000000..595e09a Binary files /dev/null and b/res/module/hoare/help/pics/erste Regelanwendung (SN).png differ diff --git a/res/module/hoare/help/pics/log.png b/res/module/hoare/help/pics/log.png new file mode 100644 index 0000000..02b9a54 Binary files /dev/null and b/res/module/hoare/help/pics/log.png differ diff --git a/res/module/hoare/help/pics/logo.gif b/res/module/hoare/help/pics/logo.gif new file mode 100644 index 0000000..be686a1 Binary files /dev/null and b/res/module/hoare/help/pics/logo.gif differ diff --git a/res/module/hoare/help/pics/logo_help.png b/res/module/hoare/help/pics/logo_help.png new file mode 100644 index 0000000..97560c8 Binary files /dev/null and b/res/module/hoare/help/pics/logo_help.png differ diff --git a/res/module/hoare/help/pics/menu.gif b/res/module/hoare/help/pics/menu.gif new file mode 100644 index 0000000..911a870 Binary files /dev/null and b/res/module/hoare/help/pics/menu.gif differ diff --git a/res/module/hoare/help/pics/new.gif b/res/module/hoare/help/pics/new.gif new file mode 100644 index 0000000..da98fca Binary files /dev/null and b/res/module/hoare/help/pics/new.gif differ diff --git a/res/module/hoare/help/pics/new_welcome_0.gif b/res/module/hoare/help/pics/new_welcome_0.gif new file mode 100644 index 0000000..e1db89a Binary files /dev/null and b/res/module/hoare/help/pics/new_welcome_0.gif differ diff --git a/res/module/hoare/help/pics/normalMouse.gif b/res/module/hoare/help/pics/normalMouse.gif new file mode 100644 index 0000000..5d4ad1b Binary files /dev/null and b/res/module/hoare/help/pics/normalMouse.gif differ diff --git a/res/module/hoare/help/pics/open.gif b/res/module/hoare/help/pics/open.gif new file mode 100644 index 0000000..daa1f0c Binary files /dev/null and b/res/module/hoare/help/pics/open.gif differ diff --git a/res/module/hoare/help/pics/open_welcome_0.gif b/res/module/hoare/help/pics/open_welcome_0.gif new file mode 100644 index 0000000..016aca4 Binary files /dev/null and b/res/module/hoare/help/pics/open_welcome_0.gif differ diff --git a/res/module/hoare/help/pics/openc0_welcome_0.gif b/res/module/hoare/help/pics/openc0_welcome_0.gif new file mode 100644 index 0000000..6c694c0 Binary files /dev/null and b/res/module/hoare/help/pics/openc0_welcome_0.gif differ diff --git a/res/module/hoare/help/pics/redo.gif b/res/module/hoare/help/pics/redo.gif new file mode 100644 index 0000000..6909058 Binary files /dev/null and b/res/module/hoare/help/pics/redo.gif differ diff --git a/res/module/hoare/help/pics/reinit.gif b/res/module/hoare/help/pics/reinit.gif new file mode 100644 index 0000000..58ebfad Binary files /dev/null and b/res/module/hoare/help/pics/reinit.gif differ diff --git a/res/module/hoare/help/pics/resetZoom.gif b/res/module/hoare/help/pics/resetZoom.gif new file mode 100644 index 0000000..f778a6a Binary files /dev/null and b/res/module/hoare/help/pics/resetZoom.gif differ diff --git a/res/module/hoare/help/pics/save.gif b/res/module/hoare/help/pics/save.gif new file mode 100644 index 0000000..cbe3657 Binary files /dev/null and b/res/module/hoare/help/pics/save.gif differ diff --git a/res/module/hoare/help/pics/save_as.gif b/res/module/hoare/help/pics/save_as.gif new file mode 100644 index 0000000..e4ff5f7 Binary files /dev/null and b/res/module/hoare/help/pics/save_as.gif differ diff --git a/res/module/hoare/help/pics/toggleSplitter.gif b/res/module/hoare/help/pics/toggleSplitter.gif new file mode 100644 index 0000000..5d506da Binary files /dev/null and b/res/module/hoare/help/pics/toggleSplitter.gif differ diff --git a/res/module/hoare/help/pics/tool.gif b/res/module/hoare/help/pics/tool.gif new file mode 100644 index 0000000..348e1e2 Binary files /dev/null and b/res/module/hoare/help/pics/tool.gif differ diff --git a/res/module/hoare/help/pics/undo.gif b/res/module/hoare/help/pics/undo.gif new file mode 100644 index 0000000..f0230be Binary files /dev/null and b/res/module/hoare/help/pics/undo.gif differ diff --git a/res/module/hoare/help/pics/welcome.gif b/res/module/hoare/help/pics/welcome.gif new file mode 100644 index 0000000..4c5f89e Binary files /dev/null and b/res/module/hoare/help/pics/welcome.gif differ diff --git a/res/module/hoare/help/pics/zoomIn.gif b/res/module/hoare/help/pics/zoomIn.gif new file mode 100644 index 0000000..d33b6f7 Binary files /dev/null and b/res/module/hoare/help/pics/zoomIn.gif differ diff --git a/res/module/hoare/help/pics/zoomOut.gif b/res/module/hoare/help/pics/zoomOut.gif new file mode 100644 index 0000000..563c80e Binary files /dev/null and b/res/module/hoare/help/pics/zoomOut.gif differ diff --git a/res/module/hoare/help/pics/zweite Regelanwendung (Iter) Knoten gross.png b/res/module/hoare/help/pics/zweite Regelanwendung (Iter) Knoten gross.png new file mode 100644 index 0000000..023e601 Binary files /dev/null and b/res/module/hoare/help/pics/zweite Regelanwendung (Iter) Knoten gross.png differ diff --git a/res/module/hoare/help/style.css b/res/module/hoare/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/hoare/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/hoare/hoare.prefs b/res/module/hoare/hoare.prefs new file mode 100644 index 0000000..526fe73 --- /dev/null +++ b/res/module/hoare/hoare.prefs @@ -0,0 +1,11 @@ +#j-Algo Default-Settings for Hoare-Module +Version=2.0.0 +isBeamerMode=false +formulaEditor.maximized=false +formulaEditor.top=100 +formulaEditor.left=100 +formulaEditor.width=600 +formulaEditor.height=250 +workScreen.mainSplitterRelation=0.6 +workScreen.rightUpndownSplitterLocation=240 +workScreen.rightLeftRightSplitterLocation=195 \ No newline at end of file diff --git a/res/module/hoare/hoare_font/CVS/Entries b/res/module/hoare/hoare_font/CVS/Entries new file mode 100644 index 0000000..811d79e --- /dev/null +++ b/res/module/hoare/hoare_font/CVS/Entries @@ -0,0 +1,2 @@ +/DejaVuSans.ttf/1.1/Wed Aug 27 13:02:58 2008/-kb/ +/DejaVuSansMono.ttf/1.1/Wed Aug 27 13:02:57 2008/-kb/ diff --git a/res/module/hoare/hoare_font/CVS/Repository b/res/module/hoare/hoare_font/CVS/Repository new file mode 100644 index 0000000..b69228f --- /dev/null +++ b/res/module/hoare/hoare_font/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/hoare_font diff --git a/res/module/hoare/hoare_font/CVS/Root b/res/module/hoare/hoare_font/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/hoare_font/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/hoare_font/DejaVuSans.ttf b/res/module/hoare/hoare_font/DejaVuSans.ttf new file mode 100644 index 0000000..b25cc05 Binary files /dev/null and b/res/module/hoare/hoare_font/DejaVuSans.ttf differ diff --git a/res/module/hoare/hoare_font/DejaVuSansMono.ttf b/res/module/hoare/hoare_font/DejaVuSansMono.ttf new file mode 100644 index 0000000..4528c36 Binary files /dev/null and b/res/module/hoare/hoare_font/DejaVuSansMono.ttf differ diff --git a/res/module/hoare/hoare_pix/Block.gif b/res/module/hoare/hoare_pix/Block.gif new file mode 100644 index 0000000..479d822 Binary files /dev/null and b/res/module/hoare/hoare_pix/Block.gif differ diff --git a/res/module/hoare/hoare_pix/CNull.gif b/res/module/hoare/hoare_pix/CNull.gif new file mode 100644 index 0000000..87b684d Binary files /dev/null and b/res/module/hoare/hoare_pix/CNull.gif differ diff --git a/res/module/hoare/hoare_pix/CVS/Entries b/res/module/hoare/hoare_pix/CVS/Entries new file mode 100644 index 0000000..f759516 --- /dev/null +++ b/res/module/hoare/hoare_pix/CVS/Entries @@ -0,0 +1,34 @@ +/Block.gif/1.1/Wed Aug 27 13:01:34 2008/-kb/ +/CNull.gif/1.2/Wed Aug 27 13:01:30 2008/-kb/ +/SN.gif/1.1/Wed Aug 27 13:01:32 2008/-kb/ +/SV.gif/1.1/Wed Aug 27 13:01:30 2008/-kb/ +/Sequenz.gif/1.1/Wed Aug 27 13:01:36 2008/-kb/ +/assign.gif/1.1/Wed Aug 27 13:01:35 2008/-kb/ +/delnode.gif/1.2/Wed Aug 27 13:01:33 2008/-kb/ +/duck.png/1.1/Wed Aug 27 13:01:33 2008/-kb/ +/grayredo.gif/1.1/Wed Aug 27 13:01:33 2008/-kb/ +/grayundo.gif/1.1/Wed Aug 27 13:01:32 2008/-kb/ +/if.gif/1.1/Wed Aug 27 13:01:31 2008/-kb/ +/ifelse.gif/1.1/Wed Aug 27 13:01:31 2008/-kb/ +/logo.gif/1.1/Mon Jan 14 22:16:23 2008/-kb/ +/new_welcome_0.gif/1.2/Wed Aug 27 13:01:35 2008/-kb/ +/new_welcome_1.gif/1.2/Wed Aug 27 13:01:33 2008/-kb/ +/new_welcome_Desc_de.gif/1.2/Wed Aug 27 13:01:37 2008/-kb/ +/new_welcome_Desc_en.gif/1.2/Wed Aug 27 13:01:36 2008/-kb/ +/normalMouse.gif/1.1/Wed Aug 27 13:01:35 2008/-kb/ +/open_welcome_0.gif/1.2/Wed Aug 27 13:01:33 2008/-kb/ +/open_welcome_1.gif/1.2/Wed Aug 27 13:01:32 2008/-kb/ +/open_welcome_Desc_de.gif/1.2/Wed Aug 27 13:01:37 2008/-kb/ +/open_welcome_Desc_en.gif/1.2/Wed Aug 27 13:01:30 2008/-kb/ +/openc0_welcome_0.gif/1.2/Wed Aug 27 13:01:36 2008/-kb/ +/openc0_welcome_1.gif/1.2/Wed Aug 27 13:01:31 2008/-kb/ +/openc0_welcome_Desc_de.gif/1.2/Wed Aug 27 13:01:37 2008/-kb/ +/openc0_welcome_Desc_en.gif/1.2/Wed Aug 27 13:01:37 2008/-kb/ +/redo.gif/1.2/Wed Aug 27 13:01:31 2008/-kb/ +/reinit.gif/1.1/Mon Jan 14 22:16:23 2008/-kb/ +/resetZoom.gif/1.1/Wed Aug 27 13:01:34 2008/-kb/ +/toggleSplitter.gif/1.1/Wed Aug 27 13:01:31 2008/-kb/ +/undo.gif/1.2/Wed Aug 27 13:01:33 2008/-kb/ +/while.gif/1.1/Wed Aug 27 13:01:32 2008/-kb/ +/zoomIn.gif/1.1/Wed Aug 27 13:01:34 2008/-kb/ +/zoomOut.gif/1.1/Wed Aug 27 13:01:35 2008/-kb/ diff --git a/res/module/hoare/hoare_pix/CVS/Repository b/res/module/hoare/hoare_pix/CVS/Repository new file mode 100644 index 0000000..ee4fb1d --- /dev/null +++ b/res/module/hoare/hoare_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/hoare_pix diff --git a/res/module/hoare/hoare_pix/CVS/Root b/res/module/hoare/hoare_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/hoare_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/hoare_pix/SN.gif b/res/module/hoare/hoare_pix/SN.gif new file mode 100644 index 0000000..ed4adcc Binary files /dev/null and b/res/module/hoare/hoare_pix/SN.gif differ diff --git a/res/module/hoare/hoare_pix/SV.gif b/res/module/hoare/hoare_pix/SV.gif new file mode 100644 index 0000000..78225be Binary files /dev/null and b/res/module/hoare/hoare_pix/SV.gif differ diff --git a/res/module/hoare/hoare_pix/Sequenz.gif b/res/module/hoare/hoare_pix/Sequenz.gif new file mode 100644 index 0000000..bb13bed Binary files /dev/null and b/res/module/hoare/hoare_pix/Sequenz.gif differ diff --git a/res/module/hoare/hoare_pix/assign.gif b/res/module/hoare/hoare_pix/assign.gif new file mode 100644 index 0000000..4146218 Binary files /dev/null and b/res/module/hoare/hoare_pix/assign.gif differ diff --git a/res/module/hoare/hoare_pix/delnode.gif b/res/module/hoare/hoare_pix/delnode.gif new file mode 100644 index 0000000..e116647 Binary files /dev/null and b/res/module/hoare/hoare_pix/delnode.gif differ diff --git a/res/module/hoare/hoare_pix/duck.png b/res/module/hoare/hoare_pix/duck.png new file mode 100644 index 0000000..6a3fb4b Binary files /dev/null and b/res/module/hoare/hoare_pix/duck.png differ diff --git a/res/module/hoare/hoare_pix/grayredo.gif b/res/module/hoare/hoare_pix/grayredo.gif new file mode 100644 index 0000000..dfc079c Binary files /dev/null and b/res/module/hoare/hoare_pix/grayredo.gif differ diff --git a/res/module/hoare/hoare_pix/grayundo.gif b/res/module/hoare/hoare_pix/grayundo.gif new file mode 100644 index 0000000..66d5fbc Binary files /dev/null and b/res/module/hoare/hoare_pix/grayundo.gif differ diff --git a/res/module/hoare/hoare_pix/if.gif b/res/module/hoare/hoare_pix/if.gif new file mode 100644 index 0000000..3323e7e Binary files /dev/null and b/res/module/hoare/hoare_pix/if.gif differ diff --git a/res/module/hoare/hoare_pix/ifelse.gif b/res/module/hoare/hoare_pix/ifelse.gif new file mode 100644 index 0000000..fa4a175 Binary files /dev/null and b/res/module/hoare/hoare_pix/ifelse.gif differ diff --git a/res/module/hoare/hoare_pix/logo.gif b/res/module/hoare/hoare_pix/logo.gif new file mode 100644 index 0000000..be686a1 Binary files /dev/null and b/res/module/hoare/hoare_pix/logo.gif differ diff --git a/res/module/hoare/hoare_pix/new_welcome_0.gif b/res/module/hoare/hoare_pix/new_welcome_0.gif new file mode 100644 index 0000000..e1db89a Binary files /dev/null and b/res/module/hoare/hoare_pix/new_welcome_0.gif differ diff --git a/res/module/hoare/hoare_pix/new_welcome_1.gif b/res/module/hoare/hoare_pix/new_welcome_1.gif new file mode 100644 index 0000000..897c4a6 Binary files /dev/null and b/res/module/hoare/hoare_pix/new_welcome_1.gif differ diff --git a/res/module/hoare/hoare_pix/new_welcome_Desc_de.gif b/res/module/hoare/hoare_pix/new_welcome_Desc_de.gif new file mode 100644 index 0000000..c3c0daf Binary files /dev/null and b/res/module/hoare/hoare_pix/new_welcome_Desc_de.gif differ diff --git a/res/module/hoare/hoare_pix/new_welcome_Desc_en.gif b/res/module/hoare/hoare_pix/new_welcome_Desc_en.gif new file mode 100644 index 0000000..8d8af38 Binary files /dev/null and b/res/module/hoare/hoare_pix/new_welcome_Desc_en.gif differ diff --git a/res/module/hoare/hoare_pix/normalMouse.gif b/res/module/hoare/hoare_pix/normalMouse.gif new file mode 100644 index 0000000..5d4ad1b Binary files /dev/null and b/res/module/hoare/hoare_pix/normalMouse.gif differ diff --git a/res/module/hoare/hoare_pix/open_welcome_0.gif b/res/module/hoare/hoare_pix/open_welcome_0.gif new file mode 100644 index 0000000..016aca4 Binary files /dev/null and b/res/module/hoare/hoare_pix/open_welcome_0.gif differ diff --git a/res/module/hoare/hoare_pix/open_welcome_1.gif b/res/module/hoare/hoare_pix/open_welcome_1.gif new file mode 100644 index 0000000..fcee41f Binary files /dev/null and b/res/module/hoare/hoare_pix/open_welcome_1.gif differ diff --git a/res/module/hoare/hoare_pix/open_welcome_Desc_de.gif b/res/module/hoare/hoare_pix/open_welcome_Desc_de.gif new file mode 100644 index 0000000..7335403 Binary files /dev/null and b/res/module/hoare/hoare_pix/open_welcome_Desc_de.gif differ diff --git a/res/module/hoare/hoare_pix/open_welcome_Desc_en.gif b/res/module/hoare/hoare_pix/open_welcome_Desc_en.gif new file mode 100644 index 0000000..e5441d4 Binary files /dev/null and b/res/module/hoare/hoare_pix/open_welcome_Desc_en.gif differ diff --git a/res/module/hoare/hoare_pix/openc0_welcome_0.gif b/res/module/hoare/hoare_pix/openc0_welcome_0.gif new file mode 100644 index 0000000..6c694c0 Binary files /dev/null and b/res/module/hoare/hoare_pix/openc0_welcome_0.gif differ diff --git a/res/module/hoare/hoare_pix/openc0_welcome_1.gif b/res/module/hoare/hoare_pix/openc0_welcome_1.gif new file mode 100644 index 0000000..b33e9eb Binary files /dev/null and b/res/module/hoare/hoare_pix/openc0_welcome_1.gif differ diff --git a/res/module/hoare/hoare_pix/openc0_welcome_Desc_de.gif b/res/module/hoare/hoare_pix/openc0_welcome_Desc_de.gif new file mode 100644 index 0000000..6379052 Binary files /dev/null and b/res/module/hoare/hoare_pix/openc0_welcome_Desc_de.gif differ diff --git a/res/module/hoare/hoare_pix/openc0_welcome_Desc_en.gif b/res/module/hoare/hoare_pix/openc0_welcome_Desc_en.gif new file mode 100644 index 0000000..a95744c Binary files /dev/null and b/res/module/hoare/hoare_pix/openc0_welcome_Desc_en.gif differ diff --git a/res/module/hoare/hoare_pix/redo.gif b/res/module/hoare/hoare_pix/redo.gif new file mode 100644 index 0000000..6909058 Binary files /dev/null and b/res/module/hoare/hoare_pix/redo.gif differ diff --git a/res/module/hoare/hoare_pix/reinit.gif b/res/module/hoare/hoare_pix/reinit.gif new file mode 100644 index 0000000..58ebfad Binary files /dev/null and b/res/module/hoare/hoare_pix/reinit.gif differ diff --git a/res/module/hoare/hoare_pix/resetZoom.gif b/res/module/hoare/hoare_pix/resetZoom.gif new file mode 100644 index 0000000..f778a6a Binary files /dev/null and b/res/module/hoare/hoare_pix/resetZoom.gif differ diff --git a/res/module/hoare/hoare_pix/toggleSplitter.gif b/res/module/hoare/hoare_pix/toggleSplitter.gif new file mode 100644 index 0000000..5d506da Binary files /dev/null and b/res/module/hoare/hoare_pix/toggleSplitter.gif differ diff --git a/res/module/hoare/hoare_pix/undo.gif b/res/module/hoare/hoare_pix/undo.gif new file mode 100644 index 0000000..f0230be Binary files /dev/null and b/res/module/hoare/hoare_pix/undo.gif differ diff --git a/res/module/hoare/hoare_pix/while.gif b/res/module/hoare/hoare_pix/while.gif new file mode 100644 index 0000000..22875b8 Binary files /dev/null and b/res/module/hoare/hoare_pix/while.gif differ diff --git a/res/module/hoare/hoare_pix/zoomIn.gif b/res/module/hoare/hoare_pix/zoomIn.gif new file mode 100644 index 0000000..d33b6f7 Binary files /dev/null and b/res/module/hoare/hoare_pix/zoomIn.gif differ diff --git a/res/module/hoare/hoare_pix/zoomOut.gif b/res/module/hoare/hoare_pix/zoomOut.gif new file mode 100644 index 0000000..563c80e Binary files /dev/null and b/res/module/hoare/hoare_pix/zoomOut.gif differ diff --git a/res/module/hoare/hoare_res/CVS/Entries b/res/module/hoare/hoare_res/CVS/Entries new file mode 100644 index 0000000..7ff365a --- /dev/null +++ b/res/module/hoare/hoare_res/CVS/Entries @@ -0,0 +1,8 @@ +/input.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/inputB.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/log.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/logB.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/rule.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/ruleB.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/tree.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ +/treeB.css/1.1/Mon Jan 14 22:16:24 2008/-kb/ diff --git a/res/module/hoare/hoare_res/CVS/Repository b/res/module/hoare/hoare_res/CVS/Repository new file mode 100644 index 0000000..1f6ad6f --- /dev/null +++ b/res/module/hoare/hoare_res/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/hoare/hoare_res diff --git a/res/module/hoare/hoare_res/CVS/Root b/res/module/hoare/hoare_res/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/hoare/hoare_res/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/hoare/hoare_res/input.css b/res/module/hoare/hoare_res/input.css new file mode 100644 index 0000000..75078aa --- /dev/null +++ b/res/module/hoare/hoare_res/input.css @@ -0,0 +1,9 @@ +.cond{ +font-size:12pt; +text-align: center; +} + +.codeseg{ +font-size:12pt; +text-align: center; +} diff --git a/res/module/hoare/hoare_res/inputB.css b/res/module/hoare/hoare_res/inputB.css new file mode 100644 index 0000000..68d146b --- /dev/null +++ b/res/module/hoare/hoare_res/inputB.css @@ -0,0 +1,9 @@ +.cond{ +font-size:18pt; +text-align: center; +} + +.codeseg{ +font-size:18pt; +text-align: center; +} diff --git a/res/module/hoare/hoare_res/log.css b/res/module/hoare/hoare_res/log.css new file mode 100644 index 0000000..37ae7b3 --- /dev/null +++ b/res/module/hoare/hoare_res/log.css @@ -0,0 +1,7 @@ +.error { + color: rgb(255,0,0); +} + +.info { + +} \ No newline at end of file diff --git a/res/module/hoare/hoare_res/logB.css b/res/module/hoare/hoare_res/logB.css new file mode 100644 index 0000000..eae443e --- /dev/null +++ b/res/module/hoare/hoare_res/logB.css @@ -0,0 +1,7 @@ +.error { + color: rgb(255,0,0); +} + +.info { + +} diff --git a/res/module/hoare/hoare_res/rule.css b/res/module/hoare/hoare_res/rule.css new file mode 100644 index 0000000..4bb9da9 --- /dev/null +++ b/res/module/hoare/hoare_res/rule.css @@ -0,0 +1,28 @@ + +.rule { + text-decoration: none; + color: black; +} + +.activeRule { + text-decoration: none; + color: black; + background-color: #ffff00; +} + +.rules { + font-size: 12pt; +} + +.title { + text-align: left; +} + +.content { + text-align: center; + font-size: large; +} + +.codeseg { + font-size: small; +} diff --git a/res/module/hoare/hoare_res/ruleB.css b/res/module/hoare/hoare_res/ruleB.css new file mode 100644 index 0000000..de16305 --- /dev/null +++ b/res/module/hoare/hoare_res/ruleB.css @@ -0,0 +1,28 @@ + +.rule { + text-decoration: none; + color: black; +} + +.activeRule { + text-decoration: none; + color: black; + background-color: yellow; +} + +.rules { + font-size: 16pt; +} + +.title { + text-align: left; +} + +.content { + text-align: center; + font-size: 18pt; +} + +.codeseg { + font-size: large; +} diff --git a/res/module/hoare/hoare_res/tree.css b/res/module/hoare/hoare_res/tree.css new file mode 100644 index 0000000..a5ebf17 --- /dev/null +++ b/res/module/hoare/hoare_res/tree.css @@ -0,0 +1,54 @@ +table { + empty-cell: show; + width:100%; + height:100%; + margin: 0 0 0 0; + padding: 0 0 0 0; + vertical-align: bottom; + font-size:12pt; +} +table td { + text-align: center; + vertical-align: bottom; + margin: 0 0 0 0; + padding: 0 5 0 5; +} +table tr { + margin: 0 0 0 0; + padding: 0 0 0 0; +} + +.active{ + background-color: YELLOW; + +} + +.pre{ + text-decoration: none; + color: black; +} + +.post{ + text-decoration: none; + color: black; +} + +.vf{ + text-decoration: none; + color: black; + background-color: rgb(200,200,200); +} + +.impl{ + text-decoration: none; + color: black; +} + +.desc{ + text-align: left; +} + + +.leaf{ + border-style: inset; +} diff --git a/res/module/hoare/hoare_res/treeB.css b/res/module/hoare/hoare_res/treeB.css new file mode 100644 index 0000000..e0578b1 --- /dev/null +++ b/res/module/hoare/hoare_res/treeB.css @@ -0,0 +1,54 @@ +table { + empty-cell: show; + width:100%; + height:100%; + margin: 0 0 0 0; + padding: 0 0 0 0; + vertical-align: bottom; + + font-size:20pt; +} +table td { + text-align: center; + vertical-align: bottom; + margin: 0 0 0 0; + padding: 0 10 0 10; +} +table tr { + margin: 0 0 0 0; + padding: 0 0 0 0; +} + +.active{ + background-color: YELLOW; + +} + +.pre{ + text-decoration: none; + color: black; +} + +.post{ + text-decoration: none; + color: black; +} + +.vf{ + text-decoration: none; + color: black; + background-color: rgb(200,200,200); +} + +.impl{ + text-decoration: none; + color: black; +} + +.desc{ + text-align: left; +} + +.leaf{ + border-style: inset; +} diff --git a/res/module/kmp/CVS/Entries b/res/module/kmp/CVS/Entries new file mode 100644 index 0000000..a3ce881 --- /dev/null +++ b/res/module/kmp/CVS/Entries @@ -0,0 +1,2 @@ +D/help//// +D/kmp_pix//// diff --git a/res/module/kmp/CVS/Repository b/res/module/kmp/CVS/Repository new file mode 100644 index 0000000..3dbed33 --- /dev/null +++ b/res/module/kmp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp diff --git a/res/module/kmp/CVS/Root b/res/module/kmp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/CVS/Entries b/res/module/kmp/help/CVS/Entries new file mode 100644 index 0000000..b931d74 --- /dev/null +++ b/res/module/kmp/help/CVS/Entries @@ -0,0 +1,3 @@ +D/html//// +D/jhelp//// +D/pics//// diff --git a/res/module/kmp/help/CVS/Repository b/res/module/kmp/help/CVS/Repository new file mode 100644 index 0000000..be23927 --- /dev/null +++ b/res/module/kmp/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help diff --git a/res/module/kmp/help/CVS/Root b/res/module/kmp/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/html/CVS/Entries b/res/module/kmp/help/html/CVS/Entries new file mode 100644 index 0000000..b259ca6 --- /dev/null +++ b/res/module/kmp/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Fri Jun 30 14:35:20 2006// +D/data//// +/index.htm/1.1/Fri Jun 30 14:35:20 2006// +/top_frame.htm/1.1/Fri Jun 30 14:35:20 2006// diff --git a/res/module/kmp/help/html/CVS/Repository b/res/module/kmp/help/html/CVS/Repository new file mode 100644 index 0000000..a6762d7 --- /dev/null +++ b/res/module/kmp/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help/html diff --git a/res/module/kmp/help/html/CVS/Root b/res/module/kmp/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/html/contents.htm b/res/module/kmp/help/html/contents.htm new file mode 100644 index 0000000..2df7677 --- /dev/null +++ b/res/module/kmp/help/html/contents.htm @@ -0,0 +1,61 @@ + + + Inhaltsverzeichnis + + + + +

      Das Modul KMP

      + + + \ No newline at end of file diff --git a/res/module/kmp/help/html/data/CVS/Entries b/res/module/kmp/help/html/data/CVS/Entries new file mode 100644 index 0000000..8689c49 --- /dev/null +++ b/res/module/kmp/help/html/data/CVS/Entries @@ -0,0 +1,6 @@ +/flowcontrol.htm/1.1/Fri Jun 30 14:35:20 2006// +/functions.htm/1.1/Fri Jun 30 14:35:19 2006// +/info.htm/1.1/Fri Jun 30 14:35:19 2006// +/overview.htm/1.1/Fri Jun 30 14:35:20 2006// +/screen.htm/1.1/Fri Jun 30 14:35:19 2006// +/start.htm/1.1/Fri Jun 30 14:35:19 2006// diff --git a/res/module/kmp/help/html/data/CVS/Repository b/res/module/kmp/help/html/data/CVS/Repository new file mode 100644 index 0000000..f6c4593 --- /dev/null +++ b/res/module/kmp/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help/html/data diff --git a/res/module/kmp/help/html/data/CVS/Root b/res/module/kmp/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/html/data/flowcontrol.htm b/res/module/kmp/help/html/data/flowcontrol.htm new file mode 100644 index 0000000..2117fc9 --- /dev/null +++ b/res/module/kmp/help/html/data/flowcontrol.htm @@ -0,0 +1,51 @@ + + + Algorithmussteuerung + + + + +

      Algorithmussteuerung + +

      Pfeile

      + +

      Startbildschirm

      + + Hierbei wird der aktuelle Arbeitsbereich verlassen und der Benutzer kehrt zum Startbildschirm zurück. + +

      Abbruch

      + + Hierbei wird zum Anfang des Algorithmus gesprungen. + +

      "Schnelles" Zurück

      + + Hierbei wird ein Schritt vollzogen, der mehreren vorherigen Statements im Quelltext entspricht. + +

      Zurück

      + + Hierbei wird einer Schritt vollzogen, der dem vorherigen Statement im Quelltext entspricht. + + + + +

      Weiter

      + + Hierbei wird ein Schritt vollzogen, der dem nächsten Statement im Quelltext entspricht. + +

      "Schnelles" Weiter

      + + Hierbei wird ein Schritt vollzogen, der mehreren nächsten Statements im Quelltext entspricht. + Beim Erstellen der Verschiebetabelle entspricht dieser Schritt der Berechnung der Verschiebeinformation je eines Zeichens. + Beim Anwenden der Verschiebetabelle an einem Text entspricht dieser Schritt dem Verschieben des Patterns unter Berücksichtigung der Verschiebetabelle. + + + +

      Ende

      + + Hierbei werden alle Schritte, die bis zum Ende des Algorithmus durchgeführt werden, vollzogen. + + + + + + \ No newline at end of file diff --git a/res/module/kmp/help/html/data/functions.htm b/res/module/kmp/help/html/data/functions.htm new file mode 100644 index 0000000..915bcc1 --- /dev/null +++ b/res/module/kmp/help/html/data/functions.htm @@ -0,0 +1,104 @@ + + + Modulfunktionen + + + +

      Modulfunktionen

      + +

      Eingabe von Pattern und Text

      + +

      Pattern eingeben

      + +

      Phase2Screen Exampel

      + +Das Pattern kann manuell eingegeben werden, hierbei ist die maximale Länge von 10 Zeichen zu beachten. Das Alphabet kann aus beliebigen Zeichen bestehen. +Die Eingabe erfolgt im Steuerungsbereich in die Eingabezeile "Pattern". Um das Pattern zu übernehmen klicken Sie auf "Setzen". + +

      Suchtext eingeben

      +

      +Der Text unterliegt keinen Beschränkungen und kann manuell eingegeben oder aus einer vorhandenen *.txt-Datei importiert werden.
      +Die Eingabe erfolgt im Steuerungsbereich, klicken Sie hierfür auf "Eingeben". +

      Phase2Screen Exampel

      +Es öffnet sich ein Fenster, in dem Sie den Text manuell eingeben (oder auch per Copy&Paste einfügen) oder eine *.txt-Datei laden können. Um den Text zu übernehmen klicken Sie auf "Anwenden". + +

      Phase2Screen Exampel

      + + + + +

      + + +

      Generieren von Pattern und passenden Texten

      + +

      Pattern eingeben

      + +

      Phase2Screen Exampel

      +Neben der manuellen Eingabe des Patterns gibt es die Möglichkeit, ein Pattern generieren zu lassen. Klicken Sie dafür auf den Knopf "Zufall" (im Steuerungsbereich neben der Eingabezeile "Pattern") und wählen Sie im folgenden Fenster die Kardinalität des zu nutzenden Alphabets und die gewünschte Länge des Patterns aus. Das Pattern wird mit Klick auf "Anwenden" geniert und Sie kehren zum Arbeitsbereich zurück. +

      Phase2Screen Exampel

      + + +

      Suchtext eingeben

      + +

      Phase2Screen Exampel

      +

      +Um einen zum Pattern passenden Text generieren zu lassen, klicken Sie auf "Generieren" (im Steuerungsbereich neben "Text"). Dadurch wird eine Text erstellt, der das Pattern enthält und nur aus den im Pattern genutzten Zeichen besteht. Dieser Text wird sofort übernommen, Sie haben aber die Möglichkeit, ihn zu bearbeiten, indem Sie auf "Eingeben" klicken. +

      + + +

      Generierung der Verschiebetabelle

      + +Wenn ein Pattern gesetzt wurde, kann die Verschiebetabelle erstellt werden. Um den Algorithmus zu starten und zu steuern, benutzen Sie die Pfeile im Steuerungsbereich. +

      Pfeile

      +

      +Das Pattern kann nun noch erweitert werden ohne den aktuellen Algorithmus zu unterbrechen, geben Sie hierfür das gewünschte Zeichen in das Eingabefeld "Erweiterung" im Steuerungsbereich ein. Sollte das Pattern bereits die maximale Länge haben, ist eine Erweiterung nicht möglich. +

      Erweiterung

      + +

      +Nachdem die Verschiebetabelle erstellt wurde, können Pattern und Verschiebetabelle für eine Suche im Text genutzt werden. Klicken Sie hierfür auf das Feld "Weiter zu Phase 2", welches erst am Ende des Algorithmus im Steuerungsbereich erscheint. + +

      Weiter zu Phase 2

      + +

      + +

      Suchen im Suchtext

      + +Erst wenn Pattern und Text gesetzt sind, kann das Anwenden der Verschiebetabelle an einem Text durchgeführt werden. +Um Pattern und Text zu setzen, haben Sie verschiedene Möglichkeiten, siehe: + Eingabe von Pattern und Text , + Generieren von Pattern und passenden Texten.
      +Um den Algorithmus zu starten und zu steuern, benutzen Sie die Pfeile im Steuerungsbereich. +

      Pfeile

      + +

      +Sollten Sie während der Durchführung des Algorithmus das Pattern und/oder den Text ändern, wird die aktuelle Durchführung des Algorithmus unterbrochen.
      +

      +Der Suchvorgang wird beendet, wenn das Pattern gefunden wurde oder das Textende erreicht wurde, es erscheint eine Meldung dazu im Steuerungsbereich. +

      Pattern gefunden

      +

      Pattern nicht gefunden

      +

      + +

      Öffnen einer KMP-Sitzung

      +

      +Mit Klick auf das Ordner-Symbol öffnet sich ein Dialogfenster, in dem Ihnen die Möglichkeit gegeben wird, eine "*.jalgo" - Datei auszuwählen, in welcher eine KMP-Sitzung gespeichert wurde. +

      Pattern nicht gefunden

      +

      + + +

      Präsentation von Lernbeispielen

      + +Es stehen Ihnen zehn Beispiele zur Auswahl, die jeweils eine besondere Eigenschaft des KMP-Algorithmus repräsentieren. Wenn Sie mit dem Mauszeiger über die Beispiele fahren, werden diese Eigenschaften kurz beschrieben. Wählen Sie das gewünschte Lernbeispiel aus und klicken Sie auf "Laden" um das Beispiel zu starten.
      +Die Beispiele bestehen aus Pattern- und passendem Text. + +

      Präsentation von Lernbeispielen

      +

      + +

      +Die Steuerung der Lernbeispiele erfolgt durch die Pfeile im Steuerungsbereich. +

      Pfeile

      +

      + + + + \ No newline at end of file diff --git a/res/module/kmp/help/html/data/info.htm b/res/module/kmp/help/html/data/info.htm new file mode 100644 index 0000000..7350e5d --- /dev/null +++ b/res/module/kmp/help/html/data/info.htm @@ -0,0 +1,24 @@ + + + Dokumentation + + + +

      Dokumentation

      +Im Dokumentationsbereich stehen verschiedene Perspektiven und ihre Kombinationen zur Auswahl, die Aktivierung der Perspektive erfolgt über Reiter. + +
        +
      • Code - der Quellcode des Algorithmus, entnommen dem Vorlesungsskript von Prof. Vogler "Algorithmen, Datenstrukturen und Programmierung". +
      • Protokoll - jeder vom Benutzer durchgeführte Schritt wird aufgelistet, egal ob es sich um Vorwärts- oder Rückwärts-Schritte handelt. +
      • Suchtext - der zu durchsuchende Text. +
      + +

      Phase2Screen Exampel

      + + + +Die Größe sowie die Aufteilung des Dokumentationsbereichs lassen sich vom Benutzer einstellen, siehe Anzeigeoptionen.
      +Die Bedeutung der verwendeten Farben wird in der Legende erklärt. + + + \ No newline at end of file diff --git a/res/module/kmp/help/html/data/overview.htm b/res/module/kmp/help/html/data/overview.htm new file mode 100644 index 0000000..c58516a --- /dev/null +++ b/res/module/kmp/help/html/data/overview.htm @@ -0,0 +1,28 @@ + + + Einleitung + + + +

      Das Modul KMP

      +

      Einleitung

      +

      Dieses Modul behandelt den Suchalgorithmus "Knuth Morris Pratt" (KMP) und zeigt Arbeitsweise am Pattern und Text. + Für eine detaillierte Beschreibung des Algorithmus sei auf das Vorlesungsskript von Prof. Vogler "Algorithmen, Datenstrukturen und Programmierung" verwiesen. +

      +

      Funktionsübersicht

      +

      Das Modul KMP realisiert folgende + Funktionen: +

      +
        +
      • Visualisierung und Erläuterung des Algorithmus +
      • Manuelle Eingabe von Pattern und Text +
      • Generieren von Pattern und passenden Texten +
      • Erstellen der Verschiebetabelle +
      • Suchen im Suchtext +
      • Präsentation von Lernbeispielen +
      • Speichern und Laden von KMP-Beispielen +
      • +
      + + + diff --git a/res/module/kmp/help/html/data/screen.htm b/res/module/kmp/help/html/data/screen.htm new file mode 100644 index 0000000..9f0264c --- /dev/null +++ b/res/module/kmp/help/html/data/screen.htm @@ -0,0 +1,115 @@ + + + Die Arbeitsfläche + + +

      Der Arbeitsbereich

      + + + +Der Arbeitsbereich ist untergliedert in drei Bereiche, die Ihnen Zugriff auf alle wesentlichen Funktionen in den Algorithmus-Phasen ermöglicht: +

      Phase1Screen

      +
        +
      1. Steuerung

        + +Hier wird der Algorithmus gestartet und gesteuert.
        +Mehr Informationen hierzu: Algorithmussteuerung +
      2. Visualisierung

        +Hier werden die Verschiebetabelle bzw. der Text dargestellt.
        +Mehr Informationen hierzu: Anzeigeoptionen, Legende +
      3. Dokumentation

        +Hier gibt es verschiedene Perspektiven, die miteinander kombiniert werden können: Quellcode, Text, Protokoll.
        +Mehr Informationen hierzu: Dokumentation, Legende +
      4. +
      + +

      Anzeigeoptionen

      + +

      Skalierung

      +Die Größe der Elemente des Visualisierungs- und Dokumentationsbereichs kann eingestellt werden, klicken Sie dafür auf den Schieberegler im Visualisierungsbereich und ziehen Sie ihn nach oben bzw. unten.

      Skalierung des Arbeitsbereichs

      + + + + +

      Aufteilung der Bereiche

      +Die Aufteilung zwischen dem Visualisierungs- und dem Dokumentationsbereich kann mit einem Schiebebalken verändert werden. Per Klick auf die Kante können Sie die Grenze verschieben. +

      Aufteilung zwischen dem Visualisierungs- und dem Dokumentationsbereich

      + + +

      Beamer - Modus

      +Der Beamer-Modus ermöglicht das schnelle Einstellen von Anzeigeoptionen, die die Präsentation in Vorlesungen oder ähnlichen Veranstaltungen begünstigen. Dieser Modus ist zu finden unter "Knuth Morris Pratt" => "Beamermodus".
      +Die Anzeige ist für die Auflösung 1024x768 optimiert und vergrößert die Elemente um den Faktor 1,5. Im Dokumentationsbereich wird die Perspektive "Code" angezeigt.
      +Ist der Modus aktiv, so erscheint vor diesem Menüeintrag ein Häkchen. Um den Modus wieder auszuschalten, entfernen Sie einfach den Haken per Klick. +

      Skalierung des Arbeitsbereichs

      + + +

      Zyklus - Anzeige

      +Im Visualisierungsbereich der Phase 1 "Generierung der Verschiebetabelle" können optional die Zyklen angezeigt werden, setzen Sie dazu das Häkchen "Zyklen" im Steuerungsbereich. Es werden maximal drei Zyklen gleichzeitig angezeigt. +

      Zyklus-Anzeige

      + + +

      Legende

      + +

      Elemente in der Phase "Generierung der Verschiebetabelle"

      + +

      Phase1Screen Exampel

      + +

      +Visualisierungsbereich
      +Pfeil schwarz mit weißem "P" - Zeiger auf die Variable "patpos", die Patternposition
      +Pfeil weiß mit schwarzem "V" - Zeiger auf die Variable "VglInd", der Vergleichsindex
      +schwarzer Pfeil über der Tabelle - die verglichenen Zeichen
      +gelber Hintergrund von Zellen - Zellenkopf
      +schwarzer Rahmen um Zelle in der Zeile "Index" - aktuell kopierte Verschiebeinformation
      +roter Rahmen um Zellen - negative boolesche Bedingung
      +lila Strich - Zyklen, die im Pattern auftreten +

      +

      +Schriftfarben
      +blau - aktuell geschriebene Verschiebeinformation (entspricht Zuweisungsstatement im Code) +
      rot - die verglichenen Zeichen stimmen nicht überein (entspricht booleschem Statement im Code) +
      grün - die verglichenen Zeichen stimmen überein (entspricht booleschem Statement im Code) +

      + +

      Legende des Dokumentationsbereichs

      + +

      Elemente in der Phase "Suchen im Suchtext"

      + +

      Phase2Screen Exampel

      + +

      +Visualisierungsbereich
      +lila Rahmen - das Sichtfenster, welches die aktuell betrachteten Zeichen des Textes und des Patterns justiert +

      + +

      +Schriftfarben
      +blau - aktuell geschriebene Verschiebeinformation (entspricht Zuweisungsstatement im Code) +

      +

      Legende des Dokumentationsbereichs

      + +

      Im Dokumentationsbereich

      + + +

      Phase2Screen Exampel

      + +

      +Perspektive "Code"
      +roter Hintergrund - negative boolesche Bedingung +
      grüner Hintergrund - positive boolesche Bedingung +
      blauer Hintergrund - sonstige Statements +

      + +

      +Perspektive "Protokoll"
      +blaue Schrift - zuletzt vollzogener Schritt +
      schwarze Schrift - für den aktuellen Stand irrelevante vorausgegangene Schritte +

      + +

      +Perspektive "Suchtext"
      +gelber Hintergrund - der Textausschnitt, an dem das Pattern momentan anliegt +

      + + + \ No newline at end of file diff --git a/res/module/kmp/help/html/data/start.htm b/res/module/kmp/help/html/data/start.htm new file mode 100644 index 0000000..1395f10 --- /dev/null +++ b/res/module/kmp/help/html/data/start.htm @@ -0,0 +1,43 @@ + + + Programmstart - Der Willkommensbildschirm + + + +

      Der Willkommensbildschirm

      + + +

      Modul KMP starten

      + + + Nach Starten des Hauptprogramms j-Algo können Sie über den Button "Neu" oder mit dem Menüpunkt "Datei" => "Neu" eine neue Instanz des Moduls KMP öffnen. Anschließend öffnet sich der Willkommensbildschirm des Moduls, der Ihnen verschiedene Möglichkeiten eröffnet. + + +

      WelcomeScreen

      + + +

      WelcomeScreen Generierung der Verschiebetabelle

      + + + Mit Klick auf das erste Symbol gelangen Sie zur ersten Phase des KMP-Algorithmus, in dem für ein Pattern die Verschiebetabelle erstellt wird.
      + Siehe: Modulfunktionen + + +

      WelcomeScreen Suchen im Suchtext

      + + Mit Klick auf das zweite Symbol gelangen Sie zur zweiten Phase des KMP-Algorithmus, in dem ein Text nach einem Pattern durchsucht wird.
      + Siehe: Modulfunktionen + + +

      WelcomeScreen Öffnen einer KMP-Sitzung

      + + Mit Klick auf das Ordner-Symbol erhalten Sie die Möglichkeit, ein zuvor gespeichertes KMP-Beispiel zu laden ("*.jalgo" - Datei)
      + Siehe: Modulfunktionen + + +

      WelcomeScreen Präsentation von Lernbeispielen

      + + Mit Klick auf das Tafel-Symbol erhalten Sie die Möglichkeit, anhand gegebener repräsentativer Lernbeispiele die Funktions- und Arbeitsweise des Algorithmus kennenzulernen.
      + Siehe: Modulfunktionen + + \ No newline at end of file diff --git a/res/module/kmp/help/html/index.htm b/res/module/kmp/help/html/index.htm new file mode 100644 index 0000000..f7eb132 --- /dev/null +++ b/res/module/kmp/help/html/index.htm @@ -0,0 +1,26 @@ + + + + Hilfe zum Modul KMP + + + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + diff --git a/res/module/kmp/help/html/top_frame.htm b/res/module/kmp/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/kmp/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/kmp/help/jhelp/CVS/Entries b/res/module/kmp/help/jhelp/CVS/Entries new file mode 100644 index 0000000..1acc2f2 --- /dev/null +++ b/res/module/kmp/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/kmpIndex.xml/1.1/Fri Jun 30 14:35:20 2006// +/kmpMap.jhm/1.1/Fri Jun 30 14:35:20 2006/-kb/ +/kmpTOC.xml/1.1/Fri Jun 30 14:35:20 2006// +/kmp_help.hs/1.1/Fri Jun 30 14:35:20 2006/-kb/ diff --git a/res/module/kmp/help/jhelp/CVS/Repository b/res/module/kmp/help/jhelp/CVS/Repository new file mode 100644 index 0000000..c6cca49 --- /dev/null +++ b/res/module/kmp/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help/jhelp diff --git a/res/module/kmp/help/jhelp/CVS/Root b/res/module/kmp/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..5618eea --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/DOCS.TAB/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/OFFSETS/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/POSITIONS/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/SCHEMA/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/TMAP/1.1/Fri Jun 30 14:35:15 2006/-kb/ +/config.ini/1.1/Fri Jun 30 14:35:15 2006// diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..de0e666 --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help/jhelp/JavaHelpSearch diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS b/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..0e73801 Binary files /dev/null and b/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..6d5d9b7 --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿ@z0»¾ªúú¾ó «0»ªÿúü¯ûë«ê«îÿêê¿»«ÿë꺪®ººªºªë«»ûúªª¿îú¾®«®ª«ïêï¿ÿªª®ÿ«¾«ûª«êªªªªªªºªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª˜ \ No newline at end of file diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/kmp/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..9cf2715 Binary files /dev/null and b/res/module/kmp/help/jhelp/JavaHelpSearch/OFFSETS differ diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/kmp/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..96c265e Binary files /dev/null and b/res/module/kmp/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/kmp/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..1f07d10 --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=461 id2=1 diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/TMAP b/res/module/kmp/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..291b6f4 Binary files /dev/null and b/res/module/kmp/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/kmp/help/jhelp/JavaHelpSearch/config.ini b/res/module/kmp/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/kmp/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/kmp/help/jhelp/kmpIndex.xml b/res/module/kmp/help/jhelp/kmpIndex.xml new file mode 100644 index 0000000..208bdb9 --- /dev/null +++ b/res/module/kmp/help/jhelp/kmpIndex.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + diff --git a/res/module/kmp/help/jhelp/kmpMap.jhm b/res/module/kmp/help/jhelp/kmpMap.jhm new file mode 100644 index 0000000..13bf3ad --- /dev/null +++ b/res/module/kmp/help/jhelp/kmpMap.jhm @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/kmp/help/jhelp/kmpTOC.xml b/res/module/kmp/help/jhelp/kmpTOC.xml new file mode 100644 index 0000000..b043788 --- /dev/null +++ b/res/module/kmp/help/jhelp/kmpTOC.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/kmp/help/jhelp/kmp_help.hs b/res/module/kmp/help/jhelp/kmp_help.hs new file mode 100644 index 0000000..da84836 --- /dev/null +++ b/res/module/kmp/help/jhelp/kmp_help.hs @@ -0,0 +1,65 @@ + + + + + + + + Hilfe zum KMP-Modul + + + + + kmp + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + kmpTOC.xml + + + + Index + + javax.help.IndexView + kmpIndex.xml + + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/kmp/help/pics/CVS/Entries b/res/module/kmp/help/pics/CVS/Entries new file mode 100644 index 0000000..ac23234 --- /dev/null +++ b/res/module/kmp/help/pics/CVS/Entries @@ -0,0 +1,32 @@ +/beamermod.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/control.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/cycle.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/endnegativ.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/endpositiv.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/expand.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/go_p2.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/learning.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/load.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/logo_help.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/move.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/pattern.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/pattern1.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/pattern2.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/pattern3.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/phase1screen.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/phase1screen_ex1.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/phase2screen_ex1.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/phase2screen_ex2.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/slide.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/text1.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/text2.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/text3.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_example.gif/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_example.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_open.gif/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_open.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_phaseone.gif/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_phaseone.png/1.1/Fri Jun 30 14:35:16 2006/-kb/ +/welcome_phasetwo.gif/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcome_phasetwo.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/welcomescreen.png/1.1/Fri Jun 30 14:35:17 2006/-kb/ diff --git a/res/module/kmp/help/pics/CVS/Repository b/res/module/kmp/help/pics/CVS/Repository new file mode 100644 index 0000000..26dbe72 --- /dev/null +++ b/res/module/kmp/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/help/pics diff --git a/res/module/kmp/help/pics/CVS/Root b/res/module/kmp/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/help/pics/beamermod.png b/res/module/kmp/help/pics/beamermod.png new file mode 100644 index 0000000..9bee223 Binary files /dev/null and b/res/module/kmp/help/pics/beamermod.png differ diff --git a/res/module/kmp/help/pics/control.png b/res/module/kmp/help/pics/control.png new file mode 100644 index 0000000..996ce01 Binary files /dev/null and b/res/module/kmp/help/pics/control.png differ diff --git a/res/module/kmp/help/pics/cycle.png b/res/module/kmp/help/pics/cycle.png new file mode 100644 index 0000000..69c57d5 Binary files /dev/null and b/res/module/kmp/help/pics/cycle.png differ diff --git a/res/module/kmp/help/pics/endnegativ.png b/res/module/kmp/help/pics/endnegativ.png new file mode 100644 index 0000000..33391e1 Binary files /dev/null and b/res/module/kmp/help/pics/endnegativ.png differ diff --git a/res/module/kmp/help/pics/endpositiv.png b/res/module/kmp/help/pics/endpositiv.png new file mode 100644 index 0000000..3ce178a Binary files /dev/null and b/res/module/kmp/help/pics/endpositiv.png differ diff --git a/res/module/kmp/help/pics/expand.png b/res/module/kmp/help/pics/expand.png new file mode 100644 index 0000000..d297a17 Binary files /dev/null and b/res/module/kmp/help/pics/expand.png differ diff --git a/res/module/kmp/help/pics/go_p2.png b/res/module/kmp/help/pics/go_p2.png new file mode 100644 index 0000000..4b33c76 Binary files /dev/null and b/res/module/kmp/help/pics/go_p2.png differ diff --git a/res/module/kmp/help/pics/learning.png b/res/module/kmp/help/pics/learning.png new file mode 100644 index 0000000..6d4bb51 Binary files /dev/null and b/res/module/kmp/help/pics/learning.png differ diff --git a/res/module/kmp/help/pics/load.png b/res/module/kmp/help/pics/load.png new file mode 100644 index 0000000..ef8ca9a Binary files /dev/null and b/res/module/kmp/help/pics/load.png differ diff --git a/res/module/kmp/help/pics/logo_help.png b/res/module/kmp/help/pics/logo_help.png new file mode 100644 index 0000000..97560c8 Binary files /dev/null and b/res/module/kmp/help/pics/logo_help.png differ diff --git a/res/module/kmp/help/pics/move.png b/res/module/kmp/help/pics/move.png new file mode 100644 index 0000000..ca5b8cc Binary files /dev/null and b/res/module/kmp/help/pics/move.png differ diff --git a/res/module/kmp/help/pics/pattern.png b/res/module/kmp/help/pics/pattern.png new file mode 100644 index 0000000..497b95f Binary files /dev/null and b/res/module/kmp/help/pics/pattern.png differ diff --git a/res/module/kmp/help/pics/pattern1.png b/res/module/kmp/help/pics/pattern1.png new file mode 100644 index 0000000..c2ced05 Binary files /dev/null and b/res/module/kmp/help/pics/pattern1.png differ diff --git a/res/module/kmp/help/pics/pattern2.png b/res/module/kmp/help/pics/pattern2.png new file mode 100644 index 0000000..497b95f Binary files /dev/null and b/res/module/kmp/help/pics/pattern2.png differ diff --git a/res/module/kmp/help/pics/pattern3.png b/res/module/kmp/help/pics/pattern3.png new file mode 100644 index 0000000..a11fb16 Binary files /dev/null and b/res/module/kmp/help/pics/pattern3.png differ diff --git a/res/module/kmp/help/pics/phase1screen.png b/res/module/kmp/help/pics/phase1screen.png new file mode 100644 index 0000000..d3131a0 Binary files /dev/null and b/res/module/kmp/help/pics/phase1screen.png differ diff --git a/res/module/kmp/help/pics/phase1screen_ex1.png b/res/module/kmp/help/pics/phase1screen_ex1.png new file mode 100644 index 0000000..e050f8c Binary files /dev/null and b/res/module/kmp/help/pics/phase1screen_ex1.png differ diff --git a/res/module/kmp/help/pics/phase2screen_ex1.png b/res/module/kmp/help/pics/phase2screen_ex1.png new file mode 100644 index 0000000..6dd9000 Binary files /dev/null and b/res/module/kmp/help/pics/phase2screen_ex1.png differ diff --git a/res/module/kmp/help/pics/phase2screen_ex2.png b/res/module/kmp/help/pics/phase2screen_ex2.png new file mode 100644 index 0000000..909534e Binary files /dev/null and b/res/module/kmp/help/pics/phase2screen_ex2.png differ diff --git a/res/module/kmp/help/pics/slide.png b/res/module/kmp/help/pics/slide.png new file mode 100644 index 0000000..3c2ec44 Binary files /dev/null and b/res/module/kmp/help/pics/slide.png differ diff --git a/res/module/kmp/help/pics/text1.png b/res/module/kmp/help/pics/text1.png new file mode 100644 index 0000000..de2385b Binary files /dev/null and b/res/module/kmp/help/pics/text1.png differ diff --git a/res/module/kmp/help/pics/text2.png b/res/module/kmp/help/pics/text2.png new file mode 100644 index 0000000..234ac8a Binary files /dev/null and b/res/module/kmp/help/pics/text2.png differ diff --git a/res/module/kmp/help/pics/text3.png b/res/module/kmp/help/pics/text3.png new file mode 100644 index 0000000..e9699d8 Binary files /dev/null and b/res/module/kmp/help/pics/text3.png differ diff --git a/res/module/kmp/help/pics/welcome_example.gif b/res/module/kmp/help/pics/welcome_example.gif new file mode 100644 index 0000000..c9098c4 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_example.gif differ diff --git a/res/module/kmp/help/pics/welcome_example.png b/res/module/kmp/help/pics/welcome_example.png new file mode 100644 index 0000000..deee488 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_example.png differ diff --git a/res/module/kmp/help/pics/welcome_open.gif b/res/module/kmp/help/pics/welcome_open.gif new file mode 100644 index 0000000..84ef146 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_open.gif differ diff --git a/res/module/kmp/help/pics/welcome_open.png b/res/module/kmp/help/pics/welcome_open.png new file mode 100644 index 0000000..ddd1316 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_open.png differ diff --git a/res/module/kmp/help/pics/welcome_phaseone.gif b/res/module/kmp/help/pics/welcome_phaseone.gif new file mode 100644 index 0000000..dbbb998 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_phaseone.gif differ diff --git a/res/module/kmp/help/pics/welcome_phaseone.png b/res/module/kmp/help/pics/welcome_phaseone.png new file mode 100644 index 0000000..9eec803 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_phaseone.png differ diff --git a/res/module/kmp/help/pics/welcome_phasetwo.gif b/res/module/kmp/help/pics/welcome_phasetwo.gif new file mode 100644 index 0000000..a06d7ad Binary files /dev/null and b/res/module/kmp/help/pics/welcome_phasetwo.gif differ diff --git a/res/module/kmp/help/pics/welcome_phasetwo.png b/res/module/kmp/help/pics/welcome_phasetwo.png new file mode 100644 index 0000000..149a4c8 Binary files /dev/null and b/res/module/kmp/help/pics/welcome_phasetwo.png differ diff --git a/res/module/kmp/help/pics/welcomescreen.png b/res/module/kmp/help/pics/welcomescreen.png new file mode 100644 index 0000000..8023309 Binary files /dev/null and b/res/module/kmp/help/pics/welcomescreen.png differ diff --git a/res/module/kmp/kmp_pix/CVS/Entries b/res/module/kmp/kmp_pix/CVS/Entries new file mode 100644 index 0000000..bb9de8f --- /dev/null +++ b/res/module/kmp/kmp_pix/CVS/Entries @@ -0,0 +1,17 @@ +/logo.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_example.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_example_desc_de.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_example_desc_en.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_example_rollover.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_open.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_open_desc_de.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_open_desc_en.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_open_rollover.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phaseone.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phaseone_desc_de.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phaseone_desc_en.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phaseone_rollover.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phasetwo.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phasetwo_desc_de.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phasetwo_desc_en.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ +/welcome_phasetwo_rollover.gif/1.1/Fri Jun 30 14:35:14 2006/-kb/ diff --git a/res/module/kmp/kmp_pix/CVS/Repository b/res/module/kmp/kmp_pix/CVS/Repository new file mode 100644 index 0000000..f9e5c42 --- /dev/null +++ b/res/module/kmp/kmp_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/kmp/kmp_pix diff --git a/res/module/kmp/kmp_pix/CVS/Root b/res/module/kmp/kmp_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/kmp/kmp_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/kmp/kmp_pix/logo.gif b/res/module/kmp/kmp_pix/logo.gif new file mode 100644 index 0000000..af10299 Binary files /dev/null and b/res/module/kmp/kmp_pix/logo.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_example.gif b/res/module/kmp/kmp_pix/welcome_example.gif new file mode 100644 index 0000000..b769003 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_example.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_example_desc_de.gif b/res/module/kmp/kmp_pix/welcome_example_desc_de.gif new file mode 100644 index 0000000..1d0f0ed Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_example_desc_de.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_example_desc_en.gif b/res/module/kmp/kmp_pix/welcome_example_desc_en.gif new file mode 100644 index 0000000..2772095 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_example_desc_en.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_example_rollover.gif b/res/module/kmp/kmp_pix/welcome_example_rollover.gif new file mode 100644 index 0000000..6baa99f Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_example_rollover.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_open.gif b/res/module/kmp/kmp_pix/welcome_open.gif new file mode 100644 index 0000000..fcb9730 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_open.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_open_desc_de.gif b/res/module/kmp/kmp_pix/welcome_open_desc_de.gif new file mode 100644 index 0000000..0d84ad3 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_open_desc_de.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_open_desc_en.gif b/res/module/kmp/kmp_pix/welcome_open_desc_en.gif new file mode 100644 index 0000000..4a34838 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_open_desc_en.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_open_rollover.gif b/res/module/kmp/kmp_pix/welcome_open_rollover.gif new file mode 100644 index 0000000..be1d746 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_open_rollover.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phaseone.gif b/res/module/kmp/kmp_pix/welcome_phaseone.gif new file mode 100644 index 0000000..1829bb2 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phaseone.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phaseone_desc_de.gif b/res/module/kmp/kmp_pix/welcome_phaseone_desc_de.gif new file mode 100644 index 0000000..59479cd Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phaseone_desc_de.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phaseone_desc_en.gif b/res/module/kmp/kmp_pix/welcome_phaseone_desc_en.gif new file mode 100644 index 0000000..57be81d Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phaseone_desc_en.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phaseone_rollover.gif b/res/module/kmp/kmp_pix/welcome_phaseone_rollover.gif new file mode 100644 index 0000000..cb75b75 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phaseone_rollover.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phasetwo.gif b/res/module/kmp/kmp_pix/welcome_phasetwo.gif new file mode 100644 index 0000000..3b225be Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phasetwo.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phasetwo_desc_de.gif b/res/module/kmp/kmp_pix/welcome_phasetwo_desc_de.gif new file mode 100644 index 0000000..7f72815 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phasetwo_desc_de.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phasetwo_desc_en.gif b/res/module/kmp/kmp_pix/welcome_phasetwo_desc_en.gif new file mode 100644 index 0000000..c057f2e Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phasetwo_desc_en.gif differ diff --git a/res/module/kmp/kmp_pix/welcome_phasetwo_rollover.gif b/res/module/kmp/kmp_pix/welcome_phasetwo_rollover.gif new file mode 100644 index 0000000..59526b7 Binary files /dev/null and b/res/module/kmp/kmp_pix/welcome_phasetwo_rollover.gif differ diff --git a/res/module/lambda/CVS/Entries b/res/module/lambda/CVS/Entries new file mode 100644 index 0000000..dc6a288 --- /dev/null +++ b/res/module/lambda/CVS/Entries @@ -0,0 +1,2 @@ +D/help//// +D/lambda_pix//// diff --git a/res/module/lambda/CVS/Repository b/res/module/lambda/CVS/Repository new file mode 100644 index 0000000..c978d40 --- /dev/null +++ b/res/module/lambda/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda diff --git a/res/module/lambda/CVS/Root b/res/module/lambda/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/CVS/Entries b/res/module/lambda/help/CVS/Entries new file mode 100644 index 0000000..d530d62 --- /dev/null +++ b/res/module/lambda/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Thu Aug 6 14:39:03 2009/-kb/ diff --git a/res/module/lambda/help/CVS/Repository b/res/module/lambda/help/CVS/Repository new file mode 100644 index 0000000..f496853 --- /dev/null +++ b/res/module/lambda/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help diff --git a/res/module/lambda/help/CVS/Root b/res/module/lambda/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/html/CVS/Entries b/res/module/lambda/help/html/CVS/Entries new file mode 100644 index 0000000..377bcb7 --- /dev/null +++ b/res/module/lambda/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Thu Aug 6 14:39:03 2009// +D/data//// +/index.htm/1.1/Thu Aug 6 14:39:03 2009// +/top_frame.htm/1.1/Thu Aug 6 14:39:03 2009// diff --git a/res/module/lambda/help/html/CVS/Repository b/res/module/lambda/help/html/CVS/Repository new file mode 100644 index 0000000..667ca14 --- /dev/null +++ b/res/module/lambda/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help/html diff --git a/res/module/lambda/help/html/CVS/Root b/res/module/lambda/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/html/contents.htm b/res/module/lambda/help/html/contents.htm new file mode 100644 index 0000000..844dd41 --- /dev/null +++ b/res/module/lambda/help/html/contents.htm @@ -0,0 +1,45 @@ + + + Inhaltsverzeichnis + + + + +
        +Das Modul Lambda-Kalkül + +
      + + + \ No newline at end of file diff --git a/res/module/lambda/help/html/data/CVS/Entries b/res/module/lambda/help/html/data/CVS/Entries new file mode 100644 index 0000000..d7cf5e0 --- /dev/null +++ b/res/module/lambda/help/html/data/CVS/Entries @@ -0,0 +1,4 @@ +/examples.htm/1.1/Thu Aug 6 14:39:02 2009// +/overview.htm/1.1/Thu Aug 6 14:39:02 2009// +/welcomeScreen.htm/1.1/Thu Aug 6 14:39:02 2009// +/workScreen.htm/1.1/Thu Aug 6 14:39:02 2009// diff --git a/res/module/lambda/help/html/data/CVS/Repository b/res/module/lambda/help/html/data/CVS/Repository new file mode 100644 index 0000000..cede96d --- /dev/null +++ b/res/module/lambda/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help/html/data diff --git a/res/module/lambda/help/html/data/CVS/Root b/res/module/lambda/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/html/data/examples.htm b/res/module/lambda/help/html/data/examples.htm new file mode 100644 index 0000000..947e9f8 --- /dev/null +++ b/res/module/lambda/help/html/data/examples.htm @@ -0,0 +1,30 @@ + + + Beispielabläufe + + + +

      Zwei Beispielabläufe

      + +

      Einen Term bearbeiten

      +

      Wählen sie auf dem Willkommesbildschirm 'Lambda-Term eingeben'. + Geben sie nun im Eingabefeld einen gültigen Lambdaterm ein. (z.B. '((\x.xy)(\y.xx))' ) + Bestätigen sie die Eingabe mit oder ENTER. + Nun können sie entweder mit einen automatischen + Schritt ausführen oder manuell mit und den Term umformen. + Bevor sie mit eine Alphakonversion ausführen können, + müssen sie eine Abstraktion auswählen, sofern der Gesamte Term nicht bereits eine + Abstraktion ist. In unserem Beispiel wären dies '(\x.xy)' oder '(\y.xx)'. + Um mit eine Betareduktion durchzuführen, wählen sie zunächst eine + Applikation mit Abstraktion auf der linken Seite aus. In unserem Beispiel ist + der gesamte Term bereits reduzierbar. Sie können den Term nun mit zwei Beta- + Reduktionen in Normalform bringen.

      + +

      Eine Abkürzung selbst definieren

      +

      Geben sie einen gültigen Lambdaterm ein und bestätigen sie mit oder + ENTER. + Mit dem 'Neu'-Button unterhalb der Abkürzungsliste lässt sich nun eine neue + Abkürzung definieren, sofern weder der Name der Abkürzung noch der abgekürzte Term + bereits in der Liste enthalten sind.

      + + \ No newline at end of file diff --git a/res/module/lambda/help/html/data/overview.htm b/res/module/lambda/help/html/data/overview.htm new file mode 100644 index 0000000..012c3a4 --- /dev/null +++ b/res/module/lambda/help/html/data/overview.htm @@ -0,0 +1,30 @@ + + + Einleitung + + + +

      Dies ist die Hilfe des Moduls Lambda-Kalkül

      + +

      Überblick

      +

      Das Modul Lambda-Kalkül ermöglicht es dem Nutzer Lambdaterme einzugeben und auf ihre Korrektheit zu prüfen. + Wurde der Term als korrekt erkannt, so kann nun mit ihm gearbeitet werden.

      + +

      Funktionsumfang

      +

      Das Modul Lambda-Kalkül bietet folgende Funktionen:

      +
        +
      • Terme auf Korrektheit prüfen
      • +
      • Alpha-Konversion anwenden
      • +
      • Beta-Reduktion durchführen
      • +
      • Terme schrittweise automatisch lösen
      • +
      • Terme komplett automatisch lösen
      • +
      • Rechnen mit vordefinierten und selbstdefinierten Abkürzungen
      • +
      • Speichern und Laden von Termen und Abkürzungen
      • +
      + +

      Weitere Hinweise

      +

      Beispielterme aus dem Skript "Algorithmen, Datenstrukturen und Programmierung"1 können im Ordner examples gefunden werden.

      + +
      1) Stand: 21. September 2007, TU Dresden, Fakultät Informatik, Lehrstuhl Grundlagen der Programmierung, Prof. H. Vogler
      + + \ No newline at end of file diff --git a/res/module/lambda/help/html/data/welcomeScreen.htm b/res/module/lambda/help/html/data/welcomeScreen.htm new file mode 100644 index 0000000..d303fa7 --- /dev/null +++ b/res/module/lambda/help/html/data/welcomeScreen.htm @@ -0,0 +1,19 @@ + + + Willkommensbildschirm + + + +

      Der Willkommensbildschirm

      + +

      Überblick

      +

      Wenn das Modul Lambda-Kalkül geoffnet wird zeigt sich als erstes der Willkommensbildschirm. + Es besteht hier die Möglichkeit auszuwählen ob man einen neuen Term eingeben oder einen Term + aus einer Datei laden möchte.

      + +


      + Einen Term eingeben

      +


      + Einen Term laden

      + + \ No newline at end of file diff --git a/res/module/lambda/help/html/data/workScreen.htm b/res/module/lambda/help/html/data/workScreen.htm new file mode 100644 index 0000000..176f5e0 --- /dev/null +++ b/res/module/lambda/help/html/data/workScreen.htm @@ -0,0 +1,63 @@ + + + Arbeitsbildschirm + + + +

      Der Arbeitsbildschirm

      + +

      Überblick

      +

      Der Arbeitsbildschirm gliedert sich in sechs Teile.

      + + +

      1) Die Toolbar

      +
      +

      Die Toolbar bietet folgende Funktionen:

      +
        +
      • Nimmt alle bisherigen Schritte zurück
      • +
      • Nimmt einen Schritte zurück
      • +
      • Geht einen Schritt vorwärts
      • +
      • Geht alle bisherigen Schritte vorwärts
      • +
      • Führt einen automatischen Schritt aus
      • +
      • Führt einen Schritt auf Abkürzungen aus
      • +
      • Führt die Berechenung bis zum Ende aus
      • +
      • Wendet eine Alpha-Konversion auf den selektierten (Teil-)Term an
      • +
      • Führt eine Beta-Reduktion auf dem selektierten (Teil-)Term aus
      • +
      • Zeigt alle freien Variablen des selektierten (Teil-)Terms an
      • +
      • Zeigt alle gebundenen Variablen des selektierten (Teil-)Terms an
      • +
      • Macht alle Klammern grau
      • +
      • Löst eine Abkürzung auf
      • +
      • Versucht den selektierten (Teil-)Term durch eine definierte Abkürzung zu ersetzen
      • +
      + +

      2) Das Eingabefeld

      +
      +

      Hier wird der Lambdaterm zu Beginn der Arbeit mit dem Modul eingegeben. Das Eingabefeld ersetz + automatisch '\' durch Lambdas bei der Eingabe. Auf die Klammerung der Applikation kann hierbei + verzichtet werden, sie wird gemäß Definition linksassoziativ eingefügt (Bsp.: '(\x.xxx)' zu '(\x.((xx)x))' ). + Mit dem Button wird die Eingabe bestätigt. Der Button löscht + das Eingabefeld, sowie Anzeige- und Ausgabefeld.

      + +

      3) Das Ausgabefeld

      +
      +

      Im Ausgabefeld werden alle durchgeführten Berechnungs- und Umformungsschritte aufgelistet. Bei erreichen der + Normalform (welche noch Abkürzungen enthalten kann) wird der Term aus dem Anzeigefeld als letzter Schritt + mit in die Auflistung übernommen.

      + +

      4) Die Abkürzungsliste

      +
      +

      In der Abkürzungsliste werden alle definierten Abkürzungen aufgelistet. Nur diese und alle Zahlen (Bsp.: '<13>') + können bei der Arbeit verwendet werden. Neben einer Reihe vordefinierter Abkürzungen ist es für den Nutzer möglich + eigene Abkürzungen zu definieren. Hier sei auf das Beispiel 'Abkürzungen erstellen' der Hilfe verwiesen.

      + +

      5) Das Arbeitsfeld

      +
      +

      Im Arbeitsfeld wird der aktuelle Term angezeigt. Hier können mit Hilfe der Maus Teilterme ausgewählt + werden, die bearbeitet werden sollen. Ist kein Teilterm ausgewählt so wird auf dem gesamten Term gearbeitet.

      + +

      6) Die Statuszeile

      +
      +

      In der Statuszeile werden Fehlermeldungen und Hinweise ausgegeben, welche beispielsweise auf eine ungültige Eingabe + hinweisen.

      + + \ No newline at end of file diff --git a/res/module/lambda/help/html/index.htm b/res/module/lambda/help/html/index.htm new file mode 100644 index 0000000..84069cf --- /dev/null +++ b/res/module/lambda/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum Modul Lambda Kalkül + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/lambda/help/html/top_frame.htm b/res/module/lambda/help/html/top_frame.htm new file mode 100644 index 0000000..1747570 --- /dev/null +++ b/res/module/lambda/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/CVS/Entries b/res/module/lambda/help/jhelp/CVS/Entries new file mode 100644 index 0000000..f9f4b8b --- /dev/null +++ b/res/module/lambda/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/lambdaIndex.xml/1.1/Thu Aug 6 14:39:02 2009// +/lambdaTOC.xml/1.1/Thu Aug 6 14:39:02 2009// +/lambda_help.hs/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/map.jhm/1.1/Thu Aug 6 14:39:02 2009/-kb/ diff --git a/res/module/lambda/help/jhelp/CVS/Repository b/res/module/lambda/help/jhelp/CVS/Repository new file mode 100644 index 0000000..b6473ad --- /dev/null +++ b/res/module/lambda/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help/jhelp diff --git a/res/module/lambda/help/jhelp/CVS/Root b/res/module/lambda/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..dfebddf --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/DOCS.TAB/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/OFFSETS/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/POSITIONS/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/SCHEMA/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/TMAP/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/config.ini/1.1/Thu Aug 6 14:39:01 2009// diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..35f3799 --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help/jhelp/JavaHelpSearch diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS b/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..be0db5f Binary files /dev/null and b/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..9e8d6d9 --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,4 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿuÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ@k£ +2Šëúêû0³ +î³ ë®Œ*£ +ª«ªª«ã"ªÿ*®ë¨Âº«ú»ú««þûªºÿû®ú®¯¯ªþ«¯ººú¸Âª¿þîªë«ªïúªªêªªª«îªî¿«êªªú«ªîëÿªªª¯úꪺ껪몫«ºêªî¾«ªª®®ïꪪú¾ªºªªªªªªªªªªªªªªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/lambda/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..47c3238 --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ñîaÖ©Ê€0O—ƒ £÷˜¸÷Û7CØ`Ê¢ \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/lambda/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1aa79bf Binary files /dev/null and b/res/module/lambda/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/lambda/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..4a81846 --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=597 id2=1 diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/TMAP b/res/module/lambda/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..e38ae3b Binary files /dev/null and b/res/module/lambda/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/lambda/help/jhelp/JavaHelpSearch/config.ini b/res/module/lambda/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/lambda/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/lambdaIndex.xml b/res/module/lambda/help/jhelp/lambdaIndex.xml new file mode 100644 index 0000000..4c3868b --- /dev/null +++ b/res/module/lambda/help/jhelp/lambdaIndex.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/module/lambda/help/jhelp/lambdaTOC.xml b/res/module/lambda/help/jhelp/lambdaTOC.xml new file mode 100644 index 0000000..98a59e3 --- /dev/null +++ b/res/module/lambda/help/jhelp/lambdaTOC.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/lambda_help.hs b/res/module/lambda/help/jhelp/lambda_help.hs new file mode 100644 index 0000000..866aa64 --- /dev/null +++ b/res/module/lambda/help/jhelp/lambda_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Modul Lambda Kalkül + + + + + lambda + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + lambdaTOC.xml + + + + Index + + javax.help.IndexView + lambdaIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/lambda/help/jhelp/map.jhm b/res/module/lambda/help/jhelp/map.jhm new file mode 100644 index 0000000..eb3e7cb --- /dev/null +++ b/res/module/lambda/help/jhelp/map.jhm @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/lambda/help/pics/CVS/Entries b/res/module/lambda/help/pics/CVS/Entries new file mode 100644 index 0000000..df6f016 --- /dev/null +++ b/res/module/lambda/help/pics/CVS/Entries @@ -0,0 +1,27 @@ +/alpha.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/autoStep.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/beta.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/boundVar.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/brackets.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/finishAlg.gif/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/freeVar.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/logo.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/performAll.gif/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/performStep.gif/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/sc_brackets.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/sc_brackets_x.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/shortcutStep.png/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/undoAll.gif/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/undoStep.gif/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/welcome_screen.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/welcome_screen_load.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/welcome_screen_new.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_input.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_input_clear.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_input_ok.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_output.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_render.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_shortcut.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_statusbar.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ +/work_screen_toolbar.jpg/1.1/Thu Aug 6 14:39:00 2009/-kb/ diff --git a/res/module/lambda/help/pics/CVS/Repository b/res/module/lambda/help/pics/CVS/Repository new file mode 100644 index 0000000..2cc65e8 --- /dev/null +++ b/res/module/lambda/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/help/pics diff --git a/res/module/lambda/help/pics/CVS/Root b/res/module/lambda/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/help/pics/alpha.jpg b/res/module/lambda/help/pics/alpha.jpg new file mode 100644 index 0000000..2d2cac0 Binary files /dev/null and b/res/module/lambda/help/pics/alpha.jpg differ diff --git a/res/module/lambda/help/pics/autoStep.jpg b/res/module/lambda/help/pics/autoStep.jpg new file mode 100644 index 0000000..642e8ea Binary files /dev/null and b/res/module/lambda/help/pics/autoStep.jpg differ diff --git a/res/module/lambda/help/pics/beta.jpg b/res/module/lambda/help/pics/beta.jpg new file mode 100644 index 0000000..8d1c766 Binary files /dev/null and b/res/module/lambda/help/pics/beta.jpg differ diff --git a/res/module/lambda/help/pics/boundVar.jpg b/res/module/lambda/help/pics/boundVar.jpg new file mode 100644 index 0000000..6ae0994 Binary files /dev/null and b/res/module/lambda/help/pics/boundVar.jpg differ diff --git a/res/module/lambda/help/pics/brackets.jpg b/res/module/lambda/help/pics/brackets.jpg new file mode 100644 index 0000000..2803bb4 Binary files /dev/null and b/res/module/lambda/help/pics/brackets.jpg differ diff --git a/res/module/lambda/help/pics/finishAlg.gif b/res/module/lambda/help/pics/finishAlg.gif new file mode 100644 index 0000000..347d32c Binary files /dev/null and b/res/module/lambda/help/pics/finishAlg.gif differ diff --git a/res/module/lambda/help/pics/freeVar.jpg b/res/module/lambda/help/pics/freeVar.jpg new file mode 100644 index 0000000..3101ab8 Binary files /dev/null and b/res/module/lambda/help/pics/freeVar.jpg differ diff --git a/res/module/lambda/help/pics/logo.jpg b/res/module/lambda/help/pics/logo.jpg new file mode 100644 index 0000000..c8b015c Binary files /dev/null and b/res/module/lambda/help/pics/logo.jpg differ diff --git a/res/module/lambda/help/pics/performAll.gif b/res/module/lambda/help/pics/performAll.gif new file mode 100644 index 0000000..be79869 Binary files /dev/null and b/res/module/lambda/help/pics/performAll.gif differ diff --git a/res/module/lambda/help/pics/performStep.gif b/res/module/lambda/help/pics/performStep.gif new file mode 100644 index 0000000..b5ee47e Binary files /dev/null and b/res/module/lambda/help/pics/performStep.gif differ diff --git a/res/module/lambda/help/pics/sc_brackets.jpg b/res/module/lambda/help/pics/sc_brackets.jpg new file mode 100644 index 0000000..b714f91 Binary files /dev/null and b/res/module/lambda/help/pics/sc_brackets.jpg differ diff --git a/res/module/lambda/help/pics/sc_brackets_x.jpg b/res/module/lambda/help/pics/sc_brackets_x.jpg new file mode 100644 index 0000000..4f37548 Binary files /dev/null and b/res/module/lambda/help/pics/sc_brackets_x.jpg differ diff --git a/res/module/lambda/help/pics/shortcutStep.png b/res/module/lambda/help/pics/shortcutStep.png new file mode 100644 index 0000000..a5f8b63 Binary files /dev/null and b/res/module/lambda/help/pics/shortcutStep.png differ diff --git a/res/module/lambda/help/pics/undoAll.gif b/res/module/lambda/help/pics/undoAll.gif new file mode 100644 index 0000000..5d27cb6 Binary files /dev/null and b/res/module/lambda/help/pics/undoAll.gif differ diff --git a/res/module/lambda/help/pics/undoStep.gif b/res/module/lambda/help/pics/undoStep.gif new file mode 100644 index 0000000..4551e4f Binary files /dev/null and b/res/module/lambda/help/pics/undoStep.gif differ diff --git a/res/module/lambda/help/pics/welcome_screen.jpg b/res/module/lambda/help/pics/welcome_screen.jpg new file mode 100644 index 0000000..d64b5bd Binary files /dev/null and b/res/module/lambda/help/pics/welcome_screen.jpg differ diff --git a/res/module/lambda/help/pics/welcome_screen_load.jpg b/res/module/lambda/help/pics/welcome_screen_load.jpg new file mode 100644 index 0000000..141a7eb Binary files /dev/null and b/res/module/lambda/help/pics/welcome_screen_load.jpg differ diff --git a/res/module/lambda/help/pics/welcome_screen_new.jpg b/res/module/lambda/help/pics/welcome_screen_new.jpg new file mode 100644 index 0000000..9079e5c Binary files /dev/null and b/res/module/lambda/help/pics/welcome_screen_new.jpg differ diff --git a/res/module/lambda/help/pics/work_screen.jpg b/res/module/lambda/help/pics/work_screen.jpg new file mode 100644 index 0000000..9cb1e06 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_input.jpg b/res/module/lambda/help/pics/work_screen_input.jpg new file mode 100644 index 0000000..5ebb4bb Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_input.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_input_clear.jpg b/res/module/lambda/help/pics/work_screen_input_clear.jpg new file mode 100644 index 0000000..905b231 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_input_clear.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_input_ok.jpg b/res/module/lambda/help/pics/work_screen_input_ok.jpg new file mode 100644 index 0000000..50b46e5 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_input_ok.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_output.jpg b/res/module/lambda/help/pics/work_screen_output.jpg new file mode 100644 index 0000000..9e4685b Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_output.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_render.jpg b/res/module/lambda/help/pics/work_screen_render.jpg new file mode 100644 index 0000000..61a3921 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_render.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_shortcut.jpg b/res/module/lambda/help/pics/work_screen_shortcut.jpg new file mode 100644 index 0000000..b4a5413 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_shortcut.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_statusbar.jpg b/res/module/lambda/help/pics/work_screen_statusbar.jpg new file mode 100644 index 0000000..c062c77 Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_statusbar.jpg differ diff --git a/res/module/lambda/help/pics/work_screen_toolbar.jpg b/res/module/lambda/help/pics/work_screen_toolbar.jpg new file mode 100644 index 0000000..0012c6c Binary files /dev/null and b/res/module/lambda/help/pics/work_screen_toolbar.jpg differ diff --git a/res/module/lambda/help/style.css b/res/module/lambda/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/lambda/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/lambda/lambda_pix/CVS/Entries b/res/module/lambda/lambda_pix/CVS/Entries new file mode 100644 index 0000000..f0790c3 --- /dev/null +++ b/res/module/lambda/lambda_pix/CVS/Entries @@ -0,0 +1,15 @@ +/WelcomeNew.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/WelcomeNewOver.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/WelcomeOpen.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/WelcomeOpenOver.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/alpha.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/autoStep.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/beta.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/boundVar.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/brackets.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/freeVar.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/logo.jpg/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/logo_big.jpg/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/sc_brackets.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/sc_brackets_x.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/shortcutStep.png/1.1/Thu Aug 6 14:39:02 2009/-kb/ diff --git a/res/module/lambda/lambda_pix/CVS/Repository b/res/module/lambda/lambda_pix/CVS/Repository new file mode 100644 index 0000000..9688a81 --- /dev/null +++ b/res/module/lambda/lambda_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/lambda/lambda_pix diff --git a/res/module/lambda/lambda_pix/CVS/Root b/res/module/lambda/lambda_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/lambda/lambda_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/lambda/lambda_pix/WelcomeNew.png b/res/module/lambda/lambda_pix/WelcomeNew.png new file mode 100644 index 0000000..1ceb15a Binary files /dev/null and b/res/module/lambda/lambda_pix/WelcomeNew.png differ diff --git a/res/module/lambda/lambda_pix/WelcomeNewOver.png b/res/module/lambda/lambda_pix/WelcomeNewOver.png new file mode 100644 index 0000000..9079e5c Binary files /dev/null and b/res/module/lambda/lambda_pix/WelcomeNewOver.png differ diff --git a/res/module/lambda/lambda_pix/WelcomeOpen.png b/res/module/lambda/lambda_pix/WelcomeOpen.png new file mode 100644 index 0000000..6f2023f Binary files /dev/null and b/res/module/lambda/lambda_pix/WelcomeOpen.png differ diff --git a/res/module/lambda/lambda_pix/WelcomeOpenOver.png b/res/module/lambda/lambda_pix/WelcomeOpenOver.png new file mode 100644 index 0000000..141a7eb Binary files /dev/null and b/res/module/lambda/lambda_pix/WelcomeOpenOver.png differ diff --git a/res/module/lambda/lambda_pix/alpha.png b/res/module/lambda/lambda_pix/alpha.png new file mode 100644 index 0000000..26f224f Binary files /dev/null and b/res/module/lambda/lambda_pix/alpha.png differ diff --git a/res/module/lambda/lambda_pix/autoStep.png b/res/module/lambda/lambda_pix/autoStep.png new file mode 100644 index 0000000..c393b96 Binary files /dev/null and b/res/module/lambda/lambda_pix/autoStep.png differ diff --git a/res/module/lambda/lambda_pix/beta.png b/res/module/lambda/lambda_pix/beta.png new file mode 100644 index 0000000..8171c77 Binary files /dev/null and b/res/module/lambda/lambda_pix/beta.png differ diff --git a/res/module/lambda/lambda_pix/boundVar.png b/res/module/lambda/lambda_pix/boundVar.png new file mode 100644 index 0000000..dcfb5a7 Binary files /dev/null and b/res/module/lambda/lambda_pix/boundVar.png differ diff --git a/res/module/lambda/lambda_pix/brackets.png b/res/module/lambda/lambda_pix/brackets.png new file mode 100644 index 0000000..49e7287 Binary files /dev/null and b/res/module/lambda/lambda_pix/brackets.png differ diff --git a/res/module/lambda/lambda_pix/freeVar.png b/res/module/lambda/lambda_pix/freeVar.png new file mode 100644 index 0000000..53d8f28 Binary files /dev/null and b/res/module/lambda/lambda_pix/freeVar.png differ diff --git a/res/module/lambda/lambda_pix/logo.jpg b/res/module/lambda/lambda_pix/logo.jpg new file mode 100644 index 0000000..c8b015c Binary files /dev/null and b/res/module/lambda/lambda_pix/logo.jpg differ diff --git a/res/module/lambda/lambda_pix/logo_big.jpg b/res/module/lambda/lambda_pix/logo_big.jpg new file mode 100644 index 0000000..1261126 Binary files /dev/null and b/res/module/lambda/lambda_pix/logo_big.jpg differ diff --git a/res/module/lambda/lambda_pix/sc_brackets.png b/res/module/lambda/lambda_pix/sc_brackets.png new file mode 100644 index 0000000..2c4ea74 Binary files /dev/null and b/res/module/lambda/lambda_pix/sc_brackets.png differ diff --git a/res/module/lambda/lambda_pix/sc_brackets_x.png b/res/module/lambda/lambda_pix/sc_brackets_x.png new file mode 100644 index 0000000..72f3029 Binary files /dev/null and b/res/module/lambda/lambda_pix/sc_brackets_x.png differ diff --git a/res/module/lambda/lambda_pix/shortcutStep.png b/res/module/lambda/lambda_pix/shortcutStep.png new file mode 100644 index 0000000..a5f8b63 Binary files /dev/null and b/res/module/lambda/lambda_pix/shortcutStep.png differ diff --git a/res/module/pulsemem/CVS/Entries b/res/module/pulsemem/CVS/Entries new file mode 100644 index 0000000..e3ca217 --- /dev/null +++ b/res/module/pulsemem/CVS/Entries @@ -0,0 +1,3 @@ +D/help//// +/manifest.mf/1.1/Wed Jan 16 19:19:19 2008/-ko/ +D/pulsemem_pix//// diff --git a/res/module/pulsemem/CVS/Repository b/res/module/pulsemem/CVS/Repository new file mode 100644 index 0000000..d3623a5 --- /dev/null +++ b/res/module/pulsemem/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem diff --git a/res/module/pulsemem/CVS/Root b/res/module/pulsemem/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/CVS/Entries b/res/module/pulsemem/help/CVS/Entries new file mode 100644 index 0000000..e394f7b --- /dev/null +++ b/res/module/pulsemem/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Wed Jan 16 19:19:16 2008/-ko/ diff --git a/res/module/pulsemem/help/CVS/Repository b/res/module/pulsemem/help/CVS/Repository new file mode 100644 index 0000000..5c3a675 --- /dev/null +++ b/res/module/pulsemem/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help diff --git a/res/module/pulsemem/help/CVS/Root b/res/module/pulsemem/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/html/CVS/Entries b/res/module/pulsemem/help/html/CVS/Entries new file mode 100644 index 0000000..44e891c --- /dev/null +++ b/res/module/pulsemem/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ +D/data//// +/index.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ +/top_frame.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ diff --git a/res/module/pulsemem/help/html/CVS/Repository b/res/module/pulsemem/help/html/CVS/Repository new file mode 100644 index 0000000..63eb0f8 --- /dev/null +++ b/res/module/pulsemem/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help/html diff --git a/res/module/pulsemem/help/html/CVS/Root b/res/module/pulsemem/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/html/contents.htm b/res/module/pulsemem/help/html/contents.htm new file mode 100644 index 0000000..90c8826 --- /dev/null +++ b/res/module/pulsemem/help/html/contents.htm @@ -0,0 +1,20 @@ + + + Inhaltsverzeichnis + + + + +

      Das Modul Pulsemem

      + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/html/data/CVS/Entries b/res/module/pulsemem/help/html/data/CVS/Entries new file mode 100644 index 0000000..8381359 --- /dev/null +++ b/res/module/pulsemem/help/html/data/CVS/Entries @@ -0,0 +1,3 @@ +/overview.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ +/peculiarity.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ +/workspace.htm/1.1/Wed Jan 16 19:19:14 2008/-ko/ diff --git a/res/module/pulsemem/help/html/data/CVS/Repository b/res/module/pulsemem/help/html/data/CVS/Repository new file mode 100644 index 0000000..c76024d --- /dev/null +++ b/res/module/pulsemem/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help/html/data diff --git a/res/module/pulsemem/help/html/data/CVS/Root b/res/module/pulsemem/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/html/data/overview.htm b/res/module/pulsemem/help/html/data/overview.htm new file mode 100644 index 0000000..215c553 --- /dev/null +++ b/res/module/pulsemem/help/html/data/overview.htm @@ -0,0 +1,30 @@ + + + Das Modul Pulsierender Speicher + + + + +

      Das Modul Pulsierender Speicher

      + +

      Kurzbeschreibung

      +

      + Obwohl moderne objektorientierte Hochsprachen wie C# oder Java den herkömmlichen Sprachen auf vielen + Gebieten immer mehr den Rang ablaufen arbeiten doch alle Compuerprogramme immer auf dieselbe Art und Weise. + Besonders der Stapelspeicher spielt für deren Funktionsweise eine wichtige Rolle. Dieses Modul soll dem + Nutzer dabei helfen die arbeitsweise des Stapelspeichers und auch Grundlagen der Zeigerarithmetik + zu verstehen. Das Modul ist in der Lage, Programme der in der Vorlesung "Algorithmen und Datenstrukturen" + eingeführten Sprache C0 zu interpretieren und auszuführen. +

      +

      Funktionsbeschreibung

      +
    • Parsen und Interpretieren eines C0 Programmes
    • +
    • Formattierung des Programmcodes und automatische Generierung der Rücksprungmarken
    • +
    • Setzen von Haltepunkten an beliebigen Programmstellen
    • +
    • Visualisierung des pulsierenden Speichers an den gewählten Haltepunkten
    • +
    • Import und Export geschriebener C0 Programme
    • + +
      +
      + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/html/data/peculiarity.htm b/res/module/pulsemem/help/html/data/peculiarity.htm new file mode 100644 index 0000000..2722010 --- /dev/null +++ b/res/module/pulsemem/help/html/data/peculiarity.htm @@ -0,0 +1,18 @@ + + + Besonderheiten + + + +

      Besonderheiten

      + +

      C0 Syntax

      +

      + Dieses Programm orientiert sich an der Definition der in der Vorlesung + Algorithmen und Datenstrukturen eingeführten Syntax. Nach dieser sind + im Quellcode keine Kommentare erlaubt. Auch Rücksprungmarken gehören nicht + zur Syntax eines C0 Programmes. Folglich sind Programme mit manuell gesetzten + Rücksprungmarken syntaktisch nicht korrekt und werden vom Parser als Syntaxfehler gemeldet. +

      + + \ No newline at end of file diff --git a/res/module/pulsemem/help/html/data/workspace.htm b/res/module/pulsemem/help/html/data/workspace.htm new file mode 100644 index 0000000..a83aeb6 --- /dev/null +++ b/res/module/pulsemem/help/html/data/workspace.htm @@ -0,0 +1,102 @@ + + + Die Arbeitsfläche + + + + +

      Die Arbeitsfläche

      +
      + +
      +

      + Die Arbeitsfläche des Moduls kann zwei Zustände einnehmen. Der Nutzer kann sich entweder im Editiermodus + oder im Speicherbetrachtungsmodus befinden. In den Betrachtungsmodus gelangt man nur indem man einen gültigen + C0-Quellcode eingibt, der geparst und interpretiert werden kann. Konnte der C0-Quellcode nicht validiert werden, so + müssen zuerst alle syntaktischen Fehler bereinigen werden. +

      +

      Die Menüleiste

      +
      + +
      +

      C0 Datei importieren

      +

      + Mit Hilfe dieser Option kann eine beliebige Textdatei in den Editor geladen werden. Ist der geladene + Text ein gültiger C0 Quellcode, so wird dieser auch gleich formatiert. Beim Wechsel in den Betrachtungsmodus werden + außerdem alle Labels im Quellcode als Haltepunkte markiert. +

      +

      C0 Datei exportieren

      +

      + Mit Hilfe dieser Option kann die aktuelle Eingabe im Editorfenster in eine externe Datei gespeichert werden. +

      +

      Interpretation und Ausführung

      +

      + Mit Hilfe dieser Option wird der im Editor eingegebene Quellcode auf seine Gültigkeit überprüft. Sind alle + syntaktischen Voraussetzungen erfüllt wird der Code interpretiert und ausgeführt. Hierbei bittet das Programm + den Nutzer falls nötig um diverse Eingaben und erzeugt eine interne Speichertabelle. Auch während der + Ausführung des Programmes können noch Fehler auftreten. Die interne Speichertabelle kann sehr groß werden + und so kann es bereits bei kleinen Programmen mit genügend Rekursionen bzw. Iterationen zu einem Speicherüberlauf + kommen. Versuchen Sie in diesem Fall die Anzahl der Rekursionen und Iterationen zu senken und suchen Sie + in ihrem Programm nach Endlosschleifen. + Wenn das Programm erfolgreich ausgeführt werden konnte gelangt der Nutzer in den Speicherbetrachtungsmodus.
      + Diese Option steht nur im Editiermodus zur Verfügung. +

      +

      Rückkehr in den Editiermodus

      +

      + Mit dieser Option gelangt der Nutzer zurück in den Editiermodus. Bei Änderungen am Quelltext, gehen bereits + gesetzte Haltepunkte verloren, da der Text eventuell neu formatiert werden muss.
      + Diese Option steht erst im Speicherbetrachtungsmodus zur Verfügung. +

      +

      Zurück zum ersten Haltepunkt

      +

      + Mit dieser Option wird die komplette Tabelle in der Speicherabbildfläche geleert und der Programmzustand + am ersten Haltepunkt wird dargestellt.
      + Diese Option steht erst im Speicherbetrachtungsmodus zur Verfügung. +

      +

      Zurück zum vorherigen Haltepunkt

      +

      + Mit dieser Option geht der Nutzer im Programmablauf zur Position des vorherigen Haltepunktes.
      + Diese Option steht erst im Speicherbetrachtungsmodus zur Verfügung. +

      +

      Zum nächsten Haltepunkt

      +

      + Mit dieser Option gelangt der Nutzer im Programmablauf zur Position des nächsten gesetzten Haltepunktes.
      + Diese Option steht erst im Speicherbetrachtungsmodus zur Verfügung. +

      +

      Zum letzten Haltepunkt

      +

      + Mit dieser Option gelangt der Nutzer zur Position des letzten Haltepunktes im Programmablauf.
      + Diese Option steht erst im Speicherbetrachtungsmodus zur Verfügung. +

      + +

      Die Editorfläche

      +
      + +
      +

      + In dieser Fläche befindet sich die Textbox mit dem aktuellen Quellcode. Wenn sich das Programm im + Editiermodus befindet ist es möglich diesen Quellcode direkt zu bearbeiten. Außerhalb des Editiermodus + ist eine Veränderung des Quellcodes nicht möglich. + In der kleinen Fläche zwischen der Zeilenangabe und der Textbox können die Haltepunkte durch + einen einfachen Mausklick gesetzt bzw. wieder entfernt werden. Haltepunkte können immer gesetzt + oder entfernt werden, selbst wenn das Programm bereits ausgeführt wurde. +

      +

      Die Speicherabbildfläche

      + +

      + Diese Fläche bildet das Herz des Moduls. In der Tabelle wird der komplette Programmzustand an den + gesetzten Haltepunkten dargestellt. Die erste Spalte identifiziert den jeweiligen Haltepunkt anhand seiner + Zeile im Quellcode. Befindet sich in der selben Zeile auch ein Label, so wird zusätzlich + dessen Name angezeigt.
      + Die zweite Spalte stellt den jeweiligen Rücksprungmarkenkeller dar. Die darin enthaltenen Rücksprungmarken + wurden beim Interpretieren automatisch generiert und sind ebenfalls im Quellcode zu finden.
      + Alle weiteren Spalten stellen den Zustand der Speicherzellen dar. Der Spaltenname steht hier gleichzeitig für den + Index der Speicherzelle. Die ersten Speicherzellen mit einem schwarzen Tabellenkopf sind die globalen Variablen. + Alle weiteren Speicherzellen sind lokale Variablen einer Funktion. Wird eine Funktion verlassen + so wird der Speicher dieser Zelle wieder freigegeben und kann später von einer anderen lokalen Variablen + in einer anderen Funktion wiederverwendet werden.
      + Der Eintrag in einer solchen Tabellenzelle zeigt den Namen der Variable an dem Speicherplatz und deren aktuellen + Wert. Zeiger werden kursiv dargestellt und ihr Wert steht fu¨r die Speicherzelle, auf die sie zeigen. +

      + + \ No newline at end of file diff --git a/res/module/pulsemem/help/html/index.htm b/res/module/pulsemem/help/html/index.htm new file mode 100644 index 0000000..5fa70f5 --- /dev/null +++ b/res/module/pulsemem/help/html/index.htm @@ -0,0 +1,26 @@ + + + + Hilfe zum Modul Pulsemem + + + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + diff --git a/res/module/pulsemem/help/html/top_frame.htm b/res/module/pulsemem/help/html/top_frame.htm new file mode 100644 index 0000000..afd3315 --- /dev/null +++ b/res/module/pulsemem/help/html/top_frame.htm @@ -0,0 +1,12 @@ + + + oberer_frame + + + + + Logo + + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/CVS/Entries b/res/module/pulsemem/help/jhelp/CVS/Entries new file mode 100644 index 0000000..c262dc8 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/map.jhm/1.1/Wed Jan 16 19:19:19 2008/-ko/ +/pulsememIndex.xml/1.1/Wed Jan 16 19:19:19 2008/-ko/ +/pulsememTOC.xml/1.1/Wed Jan 16 19:19:19 2008/-ko/ +/pulsemem_help.hs/1.1/Wed Jan 16 19:19:19 2008/-ko/ diff --git a/res/module/pulsemem/help/jhelp/CVS/Repository b/res/module/pulsemem/help/jhelp/CVS/Repository new file mode 100644 index 0000000..d06edc7 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help/jhelp diff --git a/res/module/pulsemem/help/jhelp/CVS/Root b/res/module/pulsemem/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..a504ce8 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/DOCS.TAB/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/OFFSETS/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/POSITIONS/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/SCHEMA/1.1/Wed Jan 16 19:19:18 2008/-ko/ +/TMAP/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/config.ini/1.1/Wed Jan 16 19:19:18 2008/-ko/ diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..065efb9 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help/jhelp/JavaHelpSearch diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS b/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..be0db5f Binary files /dev/null and b/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..9e8d6d9 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,4 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿuÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ@k£ +2Šëúêû0³ +î³ ë®Œ*£ +ª«ªª«ã"ªÿ*®ë¨Âº«ú»ú««þûªºÿû®ú®¯¯ªþ«¯ººú¸Âª¿þîªë«ªïúªªêªªª«îªî¿«êªªú«ªîëÿªªª¯úꪺ껪몫«ºêªî¾«ªª®®ïꪪú¾ªºªªªªªªªªªªªªªªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/pulsemem/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..47c3238 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ñîaÖ©Ê€0O—ƒ £÷˜¸÷Û7CØ`Ê¢ \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/pulsemem/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1aa79bf Binary files /dev/null and b/res/module/pulsemem/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/pulsemem/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..4a81846 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=597 id2=1 diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/TMAP b/res/module/pulsemem/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..e38ae3b Binary files /dev/null and b/res/module/pulsemem/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/pulsemem/help/jhelp/JavaHelpSearch/config.ini b/res/module/pulsemem/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..f0ae630 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus, z.B. \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/map.jhm b/res/module/pulsemem/help/jhelp/map.jhm new file mode 100644 index 0000000..8d24bad --- /dev/null +++ b/res/module/pulsemem/help/jhelp/map.jhm @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/pulsememIndex.xml b/res/module/pulsemem/help/jhelp/pulsememIndex.xml new file mode 100644 index 0000000..71ee730 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/pulsememIndex.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/res/module/pulsemem/help/jhelp/pulsememTOC.xml b/res/module/pulsemem/help/jhelp/pulsememTOC.xml new file mode 100644 index 0000000..5bf8770 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/pulsememTOC.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/jhelp/pulsemem_help.hs b/res/module/pulsemem/help/jhelp/pulsemem_help.hs new file mode 100644 index 0000000..361e592 --- /dev/null +++ b/res/module/pulsemem/help/jhelp/pulsemem_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Pulsemem-Modul + + + + + pulsemem + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + pulsememTOC.xml + + + + Index + + javax.help.IndexView + pulsememIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/pulsemem/help/pics/CVS/Entries b/res/module/pulsemem/help/pics/CVS/Entries new file mode 100644 index 0000000..5c3363e --- /dev/null +++ b/res/module/pulsemem/help/pics/CVS/Entries @@ -0,0 +1,6 @@ +/editor.jpg/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/icon.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/logo_help.png/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/memoryview.jpg/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/menubar.jpg/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/module.jpg/1.1/Wed Jan 16 19:19:18 2008/-kb/ diff --git a/res/module/pulsemem/help/pics/CVS/Repository b/res/module/pulsemem/help/pics/CVS/Repository new file mode 100644 index 0000000..99aa159 --- /dev/null +++ b/res/module/pulsemem/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/help/pics diff --git a/res/module/pulsemem/help/pics/CVS/Root b/res/module/pulsemem/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/help/pics/editor.jpg b/res/module/pulsemem/help/pics/editor.jpg new file mode 100644 index 0000000..d859a4e Binary files /dev/null and b/res/module/pulsemem/help/pics/editor.jpg differ diff --git a/res/module/pulsemem/help/pics/icon.gif b/res/module/pulsemem/help/pics/icon.gif new file mode 100644 index 0000000..1afae24 Binary files /dev/null and b/res/module/pulsemem/help/pics/icon.gif differ diff --git a/res/module/pulsemem/help/pics/logo_help.png b/res/module/pulsemem/help/pics/logo_help.png new file mode 100644 index 0000000..e425983 Binary files /dev/null and b/res/module/pulsemem/help/pics/logo_help.png differ diff --git a/res/module/pulsemem/help/pics/memoryview.jpg b/res/module/pulsemem/help/pics/memoryview.jpg new file mode 100644 index 0000000..0427dc8 Binary files /dev/null and b/res/module/pulsemem/help/pics/memoryview.jpg differ diff --git a/res/module/pulsemem/help/pics/menubar.jpg b/res/module/pulsemem/help/pics/menubar.jpg new file mode 100644 index 0000000..54eb5ae Binary files /dev/null and b/res/module/pulsemem/help/pics/menubar.jpg differ diff --git a/res/module/pulsemem/help/pics/module.jpg b/res/module/pulsemem/help/pics/module.jpg new file mode 100644 index 0000000..236343d Binary files /dev/null and b/res/module/pulsemem/help/pics/module.jpg differ diff --git a/res/module/pulsemem/help/style.css b/res/module/pulsemem/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/pulsemem/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/pulsemem/manifest.mf b/res/module/pulsemem/manifest.mf new file mode 100644 index 0000000..7565a2c --- /dev/null +++ b/res/module/pulsemem/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.2 +Class-Path: ../j-Algo.jar ../../extlibs/parser.jar ../../extlibs/antlr-3.0b6.jar + diff --git a/res/module/pulsemem/pulsemem_pix/CVS/Entries b/res/module/pulsemem/pulsemem_pix/CVS/Entries new file mode 100644 index 0000000..bd3df9a --- /dev/null +++ b/res/module/pulsemem/pulsemem_pix/CVS/Entries @@ -0,0 +1,16 @@ +/backward_nav.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/exportCFile.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/forward_nav.gif/1.1/Wed Jan 16 19:19:17 2008/-kb/ +/generic_element.gif/1.1/Wed Jan 16 19:19:17 2008/-kb/ +/icon.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/importCFile.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/importzip_wiz.png/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/newfile_wiz.png/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/progress_stop.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/quick_fix.png/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/restart_task.gif/1.1/Wed Jan 16 19:19:17 2008/-kb/ +/shift_l_edit.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/shift_r_edit.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/start_task.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/trash.gif/1.1/Wed Jan 16 19:19:18 2008/-kb/ +/workset_wiz.png/1.1/Wed Jan 16 19:19:18 2008/-kb/ diff --git a/res/module/pulsemem/pulsemem_pix/CVS/Repository b/res/module/pulsemem/pulsemem_pix/CVS/Repository new file mode 100644 index 0000000..e5c3e7a --- /dev/null +++ b/res/module/pulsemem/pulsemem_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/pulsemem/pulsemem_pix diff --git a/res/module/pulsemem/pulsemem_pix/CVS/Root b/res/module/pulsemem/pulsemem_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/pulsemem/pulsemem_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/pulsemem/pulsemem_pix/backward_nav.gif b/res/module/pulsemem/pulsemem_pix/backward_nav.gif new file mode 100644 index 0000000..4fb4150 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/backward_nav.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/exportCFile.gif b/res/module/pulsemem/pulsemem_pix/exportCFile.gif new file mode 100644 index 0000000..9e62914 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/exportCFile.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/forward_nav.gif b/res/module/pulsemem/pulsemem_pix/forward_nav.gif new file mode 100644 index 0000000..e2f8c3e Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/forward_nav.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/generic_element.gif b/res/module/pulsemem/pulsemem_pix/generic_element.gif new file mode 100644 index 0000000..bf043f9 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/generic_element.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/icon.gif b/res/module/pulsemem/pulsemem_pix/icon.gif new file mode 100644 index 0000000..1afae24 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/icon.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/importCFile.gif b/res/module/pulsemem/pulsemem_pix/importCFile.gif new file mode 100644 index 0000000..92af02a Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/importCFile.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/importzip_wiz.png b/res/module/pulsemem/pulsemem_pix/importzip_wiz.png new file mode 100644 index 0000000..38d0216 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/importzip_wiz.png differ diff --git a/res/module/pulsemem/pulsemem_pix/newfile_wiz.png b/res/module/pulsemem/pulsemem_pix/newfile_wiz.png new file mode 100644 index 0000000..b3f71ae Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/newfile_wiz.png differ diff --git a/res/module/pulsemem/pulsemem_pix/progress_stop.gif b/res/module/pulsemem/pulsemem_pix/progress_stop.gif new file mode 100644 index 0000000..dc47edf Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/progress_stop.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/quick_fix.png b/res/module/pulsemem/pulsemem_pix/quick_fix.png new file mode 100644 index 0000000..3130711 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/quick_fix.png differ diff --git a/res/module/pulsemem/pulsemem_pix/restart_task.gif b/res/module/pulsemem/pulsemem_pix/restart_task.gif new file mode 100644 index 0000000..02448ca Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/restart_task.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/shift_l_edit.gif b/res/module/pulsemem/pulsemem_pix/shift_l_edit.gif new file mode 100644 index 0000000..328e97e Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/shift_l_edit.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/shift_r_edit.gif b/res/module/pulsemem/pulsemem_pix/shift_r_edit.gif new file mode 100644 index 0000000..c39cf62 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/shift_r_edit.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/start_task.gif b/res/module/pulsemem/pulsemem_pix/start_task.gif new file mode 100644 index 0000000..ec477ea Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/start_task.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/trash.gif b/res/module/pulsemem/pulsemem_pix/trash.gif new file mode 100644 index 0000000..bf961b3 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/trash.gif differ diff --git a/res/module/pulsemem/pulsemem_pix/workset_wiz.png b/res/module/pulsemem/pulsemem_pix/workset_wiz.png new file mode 100644 index 0000000..b720214 Binary files /dev/null and b/res/module/pulsemem/pulsemem_pix/workset_wiz.png differ diff --git a/res/module/testModule/CVS/Entries b/res/module/testModule/CVS/Entries new file mode 100644 index 0000000..281fcc3 --- /dev/null +++ b/res/module/testModule/CVS/Entries @@ -0,0 +1,2 @@ +D/help//// +D/test_pix//// diff --git a/res/module/testModule/CVS/Repository b/res/module/testModule/CVS/Repository new file mode 100644 index 0000000..61dcc7e --- /dev/null +++ b/res/module/testModule/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule diff --git a/res/module/testModule/CVS/Root b/res/module/testModule/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/CVS/Entries b/res/module/testModule/help/CVS/Entries new file mode 100644 index 0000000..6bc5cb1 --- /dev/null +++ b/res/module/testModule/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Wed Mar 29 11:51:56 2006/-kb/ diff --git a/res/module/testModule/help/CVS/Repository b/res/module/testModule/help/CVS/Repository new file mode 100644 index 0000000..9856c87 --- /dev/null +++ b/res/module/testModule/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help diff --git a/res/module/testModule/help/CVS/Root b/res/module/testModule/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/html/CVS/Entries b/res/module/testModule/help/html/CVS/Entries new file mode 100644 index 0000000..2e1ce2f --- /dev/null +++ b/res/module/testModule/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Wed Mar 29 11:51:56 2006// +D/data//// +/index.htm/1.1/Wed Mar 29 11:51:56 2006// +/top_frame.htm/1.1/Wed Mar 29 11:51:56 2006// diff --git a/res/module/testModule/help/html/CVS/Repository b/res/module/testModule/help/html/CVS/Repository new file mode 100644 index 0000000..e5058a6 --- /dev/null +++ b/res/module/testModule/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help/html diff --git a/res/module/testModule/help/html/CVS/Root b/res/module/testModule/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/html/contents.htm b/res/module/testModule/help/html/contents.htm new file mode 100644 index 0000000..e69a59b --- /dev/null +++ b/res/module/testModule/help/html/contents.htm @@ -0,0 +1,109 @@ + + + Inhaltsverzeichnis + + + +
        + Das Modul AVL + +
      + + \ No newline at end of file diff --git a/res/module/testModule/help/html/data/CVS/Entries b/res/module/testModule/help/html/data/CVS/Entries new file mode 100644 index 0000000..8279527 --- /dev/null +++ b/res/module/testModule/help/html/data/CVS/Entries @@ -0,0 +1 @@ +/overview.htm/1.1/Wed Mar 29 11:51:56 2006// diff --git a/res/module/testModule/help/html/data/CVS/Repository b/res/module/testModule/help/html/data/CVS/Repository new file mode 100644 index 0000000..8ed274b --- /dev/null +++ b/res/module/testModule/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help/html/data diff --git a/res/module/testModule/help/html/data/CVS/Root b/res/module/testModule/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/html/data/overview.htm b/res/module/testModule/help/html/data/overview.htm new file mode 100644 index 0000000..e686f9e --- /dev/null +++ b/res/module/testModule/help/html/data/overview.htm @@ -0,0 +1,12 @@ + + + Einleitung + + + +

      Dies ist die Hilfe des Testmodules

      + +

      Hier also mal eine kleinere Überschrift

      +

      Leider zeichnet sich dieser Absatz weder mit Inhalt noch mit Sinn aus.

      + + \ No newline at end of file diff --git a/res/module/testModule/help/html/index.htm b/res/module/testModule/help/html/index.htm new file mode 100644 index 0000000..079f448 --- /dev/null +++ b/res/module/testModule/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AVL Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/testModule/help/html/top_frame.htm b/res/module/testModule/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/testModule/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/CVS/Entries b/res/module/testModule/help/jhelp/CVS/Entries new file mode 100644 index 0000000..42d59d7 --- /dev/null +++ b/res/module/testModule/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/map.jhm/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/testIndex.xml/1.1/Wed Mar 29 11:51:56 2006// +/testTOC.xml/1.2/Fri Apr 7 08:17:27 2006// +/test_help.hs/1.2/Fri Apr 7 08:17:27 2006/-kb/ diff --git a/res/module/testModule/help/jhelp/CVS/Repository b/res/module/testModule/help/jhelp/CVS/Repository new file mode 100644 index 0000000..347f8dd --- /dev/null +++ b/res/module/testModule/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help/jhelp diff --git a/res/module/testModule/help/jhelp/CVS/Root b/res/module/testModule/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..4b68571 --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/DOCS.TAB/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/OFFSETS/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/POSITIONS/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/SCHEMA/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/TMAP/1.1/Wed Mar 29 11:51:56 2006/-kb/ +/config.ini/1.1/Wed Mar 29 11:51:56 2006// diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..079204b --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help/jhelp/JavaHelpSearch diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS b/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..be0db5f Binary files /dev/null and b/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..9e8d6d9 --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,4 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿuÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ@k£ +2Šëúêû0³ +î³ ë®Œ*£ +ª«ªª«ã"ªÿ*®ë¨Âº«ú»ú««þûªºÿû®ú®¯¯ªþ«¯ººú¸Âª¿þîªë«ªïúªªêªªª«îªî¿«êªªú«ªîëÿªªª¯úꪺ껪몫«ºêªî¾«ªª®®ïꪪú¾ªºªªªªªªªªªªªªªªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/testModule/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..47c3238 --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ñîaÖ©Ê€0O—ƒ £÷˜¸÷Û7CØ`Ê¢ \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/testModule/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1aa79bf Binary files /dev/null and b/res/module/testModule/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/testModule/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..4a81846 --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=597 id2=1 diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/TMAP b/res/module/testModule/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..e38ae3b Binary files /dev/null and b/res/module/testModule/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/testModule/help/jhelp/JavaHelpSearch/config.ini b/res/module/testModule/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/testModule/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/map.jhm b/res/module/testModule/help/jhelp/map.jhm new file mode 100644 index 0000000..cb547f7 --- /dev/null +++ b/res/module/testModule/help/jhelp/map.jhm @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/testIndex.xml b/res/module/testModule/help/jhelp/testIndex.xml new file mode 100644 index 0000000..60a3917 --- /dev/null +++ b/res/module/testModule/help/jhelp/testIndex.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/res/module/testModule/help/jhelp/testTOC.xml b/res/module/testModule/help/jhelp/testTOC.xml new file mode 100644 index 0000000..e602696 --- /dev/null +++ b/res/module/testModule/help/jhelp/testTOC.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/res/module/testModule/help/jhelp/test_help.hs b/res/module/testModule/help/jhelp/test_help.hs new file mode 100644 index 0000000..1e18296 --- /dev/null +++ b/res/module/testModule/help/jhelp/test_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Test-Modul + + + + + test + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + testTOC.xml + + + + Index + + javax.help.IndexView + testIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/testModule/help/pics/CVS/Entries b/res/module/testModule/help/pics/CVS/Entries new file mode 100644 index 0000000..a329abd --- /dev/null +++ b/res/module/testModule/help/pics/CVS/Entries @@ -0,0 +1 @@ +/logo.gif/1.1/Wed Mar 29 11:51:56 2006/-kb/ diff --git a/res/module/testModule/help/pics/CVS/Repository b/res/module/testModule/help/pics/CVS/Repository new file mode 100644 index 0000000..4a56951 --- /dev/null +++ b/res/module/testModule/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/help/pics diff --git a/res/module/testModule/help/pics/CVS/Root b/res/module/testModule/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/help/pics/logo.gif b/res/module/testModule/help/pics/logo.gif new file mode 100644 index 0000000..e2e5c88 Binary files /dev/null and b/res/module/testModule/help/pics/logo.gif differ diff --git a/res/module/testModule/help/style.css b/res/module/testModule/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/testModule/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/testModule/test_pix/CVS/Entries b/res/module/testModule/test_pix/CVS/Entries new file mode 100644 index 0000000..0e2120b --- /dev/null +++ b/res/module/testModule/test_pix/CVS/Entries @@ -0,0 +1 @@ +/logo.gif/1.1/Sun Jul 10 11:42:14 2005/-kb/ diff --git a/res/module/testModule/test_pix/CVS/Repository b/res/module/testModule/test_pix/CVS/Repository new file mode 100644 index 0000000..055072d --- /dev/null +++ b/res/module/testModule/test_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/testModule/test_pix diff --git a/res/module/testModule/test_pix/CVS/Root b/res/module/testModule/test_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/testModule/test_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/testModule/test_pix/logo.gif b/res/module/testModule/test_pix/logo.gif new file mode 100644 index 0000000..e2e5c88 Binary files /dev/null and b/res/module/testModule/test_pix/logo.gif differ diff --git a/res/module/unifikation/CVS/Entries b/res/module/unifikation/CVS/Entries new file mode 100644 index 0000000..7d4983f --- /dev/null +++ b/res/module/unifikation/CVS/Entries @@ -0,0 +1,2 @@ +D/help//// +D/unifikation_pix//// diff --git a/res/module/unifikation/CVS/Repository b/res/module/unifikation/CVS/Repository new file mode 100644 index 0000000..ae3ace6 --- /dev/null +++ b/res/module/unifikation/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation diff --git a/res/module/unifikation/CVS/Root b/res/module/unifikation/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/CVS/Entries b/res/module/unifikation/help/CVS/Entries new file mode 100644 index 0000000..6f06f60 --- /dev/null +++ b/res/module/unifikation/help/CVS/Entries @@ -0,0 +1,4 @@ +D/html//// +D/jhelp//// +D/pics//// +/style.css/1.1/Mon Aug 16 12:12:09 2010// diff --git a/res/module/unifikation/help/CVS/Repository b/res/module/unifikation/help/CVS/Repository new file mode 100644 index 0000000..3f7e153 --- /dev/null +++ b/res/module/unifikation/help/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help diff --git a/res/module/unifikation/help/CVS/Root b/res/module/unifikation/help/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/html/CVS/Entries b/res/module/unifikation/help/html/CVS/Entries new file mode 100644 index 0000000..9b7be17 --- /dev/null +++ b/res/module/unifikation/help/html/CVS/Entries @@ -0,0 +1,4 @@ +/contents.htm/1.1/Mon Aug 16 12:12:08 2010// +D/data//// +/index.htm/1.1/Mon Aug 16 12:12:08 2010// +/top_frame.htm/1.1/Mon Aug 16 12:12:08 2010// diff --git a/res/module/unifikation/help/html/CVS/Repository b/res/module/unifikation/help/html/CVS/Repository new file mode 100644 index 0000000..d4b22ca --- /dev/null +++ b/res/module/unifikation/help/html/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help/html diff --git a/res/module/unifikation/help/html/CVS/Root b/res/module/unifikation/help/html/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/html/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/html/contents.htm b/res/module/unifikation/help/html/contents.htm new file mode 100644 index 0000000..e69a59b --- /dev/null +++ b/res/module/unifikation/help/html/contents.htm @@ -0,0 +1,109 @@ + + + Inhaltsverzeichnis + + + +
        + Das Modul AVL + +
      + + \ No newline at end of file diff --git a/res/module/unifikation/help/html/data/CVS/Entries b/res/module/unifikation/help/html/data/CVS/Entries new file mode 100644 index 0000000..974e61f --- /dev/null +++ b/res/module/unifikation/help/html/data/CVS/Entries @@ -0,0 +1 @@ +/overview.htm/1.1/Mon Aug 16 12:12:09 2010// diff --git a/res/module/unifikation/help/html/data/CVS/Repository b/res/module/unifikation/help/html/data/CVS/Repository new file mode 100644 index 0000000..69e8b59 --- /dev/null +++ b/res/module/unifikation/help/html/data/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help/html/data diff --git a/res/module/unifikation/help/html/data/CVS/Root b/res/module/unifikation/help/html/data/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/html/data/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/html/data/overview.htm b/res/module/unifikation/help/html/data/overview.htm new file mode 100644 index 0000000..e686f9e --- /dev/null +++ b/res/module/unifikation/help/html/data/overview.htm @@ -0,0 +1,12 @@ + + + Einleitung + + + +

      Dies ist die Hilfe des Testmodules

      + +

      Hier also mal eine kleinere Überschrift

      +

      Leider zeichnet sich dieser Absatz weder mit Inhalt noch mit Sinn aus.

      + + \ No newline at end of file diff --git a/res/module/unifikation/help/html/index.htm b/res/module/unifikation/help/html/index.htm new file mode 100644 index 0000000..079f448 --- /dev/null +++ b/res/module/unifikation/help/html/index.htm @@ -0,0 +1,24 @@ + + + + Hilfe zum AVL Modul + + + + + + + + + + + + + + + Ihr Browser kann diese Seite leider nicht anzeigen. + + + \ No newline at end of file diff --git a/res/module/unifikation/help/html/top_frame.htm b/res/module/unifikation/help/html/top_frame.htm new file mode 100644 index 0000000..1ce2eaa --- /dev/null +++ b/res/module/unifikation/help/html/top_frame.htm @@ -0,0 +1,10 @@ + + + oberer_frame + + + + Logo + + + \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/CVS/Entries b/res/module/unifikation/help/jhelp/CVS/Entries new file mode 100644 index 0000000..34834ad --- /dev/null +++ b/res/module/unifikation/help/jhelp/CVS/Entries @@ -0,0 +1,5 @@ +D/JavaHelpSearch//// +/map.jhm/1.1/Mon Aug 16 12:12:09 2010/-kb/ +/testIndex.xml/1.1/Mon Aug 16 12:12:09 2010// +/testTOC.xml/1.1/Mon Aug 16 12:12:09 2010// +/test_help.hs/1.1/Mon Aug 16 12:12:09 2010/-kb/ diff --git a/res/module/unifikation/help/jhelp/CVS/Repository b/res/module/unifikation/help/jhelp/CVS/Repository new file mode 100644 index 0000000..3a01ae6 --- /dev/null +++ b/res/module/unifikation/help/jhelp/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help/jhelp diff --git a/res/module/unifikation/help/jhelp/CVS/Root b/res/module/unifikation/help/jhelp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/jhelp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Entries b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Entries new file mode 100644 index 0000000..18b6a81 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Entries @@ -0,0 +1,7 @@ +/DOCS/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/DOCS.TAB/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/OFFSETS/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/POSITIONS/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/SCHEMA/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/TMAP/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/config.ini/1.1/Mon Aug 16 12:12:08 2010// diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Repository b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Repository new file mode 100644 index 0000000..fe91162 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help/jhelp/JavaHelpSearch diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Root b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS b/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS new file mode 100644 index 0000000..be0db5f Binary files /dev/null and b/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS differ diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS.TAB b/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS.TAB new file mode 100644 index 0000000..9e8d6d9 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/DOCS.TAB @@ -0,0 +1,4 @@ +eÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÝÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿý×ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ÷_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿuÿÿÿÿÿÿuÿÿÿÿÿÿÿuÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ@k£ +2Šëúêû0³ +î³ ë®Œ*£ +ª«ªª«ã"ªÿ*®ë¨Âº«ú»ú««þûªºÿû®ú®¯¯ªþ«¯ººú¸Âª¿þîªë«ªïúªªêªªª«îªî¿«êªªú«ªîëÿªªª¯úꪺ껪몫«ºêªî¾«ªª®®ïꪪú¾ªºªªªªªªªªªªªªªªªªªªªªªªªª©€ \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/OFFSETS b/res/module/unifikation/help/jhelp/JavaHelpSearch/OFFSETS new file mode 100644 index 0000000..47c3238 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/OFFSETS @@ -0,0 +1 @@ +ñîaÖ©Ê€0O—ƒ £÷˜¸÷Û7CØ`Ê¢ \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/POSITIONS b/res/module/unifikation/help/jhelp/JavaHelpSearch/POSITIONS new file mode 100644 index 0000000..1aa79bf Binary files /dev/null and b/res/module/unifikation/help/jhelp/JavaHelpSearch/POSITIONS differ diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/SCHEMA b/res/module/unifikation/help/jhelp/JavaHelpSearch/SCHEMA new file mode 100644 index 0000000..4a81846 --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/SCHEMA @@ -0,0 +1,2 @@ +JavaSearch 1.0 +TMAP bs=2048 rt=1 fl=-1 id1=597 id2=1 diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/TMAP b/res/module/unifikation/help/jhelp/JavaHelpSearch/TMAP new file mode 100644 index 0000000..e38ae3b Binary files /dev/null and b/res/module/unifikation/help/jhelp/JavaHelpSearch/TMAP differ diff --git a/res/module/unifikation/help/jhelp/JavaHelpSearch/config.ini b/res/module/unifikation/help/jhelp/JavaHelpSearch/config.ini new file mode 100644 index 0000000..df6034a --- /dev/null +++ b/res/module/unifikation/help/jhelp/JavaHelpSearch/config.ini @@ -0,0 +1,5 @@ +StopWords der, die, das, dessen, dem, den, deren, dar, an, was, warum, +StopWords wieso, wer, woher, wenn, eins, zwei, drei, oder, ein, eine, eines, einer, einem, einen +StopWords es, er, sie, ihn, ihre, seine, sein, seines, bei, beim, und, daher, auf, da, per, nach +StopWords ist, in, im, ja, nein, nicht, oder, mit, zum, zur, zu, um, gerade, d.h., ob, welche +StopWords welches, von, für, hat, ist, so, nur, jede, jedes, jeder, bzw, evtl, aus \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/map.jhm b/res/module/unifikation/help/jhelp/map.jhm new file mode 100644 index 0000000..cb547f7 --- /dev/null +++ b/res/module/unifikation/help/jhelp/map.jhm @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/testIndex.xml b/res/module/unifikation/help/jhelp/testIndex.xml new file mode 100644 index 0000000..60a3917 --- /dev/null +++ b/res/module/unifikation/help/jhelp/testIndex.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/res/module/unifikation/help/jhelp/testTOC.xml b/res/module/unifikation/help/jhelp/testTOC.xml new file mode 100644 index 0000000..e602696 --- /dev/null +++ b/res/module/unifikation/help/jhelp/testTOC.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/res/module/unifikation/help/jhelp/test_help.hs b/res/module/unifikation/help/jhelp/test_help.hs new file mode 100644 index 0000000..1e18296 --- /dev/null +++ b/res/module/unifikation/help/jhelp/test_help.hs @@ -0,0 +1,64 @@ + + + + + + + + Hilfe zum Test-Modul + + + + + test + + + + + + + main window + + + mainicon + + + javax.help.BackAction + javax.help.ForwardAction + javax.help.ReloadAction + javax.help.SeparatorAction + javax.help.HomeAction + javax.help.SeparatorAction + javax.help.PrintAction + javax.help.PrintSetupAction + + + + + + + TOC + + javax.help.TOCView + testTOC.xml + + + + Index + + javax.help.IndexView + testIndex.xml + + + + Search + + javax.help.SearchView + + JavaHelpSearch + + + + \ No newline at end of file diff --git a/res/module/unifikation/help/pics/CVS/Entries b/res/module/unifikation/help/pics/CVS/Entries new file mode 100644 index 0000000..400094b --- /dev/null +++ b/res/module/unifikation/help/pics/CVS/Entries @@ -0,0 +1 @@ +/logo.gif/1.1/Mon Aug 16 12:12:09 2010/-kb/ diff --git a/res/module/unifikation/help/pics/CVS/Repository b/res/module/unifikation/help/pics/CVS/Repository new file mode 100644 index 0000000..9ff0363 --- /dev/null +++ b/res/module/unifikation/help/pics/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/help/pics diff --git a/res/module/unifikation/help/pics/CVS/Root b/res/module/unifikation/help/pics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/help/pics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/help/pics/logo.gif b/res/module/unifikation/help/pics/logo.gif new file mode 100644 index 0000000..e2e5c88 Binary files /dev/null and b/res/module/unifikation/help/pics/logo.gif differ diff --git a/res/module/unifikation/help/style.css b/res/module/unifikation/help/style.css new file mode 100644 index 0000000..0a9c224 --- /dev/null +++ b/res/module/unifikation/help/style.css @@ -0,0 +1,235 @@ +/* + * Style Sheet for the j-Algo JavaHelpSystem. + * + * @author Matthias Schmidt + */ + +body {font-size: 12pt; + font-family: arial,sans-serif; + margin-left: 5; + margin-right: 5; + color: black} + +p {font-size: small; + font-weight: normal; + margin-top: 10 + margon-bottom: 10} + +h1 {font-size: x-large; + font-family: times new roman, serif + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h2 {font-size: large; + font-weight: bold; + margin-top: 20; + margin-bottom: 15} + +h3 {font-size: medium; + font-weight: bold; + margin-top: 15; + margin-bottom: 10} + +h4 {font-size: small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h5 {font-size: x-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +h6 {font-size: xx-small; + font-weight: bold; + margin-top: 10; + margin-bottom: 5} + +li p {margin-top: 0; + margin-bottom: 0} + +menu li p {margin-top: 0; + margin-bottom: 0} + +menu li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +menu {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dir li p {margin-top: 0; + margin-bottom: 0} + +dir li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +dir {margin-left: 40; + margin-top: 10; + margin-bottom: 10} + +dd p {margin-left: 40; + margin-top: 0; + margin-bottom: 0} + +dt {margin-top: 0; + margin-bottom: 0} + +dl {margin-left: 10; + margin-top: 10; + margin-bottom: 10} + +ol li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ol { + margin-top: 10; + margin-bottom: 10; + margin-left: 30; + list-style-type: decimal +} + +ol li p {margin-top: 0; + margin-bottom:0} + +ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul {margin-top: 13; + margin-bottom: 13; + margin-left: 30; + list-style-type: disc; + -bullet-gap: 10} + +ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul {list-style-type: circle; + margin-left: 25} + +ul li ul li ul li {margin-left: 0; + margin-right: 0; + margin-top: 0; + margin-bottom: 0} + +ul li ul li ul {list-style-type: square; + margin-left: 25} + +ul li menu {list-style-type: circle; + margin-left: 25} + +ul li p {margin-top: 0; + margin-bottom:0} + +a {color: black} + +big {font-size: x-large} + +small {font-size: x-small} + +samp {font-size: small; + font-family: Monospaced} + +cite {font-style: italic} + +code {font-size: small; + font-family: Monospaced} + +dfn {font-style: italic} + +em {font-style: italic} + +i {font-style: italic} + +b {font-weight: bold} + +kbd {font-size: small; + font-family: Monospaced} + +s {text-decoration: line-through} + +strike {text-decoration: line-through} + +strong {font-weight: bold} + +sub {vertical-align: sub} + +sup {vertical-align: sup} + +tt {font-family: Monospaced} + +u {text-decoration: underline} + +var {font-weight: bold; + font-style: italic} + +table { + margin-top: 5; + margin-bottom: 5; + margin-left: 5; + margin-right: 5 +} + +td { + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +th { + border-color: Gray; + border-style: inset; + padding-left: 1; + padding-right: 1; + padding-top: 1; + padding-bottom: 1 +} + +td p { + margin-top: 0; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +th p { + margin-top: 0; + font-weight: bold; + padding-top: 2; + padding-bottom: 2; + padding-left: 2; + padding-right: 2 +} + +address { + color: blue; + font-style: italic +} + +blockquote { + margin-top: 5; + margin-bottom: 5; + margin-left: 35; + margin-right: 35 +} + +center {text-align: center} + +pre {margin-top: 5; + margin-bottom: 5; + font-family: Monospaced} + +pre p {margin-top: 0} diff --git a/res/module/unifikation/unifikation_pix/CVS/Entries b/res/module/unifikation/unifikation_pix/CVS/Entries new file mode 100644 index 0000000..d14f76d --- /dev/null +++ b/res/module/unifikation/unifikation_pix/CVS/Entries @@ -0,0 +1,6 @@ +/WelcomeLoad.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/WelcomeLoadHover.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/WelcomeNew.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/WelcomeNewHover.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/icon.jpg/1.1/Mon Aug 16 12:12:08 2010/-kb/ +/pencilbutton.png/1.1/Mon Aug 16 12:12:08 2010/-kb/ diff --git a/res/module/unifikation/unifikation_pix/CVS/Repository b/res/module/unifikation/unifikation_pix/CVS/Repository new file mode 100644 index 0000000..ad8535b --- /dev/null +++ b/res/module/unifikation/unifikation_pix/CVS/Repository @@ -0,0 +1 @@ +j-algo/res/module/unifikation/unifikation_pix diff --git a/res/module/unifikation/unifikation_pix/CVS/Root b/res/module/unifikation/unifikation_pix/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/res/module/unifikation/unifikation_pix/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/res/module/unifikation/unifikation_pix/WelcomeLoad.jpg b/res/module/unifikation/unifikation_pix/WelcomeLoad.jpg new file mode 100644 index 0000000..96d0222 Binary files /dev/null and b/res/module/unifikation/unifikation_pix/WelcomeLoad.jpg differ diff --git a/res/module/unifikation/unifikation_pix/WelcomeLoadHover.jpg b/res/module/unifikation/unifikation_pix/WelcomeLoadHover.jpg new file mode 100644 index 0000000..91fc456 Binary files /dev/null and b/res/module/unifikation/unifikation_pix/WelcomeLoadHover.jpg differ diff --git a/res/module/unifikation/unifikation_pix/WelcomeNew.jpg b/res/module/unifikation/unifikation_pix/WelcomeNew.jpg new file mode 100644 index 0000000..52ab131 Binary files /dev/null and b/res/module/unifikation/unifikation_pix/WelcomeNew.jpg differ diff --git a/res/module/unifikation/unifikation_pix/WelcomeNewHover.jpg b/res/module/unifikation/unifikation_pix/WelcomeNewHover.jpg new file mode 100644 index 0000000..d6d4e74 Binary files /dev/null and b/res/module/unifikation/unifikation_pix/WelcomeNewHover.jpg differ diff --git a/res/module/unifikation/unifikation_pix/icon.jpg b/res/module/unifikation/unifikation_pix/icon.jpg new file mode 100644 index 0000000..d57aed2 Binary files /dev/null and b/res/module/unifikation/unifikation_pix/icon.jpg differ diff --git a/res/module/unifikation/unifikation_pix/pencilbutton.png b/res/module/unifikation/unifikation_pix/pencilbutton.png new file mode 100644 index 0000000..9428f6b Binary files /dev/null and b/res/module/unifikation/unifikation_pix/pencilbutton.png differ diff --git a/runtime/CVS/Entries b/runtime/CVS/Entries new file mode 100644 index 0000000..58d333b --- /dev/null +++ b/runtime/CVS/Entries @@ -0,0 +1 @@ +D/modules//// diff --git a/runtime/CVS/Repository b/runtime/CVS/Repository new file mode 100644 index 0000000..6e3e935 --- /dev/null +++ b/runtime/CVS/Repository @@ -0,0 +1 @@ +j-algo/runtime diff --git a/runtime/CVS/Root b/runtime/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/runtime/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/runtime/modules/CVS/Entries b/runtime/modules/CVS/Entries new file mode 100644 index 0000000..c543556 --- /dev/null +++ b/runtime/modules/CVS/Entries @@ -0,0 +1,16 @@ +/am0c0.jar/1.1/Wed Dec 8 13:01:52 2010// +/am1simulator.jar/1.1/Mon Mar 7 19:57:19 2011/-kb/ +/app.jar/1.1/Wed Oct 29 18:05:25 2008/-kb/ +/avl.jar/1.3/Sun Mar 26 11:18:19 2006/-kb/ +/bfsdfs.jar/1.1/Wed Dec 8 13:47:54 2010// +/c0h0.jar/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/dijkstra.jar/1.3/Sun Mar 26 11:18:20 2006/-kb/ +/ebnf.jar/1.1/Fri Aug 11 16:39:26 2006/-kb/ +/em.jar/1.1/Mon Jan 30 18:56:52 2012/-kb/ +/heapsort.jar/1.1/Mon Jan 28 17:39:16 2008/-kb/ +/hoare.jar/1.3/Wed Dec 8 13:01:52 2010/-kb/ +/kmp.jar/1.1/Fri Jun 30 14:35:21 2006/-kb/ +/lambda.jar/1.1/Wed Dec 8 13:01:52 2010// +/pulsemem.jar/1.3/Wed Dec 8 13:01:52 2010/-kb/ +/testModule.jar/1.3/Sun Mar 26 11:18:19 2006/-kb/ +/unifikation.jar/1.2/Wed Dec 8 13:01:52 2010/-kb/ diff --git a/runtime/modules/CVS/Repository b/runtime/modules/CVS/Repository new file mode 100644 index 0000000..0a2f9ea --- /dev/null +++ b/runtime/modules/CVS/Repository @@ -0,0 +1 @@ +j-algo/runtime/modules diff --git a/runtime/modules/CVS/Root b/runtime/modules/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/runtime/modules/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/runtime/modules/am0c0.jar b/runtime/modules/am0c0.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/am1simulator.jar b/runtime/modules/am1simulator.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/app.jar b/runtime/modules/app.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/avl.jar b/runtime/modules/avl.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/bfsdfs.jar b/runtime/modules/bfsdfs.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/c0h0.jar b/runtime/modules/c0h0.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/dijkstra.jar b/runtime/modules/dijkstra.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/ebnf.jar b/runtime/modules/ebnf.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/em.jar b/runtime/modules/em.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/heapsort.jar b/runtime/modules/heapsort.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/hoare.jar b/runtime/modules/hoare.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/kmp.jar b/runtime/modules/kmp.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/lambda.jar b/runtime/modules/lambda.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/pulsemem.jar b/runtime/modules/pulsemem.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/testModule.jar b/runtime/modules/testModule.jar new file mode 100644 index 0000000..e69de29 diff --git a/runtime/modules/unifikation.jar b/runtime/modules/unifikation.jar new file mode 100644 index 0000000..e69de29 diff --git a/src/CVS/Entries b/src/CVS/Entries new file mode 100644 index 0000000..f57532b --- /dev/null +++ b/src/CVS/Entries @@ -0,0 +1,2 @@ +D/c00//// +D/org//// diff --git a/src/CVS/Repository b/src/CVS/Repository new file mode 100644 index 0000000..76f7077 --- /dev/null +++ b/src/CVS/Repository @@ -0,0 +1 @@ +j-algo/src diff --git a/src/CVS/Root b/src/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/c00/AST.java b/src/c00/AST.java new file mode 100644 index 0000000..a17dde3 --- /dev/null +++ b/src/c00/AST.java @@ -0,0 +1,1271 @@ +//Author: Torsten Stueber +//28.03.2007 + +package c00; + +import java.io.IOException; + +import o3b.antlr.runtime.*; +import o3b.antlr.runtime.debug.ParseTreeBuilder; +import o3b.antlr.runtime.tree.ParseTree; + +import c00.parser.*; + + +/** +* The class AST contains the abstract syntax tree data type definition. +*/ +public abstract class AST { + + /** + * Parses a file containing a C program and returns the abstract syntax tree of the input file. + * The start symbol of the derivation tree of the input program can be specified. Notice that the ouput tree is + * of the generic type ASTTree and should be cast to one of its inherited classes. + *

      + * Example: AST.Block block = (AST.Block)AST.parseFile("foo.c", "Block"); + * + * @param fileName the name of the input file + * @param startSymbol a string containing the name of the start symbol, e.g., "Program" or "StatementSequence" + * @return the abstract syntax tree of the input program + * @see ASTTree + */ + public static ASTTree parseFile(String fileName, String startSymbol, StringBuffer err) throws RecognitionException { + try { + CharStream charStream = new ANTLRFileStream(fileName); + C00Lexer lexer = new C00Lexer(charStream); + CommonTokenStream tokenStream = new CommonTokenStream(lexer); + ParseTreeBuilder builder = new ParseTreeBuilder(startSymbol); + C00Parser parser = new C00Parser(tokenStream, builder, err, true); + + return parse(parser, startSymbol); + } + catch (IOException e) { + if(err!=null) err.append("IOError"); + } + + return null; + } + + public static ASTTree parseFile(String fileName, String startSymbol) throws RecognitionException { + return parseFile(fileName, startSymbol, null); + } + /** + * Parses a string containing a C program and returns the abstract syntax tree of the input string. + * The start symbol of the derivation tree of the input program can be specified. Notice that the ouput tree is + * of the generic type ASTTree and should be cast to one of its inherited classes. + *

      + * Example: AST.Block block = (AST.Block)AST.parseString("{int i=4; i=3-i*2;}", "Block"); + * + * @param input the input string + * @param startSymbol a string containing the name of the start symbol, e.g., "Program" or "StatementSequence" + * @return the abstract syntax tree of the input program + * @see ASTTree + */ + public static ASTTree parseString(String input, String startSymbol, StringBuffer err, boolean ignoreExceptions) throws RecognitionException { + CharStream charStream = new ANTLRStringStream(input); + C00Lexer lexer = new C00Lexer(charStream); + CommonTokenStream tokenStream = new CommonTokenStream(lexer); + ParseTreeBuilder builder = new ParseTreeBuilder(startSymbol); + C00Parser parser = new C00Parser(tokenStream, builder, err, ignoreExceptions); + + return parse(parser, startSymbol); + } + + public static ASTTree parseString(String input, String startSymbol, StringBuffer err) throws RecognitionException { + return parseString(input, startSymbol, err, true); + } + + public static ASTTree parseString(String input, String startSymbol) throws RecognitionException { + return parseString(input, startSymbol, null); + } + + private static ASTTree parse(C00Parser parser, String startSymbol) throws RecognitionException { + if (startSymbol.equals("Program")) + return parser.program().astTree; + + if (startSymbol.equals("GlobalDeclarations")) + return parser.globalDeclarations().astTree; + + if (startSymbol.equals("Declarations")) + return parser.declarations().astTree; + + if (startSymbol.equals("Declaration")) + return parser.declaration().astTree; + + if (startSymbol.equals("ConstDeclarations")) + return parser.constDeclarations().astTree; + + if (startSymbol.equals("VarDeclarations")) + return parser.varDeclarations().astTree; + + if (startSymbol.equals("FunctionImplementations")) + return parser.functionImplementations().astTree; + + if (startSymbol.equals("FunctionHeading")) + return parser.functionHeading().astTree; + + if (startSymbol.equals("FormalParameters")) + return parser.formalParameters().astTree; + + if (startSymbol.equals("ParamSections")) + return parser.paramSections().astTree; + + if (startSymbol.equals("Block")) + return parser.block().astTree; + + if (startSymbol.equals("StatementSequence")) + return parser.statementSequence().astTree; + + if (startSymbol.equals("Statement")) + return parser.statement().astTree; + + if (startSymbol.equals("Assignment")) + return parser.assignment().astTree; + + if (startSymbol.equals("SwitchBlock")) + return parser.switchBlock().astTree; + + if (startSymbol.equals("CaseSequence")) + return parser.caseSequence().astTree; + + if (startSymbol.equals("FunctionCall")) + return parser.functionCall().astTree; + + if (startSymbol.equals("ActualParameters")) + return parser.actualParameters().astTree; + + if (startSymbol.equals("EpxressionList")) + return parser.expressionList().astTree; + + if (startSymbol.equals("Expression")) + return parser.expression().astTree; + + if (startSymbol.equals("FirstTerm")) + return parser.firstTerm().astTree; + + if (startSymbol.equals("Term")) + return parser.term().astTree; + + if (startSymbol.equals("Factor")) + return parser.factor().astTree; + + if (startSymbol.equals("BoolExpression")) + return parser.boolExpression().astTree; + + return null; + } + + /** + * This is the base class of all abstract syntax trees. + */ + public static class ASTTree { + + /** + * Constructor of the class ASTTree + */ + public ASTTree() { + parent = null; + extra = null; + } + + /** + * Reference to the parent node of the ASTTree + */ + public ASTTree parent; + + /** + * Reference to an additional memory object. + */ + public Object extra; + + /** + * The code fragment that this astract syntax tree stands for starts in this line number. + * Line numbers run from 1, 2, ... + */ + public int startLine; + + /** + * The first symbol of the associated code fragment starts is in this column in line {@link startLine}. + * Column numbers run from 0, 1, ... + */ + public int startColumn; + + /** + * The code fragment that this astract syntax tree stands for ends in this line number. + * Line numbers run from 1, 2, ... + */ + public int endLine; + + /** + * This is the column number of the last symbol of the associated code fragment in {@link endLine}. + * Column numbers run from 0, 1, ... + */ + public int endColumn; + } + + + public static abstract class Program extends ASTTree {} + + /** + * 'Program' -> #include 'GlobalDeclarations' 'FunctionImplementations' int main('FormalParameters') 'Block' + */ + public static class ExpandProgram extends Program { + public GlobalDeclarations globDecl; + public FunctionImplementations funcImpl; + public FormalParameters formParam; + public Block block; + public ExpandProgram(GlobalDeclarations globDecl, FunctionImplementations funcImpl, + FormalParameters formParam, Block block) { + super(); + this.globDecl = globDecl; globDecl.parent = this; + this.funcImpl = funcImpl; funcImpl.parent = this; + this.formParam = formParam; formParam.parent = this; + this.block = block; block.parent = this; + } + } + + + public static abstract class GlobalDeclarations extends ASTTree {} + + /** + * 'GlobalDeclarations' -> epsilon + */ + public static class EmptyGlobDecls extends GlobalDeclarations { + public EmptyGlobDecls() { + super(); + } + } + + /** + * 'GlobalDeclarations' -> 'Declaration' 'GlobalDeclarations' + */ + public static class VarConstGlobDecls extends GlobalDeclarations { + public Declaration decl; + public GlobalDeclarations globDecls; + public VarConstGlobDecls(Declaration decl, GlobalDeclarations globDecls) { + super(); + this.decl = decl; decl.parent = this; + this.globDecls = globDecls; globDecls.parent = this; + } + } + + /** + * 'GlobalDeclarations' -> 'FunctionHeading'; 'GlobalDeclarations' + */ + public static class FuncGlobDecls extends GlobalDeclarations { + public FunctionHeading funcHead; + public GlobalDeclarations globDecls; + public FuncGlobDecls(FunctionHeading funcHead, GlobalDeclarations globDecls) { + super(); + this.funcHead = funcHead; funcHead.parent = this; + this.globDecls = globDecls; globDecls.parent = this; + } + } + + + public static abstract class Declarations extends ASTTree {} + + /** + * 'Declarations' -> epsilon + */ + public static class EmptyDecls extends Declarations { + public EmptyDecls() { + super(); + } + } + + /** + * 'Declarations' -> 'Declaration' 'Declarations' + */ + public static class PairDecls extends Declarations { + public Declaration decl; + public Declarations decls; + public PairDecls(Declaration decl, Declarations decls) { + super(); + this.decl = decl; decl.parent = this; + this.decls = decls; decls.parent = this; + } + } + + + public static abstract class Declaration extends ASTTree {} + + /** + * 'Declaration' -> const int 'ConstDeclarations'; + */ + public static class ConstDecl extends Declaration { + public ConstDeclarations constDecls; + public ConstDecl(ConstDeclarations constDecls) { + super(); + this.constDecls = constDecls; constDecls.parent = this; + } + } + + /** + * 'Declaration' -> int 'VarDeclarations'; + */ + public static class VarDecl extends Declaration { + public VarDeclarations varDecls; + public VarDecl(VarDeclarations varDecls) { + super(); + this.varDecls = varDecls; varDecls.parent = this; + } + } + + + public static abstract class ConstDeclarations extends ASTTree {} + + /** + * 'ConstDeclarations' -> 'Ident' = 'Number' + */ + public static class LastConstDecls extends ConstDeclarations { + public String ident; + public int number; + public LastConstDecls(String ident, int number) { + super(); + this.ident = ident; + this.number = number; + } + } + + /** + * 'ConstDeclarations' -> 'Ident' = 'Number', 'ConstDeclarations' + */ + public static class PairConstDecls extends ConstDeclarations { + public String ident; + public int number; + public ConstDeclarations constDecls; + public PairConstDecls(String ident, int number, ConstDeclarations constDecls) { + super(); + this.ident = ident; + this.number = number; + this.constDecls = constDecls; constDecls.parent = this; + } + } + + + public static abstract class VarDeclarations extends ASTTree {} + + /** + * 'VarDeclarations' -> 'Ident' + */ + public static class VarLastDecls extends VarDeclarations { + public String ident; + public VarLastDecls(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'VarDeclarations' -> *'Ident' + */ + public static class RefVarLastDecls extends VarDeclarations { + public String ident; + public RefVarLastDecls(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'VarDeclarations' -> 'Ident' = 'Number' + */ + public static class InitVarLastDecls extends VarDeclarations { + public String ident; + public int number; + public InitVarLastDecls(String ident, int number) { + super(); + this.ident = ident; + this.number = number; + } + } + + /** + * 'VarDeclarations' -> 'Ident', 'VarDeclarations' + */ + public static class VarPairDecls extends VarDeclarations { + public String ident; + public VarDeclarations varDecls; + public VarPairDecls(String ident, VarDeclarations varDecls) { + super(); + this.ident = ident; + this.varDecls = varDecls; varDecls.parent = this; + } + } + + /** + * 'VarDeclarations' -> *'Ident', 'VarDeclarations' + */ + public static class RefVarPairDecls extends VarDeclarations { + public String ident; + public VarDeclarations varDecls; + public RefVarPairDecls(String ident, VarDeclarations varDecls) { + super(); + this.ident = ident; + this.varDecls = varDecls; varDecls.parent = this; + } + } + + /** + * 'VarDeclarations' -> 'Ident' = 'Number', 'VarDeclarations' + */ + public static class InitVarPairDecls extends VarDeclarations { + public String ident; + public int number; + public VarDeclarations varDecls; + public InitVarPairDecls(String ident, int number, VarDeclarations varDecls) { + super(); + this.ident = ident; + this.number = number; + this.varDecls = varDecls; varDecls.parent = this; + } + } + + + public static abstract class FunctionImplementations extends ASTTree {} + + /** + * 'FunctionImplementations' -> epsilon + */ + public static class EmptyFuncImpls extends FunctionImplementations { + public EmptyFuncImpls() { + super(); + } + } + + /** + * 'FunctionImplementations' -> 'FunctionHeading' 'Block' 'FunctionImplementations' + */ + public static class PairFuncImpls extends FunctionImplementations { + public FunctionHeading funcHead; + public Block block; + public FunctionImplementations funcImpls; + public PairFuncImpls(FunctionHeading funcHead, Block block, FunctionImplementations funcImpls) { + super(); + this.funcHead = funcHead; funcHead.parent = this; + this.block = block; block.parent = this; + this.funcImpls = funcImpls; funcImpls.parent = this; + } + } + + + public static abstract class FunctionHeading extends ASTTree {} + + /** + * 'FunctionHeading' -> void 'Ident'('FormalParameters') + */ + public static class VoidFuncHead extends FunctionHeading { + public String ident; + public FormalParameters formParams; + public VoidFuncHead(String ident, FormalParameters formParams) { + super(); + this.ident = ident; + this.formParams = formParams; formParams.parent = this; + } + } + + /** + * 'FunctionHeading' -> int 'Ident'('FormalParameters') + */ + public static class IntFuncHead extends FunctionHeading { + public String ident; + public FormalParameters formParams; + public IntFuncHead(String ident, FormalParameters formParams) { + super(); + this.ident = ident; + this.formParams = formParams; formParams.parent = this; + } + } + + + public static abstract class FormalParameters extends ASTTree {} + + /** + * 'FormalParameters' -> epsilon + */ + public static class EmptyFormalParams extends FormalParameters { + public EmptyFormalParams() { + super(); + } + } + + /** + * 'FormalParameters' -> void + */ + public static class VoidFormalParams extends FormalParameters { + public VoidFormalParams() { + super(); + } + } + + /** + * 'FormalParameters' -> 'ParamSections' + */ + public static class NonVoidFormalParams extends FormalParameters { + public ParamSections prmSects; + public NonVoidFormalParams(ParamSections prmSects) { + super(); + this.prmSects = prmSects; prmSects.parent = this; + } + } + + + public static abstract class ParamSections extends ASTTree {} + + /** + * 'ParamSections' -> int 'Ident' + */ + public static class ValueLastPrmSects extends ParamSections { + public String ident; + public ValueLastPrmSects(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'ParamSections' -> int *'Ident' + */ + public static class RefLastPrmSects extends ParamSections { + public String ident; + public RefLastPrmSects(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'ParamSections' -> int 'Ident', 'ParamSections' + */ + public static class ValuePairPrmSects extends ParamSections { + public String ident; + public ParamSections prmSects; + public ValuePairPrmSects(String ident, ParamSections prmSects) { + super(); + this.ident = ident; + this.prmSects = prmSects; prmSects.parent = this; + } + } + + /** + * 'ParamSections' -> int *'Ident', 'ParamSections' + */ + public static class RefPairPrmSects extends ParamSections { + public String ident; + public ParamSections prmSects; + public RefPairPrmSects(String ident, ParamSections prmSects) { + super(); + this.ident = ident; + this.prmSects = prmSects; prmSects.parent = this; + } + } + + + public static abstract class Block extends ASTTree {} + + /** + * 'Block' -> {'Declarations' 'StatementSequence'} + */ + public static class ExpandBlock extends Block { + public Declarations decls; + public StatementSequence stmSeq; + public ExpandBlock(Declarations decls, StatementSequence stmSeq) { + super(); + this.decls = decls; decls.parent = this; + this.stmSeq = stmSeq; stmSeq.parent = this; + } + } + + + public static abstract class StatementSequence extends ASTTree {} + + /** + * 'StatementSequence' -> epsilon + */ + public static class EmptyStmSeq extends StatementSequence { + public EmptyStmSeq() { + super(); + } + } + + /** + * 'StatementSequence' -> 'Statement' 'StatementSequence' + */ + public static class PairStmSeq extends StatementSequence { + public Statement stm; + public StatementSequence stmSeq; + public PairStmSeq(Statement stm, StatementSequence stmSeq) { + super(); + this.stm = stm; stm.parent = this; + this.stmSeq = stmSeq; stmSeq.parent = this; + } + } + + + public static abstract class Statement extends ASTTree {} + + /** + * 'Statement' -> 'Assignment' + */ + public static class AssignStm extends Statement { + public Assignment assign; + public AssignStm(Assignment assign) { + super(); + this.assign = assign; assign.parent = this; + } + } + + /** + * 'Statement' -> if ('BoolExpression') 'Statement' + */ + public static class PureIfStm extends Statement { + public BoolExpression boolExp; + public Statement stm; + public PureIfStm(BoolExpression boolExp, Statement stm) { + super(); + this.boolExp = boolExp; boolExp.parent = this; + this.stm = stm; stm.parent = this; + } + } + + /** + * 'Statement' -> if ('BoolExpression') 'Statement' else 'Statement' + */ + public static class ElseIfStm extends Statement { + public BoolExpression boolExp; + public Statement stm1, stm2; + public ElseIfStm(BoolExpression boolExp, Statement stm1, Statement stm2) { + super(); + this.boolExp = boolExp; boolExp.parent = this; + this.stm1 = stm1; stm1.parent = this; + this.stm2 = stm2; stm2.parent = this; + } + } + + /** + * 'Statement' -> switch ('Expression') 'SwitchBlock' + */ + public static class SwitchStm extends Statement { + public Expression exp; + public SwitchBlock switchBlock; + public SwitchStm(Expression exp, SwitchBlock switchBlock) { + super(); + this.exp = exp; exp.parent = this; + this.switchBlock = switchBlock; switchBlock.parent = this; + } + } + + /** + * 'Statement' -> while ('BoolExpression') 'Statement' + */ + public static class WhileStm extends Statement { + public BoolExpression boolExp; + public Statement stm; + public WhileStm(BoolExpression boolExp, Statement stm) { + super(); + this.boolExp = boolExp; boolExp.parent = this; + this.stm = stm; stm.parent = this; + } + } + + /** + * 'Statement' -> do 'Statement' while ('BoolExpression') + */ + public static class DoWhileStm extends Statement { + public Statement stm; + public BoolExpression boolExp; + public DoWhileStm(Statement stm, BoolExpression boolExp) { + super(); + this.stm = stm; stm.parent = this; + this.boolExp = boolExp; boolExp.parent = this; + } + } + + /** + * 'Statement' -> for ('Assignment'; 'BoolExpression'; 'Assignment') 'Statement' + */ + public static class ForStm extends Statement { + public Assignment assign1; + public BoolExpression boolExp; + public Assignment assign2; + public Statement stm; + public ForStm(Assignment assign1, BoolExpression boolExp, Assignment assign2, Statement stm) { + super(); + this.assign1 = assign1; assign1.parent = this; + this.boolExp = boolExp; boolExp.parent = this; + this.assign2 = assign2; assign2.parent = this; + this.stm = stm; stm.parent = this; + } + } + + /** + * 'Statement' -> continue; + */ + public static class ContinueStm extends Statement { + public ContinueStm() { + super(); + } + } + + /** + * 'Statement' -> break; + */ + public static class BreakStm extends Statement { + public BreakStm() { + super(); + } + } + + /** + * 'Statement' -> {'Declarations' 'StatementSequence'} + */ + public static class CompStm extends Statement { + public Declarations decls; + public StatementSequence stmSeq; + public CompStm(Declarations decls, StatementSequence stmSeq) { + super(); + this.decls = decls; decls.parent = this; + this.stmSeq = stmSeq; stmSeq.parent = this; + } + } + + /** + * 'Statement' -> 'FunctionCall'; + */ + public static class FuncCallStm extends Statement { + public FunctionCall funcCall; + public FuncCallStm(FunctionCall funcCall) { + super(); + this.funcCall = funcCall; funcCall.parent = this; + } + } + + /** + * 'Statement' -> return; + */ + public static class EmptyReturnStm extends Statement { + public EmptyReturnStm() { + super(); + } + } + + /** + * 'Statement' -> return 'Expression'; + */ + public static class ExprReturnStm extends Statement { + public Expression expr; + public ExprReturnStm(Expression expr) { + super(); + this.expr = expr; expr.parent = this; + } + } + + /** + * 'Statement' -> printf('String'); + */ + public static class PurePrintfStm extends Statement { + public String string; + public PurePrintfStm(String string) { + super(); + this.string = string; + } + } + + /** + * 'Statement' -> printf('String', 'ExpressionList'); + */ + public static class ExprPrintfStm extends Statement { + public String string; + public ExpressionList exprList; + public ExprPrintfStm(String string, ExpressionList exprList) { + super(); + this.string = string; + this.exprList = exprList; + } + } + + /** + * 'Statement' -> scanf("%i", &'Ident'); + */ + public static class ScanfStm extends Statement { + public String ident; + public ScanfStm(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'Statement' -> /*label 'Number'*/ + */ + public static class LabelStm extends Statement { + public int number; + public LabelStm(int number) { + super(); + this.number = number; + } + } + + + public static abstract class Assignment extends ASTTree {} + + /** + * 'Assignment' -> 'Ident' = 'Expression' + */ + public static class ValueAssign extends Assignment { + public String ident; + public Expression expr; + public ValueAssign(String ident, Expression expr) { + super(); + this.ident = ident; + this.expr = expr; expr.parent = this; + } + } + + /** + * 'Assignment' -> *'Ident' = 'Expression' + */ + public static class RefAssign extends Assignment { + public String ident; + public Expression expr; + public RefAssign(String ident, Expression expr) { + super(); + this.ident = ident; + this.expr = expr; expr.parent = this; + } + } + + + public static abstract class SwitchBlock extends ASTTree {} + + /** + * 'SwitchBlock' -> {'CaseSequence'} + */ + public static class NoDefaultSwitchBlock extends SwitchBlock { + public CaseSequence caseSeq; + public NoDefaultSwitchBlock(CaseSequence caseSeq) { + super(); + this.caseSeq = caseSeq; caseSeq.parent = this; + } + } + + /** + * 'SwitchBlock' -> {'CaseSequence' default: 'StatementSequence'} + */ + public static class DefaultSwitchBlock extends SwitchBlock { + public CaseSequence caseSeq; + public StatementSequence stmSeq; + public DefaultSwitchBlock(CaseSequence caseSeq, StatementSequence stmSeq) { + super(); + this.caseSeq = caseSeq; caseSeq.parent = this; + this.stmSeq = stmSeq; stmSeq.parent = this; + } + } + + + public static abstract class CaseSequence extends ASTTree {} + + /** + * 'CaseSequence' -> epsilon + */ + public static class EmptyCaseSeq extends CaseSequence { + public EmptyCaseSeq() { + super(); + } + } + + /** + * 'CaseSequence' -> case 'Number': 'StatementSequence' 'CaseSequence' + */ + public static class NoBreakPairCaseSeq extends CaseSequence { + public int number; + public StatementSequence stmSeq; + public CaseSequence caseSeq; + public NoBreakPairCaseSeq(int number, StatementSequence stmSeq, CaseSequence caseSeq) { + super(); + this.number = number; + this.stmSeq = stmSeq; stmSeq.parent = this; + this.caseSeq = caseSeq; caseSeq.parent = this; + } + } + + + public static abstract class FunctionCall extends ASTTree {} + + /** + * 'FunctionCall' -> 'Ident'('ActualParameters') + */ + public static class ExpandFuncCall extends FunctionCall { + public String ident; + public ActualParameters actParams; + public ExpandFuncCall(String ident, ActualParameters actParams) { + super(); + this.ident = ident; + this.actParams = actParams; actParams.parent = this; + } + } + + + public static abstract class ActualParameters extends ASTTree {} + + /** + * 'ActualParameters' -> epsilon + */ + public static class EmptyActParams extends ActualParameters { + public EmptyActParams() { + super(); + } + } + + /** + * 'ActualParameters' -> 'ExpressionList' + */ + public static class ExprListActParams extends ActualParameters { + public ExpressionList exprList; + public ExprListActParams(ExpressionList exprList) { + super(); + this.exprList = exprList; exprList.parent = this; + } + } + + + public static abstract class ExpressionList extends ASTTree {} + + /** + * 'ExpressionList' -> 'Expression' + */ + public static class LastExprList extends ExpressionList { + public Expression expr; + public LastExprList(Expression expr) { + super(); + this.expr = expr; expr.parent = this; + } + } + + /** + * 'ExpressionList' -> 'Expression', 'ExpressionList' + */ + public static class PairExprList extends ExpressionList { + public Expression expr; + public ExpressionList exprList; + public PairExprList(Expression expr, ExpressionList exprList) { + super(); + this.expr = expr; expr.parent = this; + this.exprList = exprList; exprList.parent = this; + } + } + + + public static abstract class Expression extends ASTTree {} + + /** + * 'Expression' -> 'Expression' + 'Term' + */ + public static class PlusExpr extends Expression { + public Expression expr; + public Term term; + public PlusExpr(Expression expr, Term term) { + super(); + this.expr = expr; expr.parent = this; + this.term = term; term.parent = this; + } + } + + /** + * 'Expression' -> 'Expression' - 'Term' + */ + public static class MinusExpr extends Expression { + public Expression expr; + public Term term; + public MinusExpr(Expression expr, Term term) { + super(); + this.expr = expr; expr.parent = this; + this.term = term; term.parent = this; + } + } + + /** + * 'Expression' -> 'FirstTerm' + */ + public static class FirstTermExpr extends Expression { + public FirstTerm firstTerm; + public FirstTermExpr(FirstTerm firstTerm) { + super(); + this.firstTerm = firstTerm; firstTerm.parent = this; + } + } + + + public static abstract class FirstTerm extends ASTTree {} + + /** + * 'FirstTerm' -> 'FirstTerm' * 'Factor' + */ + public static class MultFirstTerm extends FirstTerm { + public FirstTerm firstTerm; + public Factor factor; + public MultFirstTerm(FirstTerm firstTerm, Factor factor) { + super(); + this.firstTerm = firstTerm; firstTerm.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'FirstTerm' -> 'FirstTerm' / 'Factor' + */ + public static class DivFirstTerm extends FirstTerm { + public FirstTerm firstTerm; + public Factor factor; + public DivFirstTerm(FirstTerm firstTerm, Factor factor) { + super(); + this.firstTerm = firstTerm; firstTerm.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'FirstTerm' -> 'FirstTerm' % 'Factor' + */ + public static class ModFirstTerm extends FirstTerm { + public FirstTerm firstTerm; + public Factor factor; + public ModFirstTerm(FirstTerm firstTerm, Factor factor) { + super(); + this.firstTerm = firstTerm; firstTerm.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'FirstTerm' -> 'Factor' + */ + public static class FactorFirstTerm extends FirstTerm { + public Factor factor; + public FactorFirstTerm(Factor factor) { + super(); + this.factor = factor; factor.parent = this; + } + } + + /** + * 'FirstTerm' -> +'Factor' + */ + public static class PlusFactorFirstTerm extends FirstTerm { + public Factor factor; + public PlusFactorFirstTerm(Factor factor) { + super(); + this.factor = factor; factor.parent = this; + } + } + + /** + * 'FirstTerm' -> -'Factor' + */ + public static class MinusFactorFirstTerm extends FirstTerm { + public Factor factor; + public MinusFactorFirstTerm(Factor factor) { + super(); + this.factor = factor; factor.parent = this; + } + } + + + public static abstract class Term extends ASTTree {} + + /** + * 'Term' -> 'Term' * 'Factor' + */ + public static class MultTerm extends Term { + public Term term; + public Factor factor; + public MultTerm(Term term, Factor factor) { + super(); + this.term = term; term.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'Term' -> 'Term' / 'Factor' + */ + public static class DivTerm extends Term { + public Term term; + public Factor factor; + public DivTerm(Term term, Factor factor) { + super(); + this.term = term; term.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'Term' -> 'Term' % 'Factor' + */ + public static class ModTerm extends Term { + public Term term; + public Factor factor; + public ModTerm(Term term, Factor factor) { + super(); + this.term = term; term.parent = this; + this.factor = factor; factor.parent = this; + } + } + + /** + * 'Term' -> 'Factor' + */ + public static class FactorTerm extends Term { + public Factor factor; + public FactorTerm(Factor factor) { + super(); + this.factor = factor; factor.parent = this; + } + } + + + public static abstract class Factor extends ASTTree {} + + /** + * 'Factor' -> 'Ident' + */ + public static class IdFactor extends Factor { + public String ident; + public IdFactor(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'Factor' -> *'Ident' + */ + public static class RefIdFactor extends Factor { + public String ident; + public RefIdFactor(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'Factor' -> &'Ident' + */ + public static class AddIdFactor extends Factor { + public String ident; + public AddIdFactor(String ident) { + super(); + this.ident = ident; + } + } + + /** + * 'Factor' -> 'Number' + */ + public static class NumFactor extends Factor { + public int number; + public NumFactor(int number) { + super(); + this.number = number; + } + } + + /** + * 'Factor' -> 'FunctionCall' + */ + public static class FuncCallFactor extends Factor { + public FunctionCall funcCall; + public FuncCallFactor(FunctionCall funcCall) { + super(); + this.funcCall = funcCall; funcCall.parent = this; + } + } + + /** + * 'Factor' -> ('Expression') + */ + public static class CompFactor extends Factor { + public Expression expr; + public CompFactor(Expression expr) { + super(); + this.expr = expr; expr.parent = this; + } + } + + + public static abstract class BoolExpression extends ASTTree {} + + /** + * 'BoolExpression' -> 'Expression' == 'Expression' + */ + public static class EqBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public EqBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + + /** + * 'BoolExpression' -> 'Expression' != 'Expression' + */ + public static class NotEqBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public NotEqBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + + /** + * 'BoolExpression' -> 'Expression' < 'Expression' + */ + public static class LessBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public LessBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + + /** + * 'BoolExpression' -> 'Expression' > 'Expression' + */ + public static class GreatBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public GreatBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + + /** + * 'BoolExpression' -> 'Expression' <= 'Expression' + */ + public static class LessEqBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public LessEqBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + + /** + * 'BoolExpression' -> 'Expression' >= 'Expression' + */ + public static class GreatEqBoolExpr extends BoolExpression { + public Expression expr1, expr2; + public GreatEqBoolExpr(Expression expr1, Expression expr2) { + super(); + this.expr1 = expr1; expr1.parent = this; + this.expr2 = expr2; expr2.parent = this; + } + } + +} \ No newline at end of file diff --git a/src/c00/CVS/Entries b/src/c00/CVS/Entries new file mode 100644 index 0000000..e199716 --- /dev/null +++ b/src/c00/CVS/Entries @@ -0,0 +1,2 @@ +/AST.java/1.3/Mon Aug 16 12:05:49 2010// +D/parser//// diff --git a/src/c00/CVS/Repository b/src/c00/CVS/Repository new file mode 100644 index 0000000..ec3e3e1 --- /dev/null +++ b/src/c00/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/c00 diff --git a/src/c00/CVS/Root b/src/c00/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/c00/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/c00/parser/C00Lexer.java b/src/c00/parser/C00Lexer.java new file mode 100644 index 0000000..d7795b2 --- /dev/null +++ b/src/c00/parser/C00Lexer.java @@ -0,0 +1,2583 @@ +// $ANTLR 3.0b6 C00.g 2007-05-21 11:30:10 + +package c00.parser; + + +import o3b.antlr.runtime.*; +import java.util.Stack; +import java.util.List; +import java.util.ArrayList; + +public class C00Lexer extends Lexer { + public static final int T14=14; + public static final int T29=29; + public static final int T36=36; + public static final int T35=35; + public static final int T45=45; + public static final int T20=20; + public static final int T34=34; + public static final int Ident=4; + public static final int T25=25; + public static final int T18=18; + public static final int T37=37; + public static final int EscapeSequence=8; + public static final int T26=26; + public static final int T32=32; + public static final int T17=17; + public static final int T51=51; + public static final int T46=46; + public static final int T16=16; + public static final int DIGIT=10; + public static final int T38=38; + public static final int T41=41; + public static final int T24=24; + public static final int T19=19; + public static final int T39=39; + public static final int T21=21; + public static final int T44=44; + public static final int LETTER=9; + public static final int T33=33; + public static final int T11=11; + public static final int T22=22; + public static final int T50=50; + public static final int T43=43; + public static final int T12=12; + public static final int T23=23; + public static final int T28=28; + public static final int T42=42; + public static final int T40=40; + public static final int T13=13; + public static final int WHITESPACE=7; + public static final int String=6; + public static final int T48=48; + public static final int T15=15; + public static final int EOF=-1; + public static final int T47=47; + public static final int Tokens=53; + public static final int T31=31; + public static final int T49=49; + public static final int T27=27; + public static final int T52=52; + public static final int Number=5; + public static final int T30=30; + public C00Lexer() {;} + public C00Lexer(CharStream input) { + super(input); + } + public String getGrammarFileName() { return "C00.g"; } + + // $ANTLR start T11 + public void mT11() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T11; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:6:7: ( '#include' ) + // C00.g:6:7: '#include' + { + match("#include"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T11 + + // $ANTLR start T12 + public void mT12() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T12; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:7:7: ( '' ) + // C00.g:7:7: '' + { + match(""); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T12 + + // $ANTLR start T13 + public void mT13() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T13; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:8:7: ( 'int' ) + // C00.g:8:7: 'int' + { + match("int"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T13 + + // $ANTLR start T14 + public void mT14() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T14; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:9:7: ( 'main' ) + // C00.g:9:7: 'main' + { + match("main"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T14 + + // $ANTLR start T15 + public void mT15() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T15; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:10:7: ( '(' ) + // C00.g:10:7: '(' + { + match('('); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T15 + + // $ANTLR start T16 + public void mT16() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T16; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:11:7: ( ')' ) + // C00.g:11:7: ')' + { + match(')'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T16 + + // $ANTLR start T17 + public void mT17() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T17; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:12:7: ( ';' ) + // C00.g:12:7: ';' + { + match(';'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T17 + + // $ANTLR start T18 + public void mT18() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T18; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:13:7: ( 'const' ) + // C00.g:13:7: 'const' + { + match("const"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T18 + + // $ANTLR start T19 + public void mT19() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T19; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:14:7: ( '=' ) + // C00.g:14:7: '=' + { + match('='); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T19 + + // $ANTLR start T20 + public void mT20() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T20; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:15:7: ( ',' ) + // C00.g:15:7: ',' + { + match(','); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T20 + + // $ANTLR start T21 + public void mT21() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T21; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:16:7: ( '*' ) + // C00.g:16:7: '*' + { + match('*'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T21 + + // $ANTLR start T22 + public void mT22() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T22; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:17:7: ( 'void' ) + // C00.g:17:7: 'void' + { + match("void"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T22 + + // $ANTLR start T23 + public void mT23() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T23; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:18:7: ( '{' ) + // C00.g:18:7: '{' + { + match('{'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T23 + + // $ANTLR start T24 + public void mT24() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T24; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:19:7: ( '}' ) + // C00.g:19:7: '}' + { + match('}'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T24 + + // $ANTLR start T25 + public void mT25() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T25; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:20:7: ( 'if' ) + // C00.g:20:7: 'if' + { + match("if"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T25 + + // $ANTLR start T26 + public void mT26() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T26; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:21:7: ( 'switch' ) + // C00.g:21:7: 'switch' + { + match("switch"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T26 + + // $ANTLR start T27 + public void mT27() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T27; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:22:7: ( 'while' ) + // C00.g:22:7: 'while' + { + match("while"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T27 + + // $ANTLR start T28 + public void mT28() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T28; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:23:7: ( 'do' ) + // C00.g:23:7: 'do' + { + match("do"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T28 + + // $ANTLR start T29 + public void mT29() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T29; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:24:7: ( 'for' ) + // C00.g:24:7: 'for' + { + match("for"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T29 + + // $ANTLR start T30 + public void mT30() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T30; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:25:7: ( 'continue' ) + // C00.g:25:7: 'continue' + { + match("continue"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T30 + + // $ANTLR start T31 + public void mT31() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T31; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:26:7: ( 'break' ) + // C00.g:26:7: 'break' + { + match("break"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T31 + + // $ANTLR start T32 + public void mT32() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T32; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:27:7: ( 'return' ) + // C00.g:27:7: 'return' + { + match("return"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T32 + + // $ANTLR start T33 + public void mT33() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T33; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:28:7: ( 'printf' ) + // C00.g:28:7: 'printf' + { + match("printf"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T33 + + // $ANTLR start T34 + public void mT34() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T34; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:29:7: ( 'scanf' ) + // C00.g:29:7: 'scanf' + { + match("scanf"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T34 + + // $ANTLR start T35 + public void mT35() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T35; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:30:7: ( '\"%i\"' ) + // C00.g:30:7: '\"%i\"' + { + match("\"%i\""); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T35 + + // $ANTLR start T36 + public void mT36() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T36; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:31:7: ( '&' ) + // C00.g:31:7: '&' + { + match('&'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T36 + + // $ANTLR start T37 + public void mT37() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T37; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:32:7: ( '/*label' ) + // C00.g:32:7: '/*label' + { + match("/*label"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T37 + + // $ANTLR start T38 + public void mT38() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T38; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:33:7: ( '*/' ) + // C00.g:33:7: '*/' + { + match("*/"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T38 + + // $ANTLR start T39 + public void mT39() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T39; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:34:7: ( 'else' ) + // C00.g:34:7: 'else' + { + match("else"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T39 + + // $ANTLR start T40 + public void mT40() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T40; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:35:7: ( 'default' ) + // C00.g:35:7: 'default' + { + match("default"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T40 + + // $ANTLR start T41 + public void mT41() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T41; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:36:7: ( ':' ) + // C00.g:36:7: ':' + { + match(':'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T41 + + // $ANTLR start T42 + public void mT42() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T42; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:37:7: ( 'case' ) + // C00.g:37:7: 'case' + { + match("case"); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T42 + + // $ANTLR start T43 + public void mT43() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T43; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:38:7: ( '+' ) + // C00.g:38:7: '+' + { + match('+'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T43 + + // $ANTLR start T44 + public void mT44() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T44; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:39:7: ( '-' ) + // C00.g:39:7: '-' + { + match('-'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T44 + + // $ANTLR start T45 + public void mT45() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T45; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:40:7: ( '/' ) + // C00.g:40:7: '/' + { + match('/'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T45 + + // $ANTLR start T46 + public void mT46() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T46; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:41:7: ( '%' ) + // C00.g:41:7: '%' + { + match('%'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T46 + + // $ANTLR start T47 + public void mT47() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T47; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:42:7: ( '==' ) + // C00.g:42:7: '==' + { + match("=="); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T47 + + // $ANTLR start T48 + public void mT48() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T48; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:43:7: ( '!=' ) + // C00.g:43:7: '!=' + { + match("!="); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T48 + + // $ANTLR start T49 + public void mT49() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T49; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:44:7: ( '<' ) + // C00.g:44:7: '<' + { + match('<'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T49 + + // $ANTLR start T50 + public void mT50() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T50; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:45:7: ( '>' ) + // C00.g:45:7: '>' + { + match('>'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T50 + + // $ANTLR start T51 + public void mT51() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T51; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:46:7: ( '<=' ) + // C00.g:46:7: '<=' + { + match("<="); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T51 + + // $ANTLR start T52 + public void mT52() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = T52; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:47:7: ( '>=' ) + // C00.g:47:7: '>=' + { + match(">="); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end T52 + + // $ANTLR start WHITESPACE + public void mWHITESPACE() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = WHITESPACE; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:493:14: ( ( ('\\t'|' '|'\\r'|'\\n'|'\\u000C'))+ ) + // C00.g:493:14: ( ('\\t'|' '|'\\r'|'\\n'|'\\u000C'))+ + { + // C00.g:493:14: ( ('\\t'|' '|'\\r'|'\\n'|'\\u000C'))+ + int cnt1=0; + loop1: + do { + int alt1=2; + int LA1_0 = input.LA(1); + if ( ((LA1_0>='\t' && LA1_0<='\n')||(LA1_0>='\f' && LA1_0<='\r')||LA1_0==' ') ) { + alt1=1; + } + + + switch (alt1) { + case 1 : + // C00.g:493:16: ('\\t'|' '|'\\r'|'\\n'|'\\u000C') + { + if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||(input.LA(1)>='\f' && input.LA(1)<='\r')||input.LA(1)==' ' ) { + input.consume(); + + } + else { + MismatchedSetException mse = + new MismatchedSetException(null,input); + recover(mse); throw mse; + } + + + } + break; + + default : + if ( cnt1 >= 1 ) break loop1; + EarlyExitException eee = + new EarlyExitException(1, input); + throw eee; + } + cnt1++; + } while (true); + + _channel = HIDDEN; + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end WHITESPACE + + // $ANTLR start String + public void mString() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = String; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:495:10: ( '\"' ( EscapeSequence | ~ ('\\\\'|'\"'))* '\"' ) + // C00.g:495:10: '\"' ( EscapeSequence | ~ ('\\\\'|'\"'))* '\"' + { + match('\"'); + // C00.g:495:14: ( EscapeSequence | ~ ('\\\\'|'\"'))* + loop2: + do { + int alt2=3; + int LA2_0 = input.LA(1); + if ( (LA2_0=='\\') ) { + alt2=1; + } + else if ( ((LA2_0>='\u0000' && LA2_0<='!')||(LA2_0>='#' && LA2_0<='[')||(LA2_0>=']' && LA2_0<='\uFFFE')) ) { + alt2=2; + } + + + switch (alt2) { + case 1 : + // C00.g:495:16: EscapeSequence + { + mEscapeSequence(); + + } + break; + case 2 : + // C00.g:495:33: ~ ('\\\\'|'\"') + { + if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFE') ) { + input.consume(); + + } + else { + MismatchedSetException mse = + new MismatchedSetException(null,input); + recover(mse); throw mse; + } + + + } + break; + + default : + break loop2; + } + } while (true); + + match('\"'); + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end String + + // $ANTLR start Ident + public void mIdent() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = Ident; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:496:10: ( LETTER ( LETTER | DIGIT )* ) + // C00.g:496:10: LETTER ( LETTER | DIGIT )* + { + mLETTER(); + // C00.g:496:17: ( LETTER | DIGIT )* + loop3: + do { + int alt3=3; + int LA3_0 = input.LA(1); + if ( ((LA3_0>='A' && LA3_0<='Z')||(LA3_0>='a' && LA3_0<='z')) ) { + alt3=1; + } + else if ( ((LA3_0>='0' && LA3_0<='9')) ) { + alt3=2; + } + + + switch (alt3) { + case 1 : + // C00.g:496:18: LETTER + { + mLETTER(); + + } + break; + case 2 : + // C00.g:496:27: DIGIT + { + mDIGIT(); + + } + break; + + default : + break loop3; + } + } while (true); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end Ident + + // $ANTLR start Number + public void mNumber() throws RecognitionException { + try { + ruleNestingLevel++; + int _type = Number; + int _start = getCharIndex(); + int _line = getLine(); + int _charPosition = getCharPositionInLine(); + int _channel = Token.DEFAULT_CHANNEL; + // C00.g:497:10: ( ( DIGIT )+ ) + // C00.g:497:10: ( DIGIT )+ + { + // C00.g:497:10: ( DIGIT )+ + int cnt4=0; + loop4: + do { + int alt4=2; + int LA4_0 = input.LA(1); + if ( ((LA4_0>='0' && LA4_0<='9')) ) { + alt4=1; + } + + + switch (alt4) { + case 1 : + // C00.g:497:11: DIGIT + { + mDIGIT(); + + } + break; + + default : + if ( cnt4 >= 1 ) break loop4; + EarlyExitException eee = + new EarlyExitException(4, input); + throw eee; + } + cnt4++; + } while (true); + + + } + + + + if ( token==null && ruleNestingLevel==1 ) { + emit(_type,_line,_charPosition,_channel,_start,getCharIndex()-1); + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end Number + + // $ANTLR start DIGIT + public void mDIGIT() throws RecognitionException { + try { + ruleNestingLevel++; + // C00.g:499:27: ( '0' .. '9' ) + // C00.g:499:27: '0' .. '9' + { + matchRange('0','9'); + + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end DIGIT + + // $ANTLR start LETTER + public void mLETTER() throws RecognitionException { + try { + ruleNestingLevel++; + // C00.g:500:27: ( ('A'..'Z'|'a'..'z')) + // C00.g:500:27: ('A'..'Z'|'a'..'z') + { + if ( (input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { + input.consume(); + + } + else { + MismatchedSetException mse = + new MismatchedSetException(null,input); + recover(mse); throw mse; + } + + + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end LETTER + + // $ANTLR start EscapeSequence + public void mEscapeSequence() throws RecognitionException { + try { + ruleNestingLevel++; + // C00.g:501:27: ( '\\\\' ('t'|'n'|'r'|'\\\"'|'\\''|'\\\\')) + // C00.g:501:27: '\\\\' ('t'|'n'|'r'|'\\\"'|'\\''|'\\\\') + { + match('\\'); + if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { + input.consume(); + + } + else { + MismatchedSetException mse = + new MismatchedSetException(null,input); + recover(mse); throw mse; + } + + + } + + } + finally { + ruleNestingLevel--; + } + } + // $ANTLR end EscapeSequence + + public void mTokens() throws RecognitionException { + // C00.g:1:10: ( T11 | T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | T33 | T34 | T35 | T36 | T37 | T38 | T39 | T40 | T41 | T42 | T43 | T44 | T45 | T46 | T47 | T48 | T49 | T50 | T51 | T52 | WHITESPACE | String | Ident | Number ) + int alt5=46; + switch ( input.LA(1) ) { + case '#': + alt5=1; + break; + case '<': + switch ( input.LA(2) ) { + case '=': + alt5=41; + break; + case 's': + alt5=2; + break; + default: + alt5=39;} + + break; + case 'i': + switch ( input.LA(2) ) { + case 'n': + int LA5_38 = input.LA(3); + if ( (LA5_38=='t') ) { + int LA5_64 = input.LA(4); + if ( ((LA5_64>='0' && LA5_64<='9')||(LA5_64>='A' && LA5_64<='Z')||(LA5_64>='a' && LA5_64<='z')) ) { + alt5=45; + } + else { + alt5=3;} + } + else { + alt5=45;} + break; + case 'f': + int LA5_39 = input.LA(3); + if ( ((LA5_39>='0' && LA5_39<='9')||(LA5_39>='A' && LA5_39<='Z')||(LA5_39>='a' && LA5_39<='z')) ) { + alt5=45; + } + else { + alt5=15;} + break; + default: + alt5=45;} + + break; + case 'm': + int LA5_4 = input.LA(2); + if ( (LA5_4=='a') ) { + int LA5_40 = input.LA(3); + if ( (LA5_40=='i') ) { + int LA5_66 = input.LA(4); + if ( (LA5_66=='n') ) { + int LA5_82 = input.LA(5); + if ( ((LA5_82>='0' && LA5_82<='9')||(LA5_82>='A' && LA5_82<='Z')||(LA5_82>='a' && LA5_82<='z')) ) { + alt5=45; + } + else { + alt5=4;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case '(': + alt5=5; + break; + case ')': + alt5=6; + break; + case ';': + alt5=7; + break; + case 'c': + switch ( input.LA(2) ) { + case 'o': + int LA5_41 = input.LA(3); + if ( (LA5_41=='n') ) { + switch ( input.LA(4) ) { + case 't': + int LA5_83 = input.LA(5); + if ( (LA5_83=='i') ) { + int LA5_98 = input.LA(6); + if ( (LA5_98=='n') ) { + int LA5_111 = input.LA(7); + if ( (LA5_111=='u') ) { + int LA5_120 = input.LA(8); + if ( (LA5_120=='e') ) { + int LA5_125 = input.LA(9); + if ( ((LA5_125>='0' && LA5_125<='9')||(LA5_125>='A' && LA5_125<='Z')||(LA5_125>='a' && LA5_125<='z')) ) { + alt5=45; + } + else { + alt5=20;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 's': + int LA5_84 = input.LA(5); + if ( (LA5_84=='t') ) { + int LA5_99 = input.LA(6); + if ( ((LA5_99>='0' && LA5_99<='9')||(LA5_99>='A' && LA5_99<='Z')||(LA5_99>='a' && LA5_99<='z')) ) { + alt5=45; + } + else { + alt5=8;} + } + else { + alt5=45;} + break; + default: + alt5=45;} + + } + else { + alt5=45;} + break; + case 'a': + int LA5_42 = input.LA(3); + if ( (LA5_42=='s') ) { + int LA5_68 = input.LA(4); + if ( (LA5_68=='e') ) { + int LA5_85 = input.LA(5); + if ( ((LA5_85>='0' && LA5_85<='9')||(LA5_85>='A' && LA5_85<='Z')||(LA5_85>='a' && LA5_85<='z')) ) { + alt5=45; + } + else { + alt5=32;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + default: + alt5=45;} + + break; + case '=': + int LA5_9 = input.LA(2); + if ( (LA5_9=='=') ) { + alt5=37; + } + else { + alt5=9;} + break; + case ',': + alt5=10; + break; + case '*': + int LA5_11 = input.LA(2); + if ( (LA5_11=='/') ) { + alt5=28; + } + else { + alt5=11;} + break; + case 'v': + int LA5_12 = input.LA(2); + if ( (LA5_12=='o') ) { + int LA5_47 = input.LA(3); + if ( (LA5_47=='i') ) { + int LA5_69 = input.LA(4); + if ( (LA5_69=='d') ) { + int LA5_86 = input.LA(5); + if ( ((LA5_86>='0' && LA5_86<='9')||(LA5_86>='A' && LA5_86<='Z')||(LA5_86>='a' && LA5_86<='z')) ) { + alt5=45; + } + else { + alt5=12;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case '{': + alt5=13; + break; + case '}': + alt5=14; + break; + case 's': + switch ( input.LA(2) ) { + case 'c': + int LA5_48 = input.LA(3); + if ( (LA5_48=='a') ) { + int LA5_70 = input.LA(4); + if ( (LA5_70=='n') ) { + int LA5_87 = input.LA(5); + if ( (LA5_87=='f') ) { + int LA5_102 = input.LA(6); + if ( ((LA5_102>='0' && LA5_102<='9')||(LA5_102>='A' && LA5_102<='Z')||(LA5_102>='a' && LA5_102<='z')) ) { + alt5=45; + } + else { + alt5=24;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 'w': + int LA5_49 = input.LA(3); + if ( (LA5_49=='i') ) { + int LA5_71 = input.LA(4); + if ( (LA5_71=='t') ) { + int LA5_88 = input.LA(5); + if ( (LA5_88=='c') ) { + int LA5_103 = input.LA(6); + if ( (LA5_103=='h') ) { + int LA5_114 = input.LA(7); + if ( ((LA5_114>='0' && LA5_114<='9')||(LA5_114>='A' && LA5_114<='Z')||(LA5_114>='a' && LA5_114<='z')) ) { + alt5=45; + } + else { + alt5=16;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + default: + alt5=45;} + + break; + case 'w': + int LA5_16 = input.LA(2); + if ( (LA5_16=='h') ) { + int LA5_50 = input.LA(3); + if ( (LA5_50=='i') ) { + int LA5_72 = input.LA(4); + if ( (LA5_72=='l') ) { + int LA5_89 = input.LA(5); + if ( (LA5_89=='e') ) { + int LA5_104 = input.LA(6); + if ( ((LA5_104>='0' && LA5_104<='9')||(LA5_104>='A' && LA5_104<='Z')||(LA5_104>='a' && LA5_104<='z')) ) { + alt5=45; + } + else { + alt5=17;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 'd': + switch ( input.LA(2) ) { + case 'o': + int LA5_51 = input.LA(3); + if ( ((LA5_51>='0' && LA5_51<='9')||(LA5_51>='A' && LA5_51<='Z')||(LA5_51>='a' && LA5_51<='z')) ) { + alt5=45; + } + else { + alt5=18;} + break; + case 'e': + int LA5_52 = input.LA(3); + if ( (LA5_52=='f') ) { + int LA5_74 = input.LA(4); + if ( (LA5_74=='a') ) { + int LA5_90 = input.LA(5); + if ( (LA5_90=='u') ) { + int LA5_105 = input.LA(6); + if ( (LA5_105=='l') ) { + int LA5_116 = input.LA(7); + if ( (LA5_116=='t') ) { + int LA5_122 = input.LA(8); + if ( ((LA5_122>='0' && LA5_122<='9')||(LA5_122>='A' && LA5_122<='Z')||(LA5_122>='a' && LA5_122<='z')) ) { + alt5=45; + } + else { + alt5=30;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + default: + alt5=45;} + + break; + case 'f': + int LA5_18 = input.LA(2); + if ( (LA5_18=='o') ) { + int LA5_53 = input.LA(3); + if ( (LA5_53=='r') ) { + int LA5_75 = input.LA(4); + if ( ((LA5_75>='0' && LA5_75<='9')||(LA5_75>='A' && LA5_75<='Z')||(LA5_75>='a' && LA5_75<='z')) ) { + alt5=45; + } + else { + alt5=19;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 'b': + int LA5_19 = input.LA(2); + if ( (LA5_19=='r') ) { + int LA5_54 = input.LA(3); + if ( (LA5_54=='e') ) { + int LA5_76 = input.LA(4); + if ( (LA5_76=='a') ) { + int LA5_92 = input.LA(5); + if ( (LA5_92=='k') ) { + int LA5_106 = input.LA(6); + if ( ((LA5_106>='0' && LA5_106<='9')||(LA5_106>='A' && LA5_106<='Z')||(LA5_106>='a' && LA5_106<='z')) ) { + alt5=45; + } + else { + alt5=21;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 'r': + int LA5_20 = input.LA(2); + if ( (LA5_20=='e') ) { + int LA5_55 = input.LA(3); + if ( (LA5_55=='t') ) { + int LA5_77 = input.LA(4); + if ( (LA5_77=='u') ) { + int LA5_93 = input.LA(5); + if ( (LA5_93=='r') ) { + int LA5_107 = input.LA(6); + if ( (LA5_107=='n') ) { + int LA5_118 = input.LA(7); + if ( ((LA5_118>='0' && LA5_118<='9')||(LA5_118>='A' && LA5_118<='Z')||(LA5_118>='a' && LA5_118<='z')) ) { + alt5=45; + } + else { + alt5=22;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case 'p': + int LA5_21 = input.LA(2); + if ( (LA5_21=='r') ) { + int LA5_56 = input.LA(3); + if ( (LA5_56=='i') ) { + int LA5_78 = input.LA(4); + if ( (LA5_78=='n') ) { + int LA5_94 = input.LA(5); + if ( (LA5_94=='t') ) { + int LA5_108 = input.LA(6); + if ( (LA5_108=='f') ) { + int LA5_119 = input.LA(7); + if ( ((LA5_119>='0' && LA5_119<='9')||(LA5_119>='A' && LA5_119<='Z')||(LA5_119>='a' && LA5_119<='z')) ) { + alt5=45; + } + else { + alt5=23;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case '\"': + int LA5_22 = input.LA(2); + if ( (LA5_22=='%') ) { + int LA5_57 = input.LA(3); + if ( (LA5_57=='i') ) { + int LA5_79 = input.LA(4); + if ( (LA5_79=='\"') ) { + alt5=25; + } + else if ( ((LA5_79>='\u0000' && LA5_79<='!')||(LA5_79>='#' && LA5_79<='\uFFFE')) ) { + alt5=44; + } + else { + NoViableAltException nvae = + new NoViableAltException("1:1: Tokens : ( T11 | T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | T33 | T34 | T35 | T36 | T37 | T38 | T39 | T40 | T41 | T42 | T43 | T44 | T45 | T46 | T47 | T48 | T49 | T50 | T51 | T52 | WHITESPACE | String | Ident | Number );", 5, 79, input); + + throw nvae; + } + } + else if ( ((LA5_57>='\u0000' && LA5_57<='h')||(LA5_57>='j' && LA5_57<='\uFFFE')) ) { + alt5=44; + } + else { + NoViableAltException nvae = + new NoViableAltException("1:1: Tokens : ( T11 | T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | T33 | T34 | T35 | T36 | T37 | T38 | T39 | T40 | T41 | T42 | T43 | T44 | T45 | T46 | T47 | T48 | T49 | T50 | T51 | T52 | WHITESPACE | String | Ident | Number );", 5, 57, input); + + throw nvae; + } + } + else if ( ((LA5_22>='\u0000' && LA5_22<='$')||(LA5_22>='&' && LA5_22<='\uFFFE')) ) { + alt5=44; + } + else { + NoViableAltException nvae = + new NoViableAltException("1:1: Tokens : ( T11 | T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | T33 | T34 | T35 | T36 | T37 | T38 | T39 | T40 | T41 | T42 | T43 | T44 | T45 | T46 | T47 | T48 | T49 | T50 | T51 | T52 | WHITESPACE | String | Ident | Number );", 5, 22, input); + + throw nvae; + } + break; + case '&': + alt5=26; + break; + case '/': + int LA5_24 = input.LA(2); + if ( (LA5_24=='*') ) { + alt5=27; + } + else { + alt5=35;} + break; + case 'e': + int LA5_25 = input.LA(2); + if ( (LA5_25=='l') ) { + int LA5_61 = input.LA(3); + if ( (LA5_61=='s') ) { + int LA5_80 = input.LA(4); + if ( (LA5_80=='e') ) { + int LA5_96 = input.LA(5); + if ( ((LA5_96>='0' && LA5_96<='9')||(LA5_96>='A' && LA5_96<='Z')||(LA5_96>='a' && LA5_96<='z')) ) { + alt5=45; + } + else { + alt5=29;} + } + else { + alt5=45;} + } + else { + alt5=45;} + } + else { + alt5=45;} + break; + case ':': + alt5=31; + break; + case '+': + alt5=33; + break; + case '-': + alt5=34; + break; + case '%': + alt5=36; + break; + case '!': + alt5=38; + break; + case '>': + int LA5_31 = input.LA(2); + if ( (LA5_31=='=') ) { + alt5=42; + } + else { + alt5=40;} + break; + case '\t': + case '\n': + case '\f': + case '\r': + case ' ': + alt5=43; + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + case 'G': + case 'H': + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'P': + case 'Q': + case 'R': + case 'S': + case 'T': + case 'U': + case 'V': + case 'W': + case 'X': + case 'Y': + case 'Z': + case 'a': + case 'g': + case 'h': + case 'j': + case 'k': + case 'l': + case 'n': + case 'o': + case 'q': + case 't': + case 'u': + case 'x': + case 'y': + case 'z': + alt5=45; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + alt5=46; + break; + default: + NoViableAltException nvae = + new NoViableAltException("1:1: Tokens : ( T11 | T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | T33 | T34 | T35 | T36 | T37 | T38 | T39 | T40 | T41 | T42 | T43 | T44 | T45 | T46 | T47 | T48 | T49 | T50 | T51 | T52 | WHITESPACE | String | Ident | Number );", 5, 0, input); + + throw nvae; + } + + switch (alt5) { + case 1 : + // C00.g:1:10: T11 + { + mT11(); + + } + break; + case 2 : + // C00.g:1:14: T12 + { + mT12(); + + } + break; + case 3 : + // C00.g:1:18: T13 + { + mT13(); + + } + break; + case 4 : + // C00.g:1:22: T14 + { + mT14(); + + } + break; + case 5 : + // C00.g:1:26: T15 + { + mT15(); + + } + break; + case 6 : + // C00.g:1:30: T16 + { + mT16(); + + } + break; + case 7 : + // C00.g:1:34: T17 + { + mT17(); + + } + break; + case 8 : + // C00.g:1:38: T18 + { + mT18(); + + } + break; + case 9 : + // C00.g:1:42: T19 + { + mT19(); + + } + break; + case 10 : + // C00.g:1:46: T20 + { + mT20(); + + } + break; + case 11 : + // C00.g:1:50: T21 + { + mT21(); + + } + break; + case 12 : + // C00.g:1:54: T22 + { + mT22(); + + } + break; + case 13 : + // C00.g:1:58: T23 + { + mT23(); + + } + break; + case 14 : + // C00.g:1:62: T24 + { + mT24(); + + } + break; + case 15 : + // C00.g:1:66: T25 + { + mT25(); + + } + break; + case 16 : + // C00.g:1:70: T26 + { + mT26(); + + } + break; + case 17 : + // C00.g:1:74: T27 + { + mT27(); + + } + break; + case 18 : + // C00.g:1:78: T28 + { + mT28(); + + } + break; + case 19 : + // C00.g:1:82: T29 + { + mT29(); + + } + break; + case 20 : + // C00.g:1:86: T30 + { + mT30(); + + } + break; + case 21 : + // C00.g:1:90: T31 + { + mT31(); + + } + break; + case 22 : + // C00.g:1:94: T32 + { + mT32(); + + } + break; + case 23 : + // C00.g:1:98: T33 + { + mT33(); + + } + break; + case 24 : + // C00.g:1:102: T34 + { + mT34(); + + } + break; + case 25 : + // C00.g:1:106: T35 + { + mT35(); + + } + break; + case 26 : + // C00.g:1:110: T36 + { + mT36(); + + } + break; + case 27 : + // C00.g:1:114: T37 + { + mT37(); + + } + break; + case 28 : + // C00.g:1:118: T38 + { + mT38(); + + } + break; + case 29 : + // C00.g:1:122: T39 + { + mT39(); + + } + break; + case 30 : + // C00.g:1:126: T40 + { + mT40(); + + } + break; + case 31 : + // C00.g:1:130: T41 + { + mT41(); + + } + break; + case 32 : + // C00.g:1:134: T42 + { + mT42(); + + } + break; + case 33 : + // C00.g:1:138: T43 + { + mT43(); + + } + break; + case 34 : + // C00.g:1:142: T44 + { + mT44(); + + } + break; + case 35 : + // C00.g:1:146: T45 + { + mT45(); + + } + break; + case 36 : + // C00.g:1:150: T46 + { + mT46(); + + } + break; + case 37 : + // C00.g:1:154: T47 + { + mT47(); + + } + break; + case 38 : + // C00.g:1:158: T48 + { + mT48(); + + } + break; + case 39 : + // C00.g:1:162: T49 + { + mT49(); + + } + break; + case 40 : + // C00.g:1:166: T50 + { + mT50(); + + } + break; + case 41 : + // C00.g:1:170: T51 + { + mT51(); + + } + break; + case 42 : + // C00.g:1:174: T52 + { + mT52(); + + } + break; + case 43 : + // C00.g:1:178: WHITESPACE + { + mWHITESPACE(); + + } + break; + case 44 : + // C00.g:1:189: String + { + mString(); + + } + break; + case 45 : + // C00.g:1:196: Ident + { + mIdent(); + + } + break; + case 46 : + // C00.g:1:202: Number + { + mNumber(); + + } + break; + + } + + } +} \ No newline at end of file diff --git a/src/c00/parser/C00Parser.java b/src/c00/parser/C00Parser.java new file mode 100644 index 0000000..317489a --- /dev/null +++ b/src/c00/parser/C00Parser.java @@ -0,0 +1,12656 @@ +// $ANTLR 3.0b6 C00.g 2007-05-21 11:30:09 + +package c00.parser; + + +import o3b.antlr.runtime.*; +import java.util.Stack; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import o3b.antlr.runtime.debug.*; + +import o3b.antlr.runtime.tree.*; + +import c00.AST; + +public class C00Parser extends DebugParser { + public static final String[] tokenNames = new String[] { + "", "", "", "", "Ident", "Number", "String", "WHITESPACE", "EscapeSequence", "LETTER", "DIGIT", "'#include'", "''", "'int'", "'main'", "'('", "')'", "';'", "'const'", "'='", "','", "'*'", "'void'", "'{'", "'}'", "'if'", "'switch'", "'while'", "'do'", "'for'", "'continue'", "'break'", "'return'", "'printf'", "'scanf'", "'\"%i\"'", "'&'", "'/*label'", "'*/'", "'else'", "'default'", "':'", "'case'", "'+'", "'-'", "'/'", "'%'", "'=='", "'!='", "'<'", "'>'", "'<='", "'>='" + }; + public static final int String=6; + public static final int Ident=4; + public static final int LETTER=9; + public static final int EscapeSequence=8; + public static final int EOF=-1; + public static final int DIGIT=10; + public static final int Number=5; + public static final int WHITESPACE=7; + + private final boolean ignoreExceptions; + + private StringBuffer err; + public static final String[] ruleNames = new String[] { + "invalidRule", "program", "globalDeclarations", "declarations", + "declaration", "constDeclarations", "varDeclarations", "functionImplementations", + "functionHeading", "formalParameters", "paramSections", "block", + "statementSequence", "statement", "elseClause", "assignment", "switchBlock", + "caseSequence", "functionCall", "actualParameters", "expressionList", + "expression", "expression2", "firstTerm", "firstTerm2", "term", + "term2", "factor", "boolExpression", "synpred2", "synpred34", "synpred36", + "synpred39", "synpred55", "synpred56", "synpred57", "synpred58", + "synpred59" + }; + + public int ruleLevel = 0; + public C00Parser(TokenStream input, StringBuffer err, boolean ignoreExceptions) { + super(input); + this.err = err; + this.ignoreExceptions = ignoreExceptions; + } + + public C00Parser(TokenStream input, DebugEventListener dbg, StringBuffer err, boolean ignoreExceptions) { + super(input, dbg); + this.err = err; + this.ignoreExceptions = ignoreExceptions; + } + + @Override + public void emitErrorMessage(String arg0) { + if (!ignoreExceptions) + throw new ParseException(arg0); + + if (err != null) + err.append(arg0.toString()); + else + super.emitErrorMessage(arg0); + } + + protected boolean evalPredicate(boolean result, String predicate) { + dbg.semanticPredicate(result, predicate); + return result; + } + + protected TreeAdaptor adaptor = + new DebugTreeAdaptor(dbg,new CommonTreeAdaptor()); + public void setTreeAdaptor(TreeAdaptor adaptor) { + this.adaptor = new DebugTreeAdaptor(dbg,adaptor); + } + public TreeAdaptor getTreeAdaptor() { + return adaptor; + } + + + public String[] getTokenNames() { return tokenNames; } + public String getGrammarFileName() { return "C00.g"; } + + public void determineIndices(Token start, AST.ASTTree astTree) { + determineIndices(start.getLine(), start.getCharPositionInLine(), astTree); + } + + public void determineIndices(int startLine, int startColumn, AST.ASTTree astTree) { + Token end = input.LT(-1); + astTree.startLine = startLine; + astTree.startColumn = startColumn; + if (end == null) { + astTree.endLine = astTree.startLine; + astTree.endColumn = astTree.startColumn-1; + } else { + astTree.endLine = end.getLine(); + astTree.endColumn = end.getCharPositionInLine()+end.getText().length()-1; + } + } + + public void copyIndices(AST.ASTTree dest, AST.ASTTree source) { + dest.startLine = source.startLine; + dest.startColumn = source.startColumn; + dest.endLine = source.endLine; + dest.endColumn = source.endColumn; + } + + public static class program_return extends ParserRuleReturnScope { + public AST.Program astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start program + // C00.g:45:1: program returns [AST.Program astTree] : '#include' '' gD= globalDeclarations fI= functionImplementations 'int' 'main' '(' fP= formalParameters ')' b= block ; + public program_return program() throws RecognitionException { + program_return retval = new program_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token string_literal1=null; + Token string_literal2=null; + Token string_literal3=null; + Token string_literal4=null; + Token char_literal5=null; + Token char_literal6=null; + globalDeclarations_return gD = null; + + functionImplementations_return fI = null; + + formalParameters_return fP = null; + + block_return b = null; + + + Object string_literal1_tree=null; + Object string_literal2_tree=null; + Object string_literal3_tree=null; + Object string_literal4_tree=null; + Object char_literal5_tree=null; + Object char_literal6_tree=null; + + try { dbg.enterRule("program"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(45, 1); + + try { + // C00.g:46:7: ( '#include' '' gD= globalDeclarations fI= functionImplementations 'int' 'main' '(' fP= formalParameters ')' b= block ) + dbg.enterAlt(1); + + // C00.g:46:7: '#include' '' gD= globalDeclarations fI= functionImplementations 'int' 'main' '(' fP= formalParameters ')' b= block + { + root_0 = (Object)adaptor.nil(); + + dbg.location(46,7); + string_literal1=(Token)input.LT(1); + match(input,11,FOLLOW_11_in_program70); if (failed) return retval; + if ( backtracking==0 ) { + string_literal1_tree = (Object)adaptor.create(string_literal1); + adaptor.addChild(root_0, string_literal1_tree); + } + dbg.location(46,18); + string_literal2=(Token)input.LT(1); + match(input,12,FOLLOW_12_in_program72); if (failed) return retval; + if ( backtracking==0 ) { + string_literal2_tree = (Object)adaptor.create(string_literal2); + adaptor.addChild(root_0, string_literal2_tree); + } + dbg.location(46,32); + pushFollow(FOLLOW_globalDeclarations_in_program76); + gD=globalDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, gD.getTree()); + dbg.location(46,54); + pushFollow(FOLLOW_functionImplementations_in_program80); + fI=functionImplementations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fI.getTree()); + dbg.location(46,79); + string_literal3=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_program82); if (failed) return retval; + if ( backtracking==0 ) { + string_literal3_tree = (Object)adaptor.create(string_literal3); + adaptor.addChild(root_0, string_literal3_tree); + } + dbg.location(46,85); + string_literal4=(Token)input.LT(1); + match(input,14,FOLLOW_14_in_program84); if (failed) return retval; + if ( backtracking==0 ) { + string_literal4_tree = (Object)adaptor.create(string_literal4); + adaptor.addChild(root_0, string_literal4_tree); + } + dbg.location(46,92); + char_literal5=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_program86); if (failed) return retval; + if ( backtracking==0 ) { + char_literal5_tree = (Object)adaptor.create(char_literal5); + adaptor.addChild(root_0, char_literal5_tree); + } + dbg.location(46,98); + pushFollow(FOLLOW_formalParameters_in_program90); + fP=formalParameters(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fP.getTree()); + dbg.location(46,116); + char_literal6=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_program92); if (failed) return retval; + if ( backtracking==0 ) { + char_literal6_tree = (Object)adaptor.create(char_literal6); + adaptor.addChild(root_0, char_literal6_tree); + } + dbg.location(46,121); + pushFollow(FOLLOW_block_in_program96); + b=block(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, b.getTree()); + dbg.location(47,2); + if ( backtracking==0 ) { + if (gD.astTree == null || fI.astTree == null || fP.astTree == null || b.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExpandProgram(gD.astTree, fI.astTree, fP.astTree, b.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(50, 5); + + } + finally { + dbg.exitRule("program"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end program + + public static class globalDeclarations_return extends ParserRuleReturnScope { + public AST.GlobalDeclarations astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start globalDeclarations + // C00.g:53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | ); + public globalDeclarations_return globalDeclarations() throws RecognitionException { + globalDeclarations_return retval = new globalDeclarations_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal7=null; + declaration_return d1 = null; + + globalDeclarations_return gd1 = null; + + functionHeading_return f2 = null; + + globalDeclarations_return gd2 = null; + + + Object char_literal7_tree=null; + + try { dbg.enterRule("globalDeclarations"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(53, 1); + + try { + // C00.g:54:7: ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | ) + int alt1=3; + try { dbg.enterDecision(1); + + switch ( input.LA(1) ) { + case 18: + alt1=1; + break; + case 13: + switch ( input.LA(2) ) { + case Ident: + int LA1_5 = input.LA(3); + if ( (LA1_5==15) ) { + switch ( input.LA(4) ) { + case 22: + int LA1_9 = input.LA(5); + if ( (LA1_9==16) ) { + int LA1_11 = input.LA(6); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 9, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 13: + int LA1_10 = input.LA(5); + if ( (LA1_10==Ident) ) { + int LA1_15 = input.LA(6); + if ( (LA1_15==20) ) { + int LA1_20 = input.LA(7); + if ( (LA1_20==13) ) { + int LA1_24 = input.LA(8); + if ( (LA1_24==Ident) ) { + int LA1_28 = input.LA(9); + if ( (LA1_28==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 34, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_28==16) ) { + int LA1_11 = input.LA(10); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 28, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_24==21) ) { + int LA1_29 = input.LA(9); + if ( (LA1_29==Ident) ) { + int LA1_35 = input.LA(10); + if ( (LA1_35==20) ) { + int LA1_42 = input.LA(11); + if ( (LA1_42==13) ) { + int LA1_48 = input.LA(12); + if ( (LA1_48==Ident) ) { + int LA1_54 = input.LA(13); + if ( (LA1_54==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 62, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_54==16) ) { + int LA1_11 = input.LA(14); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 54, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_48==21) ) { + int LA1_55 = input.LA(13); + if ( (LA1_55==Ident) ) { + int LA1_63 = input.LA(14); + if ( (LA1_63==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 70, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_63==16) ) { + int LA1_11 = input.LA(15); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 63, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 55, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 48, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 42, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_35==16) ) { + int LA1_11 = input.LA(11); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 35, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 29, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 24, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 20, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_15==16) ) { + int LA1_11 = input.LA(7); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 15, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_10==21) ) { + int LA1_16 = input.LA(6); + if ( (LA1_16==Ident) ) { + int LA1_21 = input.LA(7); + if ( (LA1_21==20) ) { + int LA1_25 = input.LA(8); + if ( (LA1_25==13) ) { + int LA1_30 = input.LA(9); + if ( (LA1_30==21) ) { + int LA1_36 = input.LA(10); + if ( (LA1_36==Ident) ) { + int LA1_43 = input.LA(11); + if ( (LA1_43==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 49, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_43==16) ) { + int LA1_11 = input.LA(12); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 43, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 36, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_30==Ident) ) { + int LA1_37 = input.LA(10); + if ( (LA1_37==20) ) { + int LA1_44 = input.LA(11); + if ( (LA1_44==13) ) { + int LA1_50 = input.LA(12); + if ( (LA1_50==Ident) ) { + int LA1_56 = input.LA(13); + if ( (LA1_56==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 64, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_56==16) ) { + int LA1_11 = input.LA(14); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 56, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_50==21) ) { + int LA1_57 = input.LA(13); + if ( (LA1_57==Ident) ) { + int LA1_65 = input.LA(14); + if ( (LA1_65==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 71, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_65==16) ) { + int LA1_11 = input.LA(15); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 65, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 57, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 50, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 44, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_37==16) ) { + int LA1_11 = input.LA(11); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 37, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 30, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 25, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_21==16) ) { + int LA1_11 = input.LA(8); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 21, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 16, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 10, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 16: + int LA1_11 = input.LA(5); + if ( (LA1_11==23) ) { + alt1=3; + } + else if ( (LA1_11==17) ) { + alt1=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 7, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } + else if ( (LA1_5==17||(LA1_5>=19 && LA1_5<=20)) ) { + alt1=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 5, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 14: + alt1=3; + break; + case 21: + alt1=1; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 2, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + break; + case 22: + int LA1_3 = input.LA(2); + if ( (LA1_3==Ident) ) { + int LA1_6 = input.LA(3); + if ( (LA1_6==15) ) { + switch ( input.LA(4) ) { + case 22: + int LA1_12 = input.LA(5); + if ( (LA1_12==16) ) { + int LA1_14 = input.LA(6); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 12, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 13: + int LA1_13 = input.LA(5); + if ( (LA1_13==Ident) ) { + int LA1_18 = input.LA(6); + if ( (LA1_18==20) ) { + int LA1_22 = input.LA(7); + if ( (LA1_22==13) ) { + int LA1_26 = input.LA(8); + if ( (LA1_26==21) ) { + int LA1_31 = input.LA(9); + if ( (LA1_31==Ident) ) { + int LA1_38 = input.LA(10); + if ( (LA1_38==20) ) { + int LA1_45 = input.LA(11); + if ( (LA1_45==13) ) { + int LA1_51 = input.LA(12); + if ( (LA1_51==Ident) ) { + int LA1_58 = input.LA(13); + if ( (LA1_58==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 66, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_58==16) ) { + int LA1_14 = input.LA(14); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 58, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_51==21) ) { + int LA1_59 = input.LA(13); + if ( (LA1_59==Ident) ) { + int LA1_67 = input.LA(14); + if ( (LA1_67==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 72, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_67==16) ) { + int LA1_14 = input.LA(15); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 67, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 59, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 51, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 45, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_38==16) ) { + int LA1_14 = input.LA(11); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 38, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 31, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_26==Ident) ) { + int LA1_32 = input.LA(9); + if ( (LA1_32==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 39, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_32==16) ) { + int LA1_14 = input.LA(10); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 32, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 26, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 22, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_18==16) ) { + int LA1_14 = input.LA(7); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 18, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_13==21) ) { + int LA1_19 = input.LA(6); + if ( (LA1_19==Ident) ) { + int LA1_23 = input.LA(7); + if ( (LA1_23==20) ) { + int LA1_27 = input.LA(8); + if ( (LA1_27==13) ) { + int LA1_33 = input.LA(9); + if ( (LA1_33==Ident) ) { + int LA1_40 = input.LA(10); + if ( (LA1_40==20) ) { + int LA1_46 = input.LA(11); + if ( (LA1_46==13) ) { + int LA1_52 = input.LA(12); + if ( (LA1_52==Ident) ) { + int LA1_60 = input.LA(13); + if ( (LA1_60==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 68, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_60==16) ) { + int LA1_14 = input.LA(14); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 60, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_52==21) ) { + int LA1_61 = input.LA(13); + if ( (LA1_61==Ident) ) { + int LA1_69 = input.LA(14); + if ( (LA1_69==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 73, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_69==16) ) { + int LA1_14 = input.LA(15); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 69, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 61, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 52, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 46, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_40==16) ) { + int LA1_14 = input.LA(11); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 40, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_33==21) ) { + int LA1_41 = input.LA(10); + if ( (LA1_41==Ident) ) { + int LA1_47 = input.LA(11); + if ( (LA1_47==20) ) { + if ( (synpred2()) ) { + alt1=2; + } + else if ( (true) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 53, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_47==16) ) { + int LA1_14 = input.LA(12); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 47, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 41, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 33, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 27, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA1_23==16) ) { + int LA1_14 = input.LA(8); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 23, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 19, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 13, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 16: + int LA1_14 = input.LA(5); + if ( (LA1_14==17) ) { + alt1=2; + } + else if ( (LA1_14==23) ) { + alt1=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 14, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 8, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 6, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 3, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case EOF: + alt1=3; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("53:1: globalDeclarations returns [AST.GlobalDeclarations astTree] : ( ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations | ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations | );", 1, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(1);} + + switch (alt1) { + case 1 : + dbg.enterAlt(1); + + // C00.g:54:7: ( declaration globalDeclarations )=>d1= declaration gd1= globalDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(54,9); + pushFollow(FOLLOW_declaration_in_globalDeclarations124); + d1=declaration(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, d1.getTree()); + dbg.location(54,25); + pushFollow(FOLLOW_globalDeclarations_in_globalDeclarations128); + gd1=globalDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, gd1.getTree()); + dbg.location(55,2); + if ( backtracking==0 ) { + if (d1.astTree == null || gd1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.VarConstGlobDecls(d1.astTree, gd1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:58:7: ( functionHeading ';' globalDeclarations )=>f2= functionHeading ';' gd2= globalDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(58,9); + pushFollow(FOLLOW_functionHeading_in_globalDeclarations141); + f2=functionHeading(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f2.getTree()); + dbg.location(58,26); + char_literal7=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_globalDeclarations143); if (failed) return retval; + if ( backtracking==0 ) { + char_literal7_tree = (Object)adaptor.create(char_literal7); + adaptor.addChild(root_0, char_literal7_tree); + } + dbg.location(58,33); + pushFollow(FOLLOW_globalDeclarations_in_globalDeclarations147); + gd2=globalDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, gd2.getTree()); + dbg.location(59,2); + if ( backtracking==0 ) { + if (f2.astTree == null || gd2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.FuncGlobDecls(f2.astTree, gd2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:63:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(63,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyGlobDecls(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(65, 5); + + } + finally { + dbg.exitRule("globalDeclarations"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end globalDeclarations + + public static class declarations_return extends ParserRuleReturnScope { + public AST.Declarations astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start declarations + // C00.g:68:1: declarations returns [AST.Declarations astTree] : ( ( declaration declarations )=>d1= declaration d2= declarations | ); + public declarations_return declarations() throws RecognitionException { + declarations_return retval = new declarations_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + declaration_return d1 = null; + + declarations_return d2 = null; + + + + try { dbg.enterRule("declarations"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(68, 1); + + try { + // C00.g:69:7: ( ( declaration declarations )=>d1= declaration d2= declarations | ) + int alt2=2; + try { dbg.enterDecision(2); + + int LA2_0 = input.LA(1); + if ( (LA2_0==13||LA2_0==18) ) { + alt2=1; + } + else if ( (LA2_0==EOF||LA2_0==Ident||LA2_0==21||(LA2_0>=23 && LA2_0<=34)||LA2_0==37) ) { + alt2=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("68:1: declarations returns [AST.Declarations astTree] : ( ( declaration declarations )=>d1= declaration d2= declarations | );", 2, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(2);} + + switch (alt2) { + case 1 : + dbg.enterAlt(1); + + // C00.g:69:7: ( declaration declarations )=>d1= declaration d2= declarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(69,9); + pushFollow(FOLLOW_declaration_in_declarations183); + d1=declaration(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, d1.getTree()); + dbg.location(69,24); + pushFollow(FOLLOW_declarations_in_declarations187); + d2=declarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, d2.getTree()); + dbg.location(70,2); + if ( backtracking==0 ) { + if (d1.astTree == null || d2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PairDecls(d1.astTree, d2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:74:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(74,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyDecls(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(76, 5); + + } + finally { + dbg.exitRule("declarations"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end declarations + + public static class declaration_return extends ParserRuleReturnScope { + public AST.Declaration astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start declaration + // C00.g:79:1: declaration returns [AST.Declaration astTree] : ( ( 'const' 'int' constDeclarations ';' )=> 'const' 'int' cd1= constDeclarations ';' | 'int' vd2= varDeclarations ';' ); + public declaration_return declaration() throws RecognitionException { + declaration_return retval = new declaration_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token string_literal8=null; + Token string_literal9=null; + Token char_literal10=null; + Token string_literal11=null; + Token char_literal12=null; + constDeclarations_return cd1 = null; + + varDeclarations_return vd2 = null; + + + Object string_literal8_tree=null; + Object string_literal9_tree=null; + Object char_literal10_tree=null; + Object string_literal11_tree=null; + Object char_literal12_tree=null; + + try { dbg.enterRule("declaration"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(79, 1); + + try { + // C00.g:80:7: ( ( 'const' 'int' constDeclarations ';' )=> 'const' 'int' cd1= constDeclarations ';' | 'int' vd2= varDeclarations ';' ) + int alt3=2; + try { dbg.enterDecision(3); + + int LA3_0 = input.LA(1); + if ( (LA3_0==18) ) { + alt3=1; + } + else if ( (LA3_0==13) ) { + alt3=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("79:1: declaration returns [AST.Declaration astTree] : ( ( 'const' 'int' constDeclarations ';' )=> 'const' 'int' cd1= constDeclarations ';' | 'int' vd2= varDeclarations ';' );", 3, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(3);} + + switch (alt3) { + case 1 : + dbg.enterAlt(1); + + // C00.g:80:7: ( 'const' 'int' constDeclarations ';' )=> 'const' 'int' cd1= constDeclarations ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(80,7); + string_literal8=(Token)input.LT(1); + match(input,18,FOLLOW_18_in_declaration221); if (failed) return retval; + if ( backtracking==0 ) { + string_literal8_tree = (Object)adaptor.create(string_literal8); + adaptor.addChild(root_0, string_literal8_tree); + } + dbg.location(80,15); + string_literal9=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_declaration223); if (failed) return retval; + if ( backtracking==0 ) { + string_literal9_tree = (Object)adaptor.create(string_literal9); + adaptor.addChild(root_0, string_literal9_tree); + } + dbg.location(80,24); + pushFollow(FOLLOW_constDeclarations_in_declaration227); + cd1=constDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, cd1.getTree()); + dbg.location(80,43); + char_literal10=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_declaration229); if (failed) return retval; + if ( backtracking==0 ) { + char_literal10_tree = (Object)adaptor.create(char_literal10); + adaptor.addChild(root_0, char_literal10_tree); + } + dbg.location(81,2); + if ( backtracking==0 ) { + if (cd1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ConstDecl(cd1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:84:7: 'int' vd2= varDeclarations ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(84,7); + string_literal11=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_declaration240); if (failed) return retval; + if ( backtracking==0 ) { + string_literal11_tree = (Object)adaptor.create(string_literal11); + adaptor.addChild(root_0, string_literal11_tree); + } + dbg.location(84,16); + pushFollow(FOLLOW_varDeclarations_in_declaration244); + vd2=varDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, vd2.getTree()); + dbg.location(84,33); + char_literal12=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_declaration246); if (failed) return retval; + if ( backtracking==0 ) { + char_literal12_tree = (Object)adaptor.create(char_literal12); + adaptor.addChild(root_0, char_literal12_tree); + } + dbg.location(85,2); + if ( backtracking==0 ) { + if (vd2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.VarDecl(vd2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(88, 5); + + } + finally { + dbg.exitRule("declaration"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end declaration + + public static class constDeclarations_return extends ParserRuleReturnScope { + public AST.ConstDeclarations astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start constDeclarations + // C00.g:91:1: constDeclarations returns [AST.ConstDeclarations astTree] : ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations ); + public constDeclarations_return constDeclarations() throws RecognitionException { + constDeclarations_return retval = new constDeclarations_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token n1=null; + Token i2=null; + Token n2=null; + Token char_literal13=null; + Token char_literal14=null; + Token char_literal15=null; + constDeclarations_return cd2 = null; + + + Object i1_tree=null; + Object n1_tree=null; + Object i2_tree=null; + Object n2_tree=null; + Object char_literal13_tree=null; + Object char_literal14_tree=null; + Object char_literal15_tree=null; + + try { dbg.enterRule("constDeclarations"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(91, 1); + + try { + // C00.g:92:7: ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations ) + int alt4=2; + try { dbg.enterDecision(4); + + int LA4_0 = input.LA(1); + if ( (LA4_0==Ident) ) { + int LA4_1 = input.LA(2); + if ( (LA4_1==19) ) { + int LA4_2 = input.LA(3); + if ( (LA4_2==Number) ) { + int LA4_3 = input.LA(4); + if ( (LA4_3==20) ) { + alt4=2; + } + else if ( (LA4_3==17) ) { + alt4=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("91:1: constDeclarations returns [AST.ConstDeclarations astTree] : ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations );", 4, 3, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("91:1: constDeclarations returns [AST.ConstDeclarations astTree] : ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations );", 4, 2, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("91:1: constDeclarations returns [AST.ConstDeclarations astTree] : ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations );", 4, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("91:1: constDeclarations returns [AST.ConstDeclarations astTree] : ( ( Ident '=' Number )=>i1= Ident '=' n1= Number | i2= Ident '=' n2= Number ',' cd2= constDeclarations );", 4, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(4);} + + switch (alt4) { + case 1 : + dbg.enterAlt(1); + + // C00.g:92:7: ( Ident '=' Number )=>i1= Ident '=' n1= Number + { + root_0 = (Object)adaptor.nil(); + + dbg.location(92,9); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_constDeclarations274); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(92,16); + char_literal13=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_constDeclarations276); if (failed) return retval; + if ( backtracking==0 ) { + char_literal13_tree = (Object)adaptor.create(char_literal13); + adaptor.addChild(root_0, char_literal13_tree); + } + dbg.location(92,22); + n1=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_constDeclarations280); if (failed) return retval; + if ( backtracking==0 ) { + n1_tree = (Object)adaptor.create(n1); + adaptor.addChild(root_0, n1_tree); + } + dbg.location(93,2); + if ( backtracking==0 ) { + if (i1 == null || n1 == null) {retval.astTree = null;} else + {retval.astTree = new AST.LastConstDecls(i1.getText(), Integer.parseInt(n1.getText())); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:96:7: i2= Ident '=' n2= Number ',' cd2= constDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(96,9); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_constDeclarations293); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(96,16); + char_literal14=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_constDeclarations295); if (failed) return retval; + if ( backtracking==0 ) { + char_literal14_tree = (Object)adaptor.create(char_literal14); + adaptor.addChild(root_0, char_literal14_tree); + } + dbg.location(96,22); + n2=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_constDeclarations299); if (failed) return retval; + if ( backtracking==0 ) { + n2_tree = (Object)adaptor.create(n2); + adaptor.addChild(root_0, n2_tree); + } + dbg.location(96,30); + char_literal15=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_constDeclarations301); if (failed) return retval; + if ( backtracking==0 ) { + char_literal15_tree = (Object)adaptor.create(char_literal15); + adaptor.addChild(root_0, char_literal15_tree); + } + dbg.location(96,37); + pushFollow(FOLLOW_constDeclarations_in_constDeclarations305); + cd2=constDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, cd2.getTree()); + dbg.location(97,2); + if ( backtracking==0 ) { + if (i2 == null || n2 == null || cd2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PairConstDecls(i2.getText(), Integer.parseInt(n2.getText()), cd2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(100, 5); + + } + finally { + dbg.exitRule("constDeclarations"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end constDeclarations + + public static class varDeclarations_return extends ParserRuleReturnScope { + public AST.VarDeclarations astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start varDeclarations + // C00.g:102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations ); + public varDeclarations_return varDeclarations() throws RecognitionException { + varDeclarations_return retval = new varDeclarations_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token i5=null; + Token i2=null; + Token n2=null; + Token i3=null; + Token i6=null; + Token i4=null; + Token n4=null; + Token char_literal16=null; + Token char_literal17=null; + Token char_literal18=null; + Token char_literal19=null; + Token char_literal20=null; + Token char_literal21=null; + Token char_literal22=null; + varDeclarations_return vD3 = null; + + varDeclarations_return vD6 = null; + + varDeclarations_return vD4 = null; + + + Object i1_tree=null; + Object i5_tree=null; + Object i2_tree=null; + Object n2_tree=null; + Object i3_tree=null; + Object i6_tree=null; + Object i4_tree=null; + Object n4_tree=null; + Object char_literal16_tree=null; + Object char_literal17_tree=null; + Object char_literal18_tree=null; + Object char_literal19_tree=null; + Object char_literal20_tree=null; + Object char_literal21_tree=null; + Object char_literal22_tree=null; + + try { dbg.enterRule("varDeclarations"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(102, 1); + + try { + // C00.g:103:7: ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations ) + int alt5=6; + try { dbg.enterDecision(5); + + int LA5_0 = input.LA(1); + if ( (LA5_0==Ident) ) { + switch ( input.LA(2) ) { + case 19: + int LA5_3 = input.LA(3); + if ( (LA5_3==Number) ) { + int LA5_7 = input.LA(4); + if ( (LA5_7==20) ) { + alt5=6; + } + else if ( (LA5_7==EOF||LA5_7==17) ) { + alt5=3; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 7, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 3, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 20: + alt5=4; + break; + case EOF: + case 17: + alt5=1; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } + else if ( (LA5_0==21) ) { + int LA5_2 = input.LA(2); + if ( (LA5_2==Ident) ) { + int LA5_6 = input.LA(3); + if ( (LA5_6==20) ) { + alt5=5; + } + else if ( (LA5_6==EOF||LA5_6==17) ) { + alt5=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 6, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 2, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("102:1: varDeclarations returns [AST.VarDeclarations astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i5= Ident | ( Ident '=' Number )=>i2= Ident '=' n2= Number | ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations | ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations | i4= Ident '=' n4= Number ',' vD4= varDeclarations );", 5, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(5);} + + switch (alt5) { + case 1 : + dbg.enterAlt(1); + + // C00.g:103:7: ( Ident )=>i1= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(103,9); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations336); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(104,2); + if ( backtracking==0 ) { + if (i1 == null) {retval.astTree = null;} else + {retval.astTree = new AST.VarLastDecls(i1.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:107:7: ( '*' Ident )=> '*' i5= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(107,7); + char_literal16=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_varDeclarations347); if (failed) return retval; + if ( backtracking==0 ) { + char_literal16_tree = (Object)adaptor.create(char_literal16); + adaptor.addChild(root_0, char_literal16_tree); + } + dbg.location(107,13); + i5=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations351); if (failed) return retval; + if ( backtracking==0 ) { + i5_tree = (Object)adaptor.create(i5); + adaptor.addChild(root_0, i5_tree); + } + dbg.location(108,2); + if ( backtracking==0 ) { + if (i5 == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefVarLastDecls(i5.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:111:7: ( Ident '=' Number )=>i2= Ident '=' n2= Number + { + root_0 = (Object)adaptor.nil(); + + dbg.location(111,9); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations364); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(111,16); + char_literal17=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_varDeclarations366); if (failed) return retval; + if ( backtracking==0 ) { + char_literal17_tree = (Object)adaptor.create(char_literal17); + adaptor.addChild(root_0, char_literal17_tree); + } + dbg.location(111,22); + n2=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_varDeclarations370); if (failed) return retval; + if ( backtracking==0 ) { + n2_tree = (Object)adaptor.create(n2); + adaptor.addChild(root_0, n2_tree); + } + dbg.location(112,2); + if ( backtracking==0 ) { + if (i2 == null || n2 == null) {retval.astTree = null;} else + {retval.astTree = new AST.InitVarLastDecls(i2.getText(), Integer.parseInt(n2.getText())); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 4 : + dbg.enterAlt(4); + + // C00.g:115:7: ( Ident ',' varDeclarations )=>i3= Ident ',' vD3= varDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(115,9); + i3=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations383); if (failed) return retval; + if ( backtracking==0 ) { + i3_tree = (Object)adaptor.create(i3); + adaptor.addChild(root_0, i3_tree); + } + dbg.location(115,16); + char_literal18=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_varDeclarations385); if (failed) return retval; + if ( backtracking==0 ) { + char_literal18_tree = (Object)adaptor.create(char_literal18); + adaptor.addChild(root_0, char_literal18_tree); + } + dbg.location(115,23); + pushFollow(FOLLOW_varDeclarations_in_varDeclarations389); + vD3=varDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, vD3.getTree()); + dbg.location(116,2); + if ( backtracking==0 ) { + if (i3 == null || vD3.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.VarPairDecls(i3.getText(), vD3.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 5 : + dbg.enterAlt(5); + + // C00.g:119:7: ( '*' Ident ',' varDeclarations )=> '*' i6= Ident ',' vD6= varDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(119,7); + char_literal19=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_varDeclarations400); if (failed) return retval; + if ( backtracking==0 ) { + char_literal19_tree = (Object)adaptor.create(char_literal19); + adaptor.addChild(root_0, char_literal19_tree); + } + dbg.location(119,13); + i6=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations404); if (failed) return retval; + if ( backtracking==0 ) { + i6_tree = (Object)adaptor.create(i6); + adaptor.addChild(root_0, i6_tree); + } + dbg.location(119,20); + char_literal20=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_varDeclarations406); if (failed) return retval; + if ( backtracking==0 ) { + char_literal20_tree = (Object)adaptor.create(char_literal20); + adaptor.addChild(root_0, char_literal20_tree); + } + dbg.location(119,27); + pushFollow(FOLLOW_varDeclarations_in_varDeclarations410); + vD6=varDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, vD6.getTree()); + dbg.location(120,2); + if ( backtracking==0 ) { + if (i6 == null || vD6.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefVarPairDecls(i6.getText(), vD6.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 6 : + dbg.enterAlt(6); + + // C00.g:123:7: i4= Ident '=' n4= Number ',' vD4= varDeclarations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(123,9); + i4=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_varDeclarations423); if (failed) return retval; + if ( backtracking==0 ) { + i4_tree = (Object)adaptor.create(i4); + adaptor.addChild(root_0, i4_tree); + } + dbg.location(123,16); + char_literal21=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_varDeclarations425); if (failed) return retval; + if ( backtracking==0 ) { + char_literal21_tree = (Object)adaptor.create(char_literal21); + adaptor.addChild(root_0, char_literal21_tree); + } + dbg.location(123,22); + n4=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_varDeclarations429); if (failed) return retval; + if ( backtracking==0 ) { + n4_tree = (Object)adaptor.create(n4); + adaptor.addChild(root_0, n4_tree); + } + dbg.location(123,30); + char_literal22=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_varDeclarations431); if (failed) return retval; + if ( backtracking==0 ) { + char_literal22_tree = (Object)adaptor.create(char_literal22); + adaptor.addChild(root_0, char_literal22_tree); + } + dbg.location(123,37); + pushFollow(FOLLOW_varDeclarations_in_varDeclarations435); + vD4=varDeclarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, vD4.getTree()); + dbg.location(124,2); + if ( backtracking==0 ) { + if (i4 == null || n4 == null || vD4.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.InitVarPairDecls(i4.getText(), Integer.parseInt(n4.getText()), vD4.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(127, 5); + + } + finally { + dbg.exitRule("varDeclarations"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end varDeclarations + + public static class functionImplementations_return extends ParserRuleReturnScope { + public AST.FunctionImplementations astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start functionImplementations + // C00.g:129:1: functionImplementations returns [AST.FunctionImplementations astTree] : ( ( functionHeading block functionImplementations )=>fH= functionHeading b= block fI= functionImplementations | ); + public functionImplementations_return functionImplementations() throws RecognitionException { + functionImplementations_return retval = new functionImplementations_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + functionHeading_return fH = null; + + block_return b = null; + + functionImplementations_return fI = null; + + + + try { dbg.enterRule("functionImplementations"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(129, 1); + + try { + // C00.g:130:7: ( ( functionHeading block functionImplementations )=>fH= functionHeading b= block fI= functionImplementations | ) + int alt6=2; + try { dbg.enterDecision(6); + + switch ( input.LA(1) ) { + case 22: + alt6=1; + break; + case 13: + int LA6_2 = input.LA(2); + if ( (LA6_2==14) ) { + alt6=2; + } + else if ( (LA6_2==Ident) ) { + alt6=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("129:1: functionImplementations returns [AST.FunctionImplementations astTree] : ( ( functionHeading block functionImplementations )=>fH= functionHeading b= block fI= functionImplementations | );", 6, 2, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case EOF: + alt6=2; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("129:1: functionImplementations returns [AST.FunctionImplementations astTree] : ( ( functionHeading block functionImplementations )=>fH= functionHeading b= block fI= functionImplementations | );", 6, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(6);} + + switch (alt6) { + case 1 : + dbg.enterAlt(1); + + // C00.g:130:7: ( functionHeading block functionImplementations )=>fH= functionHeading b= block fI= functionImplementations + { + root_0 = (Object)adaptor.nil(); + + dbg.location(130,9); + pushFollow(FOLLOW_functionHeading_in_functionImplementations465); + fH=functionHeading(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fH.getTree()); + dbg.location(130,27); + pushFollow(FOLLOW_block_in_functionImplementations469); + b=block(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, b.getTree()); + dbg.location(130,36); + pushFollow(FOLLOW_functionImplementations_in_functionImplementations473); + fI=functionImplementations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fI.getTree()); + dbg.location(131,2); + if ( backtracking==0 ) { + if (fH.astTree == null || b.astTree == null || fI.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PairFuncImpls(fH.astTree, b.astTree, fI.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:135:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(135,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyFuncImpls(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(137, 5); + + } + finally { + dbg.exitRule("functionImplementations"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end functionImplementations + + public static class functionHeading_return extends ParserRuleReturnScope { + public AST.FunctionHeading astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start functionHeading + // C00.g:139:1: functionHeading returns [AST.FunctionHeading astTree] : ( ( 'void' Ident '(' formalParameters ')' )=> 'void' i1= Ident '(' fP1= formalParameters ')' | 'int' i2= Ident '(' fP2= formalParameters ')' ); + public functionHeading_return functionHeading() throws RecognitionException { + functionHeading_return retval = new functionHeading_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token i2=null; + Token string_literal23=null; + Token char_literal24=null; + Token char_literal25=null; + Token string_literal26=null; + Token char_literal27=null; + Token char_literal28=null; + formalParameters_return fP1 = null; + + formalParameters_return fP2 = null; + + + Object i1_tree=null; + Object i2_tree=null; + Object string_literal23_tree=null; + Object char_literal24_tree=null; + Object char_literal25_tree=null; + Object string_literal26_tree=null; + Object char_literal27_tree=null; + Object char_literal28_tree=null; + + try { dbg.enterRule("functionHeading"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(139, 1); + + try { + // C00.g:140:7: ( ( 'void' Ident '(' formalParameters ')' )=> 'void' i1= Ident '(' fP1= formalParameters ')' | 'int' i2= Ident '(' fP2= formalParameters ')' ) + int alt7=2; + try { dbg.enterDecision(7); + + int LA7_0 = input.LA(1); + if ( (LA7_0==22) ) { + alt7=1; + } + else if ( (LA7_0==13) ) { + alt7=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("139:1: functionHeading returns [AST.FunctionHeading astTree] : ( ( 'void' Ident '(' formalParameters ')' )=> 'void' i1= Ident '(' fP1= formalParameters ')' | 'int' i2= Ident '(' fP2= formalParameters ')' );", 7, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(7);} + + switch (alt7) { + case 1 : + dbg.enterAlt(1); + + // C00.g:140:7: ( 'void' Ident '(' formalParameters ')' )=> 'void' i1= Ident '(' fP1= formalParameters ')' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(140,7); + string_literal23=(Token)input.LT(1); + match(input,22,FOLLOW_22_in_functionHeading515); if (failed) return retval; + if ( backtracking==0 ) { + string_literal23_tree = (Object)adaptor.create(string_literal23); + adaptor.addChild(root_0, string_literal23_tree); + } + dbg.location(140,16); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_functionHeading519); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(140,23); + char_literal24=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_functionHeading521); if (failed) return retval; + if ( backtracking==0 ) { + char_literal24_tree = (Object)adaptor.create(char_literal24); + adaptor.addChild(root_0, char_literal24_tree); + } + dbg.location(140,30); + pushFollow(FOLLOW_formalParameters_in_functionHeading525); + fP1=formalParameters(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fP1.getTree()); + dbg.location(140,48); + char_literal25=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_functionHeading527); if (failed) return retval; + if ( backtracking==0 ) { + char_literal25_tree = (Object)adaptor.create(char_literal25); + adaptor.addChild(root_0, char_literal25_tree); + } + dbg.location(141,2); + if ( backtracking==0 ) { + if (i1 == null || fP1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.VoidFuncHead(i1.getText(), fP1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:144:7: 'int' i2= Ident '(' fP2= formalParameters ')' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(144,7); + string_literal26=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_functionHeading538); if (failed) return retval; + if ( backtracking==0 ) { + string_literal26_tree = (Object)adaptor.create(string_literal26); + adaptor.addChild(root_0, string_literal26_tree); + } + dbg.location(144,15); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_functionHeading542); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(144,22); + char_literal27=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_functionHeading544); if (failed) return retval; + if ( backtracking==0 ) { + char_literal27_tree = (Object)adaptor.create(char_literal27); + adaptor.addChild(root_0, char_literal27_tree); + } + dbg.location(144,29); + pushFollow(FOLLOW_formalParameters_in_functionHeading548); + fP2=formalParameters(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fP2.getTree()); + dbg.location(144,47); + char_literal28=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_functionHeading550); if (failed) return retval; + if ( backtracking==0 ) { + char_literal28_tree = (Object)adaptor.create(char_literal28); + adaptor.addChild(root_0, char_literal28_tree); + } + dbg.location(145,2); + if ( backtracking==0 ) { + if (i2 == null || fP2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.IntFuncHead(i2.getText(), fP2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(148, 5); + + } + finally { + dbg.exitRule("functionHeading"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end functionHeading + + public static class formalParameters_return extends ParserRuleReturnScope { + public AST.FormalParameters astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start formalParameters + // C00.g:150:1: formalParameters returns [AST.FormalParameters astTree] : ( ( 'void' )=> 'void' | ( paramSections )=>pS2= paramSections | ); + public formalParameters_return formalParameters() throws RecognitionException { + formalParameters_return retval = new formalParameters_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token string_literal29=null; + paramSections_return pS2 = null; + + + Object string_literal29_tree=null; + + try { dbg.enterRule("formalParameters"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(150, 1); + + try { + // C00.g:151:7: ( ( 'void' )=> 'void' | ( paramSections )=>pS2= paramSections | ) + int alt8=3; + try { dbg.enterDecision(8); + + switch ( input.LA(1) ) { + case 22: + alt8=1; + break; + case 13: + alt8=2; + break; + case 16: + alt8=3; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("150:1: formalParameters returns [AST.FormalParameters astTree] : ( ( 'void' )=> 'void' | ( paramSections )=>pS2= paramSections | );", 8, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(8);} + + switch (alt8) { + case 1 : + dbg.enterAlt(1); + + // C00.g:151:7: ( 'void' )=> 'void' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(151,7); + string_literal29=(Token)input.LT(1); + match(input,22,FOLLOW_22_in_formalParameters578); if (failed) return retval; + if ( backtracking==0 ) { + string_literal29_tree = (Object)adaptor.create(string_literal29); + adaptor.addChild(root_0, string_literal29_tree); + } + dbg.location(152,2); + if ( backtracking==0 ) { + retval.astTree = new AST.VoidFormalParams(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:154:7: ( paramSections )=>pS2= paramSections + { + root_0 = (Object)adaptor.nil(); + + dbg.location(154,10); + pushFollow(FOLLOW_paramSections_in_formalParameters591); + pS2=paramSections(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, pS2.getTree()); + dbg.location(155,2); + if ( backtracking==0 ) { + if (pS2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.NonVoidFormalParams(pS2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:159:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(159,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyFormalParams(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(161, 5); + + } + finally { + dbg.exitRule("formalParameters"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end formalParameters + + public static class paramSections_return extends ParserRuleReturnScope { + public AST.ParamSections astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start paramSections + // C00.g:163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections ); + public paramSections_return paramSections() throws RecognitionException { + paramSections_return retval = new paramSections_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token i2=null; + Token i3=null; + Token i4=null; + Token string_literal30=null; + Token string_literal31=null; + Token char_literal32=null; + Token string_literal33=null; + Token char_literal34=null; + Token string_literal35=null; + Token char_literal36=null; + Token char_literal37=null; + paramSections_return pS3 = null; + + paramSections_return pS4 = null; + + + Object i1_tree=null; + Object i2_tree=null; + Object i3_tree=null; + Object i4_tree=null; + Object string_literal30_tree=null; + Object string_literal31_tree=null; + Object char_literal32_tree=null; + Object string_literal33_tree=null; + Object char_literal34_tree=null; + Object string_literal35_tree=null; + Object char_literal36_tree=null; + Object char_literal37_tree=null; + + try { dbg.enterRule("paramSections"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(163, 1); + + try { + // C00.g:164:7: ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections ) + int alt9=4; + try { dbg.enterDecision(9); + + int LA9_0 = input.LA(1); + if ( (LA9_0==13) ) { + int LA9_1 = input.LA(2); + if ( (LA9_1==21) ) { + int LA9_2 = input.LA(3); + if ( (LA9_2==Ident) ) { + int LA9_4 = input.LA(4); + if ( (LA9_4==20) ) { + alt9=4; + } + else if ( (LA9_4==EOF||LA9_4==16) ) { + alt9=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections );", 9, 4, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections );", 9, 2, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA9_1==Ident) ) { + int LA9_3 = input.LA(3); + if ( (LA9_3==20) ) { + alt9=3; + } + else if ( (LA9_3==EOF||LA9_3==16) ) { + alt9=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections );", 9, 3, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections );", 9, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("163:1: paramSections returns [AST.ParamSections astTree] : ( ( 'int' Ident )=> 'int' i1= Ident | ( 'int' '*' Ident )=> 'int' '*' i2= Ident | ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections | 'int' '*' i4= Ident ',' pS4= paramSections );", 9, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(9);} + + switch (alt9) { + case 1 : + dbg.enterAlt(1); + + // C00.g:164:7: ( 'int' Ident )=> 'int' i1= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(164,7); + string_literal30=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_paramSections628); if (failed) return retval; + if ( backtracking==0 ) { + string_literal30_tree = (Object)adaptor.create(string_literal30); + adaptor.addChild(root_0, string_literal30_tree); + } + dbg.location(164,15); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_paramSections632); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(165,2); + if ( backtracking==0 ) { + if (i1 == null) {retval.astTree = null;} else + {retval.astTree = new AST.ValueLastPrmSects(i1.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:168:7: ( 'int' '*' Ident )=> 'int' '*' i2= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(168,7); + string_literal31=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_paramSections643); if (failed) return retval; + if ( backtracking==0 ) { + string_literal31_tree = (Object)adaptor.create(string_literal31); + adaptor.addChild(root_0, string_literal31_tree); + } + dbg.location(168,13); + char_literal32=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_paramSections645); if (failed) return retval; + if ( backtracking==0 ) { + char_literal32_tree = (Object)adaptor.create(char_literal32); + adaptor.addChild(root_0, char_literal32_tree); + } + dbg.location(168,19); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_paramSections649); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(169,2); + if ( backtracking==0 ) { + if (i2 == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefLastPrmSects(i2.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:172:7: ( 'int' Ident ',' paramSections )=> 'int' i3= Ident ',' pS3= paramSections + { + root_0 = (Object)adaptor.nil(); + + dbg.location(172,7); + string_literal33=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_paramSections660); if (failed) return retval; + if ( backtracking==0 ) { + string_literal33_tree = (Object)adaptor.create(string_literal33); + adaptor.addChild(root_0, string_literal33_tree); + } + dbg.location(172,15); + i3=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_paramSections664); if (failed) return retval; + if ( backtracking==0 ) { + i3_tree = (Object)adaptor.create(i3); + adaptor.addChild(root_0, i3_tree); + } + dbg.location(172,22); + char_literal34=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_paramSections666); if (failed) return retval; + if ( backtracking==0 ) { + char_literal34_tree = (Object)adaptor.create(char_literal34); + adaptor.addChild(root_0, char_literal34_tree); + } + dbg.location(172,29); + pushFollow(FOLLOW_paramSections_in_paramSections670); + pS3=paramSections(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, pS3.getTree()); + dbg.location(173,2); + if ( backtracking==0 ) { + if (i3 == null || pS3.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ValuePairPrmSects(i3.getText(), pS3.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 4 : + dbg.enterAlt(4); + + // C00.g:176:7: 'int' '*' i4= Ident ',' pS4= paramSections + { + root_0 = (Object)adaptor.nil(); + + dbg.location(176,7); + string_literal35=(Token)input.LT(1); + match(input,13,FOLLOW_13_in_paramSections681); if (failed) return retval; + if ( backtracking==0 ) { + string_literal35_tree = (Object)adaptor.create(string_literal35); + adaptor.addChild(root_0, string_literal35_tree); + } + dbg.location(176,13); + char_literal36=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_paramSections683); if (failed) return retval; + if ( backtracking==0 ) { + char_literal36_tree = (Object)adaptor.create(char_literal36); + adaptor.addChild(root_0, char_literal36_tree); + } + dbg.location(176,19); + i4=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_paramSections687); if (failed) return retval; + if ( backtracking==0 ) { + i4_tree = (Object)adaptor.create(i4); + adaptor.addChild(root_0, i4_tree); + } + dbg.location(176,26); + char_literal37=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_paramSections689); if (failed) return retval; + if ( backtracking==0 ) { + char_literal37_tree = (Object)adaptor.create(char_literal37); + adaptor.addChild(root_0, char_literal37_tree); + } + dbg.location(176,33); + pushFollow(FOLLOW_paramSections_in_paramSections693); + pS4=paramSections(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, pS4.getTree()); + dbg.location(177,2); + if ( backtracking==0 ) { + if (i4 == null || pS4.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefPairPrmSects(i4.getText(), pS4.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(180, 5); + + } + finally { + dbg.exitRule("paramSections"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end paramSections + + public static class block_return extends ParserRuleReturnScope { + public AST.Block astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start block + // C00.g:182:1: block returns [AST.Block astTree] : '{' d= declarations sS= statementSequence '}' ; + public block_return block() throws RecognitionException { + block_return retval = new block_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal38=null; + Token char_literal39=null; + declarations_return d = null; + + statementSequence_return sS = null; + + + Object char_literal38_tree=null; + Object char_literal39_tree=null; + + try { dbg.enterRule("block"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(182, 1); + + try { + // C00.g:183:7: ( '{' d= declarations sS= statementSequence '}' ) + dbg.enterAlt(1); + + // C00.g:183:7: '{' d= declarations sS= statementSequence '}' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(183,7); + char_literal38=(Token)input.LT(1); + match(input,23,FOLLOW_23_in_block721); if (failed) return retval; + if ( backtracking==0 ) { + char_literal38_tree = (Object)adaptor.create(char_literal38); + adaptor.addChild(root_0, char_literal38_tree); + } + dbg.location(183,12); + pushFollow(FOLLOW_declarations_in_block725); + d=declarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, d.getTree()); + dbg.location(183,28); + pushFollow(FOLLOW_statementSequence_in_block729); + sS=statementSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sS.getTree()); + dbg.location(183,47); + char_literal39=(Token)input.LT(1); + match(input,24,FOLLOW_24_in_block731); if (failed) return retval; + if ( backtracking==0 ) { + char_literal39_tree = (Object)adaptor.create(char_literal39); + adaptor.addChild(root_0, char_literal39_tree); + } + dbg.location(184,2); + if ( backtracking==0 ) { + if (d.astTree == null || sS.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExpandBlock(d.astTree, sS.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(187, 5); + + } + finally { + dbg.exitRule("block"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end block + + public static class statementSequence_return extends ParserRuleReturnScope { + public AST.StatementSequence astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start statementSequence + // C00.g:189:1: statementSequence returns [AST.StatementSequence astTree] : ( ( statement statementSequence )=>s= statement sS= statementSequence | ); + public statementSequence_return statementSequence() throws RecognitionException { + statementSequence_return retval = new statementSequence_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + statement_return s = null; + + statementSequence_return sS = null; + + + + try { dbg.enterRule("statementSequence"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(189, 1); + + try { + // C00.g:190:8: ( ( statement statementSequence )=>s= statement sS= statementSequence | ) + int alt10=2; + try { dbg.enterDecision(10); + + int LA10_0 = input.LA(1); + if ( (LA10_0==Ident||LA10_0==21||LA10_0==23||(LA10_0>=25 && LA10_0<=34)||LA10_0==37) ) { + alt10=1; + } + else if ( (LA10_0==EOF||LA10_0==24||LA10_0==40||LA10_0==42) ) { + alt10=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("189:1: statementSequence returns [AST.StatementSequence astTree] : ( ( statement statementSequence )=>s= statement sS= statementSequence | );", 10, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(10);} + + switch (alt10) { + case 1 : + dbg.enterAlt(1); + + // C00.g:190:8: ( statement statementSequence )=>s= statement sS= statementSequence + { + root_0 = (Object)adaptor.nil(); + + dbg.location(190,9); + pushFollow(FOLLOW_statement_in_statementSequence762); + s=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s.getTree()); + dbg.location(190,22); + pushFollow(FOLLOW_statementSequence_in_statementSequence766); + sS=statementSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sS.getTree()); + dbg.location(191,2); + if ( backtracking==0 ) { + if (s.astTree == null || sS.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PairStmSeq(s.astTree, sS.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:195:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(195,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyStmSeq(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(197, 5); + + } + finally { + dbg.exitRule("statementSequence"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end statementSequence + + public static class statement_return extends ParserRuleReturnScope { + public AST.Statement astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start statement + // C00.g:200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' ); + public statement_return statement() throws RecognitionException { + statement_return retval = new statement_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token s15=null; + Token i16=null; + Token n14=null; + Token char_literal40=null; + Token string_literal41=null; + Token char_literal42=null; + Token char_literal43=null; + Token string_literal44=null; + Token char_literal45=null; + Token char_literal46=null; + Token string_literal47=null; + Token char_literal48=null; + Token char_literal49=null; + Token string_literal50=null; + Token string_literal51=null; + Token char_literal52=null; + Token char_literal53=null; + Token char_literal54=null; + Token string_literal55=null; + Token char_literal56=null; + Token char_literal57=null; + Token char_literal58=null; + Token char_literal59=null; + Token string_literal60=null; + Token char_literal61=null; + Token string_literal62=null; + Token char_literal63=null; + Token char_literal64=null; + Token char_literal65=null; + Token char_literal66=null; + Token string_literal67=null; + Token char_literal68=null; + Token string_literal69=null; + Token char_literal70=null; + Token string_literal71=null; + Token char_literal72=null; + Token char_literal73=null; + Token char_literal74=null; + Token string_literal75=null; + Token char_literal76=null; + Token char_literal77=null; + Token char_literal78=null; + Token char_literal79=null; + Token string_literal80=null; + Token char_literal81=null; + Token string_literal82=null; + Token char_literal83=null; + Token char_literal84=null; + Token char_literal85=null; + Token char_literal86=null; + Token string_literal87=null; + Token string_literal88=null; + assignment_return a1 = null; + + boolExpression_return bE3 = null; + + statement_return s31 = null; + + elseClause_return eC = null; + + expression_return e4 = null; + + switchBlock_return sB4 = null; + + boolExpression_return bE5 = null; + + statement_return s5 = null; + + statement_return s6 = null; + + boolExpression_return bE6 = null; + + assignment_return a71 = null; + + boolExpression_return bE7 = null; + + assignment_return a72 = null; + + statement_return s7 = null; + + declarations_return d10 = null; + + statementSequence_return sS10 = null; + + functionCall_return fC11 = null; + + expression_return e13 = null; + + expressionList_return e15 = null; + + + Object s15_tree=null; + Object i16_tree=null; + Object n14_tree=null; + Object char_literal40_tree=null; + Object string_literal41_tree=null; + Object char_literal42_tree=null; + Object char_literal43_tree=null; + Object string_literal44_tree=null; + Object char_literal45_tree=null; + Object char_literal46_tree=null; + Object string_literal47_tree=null; + Object char_literal48_tree=null; + Object char_literal49_tree=null; + Object string_literal50_tree=null; + Object string_literal51_tree=null; + Object char_literal52_tree=null; + Object char_literal53_tree=null; + Object char_literal54_tree=null; + Object string_literal55_tree=null; + Object char_literal56_tree=null; + Object char_literal57_tree=null; + Object char_literal58_tree=null; + Object char_literal59_tree=null; + Object string_literal60_tree=null; + Object char_literal61_tree=null; + Object string_literal62_tree=null; + Object char_literal63_tree=null; + Object char_literal64_tree=null; + Object char_literal65_tree=null; + Object char_literal66_tree=null; + Object string_literal67_tree=null; + Object char_literal68_tree=null; + Object string_literal69_tree=null; + Object char_literal70_tree=null; + Object string_literal71_tree=null; + Object char_literal72_tree=null; + Object char_literal73_tree=null; + Object char_literal74_tree=null; + Object string_literal75_tree=null; + Object char_literal76_tree=null; + Object char_literal77_tree=null; + Object char_literal78_tree=null; + Object char_literal79_tree=null; + Object string_literal80_tree=null; + Object char_literal81_tree=null; + Object string_literal82_tree=null; + Object char_literal83_tree=null; + Object char_literal84_tree=null; + Object char_literal85_tree=null; + Object char_literal86_tree=null; + Object string_literal87_tree=null; + Object string_literal88_tree=null; + + try { dbg.enterRule("statement"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(200, 1); + + try { + // C00.g:201:7: ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' ) + int alt11=16; + try { dbg.enterDecision(11); + + switch ( input.LA(1) ) { + case Ident: + int LA11_1 = input.LA(2); + if ( (LA11_1==15) ) { + alt11=10; + } + else if ( (LA11_1==19) ) { + alt11=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 21: + alt11=1; + break; + case 25: + alt11=2; + break; + case 26: + alt11=3; + break; + case 27: + alt11=4; + break; + case 28: + alt11=5; + break; + case 29: + alt11=6; + break; + case 30: + alt11=7; + break; + case 31: + alt11=8; + break; + case 23: + alt11=9; + break; + case 32: + int LA11_11 = input.LA(2); + if ( (LA11_11==17) ) { + alt11=11; + } + else if ( ((LA11_11>=Ident && LA11_11<=Number)||LA11_11==15||LA11_11==21||LA11_11==36||(LA11_11>=43 && LA11_11<=44)) ) { + alt11=12; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 11, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 33: + int LA11_12 = input.LA(2); + if ( (LA11_12==15) ) { + int LA11_18 = input.LA(3); + if ( (LA11_18==String) ) { + int LA11_19 = input.LA(4); + if ( (LA11_19==16) ) { + alt11=13; + } + else if ( (LA11_19==20) ) { + alt11=14; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 19, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 18, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 12, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 34: + alt11=15; + break; + case 37: + alt11=16; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("200:1: statement returns [AST.Statement astTree] : ( ( assignment ';' )=>a1= assignment ';' | ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause | ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock | ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement | ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' | ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement | ( 'continue' ';' )=> 'continue' ';' | ( 'break' ';' )=> 'break' ';' | ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' | ( functionCall ';' )=>fC11= functionCall ';' | ( 'return' ';' )=> 'return' ';' | ( 'return' expression ';' )=> 'return' e13= expression ';' | ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' | ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' | ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' | '/*label' n14= Number '*/' );", 11, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(11);} + + switch (alt11) { + case 1 : + dbg.enterAlt(1); + + // C00.g:201:7: ( assignment ';' )=>a1= assignment ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(201,9); + pushFollow(FOLLOW_assignment_in_statement806); + a1=assignment(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, a1.getTree()); + dbg.location(201,21); + char_literal40=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement808); if (failed) return retval; + if ( backtracking==0 ) { + char_literal40_tree = (Object)adaptor.create(char_literal40); + adaptor.addChild(root_0, char_literal40_tree); + } + dbg.location(202,2); + if ( backtracking==0 ) { + if (a1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.AssignStm(a1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:205:7: ( 'if' '(' boolExpression ')' statement elseClause )=> 'if' '(' bE3= boolExpression ')' s31= statement eC= elseClause + { + root_0 = (Object)adaptor.nil(); + + dbg.location(205,7); + string_literal41=(Token)input.LT(1); + match(input,25,FOLLOW_25_in_statement819); if (failed) return retval; + if ( backtracking==0 ) { + string_literal41_tree = (Object)adaptor.create(string_literal41); + adaptor.addChild(root_0, string_literal41_tree); + } + dbg.location(205,12); + char_literal42=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement821); if (failed) return retval; + if ( backtracking==0 ) { + char_literal42_tree = (Object)adaptor.create(char_literal42); + adaptor.addChild(root_0, char_literal42_tree); + } + dbg.location(205,19); + pushFollow(FOLLOW_boolExpression_in_statement825); + bE3=boolExpression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, bE3.getTree()); + dbg.location(205,35); + char_literal43=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement827); if (failed) return retval; + if ( backtracking==0 ) { + char_literal43_tree = (Object)adaptor.create(char_literal43); + adaptor.addChild(root_0, char_literal43_tree); + } + dbg.location(205,42); + pushFollow(FOLLOW_statement_in_statement831); + s31=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s31.getTree()); + dbg.location(205,55); + pushFollow(FOLLOW_elseClause_in_statement835); + eC=elseClause(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, eC.getTree()); + dbg.location(206,2); + if ( backtracking==0 ) { + if (bE3.astTree == null || s31.astTree == null) {retval.astTree = null;} else + {if (eC.astTree == null) + retval.astTree = new AST.PureIfStm(bE3.astTree, s31.astTree); + else + retval.astTree = new AST.ElseIfStm(bE3.astTree, s31.astTree, eC.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:212:7: ( 'switch' '(' expression ')' switchBlock )=> 'switch' '(' e4= expression ')' sB4= switchBlock + { + root_0 = (Object)adaptor.nil(); + + dbg.location(212,7); + string_literal44=(Token)input.LT(1); + match(input,26,FOLLOW_26_in_statement846); if (failed) return retval; + if ( backtracking==0 ) { + string_literal44_tree = (Object)adaptor.create(string_literal44); + adaptor.addChild(root_0, string_literal44_tree); + } + dbg.location(212,16); + char_literal45=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement848); if (failed) return retval; + if ( backtracking==0 ) { + char_literal45_tree = (Object)adaptor.create(char_literal45); + adaptor.addChild(root_0, char_literal45_tree); + } + dbg.location(212,22); + pushFollow(FOLLOW_expression_in_statement852); + e4=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e4.getTree()); + dbg.location(212,34); + char_literal46=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement854); if (failed) return retval; + if ( backtracking==0 ) { + char_literal46_tree = (Object)adaptor.create(char_literal46); + adaptor.addChild(root_0, char_literal46_tree); + } + dbg.location(212,41); + pushFollow(FOLLOW_switchBlock_in_statement858); + sB4=switchBlock(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sB4.getTree()); + dbg.location(213,2); + if ( backtracking==0 ) { + if (e4.astTree == null || sB4.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.SwitchStm(e4.astTree, sB4.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 4 : + dbg.enterAlt(4); + + // C00.g:216:7: ( 'while' '(' boolExpression ')' statement )=> 'while' '(' bE5= boolExpression ')' s5= statement + { + root_0 = (Object)adaptor.nil(); + + dbg.location(216,7); + string_literal47=(Token)input.LT(1); + match(input,27,FOLLOW_27_in_statement869); if (failed) return retval; + if ( backtracking==0 ) { + string_literal47_tree = (Object)adaptor.create(string_literal47); + adaptor.addChild(root_0, string_literal47_tree); + } + dbg.location(216,15); + char_literal48=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement871); if (failed) return retval; + if ( backtracking==0 ) { + char_literal48_tree = (Object)adaptor.create(char_literal48); + adaptor.addChild(root_0, char_literal48_tree); + } + dbg.location(216,22); + pushFollow(FOLLOW_boolExpression_in_statement875); + bE5=boolExpression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, bE5.getTree()); + dbg.location(216,38); + char_literal49=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement877); if (failed) return retval; + if ( backtracking==0 ) { + char_literal49_tree = (Object)adaptor.create(char_literal49); + adaptor.addChild(root_0, char_literal49_tree); + } + dbg.location(216,44); + pushFollow(FOLLOW_statement_in_statement881); + s5=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s5.getTree()); + dbg.location(217,2); + if ( backtracking==0 ) { + if (bE5.astTree == null || s5.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.WhileStm(bE5.astTree, s5.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 5 : + dbg.enterAlt(5); + + // C00.g:220:7: ( 'do' statement 'while' '(' boolExpression ')' ';' )=> 'do' s6= statement 'while' '(' bE6= boolExpression ')' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(220,7); + string_literal50=(Token)input.LT(1); + match(input,28,FOLLOW_28_in_statement892); if (failed) return retval; + if ( backtracking==0 ) { + string_literal50_tree = (Object)adaptor.create(string_literal50); + adaptor.addChild(root_0, string_literal50_tree); + } + dbg.location(220,14); + pushFollow(FOLLOW_statement_in_statement896); + s6=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s6.getTree()); + dbg.location(220,25); + string_literal51=(Token)input.LT(1); + match(input,27,FOLLOW_27_in_statement898); if (failed) return retval; + if ( backtracking==0 ) { + string_literal51_tree = (Object)adaptor.create(string_literal51); + adaptor.addChild(root_0, string_literal51_tree); + } + dbg.location(220,33); + char_literal52=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement900); if (failed) return retval; + if ( backtracking==0 ) { + char_literal52_tree = (Object)adaptor.create(char_literal52); + adaptor.addChild(root_0, char_literal52_tree); + } + dbg.location(220,40); + pushFollow(FOLLOW_boolExpression_in_statement904); + bE6=boolExpression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, bE6.getTree()); + dbg.location(220,56); + char_literal53=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement906); if (failed) return retval; + if ( backtracking==0 ) { + char_literal53_tree = (Object)adaptor.create(char_literal53); + adaptor.addChild(root_0, char_literal53_tree); + } + dbg.location(220,60); + char_literal54=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement908); if (failed) return retval; + if ( backtracking==0 ) { + char_literal54_tree = (Object)adaptor.create(char_literal54); + adaptor.addChild(root_0, char_literal54_tree); + } + dbg.location(221,2); + if ( backtracking==0 ) { + if (s6.astTree == null || bE6.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.DoWhileStm(s6.astTree, bE6.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 6 : + dbg.enterAlt(6); + + // C00.g:224:7: ( 'for' '(' assignment ';' boolExpression ';' assignment ')' statement )=> 'for' '(' a71= assignment ';' bE7= boolExpression ';' a72= assignment ')' s7= statement + { + root_0 = (Object)adaptor.nil(); + + dbg.location(224,7); + string_literal55=(Token)input.LT(1); + match(input,29,FOLLOW_29_in_statement919); if (failed) return retval; + if ( backtracking==0 ) { + string_literal55_tree = (Object)adaptor.create(string_literal55); + adaptor.addChild(root_0, string_literal55_tree); + } + dbg.location(224,13); + char_literal56=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement921); if (failed) return retval; + if ( backtracking==0 ) { + char_literal56_tree = (Object)adaptor.create(char_literal56); + adaptor.addChild(root_0, char_literal56_tree); + } + dbg.location(224,20); + pushFollow(FOLLOW_assignment_in_statement925); + a71=assignment(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, a71.getTree()); + dbg.location(224,32); + char_literal57=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement927); if (failed) return retval; + if ( backtracking==0 ) { + char_literal57_tree = (Object)adaptor.create(char_literal57); + adaptor.addChild(root_0, char_literal57_tree); + } + dbg.location(224,39); + pushFollow(FOLLOW_boolExpression_in_statement931); + bE7=boolExpression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, bE7.getTree()); + dbg.location(224,55); + char_literal58=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement933); if (failed) return retval; + if ( backtracking==0 ) { + char_literal58_tree = (Object)adaptor.create(char_literal58); + adaptor.addChild(root_0, char_literal58_tree); + } + dbg.location(224,62); + pushFollow(FOLLOW_assignment_in_statement937); + a72=assignment(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, a72.getTree()); + dbg.location(224,74); + char_literal59=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement939); if (failed) return retval; + if ( backtracking==0 ) { + char_literal59_tree = (Object)adaptor.create(char_literal59); + adaptor.addChild(root_0, char_literal59_tree); + } + dbg.location(224,80); + pushFollow(FOLLOW_statement_in_statement943); + s7=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s7.getTree()); + dbg.location(225,2); + if ( backtracking==0 ) { + if (a71.astTree == null || bE7.astTree == null || a72.astTree == null || s7.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ForStm(a71.astTree, bE7.astTree, a72.astTree, s7.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 7 : + dbg.enterAlt(7); + + // C00.g:228:7: ( 'continue' ';' )=> 'continue' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(228,7); + string_literal60=(Token)input.LT(1); + match(input,30,FOLLOW_30_in_statement954); if (failed) return retval; + if ( backtracking==0 ) { + string_literal60_tree = (Object)adaptor.create(string_literal60); + adaptor.addChild(root_0, string_literal60_tree); + } + dbg.location(228,18); + char_literal61=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement956); if (failed) return retval; + if ( backtracking==0 ) { + char_literal61_tree = (Object)adaptor.create(char_literal61); + adaptor.addChild(root_0, char_literal61_tree); + } + dbg.location(229,2); + if ( backtracking==0 ) { + retval.astTree = new AST.ContinueStm(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + case 8 : + dbg.enterAlt(8); + + // C00.g:231:7: ( 'break' ';' )=> 'break' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(231,7); + string_literal62=(Token)input.LT(1); + match(input,31,FOLLOW_31_in_statement968); if (failed) return retval; + if ( backtracking==0 ) { + string_literal62_tree = (Object)adaptor.create(string_literal62); + adaptor.addChild(root_0, string_literal62_tree); + } + dbg.location(231,15); + char_literal63=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement970); if (failed) return retval; + if ( backtracking==0 ) { + char_literal63_tree = (Object)adaptor.create(char_literal63); + adaptor.addChild(root_0, char_literal63_tree); + } + dbg.location(232,2); + if ( backtracking==0 ) { + retval.astTree = new AST.BreakStm(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + case 9 : + dbg.enterAlt(9); + + // C00.g:234:7: ( '{' declarations statementSequence '}' )=> '{' d10= declarations sS10= statementSequence '}' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(234,7); + char_literal64=(Token)input.LT(1); + match(input,23,FOLLOW_23_in_statement982); if (failed) return retval; + if ( backtracking==0 ) { + char_literal64_tree = (Object)adaptor.create(char_literal64); + adaptor.addChild(root_0, char_literal64_tree); + } + dbg.location(234,14); + pushFollow(FOLLOW_declarations_in_statement986); + d10=declarations(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, d10.getTree()); + dbg.location(234,32); + pushFollow(FOLLOW_statementSequence_in_statement990); + sS10=statementSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sS10.getTree()); + dbg.location(234,51); + char_literal65=(Token)input.LT(1); + match(input,24,FOLLOW_24_in_statement992); if (failed) return retval; + if ( backtracking==0 ) { + char_literal65_tree = (Object)adaptor.create(char_literal65); + adaptor.addChild(root_0, char_literal65_tree); + } + dbg.location(235,2); + if ( backtracking==0 ) { + if (d10.astTree == null || sS10.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.CompStm(d10.astTree, sS10.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 10 : + dbg.enterAlt(10); + + // C00.g:238:7: ( functionCall ';' )=>fC11= functionCall ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(238,11); + pushFollow(FOLLOW_functionCall_in_statement1005); + fC11=functionCall(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fC11.getTree()); + dbg.location(238,25); + char_literal66=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1007); if (failed) return retval; + if ( backtracking==0 ) { + char_literal66_tree = (Object)adaptor.create(char_literal66); + adaptor.addChild(root_0, char_literal66_tree); + } + dbg.location(239,2); + if ( backtracking==0 ) { + if (fC11.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.FuncCallStm(fC11.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 11 : + dbg.enterAlt(11); + + // C00.g:242:7: ( 'return' ';' )=> 'return' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(242,7); + string_literal67=(Token)input.LT(1); + match(input,32,FOLLOW_32_in_statement1018); if (failed) return retval; + if ( backtracking==0 ) { + string_literal67_tree = (Object)adaptor.create(string_literal67); + adaptor.addChild(root_0, string_literal67_tree); + } + dbg.location(242,16); + char_literal68=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1020); if (failed) return retval; + if ( backtracking==0 ) { + char_literal68_tree = (Object)adaptor.create(char_literal68); + adaptor.addChild(root_0, char_literal68_tree); + } + dbg.location(243,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyReturnStm(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + case 12 : + dbg.enterAlt(12); + + // C00.g:245:7: ( 'return' expression ';' )=> 'return' e13= expression ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(245,7); + string_literal69=(Token)input.LT(1); + match(input,32,FOLLOW_32_in_statement1031); if (failed) return retval; + if ( backtracking==0 ) { + string_literal69_tree = (Object)adaptor.create(string_literal69); + adaptor.addChild(root_0, string_literal69_tree); + } + dbg.location(245,19); + pushFollow(FOLLOW_expression_in_statement1035); + e13=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e13.getTree()); + dbg.location(245,31); + char_literal70=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1037); if (failed) return retval; + if ( backtracking==0 ) { + char_literal70_tree = (Object)adaptor.create(char_literal70); + adaptor.addChild(root_0, char_literal70_tree); + } + dbg.location(246,2); + if ( backtracking==0 ) { + if (e13.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExprReturnStm(e13.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 13 : + dbg.enterAlt(13); + + // C00.g:249:7: ( 'printf' '(' String ')' ';' )=> 'printf' '(' s15= String ')' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(249,7); + string_literal71=(Token)input.LT(1); + match(input,33,FOLLOW_33_in_statement1049); if (failed) return retval; + if ( backtracking==0 ) { + string_literal71_tree = (Object)adaptor.create(string_literal71); + adaptor.addChild(root_0, string_literal71_tree); + } + dbg.location(249,16); + char_literal72=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement1051); if (failed) return retval; + if ( backtracking==0 ) { + char_literal72_tree = (Object)adaptor.create(char_literal72); + adaptor.addChild(root_0, char_literal72_tree); + } + dbg.location(249,23); + s15=(Token)input.LT(1); + match(input,String,FOLLOW_String_in_statement1055); if (failed) return retval; + if ( backtracking==0 ) { + s15_tree = (Object)adaptor.create(s15); + adaptor.addChild(root_0, s15_tree); + } + dbg.location(249,31); + char_literal73=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement1057); if (failed) return retval; + if ( backtracking==0 ) { + char_literal73_tree = (Object)adaptor.create(char_literal73); + adaptor.addChild(root_0, char_literal73_tree); + } + dbg.location(249,35); + char_literal74=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1059); if (failed) return retval; + if ( backtracking==0 ) { + char_literal74_tree = (Object)adaptor.create(char_literal74); + adaptor.addChild(root_0, char_literal74_tree); + } + dbg.location(250,2); + if ( backtracking==0 ) { + if (s15 == null) {retval.astTree = null;} else + {retval.astTree = new AST.PurePrintfStm(s15.getText().substring(1,s15.getText().length()-1)); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 14 : + dbg.enterAlt(14); + + // C00.g:253:4: ( 'printf' '(' String ',' expressionList ')' ';' )=> 'printf' '(' s15= String ',' e15= expressionList ')' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(253,4); + string_literal75=(Token)input.LT(1); + match(input,33,FOLLOW_33_in_statement1067); if (failed) return retval; + if ( backtracking==0 ) { + string_literal75_tree = (Object)adaptor.create(string_literal75); + adaptor.addChild(root_0, string_literal75_tree); + } + dbg.location(253,13); + char_literal76=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement1069); if (failed) return retval; + if ( backtracking==0 ) { + char_literal76_tree = (Object)adaptor.create(char_literal76); + adaptor.addChild(root_0, char_literal76_tree); + } + dbg.location(253,20); + s15=(Token)input.LT(1); + match(input,String,FOLLOW_String_in_statement1073); if (failed) return retval; + if ( backtracking==0 ) { + s15_tree = (Object)adaptor.create(s15); + adaptor.addChild(root_0, s15_tree); + } + dbg.location(253,28); + char_literal77=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_statement1075); if (failed) return retval; + if ( backtracking==0 ) { + char_literal77_tree = (Object)adaptor.create(char_literal77); + adaptor.addChild(root_0, char_literal77_tree); + } + dbg.location(253,35); + pushFollow(FOLLOW_expressionList_in_statement1079); + e15=expressionList(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e15.getTree()); + dbg.location(253,51); + char_literal78=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement1081); if (failed) return retval; + if ( backtracking==0 ) { + char_literal78_tree = (Object)adaptor.create(char_literal78); + adaptor.addChild(root_0, char_literal78_tree); + } + dbg.location(253,55); + char_literal79=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1083); if (failed) return retval; + if ( backtracking==0 ) { + char_literal79_tree = (Object)adaptor.create(char_literal79); + adaptor.addChild(root_0, char_literal79_tree); + } + dbg.location(254,2); + if ( backtracking==0 ) { + if (s15 == null || e15 == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExprPrintfStm(s15.getText().substring(1,s15.getText().length()-1), e15.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 15 : + dbg.enterAlt(15); + + // C00.g:257:7: ( 'scanf' '(' '\"%i\"' ',' '&' Ident ')' ';' )=> 'scanf' '(' '\"%i\"' ',' '&' i16= Ident ')' ';' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(257,7); + string_literal80=(Token)input.LT(1); + match(input,34,FOLLOW_34_in_statement1094); if (failed) return retval; + if ( backtracking==0 ) { + string_literal80_tree = (Object)adaptor.create(string_literal80); + adaptor.addChild(root_0, string_literal80_tree); + } + dbg.location(257,15); + char_literal81=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_statement1096); if (failed) return retval; + if ( backtracking==0 ) { + char_literal81_tree = (Object)adaptor.create(char_literal81); + adaptor.addChild(root_0, char_literal81_tree); + } + dbg.location(257,19); + string_literal82=(Token)input.LT(1); + match(input,35,FOLLOW_35_in_statement1098); if (failed) return retval; + if ( backtracking==0 ) { + string_literal82_tree = (Object)adaptor.create(string_literal82); + adaptor.addChild(root_0, string_literal82_tree); + } + dbg.location(257,26); + char_literal83=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_statement1100); if (failed) return retval; + if ( backtracking==0 ) { + char_literal83_tree = (Object)adaptor.create(char_literal83); + adaptor.addChild(root_0, char_literal83_tree); + } + dbg.location(257,30); + char_literal84=(Token)input.LT(1); + match(input,36,FOLLOW_36_in_statement1102); if (failed) return retval; + if ( backtracking==0 ) { + char_literal84_tree = (Object)adaptor.create(char_literal84); + adaptor.addChild(root_0, char_literal84_tree); + } + dbg.location(257,37); + i16=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_statement1106); if (failed) return retval; + if ( backtracking==0 ) { + i16_tree = (Object)adaptor.create(i16); + adaptor.addChild(root_0, i16_tree); + } + dbg.location(257,44); + char_literal85=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_statement1108); if (failed) return retval; + if ( backtracking==0 ) { + char_literal85_tree = (Object)adaptor.create(char_literal85); + adaptor.addChild(root_0, char_literal85_tree); + } + dbg.location(257,48); + char_literal86=(Token)input.LT(1); + match(input,17,FOLLOW_17_in_statement1110); if (failed) return retval; + if ( backtracking==0 ) { + char_literal86_tree = (Object)adaptor.create(char_literal86); + adaptor.addChild(root_0, char_literal86_tree); + } + dbg.location(258,2); + if ( backtracking==0 ) { + if (i16 == null) {retval.astTree = null;} else + {retval.astTree = new AST.ScanfStm(i16.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 16 : + dbg.enterAlt(16); + + // C00.g:261:7: '/*label' n14= Number '*/' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(261,7); + string_literal87=(Token)input.LT(1); + match(input,37,FOLLOW_37_in_statement1121); if (failed) return retval; + if ( backtracking==0 ) { + string_literal87_tree = (Object)adaptor.create(string_literal87); + adaptor.addChild(root_0, string_literal87_tree); + } + dbg.location(261,20); + n14=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_statement1125); if (failed) return retval; + if ( backtracking==0 ) { + n14_tree = (Object)adaptor.create(n14); + adaptor.addChild(root_0, n14_tree); + } + dbg.location(261,28); + string_literal88=(Token)input.LT(1); + match(input,38,FOLLOW_38_in_statement1127); if (failed) return retval; + if ( backtracking==0 ) { + string_literal88_tree = (Object)adaptor.create(string_literal88); + adaptor.addChild(root_0, string_literal88_tree); + } + dbg.location(262,2); + if ( backtracking==0 ) { + if (n14 == null) {retval.astTree = null;} else + {retval.astTree = new AST.LabelStm(Integer.parseInt(n14.getText())); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(265, 5); + + } + finally { + dbg.exitRule("statement"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end statement + + public static class elseClause_return extends ParserRuleReturnScope { + public AST.Statement astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start elseClause + // C00.g:267:1: elseClause returns [AST.Statement astTree] : ( ( 'else' statement )=> 'else' s= statement | ); + public elseClause_return elseClause() throws RecognitionException { + elseClause_return retval = new elseClause_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token string_literal89=null; + statement_return s = null; + + + Object string_literal89_tree=null; + + try { dbg.enterRule("elseClause"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(267, 1); + + try { + // C00.g:268:7: ( ( 'else' statement )=> 'else' s= statement | ) + int alt12=2; + try { dbg.enterDecision(12); + + int LA12_0 = input.LA(1); + if ( (LA12_0==39) ) { + if ( (synpred34()) ) { + alt12=1; + } + else if ( (true) ) { + alt12=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("267:1: elseClause returns [AST.Statement astTree] : ( ( 'else' statement )=> 'else' s= statement | );", 12, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else if ( (LA12_0==EOF||LA12_0==Ident||LA12_0==21||(LA12_0>=23 && LA12_0<=34)||LA12_0==37||LA12_0==40||LA12_0==42) ) { + alt12=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("267:1: elseClause returns [AST.Statement astTree] : ( ( 'else' statement )=> 'else' s= statement | );", 12, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(12);} + + switch (alt12) { + case 1 : + dbg.enterAlt(1); + + // C00.g:268:7: ( 'else' statement )=> 'else' s= statement + { + root_0 = (Object)adaptor.nil(); + + dbg.location(268,7); + string_literal89=(Token)input.LT(1); + match(input,39,FOLLOW_39_in_elseClause1151); if (failed) return retval; + if ( backtracking==0 ) { + string_literal89_tree = (Object)adaptor.create(string_literal89); + adaptor.addChild(root_0, string_literal89_tree); + } + dbg.location(268,15); + pushFollow(FOLLOW_statement_in_elseClause1155); + s=statement(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, s.getTree()); + dbg.location(269,2); + if ( backtracking==0 ) { + retval.astTree = s.astTree; + + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:272:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(272,2); + if ( backtracking==0 ) { + retval.astTree = null; + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(273, 5); + + } + finally { + dbg.exitRule("elseClause"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end elseClause + + public static class assignment_return extends ParserRuleReturnScope { + public AST.Assignment astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start assignment + // C00.g:276:1: assignment returns [AST.Assignment astTree] : ( ( Ident '=' expression )=>i1= Ident '=' e1= expression | '*' i2= Ident '=' e2= expression ); + public assignment_return assignment() throws RecognitionException { + assignment_return retval = new assignment_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token i2=null; + Token char_literal90=null; + Token char_literal91=null; + Token char_literal92=null; + expression_return e1 = null; + + expression_return e2 = null; + + + Object i1_tree=null; + Object i2_tree=null; + Object char_literal90_tree=null; + Object char_literal91_tree=null; + Object char_literal92_tree=null; + + try { dbg.enterRule("assignment"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(276, 1); + + try { + // C00.g:277:7: ( ( Ident '=' expression )=>i1= Ident '=' e1= expression | '*' i2= Ident '=' e2= expression ) + int alt13=2; + try { dbg.enterDecision(13); + + int LA13_0 = input.LA(1); + if ( (LA13_0==Ident) ) { + alt13=1; + } + else if ( (LA13_0==21) ) { + alt13=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("276:1: assignment returns [AST.Assignment astTree] : ( ( Ident '=' expression )=>i1= Ident '=' e1= expression | '*' i2= Ident '=' e2= expression );", 13, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(13);} + + switch (alt13) { + case 1 : + dbg.enterAlt(1); + + // C00.g:277:7: ( Ident '=' expression )=>i1= Ident '=' e1= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(277,9); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_assignment1195); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(277,16); + char_literal90=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_assignment1197); if (failed) return retval; + if ( backtracking==0 ) { + char_literal90_tree = (Object)adaptor.create(char_literal90); + adaptor.addChild(root_0, char_literal90_tree); + } + dbg.location(277,22); + pushFollow(FOLLOW_expression_in_assignment1201); + e1=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e1.getTree()); + dbg.location(278,2); + if ( backtracking==0 ) { + if (i1 == null || e1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ValueAssign(i1.getText(), e1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:281:7: '*' i2= Ident '=' e2= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(281,7); + char_literal91=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_assignment1212); if (failed) return retval; + if ( backtracking==0 ) { + char_literal91_tree = (Object)adaptor.create(char_literal91); + adaptor.addChild(root_0, char_literal91_tree); + } + dbg.location(281,13); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_assignment1216); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(281,20); + char_literal92=(Token)input.LT(1); + match(input,19,FOLLOW_19_in_assignment1218); if (failed) return retval; + if ( backtracking==0 ) { + char_literal92_tree = (Object)adaptor.create(char_literal92); + adaptor.addChild(root_0, char_literal92_tree); + } + dbg.location(281,26); + pushFollow(FOLLOW_expression_in_assignment1222); + e2=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e2.getTree()); + dbg.location(282,2); + if ( backtracking==0 ) { + if (i2 == null || e2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefAssign(i2.getText(), e2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(285, 5); + + } + finally { + dbg.exitRule("assignment"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end assignment + + public static class switchBlock_return extends ParserRuleReturnScope { + public AST.SwitchBlock astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start switchBlock + // C00.g:287:1: switchBlock returns [AST.SwitchBlock astTree] : ( ( '{' caseSequence '}' )=> '{' cS1= caseSequence '}' | '{' cS2= caseSequence 'default' ':' sS2= statementSequence '}' ); + public switchBlock_return switchBlock() throws RecognitionException { + switchBlock_return retval = new switchBlock_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal93=null; + Token char_literal94=null; + Token char_literal95=null; + Token string_literal96=null; + Token char_literal97=null; + Token char_literal98=null; + caseSequence_return cS1 = null; + + caseSequence_return cS2 = null; + + statementSequence_return sS2 = null; + + + Object char_literal93_tree=null; + Object char_literal94_tree=null; + Object char_literal95_tree=null; + Object string_literal96_tree=null; + Object char_literal97_tree=null; + Object char_literal98_tree=null; + + try { dbg.enterRule("switchBlock"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(287, 1); + + try { + // C00.g:288:7: ( ( '{' caseSequence '}' )=> '{' cS1= caseSequence '}' | '{' cS2= caseSequence 'default' ':' sS2= statementSequence '}' ) + int alt14=2; + try { dbg.enterDecision(14); + + int LA14_0 = input.LA(1); + if ( (LA14_0==23) ) { + if ( (synpred36()) ) { + alt14=1; + } + else if ( (true) ) { + alt14=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("287:1: switchBlock returns [AST.SwitchBlock astTree] : ( ( '{' caseSequence '}' )=> '{' cS1= caseSequence '}' | '{' cS2= caseSequence 'default' ':' sS2= statementSequence '}' );", 14, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("287:1: switchBlock returns [AST.SwitchBlock astTree] : ( ( '{' caseSequence '}' )=> '{' cS1= caseSequence '}' | '{' cS2= caseSequence 'default' ':' sS2= statementSequence '}' );", 14, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(14);} + + switch (alt14) { + case 1 : + dbg.enterAlt(1); + + // C00.g:288:7: ( '{' caseSequence '}' )=> '{' cS1= caseSequence '}' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(288,7); + char_literal93=(Token)input.LT(1); + match(input,23,FOLLOW_23_in_switchBlock1250); if (failed) return retval; + if ( backtracking==0 ) { + char_literal93_tree = (Object)adaptor.create(char_literal93); + adaptor.addChild(root_0, char_literal93_tree); + } + dbg.location(288,14); + pushFollow(FOLLOW_caseSequence_in_switchBlock1254); + cS1=caseSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, cS1.getTree()); + dbg.location(288,28); + char_literal94=(Token)input.LT(1); + match(input,24,FOLLOW_24_in_switchBlock1256); if (failed) return retval; + if ( backtracking==0 ) { + char_literal94_tree = (Object)adaptor.create(char_literal94); + adaptor.addChild(root_0, char_literal94_tree); + } + dbg.location(289,2); + if ( backtracking==0 ) { + if (cS1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.NoDefaultSwitchBlock(cS1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:292:7: '{' cS2= caseSequence 'default' ':' sS2= statementSequence '}' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(292,7); + char_literal95=(Token)input.LT(1); + match(input,23,FOLLOW_23_in_switchBlock1267); if (failed) return retval; + if ( backtracking==0 ) { + char_literal95_tree = (Object)adaptor.create(char_literal95); + adaptor.addChild(root_0, char_literal95_tree); + } + dbg.location(292,14); + pushFollow(FOLLOW_caseSequence_in_switchBlock1271); + cS2=caseSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, cS2.getTree()); + dbg.location(292,28); + string_literal96=(Token)input.LT(1); + match(input,40,FOLLOW_40_in_switchBlock1273); if (failed) return retval; + if ( backtracking==0 ) { + string_literal96_tree = (Object)adaptor.create(string_literal96); + adaptor.addChild(root_0, string_literal96_tree); + } + dbg.location(292,38); + char_literal97=(Token)input.LT(1); + match(input,41,FOLLOW_41_in_switchBlock1275); if (failed) return retval; + if ( backtracking==0 ) { + char_literal97_tree = (Object)adaptor.create(char_literal97); + adaptor.addChild(root_0, char_literal97_tree); + } + dbg.location(292,45); + pushFollow(FOLLOW_statementSequence_in_switchBlock1279); + sS2=statementSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sS2.getTree()); + dbg.location(292,64); + char_literal98=(Token)input.LT(1); + match(input,24,FOLLOW_24_in_switchBlock1281); if (failed) return retval; + if ( backtracking==0 ) { + char_literal98_tree = (Object)adaptor.create(char_literal98); + adaptor.addChild(root_0, char_literal98_tree); + } + dbg.location(293,2); + if ( backtracking==0 ) { + if (cS2.astTree == null || sS2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.DefaultSwitchBlock(cS2.astTree, sS2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(296, 5); + + } + finally { + dbg.exitRule("switchBlock"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end switchBlock + + public static class caseSequence_return extends ParserRuleReturnScope { + public AST.CaseSequence astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start caseSequence + // C00.g:298:1: caseSequence returns [AST.CaseSequence astTree] : ( ( 'case' Number ':' statementSequence caseSequence )=> 'case' n1= Number ':' sS1= statementSequence cS1= caseSequence | ); + public caseSequence_return caseSequence() throws RecognitionException { + caseSequence_return retval = new caseSequence_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token n1=null; + Token string_literal99=null; + Token char_literal100=null; + statementSequence_return sS1 = null; + + caseSequence_return cS1 = null; + + + Object n1_tree=null; + Object string_literal99_tree=null; + Object char_literal100_tree=null; + + try { dbg.enterRule("caseSequence"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(298, 1); + + try { + // C00.g:299:7: ( ( 'case' Number ':' statementSequence caseSequence )=> 'case' n1= Number ':' sS1= statementSequence cS1= caseSequence | ) + int alt15=2; + try { dbg.enterDecision(15); + + int LA15_0 = input.LA(1); + if ( (LA15_0==42) ) { + alt15=1; + } + else if ( (LA15_0==EOF||LA15_0==24||LA15_0==40) ) { + alt15=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("298:1: caseSequence returns [AST.CaseSequence astTree] : ( ( 'case' Number ':' statementSequence caseSequence )=> 'case' n1= Number ':' sS1= statementSequence cS1= caseSequence | );", 15, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(15);} + + switch (alt15) { + case 1 : + dbg.enterAlt(1); + + // C00.g:299:7: ( 'case' Number ':' statementSequence caseSequence )=> 'case' n1= Number ':' sS1= statementSequence cS1= caseSequence + { + root_0 = (Object)adaptor.nil(); + + dbg.location(299,7); + string_literal99=(Token)input.LT(1); + match(input,42,FOLLOW_42_in_caseSequence1309); if (failed) return retval; + if ( backtracking==0 ) { + string_literal99_tree = (Object)adaptor.create(string_literal99); + adaptor.addChild(root_0, string_literal99_tree); + } + dbg.location(299,16); + n1=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_caseSequence1313); if (failed) return retval; + if ( backtracking==0 ) { + n1_tree = (Object)adaptor.create(n1); + adaptor.addChild(root_0, n1_tree); + } + dbg.location(299,24); + char_literal100=(Token)input.LT(1); + match(input,41,FOLLOW_41_in_caseSequence1315); if (failed) return retval; + if ( backtracking==0 ) { + char_literal100_tree = (Object)adaptor.create(char_literal100); + adaptor.addChild(root_0, char_literal100_tree); + } + dbg.location(299,31); + pushFollow(FOLLOW_statementSequence_in_caseSequence1319); + sS1=statementSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, sS1.getTree()); + dbg.location(299,53); + pushFollow(FOLLOW_caseSequence_in_caseSequence1323); + cS1=caseSequence(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, cS1.getTree()); + dbg.location(300,2); + if ( backtracking==0 ) { + if (n1 == null || sS1.astTree == null || cS1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.NoBreakPairCaseSeq(Integer.parseInt(n1.getText()), sS1.astTree, cS1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:304:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(304,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyCaseSeq(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(306, 5); + + } + finally { + dbg.exitRule("caseSequence"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end caseSequence + + public static class functionCall_return extends ParserRuleReturnScope { + public AST.FunctionCall astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start functionCall + // C00.g:308:1: functionCall returns [AST.FunctionCall astTree] : i= Ident '(' aP= actualParameters ')' ; + public functionCall_return functionCall() throws RecognitionException { + functionCall_return retval = new functionCall_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i=null; + Token char_literal101=null; + Token char_literal102=null; + actualParameters_return aP = null; + + + Object i_tree=null; + Object char_literal101_tree=null; + Object char_literal102_tree=null; + + try { dbg.enterRule("functionCall"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(308, 1); + + try { + // C00.g:309:7: (i= Ident '(' aP= actualParameters ')' ) + dbg.enterAlt(1); + + // C00.g:309:7: i= Ident '(' aP= actualParameters ')' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(309,8); + i=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_functionCall1362); if (failed) return retval; + if ( backtracking==0 ) { + i_tree = (Object)adaptor.create(i); + adaptor.addChild(root_0, i_tree); + } + dbg.location(309,15); + char_literal101=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_functionCall1364); if (failed) return retval; + if ( backtracking==0 ) { + char_literal101_tree = (Object)adaptor.create(char_literal101); + adaptor.addChild(root_0, char_literal101_tree); + } + dbg.location(309,21); + pushFollow(FOLLOW_actualParameters_in_functionCall1368); + aP=actualParameters(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, aP.getTree()); + dbg.location(309,39); + char_literal102=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_functionCall1370); if (failed) return retval; + if ( backtracking==0 ) { + char_literal102_tree = (Object)adaptor.create(char_literal102); + adaptor.addChild(root_0, char_literal102_tree); + } + dbg.location(310,2); + if ( backtracking==0 ) { + if (i == null || aP.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExpandFuncCall(i.getText(), aP.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(313, 5); + + } + finally { + dbg.exitRule("functionCall"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end functionCall + + public static class actualParameters_return extends ParserRuleReturnScope { + public AST.ActualParameters astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start actualParameters + // C00.g:315:1: actualParameters returns [AST.ActualParameters astTree] : ( ( expressionList )=>eL= expressionList | ); + public actualParameters_return actualParameters() throws RecognitionException { + actualParameters_return retval = new actualParameters_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + expressionList_return eL = null; + + + + try { dbg.enterRule("actualParameters"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(315, 1); + + try { + // C00.g:316:7: ( ( expressionList )=>eL= expressionList | ) + int alt16=2; + try { dbg.enterDecision(16); + + int LA16_0 = input.LA(1); + if ( ((LA16_0>=Ident && LA16_0<=Number)||LA16_0==15||LA16_0==21||LA16_0==36||(LA16_0>=43 && LA16_0<=44)) ) { + alt16=1; + } + else if ( (LA16_0==16) ) { + alt16=2; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("315:1: actualParameters returns [AST.ActualParameters astTree] : ( ( expressionList )=>eL= expressionList | );", 16, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(16);} + + switch (alt16) { + case 1 : + dbg.enterAlt(1); + + // C00.g:316:7: ( expressionList )=>eL= expressionList + { + root_0 = (Object)adaptor.nil(); + + dbg.location(316,9); + pushFollow(FOLLOW_expressionList_in_actualParameters1400); + eL=expressionList(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, eL.getTree()); + dbg.location(317,2); + if ( backtracking==0 ) { + if (eL.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ExprListActParams(eL.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:321:2: + { + root_0 = (Object)adaptor.nil(); + + dbg.location(321,2); + if ( backtracking==0 ) { + retval.astTree = new AST.EmptyActParams(); + determineIndices(((Token)retval.start), retval.astTree); + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(323, 5); + + } + finally { + dbg.exitRule("actualParameters"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end actualParameters + + public static class expressionList_return extends ParserRuleReturnScope { + public AST.ExpressionList astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start expressionList + // C00.g:325:1: expressionList returns [AST.ExpressionList astTree] : ( ( expression )=>e1= expression | e2= expression ',' eL2= expressionList ); + public expressionList_return expressionList() throws RecognitionException { + expressionList_return retval = new expressionList_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal103=null; + expression_return e1 = null; + + expression_return e2 = null; + + expressionList_return eL2 = null; + + + Object char_literal103_tree=null; + + try { dbg.enterRule("expressionList"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(325, 1); + + try { + // C00.g:326:7: ( ( expression )=>e1= expression | e2= expression ',' eL2= expressionList ) + int alt17=2; + try { dbg.enterDecision(17); + + try { + isCyclicDecision = true; + alt17 = dfa17.predict(input); + } + catch (NoViableAltException nvae) { + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(17);} + + switch (alt17) { + case 1 : + dbg.enterAlt(1); + + // C00.g:326:7: ( expression )=>e1= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(326,9); + pushFollow(FOLLOW_expression_in_expressionList1439); + e1=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e1.getTree()); + dbg.location(327,2); + if ( backtracking==0 ) { + if (e1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.LastExprList(e1.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:330:7: e2= expression ',' eL2= expressionList + { + root_0 = (Object)adaptor.nil(); + + dbg.location(330,9); + pushFollow(FOLLOW_expression_in_expressionList1452); + e2=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e2.getTree()); + dbg.location(330,21); + char_literal103=(Token)input.LT(1); + match(input,20,FOLLOW_20_in_expressionList1454); if (failed) return retval; + if ( backtracking==0 ) { + char_literal103_tree = (Object)adaptor.create(char_literal103); + adaptor.addChild(root_0, char_literal103_tree); + } + dbg.location(330,28); + pushFollow(FOLLOW_expressionList_in_expressionList1458); + eL2=expressionList(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, eL2.getTree()); + dbg.location(331,2); + if ( backtracking==0 ) { + if (e2.astTree == null || eL2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PairExprList(e2.astTree, eL2.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(334, 5); + + } + finally { + dbg.exitRule("expressionList"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end expressionList + + public static class expression_return extends ParserRuleReturnScope { + public AST.Expression astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start expression + // C00.g:336:1: expression returns [AST.Expression astTree] : fT= firstTerm e= expression2[temp] ; + public expression_return expression() throws RecognitionException { + expression_return retval = new expression_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + firstTerm_return fT = null; + + expression2_return e = null; + + + + AST.Expression temp=null; + try { dbg.enterRule("expression"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(336, 1); + + try { + // C00.g:338:7: (fT= firstTerm e= expression2[temp] ) + dbg.enterAlt(1); + + // C00.g:338:7: fT= firstTerm e= expression2[temp] + { + root_0 = (Object)adaptor.nil(); + + dbg.location(338,9); + pushFollow(FOLLOW_firstTerm_in_expression1493); + fT=firstTerm(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fT.getTree()); + dbg.location(339,2); + if ( backtracking==0 ) { + if (fT.astTree == null) {temp = null;} else + {temp = new AST.FirstTermExpr(fT.astTree); copyIndices(temp, fT.astTree);} + } + dbg.location(341,8); + pushFollow(FOLLOW_expression2_in_expression1506); + e=expression2(temp); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e.getTree()); + dbg.location(342,2); + if ( backtracking==0 ) { + retval.astTree = e.astTree; + } + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(343, 5); + + } + finally { + dbg.exitRule("expression"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end expression + + public static class expression2_return extends ParserRuleReturnScope { + public AST.Expression astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start expression2 + // C00.g:345:1: expression2[AST.Expression leftTree] returns [AST.Expression astTree] : ( ( '+' term )=> '+' t1= term | ( '-' term )=> '-' t2= term )* ; + public expression2_return expression2(AST.Expression leftTree) throws RecognitionException { + expression2_return retval = new expression2_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal104=null; + Token char_literal105=null; + term_return t1 = null; + + term_return t2 = null; + + + Object char_literal104_tree=null; + Object char_literal105_tree=null; + + retval.astTree = leftTree; + try { dbg.enterRule("expression2"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(345, 1); + + try { + // C00.g:347:7: ( ( ( '+' term )=> '+' t1= term | ( '-' term )=> '-' t2= term )* ) + dbg.enterAlt(1); + + // C00.g:347:7: ( ( '+' term )=> '+' t1= term | ( '-' term )=> '-' t2= term )* + { + root_0 = (Object)adaptor.nil(); + + dbg.location(347,7); + // C00.g:347:7: ( ( '+' term )=> '+' t1= term | ( '-' term )=> '-' t2= term )* + try { dbg.enterSubRule(18); + + loop18: + do { + int alt18=3; + try { dbg.enterDecision(18); + + int LA18_0 = input.LA(1); + if ( (LA18_0==43) ) { + alt18=1; + } + else if ( (LA18_0==44) ) { + alt18=2; + } + + + } finally {dbg.exitDecision(18);} + + switch (alt18) { + case 1 : + dbg.enterAlt(1); + + // C00.g:347:8: ( '+' term )=> '+' t1= term + { + dbg.location(347,8); + char_literal104=(Token)input.LT(1); + match(input,43,FOLLOW_43_in_expression21543); if (failed) return retval; + if ( backtracking==0 ) { + char_literal104_tree = (Object)adaptor.create(char_literal104); + adaptor.addChild(root_0, char_literal104_tree); + } + dbg.location(347,14); + pushFollow(FOLLOW_term_in_expression21547); + t1=term(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t1.getTree()); + dbg.location(348,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || t1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.PlusExpr(retval.astTree, t1.astTree); + determineIndices(l, c, retval.astTree);} + + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:353:8: ( '-' term )=> '-' t2= term + { + dbg.location(353,8); + char_literal105=(Token)input.LT(1); + match(input,44,FOLLOW_44_in_expression21560); if (failed) return retval; + if ( backtracking==0 ) { + char_literal105_tree = (Object)adaptor.create(char_literal105); + adaptor.addChild(root_0, char_literal105_tree); + } + dbg.location(353,14); + pushFollow(FOLLOW_term_in_expression21564); + t2=term(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t2.getTree()); + dbg.location(354,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || t2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.MinusExpr(retval.astTree, t2.astTree); + determineIndices(l, c, retval.astTree);} + + } + + } + break; + + default : + break loop18; + } + } while (true); + } finally {dbg.exitSubRule(18);} + + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(360, 5); + + } + finally { + dbg.exitRule("expression2"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end expression2 + + public static class firstTerm_return extends ParserRuleReturnScope { + public AST.FirstTerm astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start firstTerm + // C00.g:362:1: firstTerm returns [AST.FirstTerm astTree] : ( ( factor firstTerm2[temp] )=>f1= factor t1= firstTerm2[temp] | ( '+' factor firstTerm2[temp] )=> '+' f2= factor t2= firstTerm2[temp] | '-' f3= factor t3= firstTerm2[temp] ); + public firstTerm_return firstTerm() throws RecognitionException { + firstTerm_return retval = new firstTerm_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal106=null; + Token char_literal107=null; + factor_return f1 = null; + + firstTerm2_return t1 = null; + + factor_return f2 = null; + + firstTerm2_return t2 = null; + + factor_return f3 = null; + + firstTerm2_return t3 = null; + + + Object char_literal106_tree=null; + Object char_literal107_tree=null; + + AST.FirstTerm temp=null; + try { dbg.enterRule("firstTerm"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(362, 1); + + try { + // C00.g:364:7: ( ( factor firstTerm2[temp] )=>f1= factor t1= firstTerm2[temp] | ( '+' factor firstTerm2[temp] )=> '+' f2= factor t2= firstTerm2[temp] | '-' f3= factor t3= firstTerm2[temp] ) + int alt19=3; + try { dbg.enterDecision(19); + + switch ( input.LA(1) ) { + case Ident: + case Number: + case 15: + case 21: + case 36: + alt19=1; + break; + case 43: + alt19=2; + break; + case 44: + alt19=3; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("362:1: firstTerm returns [AST.FirstTerm astTree] : ( ( factor firstTerm2[temp] )=>f1= factor t1= firstTerm2[temp] | ( '+' factor firstTerm2[temp] )=> '+' f2= factor t2= firstTerm2[temp] | '-' f3= factor t3= firstTerm2[temp] );", 19, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(19);} + + switch (alt19) { + case 1 : + dbg.enterAlt(1); + + // C00.g:364:7: ( factor firstTerm2[temp] )=>f1= factor t1= firstTerm2[temp] + { + root_0 = (Object)adaptor.nil(); + + dbg.location(364,9); + pushFollow(FOLLOW_factor_in_firstTerm1613); + f1=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f1.getTree()); + dbg.location(365,2); + if ( backtracking==0 ) { + if (f1.astTree == null) {temp = null;} else + {temp = new AST.FactorFirstTerm(f1.astTree); copyIndices(temp, f1.astTree);} + } + dbg.location(367,9); + pushFollow(FOLLOW_firstTerm2_in_firstTerm1626); + t1=firstTerm2(temp); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t1.getTree()); + dbg.location(368,2); + if ( backtracking==0 ) { + retval.astTree = t1.astTree; + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:369:7: ( '+' factor firstTerm2[temp] )=> '+' f2= factor t2= firstTerm2[temp] + { + root_0 = (Object)adaptor.nil(); + + dbg.location(369,7); + char_literal106=(Token)input.LT(1); + match(input,43,FOLLOW_43_in_firstTerm1639); if (failed) return retval; + if ( backtracking==0 ) { + char_literal106_tree = (Object)adaptor.create(char_literal106); + adaptor.addChild(root_0, char_literal106_tree); + } + dbg.location(369,12); + pushFollow(FOLLOW_factor_in_firstTerm1642); + f2=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f2.getTree()); + dbg.location(370,2); + if ( backtracking==0 ) { + if (f2.astTree == null) {temp = null;} else + {temp = new AST.PlusFactorFirstTerm(f2.astTree); copyIndices(temp, f2.astTree); + temp.startLine = ((Token)retval.start).getLine(); temp.startColumn = ((Token)retval.start).getCharPositionInLine();} + } + dbg.location(373,9); + pushFollow(FOLLOW_firstTerm2_in_firstTerm1655); + t2=firstTerm2(temp); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t2.getTree()); + dbg.location(374,2); + if ( backtracking==0 ) { + retval.astTree = t2.astTree; + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:375:7: '-' f3= factor t3= firstTerm2[temp] + { + root_0 = (Object)adaptor.nil(); + + dbg.location(375,7); + char_literal107=(Token)input.LT(1); + match(input,44,FOLLOW_44_in_firstTerm1668); if (failed) return retval; + if ( backtracking==0 ) { + char_literal107_tree = (Object)adaptor.create(char_literal107); + adaptor.addChild(root_0, char_literal107_tree); + } + dbg.location(375,12); + pushFollow(FOLLOW_factor_in_firstTerm1671); + f3=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f3.getTree()); + dbg.location(376,2); + if ( backtracking==0 ) { + if (f3.astTree == null) {temp = null;} else + {temp = new AST.MinusFactorFirstTerm(f3.astTree); copyIndices(temp, f3.astTree); + temp.startLine = ((Token)retval.start).getLine(); temp.startColumn = ((Token)retval.start).getCharPositionInLine();} + } + dbg.location(379,9); + pushFollow(FOLLOW_firstTerm2_in_firstTerm1684); + t3=firstTerm2(temp); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t3.getTree()); + dbg.location(380,2); + if ( backtracking==0 ) { + retval.astTree = t3.astTree; + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(381, 5); + + } + finally { + dbg.exitRule("firstTerm"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end firstTerm + + public static class firstTerm2_return extends ParserRuleReturnScope { + public AST.FirstTerm astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start firstTerm2 + // C00.g:383:1: firstTerm2[AST.FirstTerm leftTree] returns [AST.FirstTerm astTree] : ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* ; + public firstTerm2_return firstTerm2(AST.FirstTerm leftTree) throws RecognitionException { + firstTerm2_return retval = new firstTerm2_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal108=null; + Token char_literal109=null; + Token char_literal110=null; + factor_return f1 = null; + + factor_return f2 = null; + + factor_return f3 = null; + + + Object char_literal108_tree=null; + Object char_literal109_tree=null; + Object char_literal110_tree=null; + + retval.astTree = leftTree; + try { dbg.enterRule("firstTerm2"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(383, 1); + + try { + // C00.g:385:7: ( ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* ) + dbg.enterAlt(1); + + // C00.g:385:7: ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* + { + root_0 = (Object)adaptor.nil(); + + dbg.location(385,7); + // C00.g:385:7: ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* + try { dbg.enterSubRule(20); + + loop20: + do { + int alt20=4; + try { dbg.enterDecision(20); + + switch ( input.LA(1) ) { + case 21: + alt20=1; + break; + case 45: + alt20=2; + break; + case 46: + alt20=3; + break; + + } + + } finally {dbg.exitDecision(20);} + + switch (alt20) { + case 1 : + dbg.enterAlt(1); + + // C00.g:385:8: ( '*' factor )=> '*' f1= factor + { + dbg.location(385,8); + char_literal108=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_firstTerm21721); if (failed) return retval; + if ( backtracking==0 ) { + char_literal108_tree = (Object)adaptor.create(char_literal108); + adaptor.addChild(root_0, char_literal108_tree); + } + dbg.location(385,14); + pushFollow(FOLLOW_factor_in_firstTerm21725); + f1=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f1.getTree()); + dbg.location(386,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.MultFirstTerm(retval.astTree, f1.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:390:8: ( '/' factor )=> '/' f2= factor + { + dbg.location(390,8); + char_literal109=(Token)input.LT(1); + match(input,45,FOLLOW_45_in_firstTerm21738); if (failed) return retval; + if ( backtracking==0 ) { + char_literal109_tree = (Object)adaptor.create(char_literal109); + adaptor.addChild(root_0, char_literal109_tree); + } + dbg.location(390,14); + pushFollow(FOLLOW_factor_in_firstTerm21742); + f2=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f2.getTree()); + dbg.location(391,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.DivFirstTerm(retval.astTree, f2.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:395:8: ( '%' factor )=> '%' f3= factor + { + dbg.location(395,8); + char_literal110=(Token)input.LT(1); + match(input,46,FOLLOW_46_in_firstTerm21755); if (failed) return retval; + if ( backtracking==0 ) { + char_literal110_tree = (Object)adaptor.create(char_literal110); + adaptor.addChild(root_0, char_literal110_tree); + } + dbg.location(395,14); + pushFollow(FOLLOW_factor_in_firstTerm21759); + f3=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f3.getTree()); + dbg.location(396,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f3.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ModFirstTerm(retval.astTree, f3.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + + default : + break loop20; + } + } while (true); + } finally {dbg.exitSubRule(20);} + + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(401, 5); + + } + finally { + dbg.exitRule("firstTerm2"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end firstTerm2 + + public static class term_return extends ParserRuleReturnScope { + public AST.Term astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start term + // C00.g:403:1: term returns [AST.Term astTree] : f= factor t= term2[temp] ; + public term_return term() throws RecognitionException { + term_return retval = new term_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + factor_return f = null; + + term2_return t = null; + + + + AST.Term temp=null; + try { dbg.enterRule("term"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(403, 1); + + try { + // C00.g:405:7: (f= factor t= term2[temp] ) + dbg.enterAlt(1); + + // C00.g:405:7: f= factor t= term2[temp] + { + root_0 = (Object)adaptor.nil(); + + dbg.location(405,8); + pushFollow(FOLLOW_factor_in_term1804); + f=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f.getTree()); + dbg.location(406,2); + if ( backtracking==0 ) { + if (f.astTree == null) {temp = null;} else + {temp = new AST.FactorTerm(f.astTree); copyIndices(temp, f.astTree);} + } + dbg.location(408,8); + pushFollow(FOLLOW_term2_in_term1817); + t=term2(temp); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, t.getTree()); + dbg.location(409,2); + if ( backtracking==0 ) { + retval.astTree = t.astTree; + } + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(410, 5); + + } + finally { + dbg.exitRule("term"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end term + + public static class term2_return extends ParserRuleReturnScope { + public AST.Term astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start term2 + // C00.g:412:1: term2[AST.Term leftTree] returns [AST.Term astTree] : ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* ; + public term2_return term2(AST.Term leftTree) throws RecognitionException { + term2_return retval = new term2_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token char_literal111=null; + Token char_literal112=null; + Token char_literal113=null; + factor_return f1 = null; + + factor_return f2 = null; + + factor_return f3 = null; + + + Object char_literal111_tree=null; + Object char_literal112_tree=null; + Object char_literal113_tree=null; + + retval.astTree = leftTree; + try { dbg.enterRule("term2"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(412, 1); + + try { + // C00.g:414:7: ( ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* ) + dbg.enterAlt(1); + + // C00.g:414:7: ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* + { + root_0 = (Object)adaptor.nil(); + + dbg.location(414,7); + // C00.g:414:7: ( ( '*' factor )=> '*' f1= factor | ( '/' factor )=> '/' f2= factor | ( '%' factor )=> '%' f3= factor )* + try { dbg.enterSubRule(21); + + loop21: + do { + int alt21=4; + try { dbg.enterDecision(21); + + switch ( input.LA(1) ) { + case 21: + alt21=1; + break; + case 45: + alt21=2; + break; + case 46: + alt21=3; + break; + + } + + } finally {dbg.exitDecision(21);} + + switch (alt21) { + case 1 : + dbg.enterAlt(1); + + // C00.g:414:8: ( '*' factor )=> '*' f1= factor + { + dbg.location(414,8); + char_literal111=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_term21854); if (failed) return retval; + if ( backtracking==0 ) { + char_literal111_tree = (Object)adaptor.create(char_literal111); + adaptor.addChild(root_0, char_literal111_tree); + } + dbg.location(414,14); + pushFollow(FOLLOW_factor_in_term21858); + f1=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f1.getTree()); + dbg.location(415,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f1.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.MultTerm(retval.astTree, f1.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:419:8: ( '/' factor )=> '/' f2= factor + { + dbg.location(419,8); + char_literal112=(Token)input.LT(1); + match(input,45,FOLLOW_45_in_term21871); if (failed) return retval; + if ( backtracking==0 ) { + char_literal112_tree = (Object)adaptor.create(char_literal112); + adaptor.addChild(root_0, char_literal112_tree); + } + dbg.location(419,14); + pushFollow(FOLLOW_factor_in_term21875); + f2=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f2.getTree()); + dbg.location(420,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f2.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.DivTerm(retval.astTree, f2.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:424:8: ( '%' factor )=> '%' f3= factor + { + dbg.location(424,8); + char_literal113=(Token)input.LT(1); + match(input,46,FOLLOW_46_in_term21888); if (failed) return retval; + if ( backtracking==0 ) { + char_literal113_tree = (Object)adaptor.create(char_literal113); + adaptor.addChild(root_0, char_literal113_tree); + } + dbg.location(424,14); + pushFollow(FOLLOW_factor_in_term21892); + f3=factor(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, f3.getTree()); + dbg.location(425,2); + if ( backtracking==0 ) { + int l=retval.astTree.startLine, c=retval.astTree.startColumn; + if (retval.astTree == null || f3.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.ModTerm(retval.astTree, f3.astTree); + determineIndices(l, c, retval.astTree);} + } + + } + break; + + default : + break loop21; + } + } while (true); + } finally {dbg.exitSubRule(21);} + + + } + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(430, 5); + + } + finally { + dbg.exitRule("term2"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end term2 + + public static class factor_return extends ParserRuleReturnScope { + public AST.Factor astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start factor + // C00.g:432:1: factor returns [AST.Factor astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i2= Ident | ( '&' Ident )=> '&' i3= Ident | ( Number )=>n4= Number | ( functionCall )=>fC5= functionCall | '(' e6= expression ')' ); + public factor_return factor() throws RecognitionException { + factor_return retval = new factor_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token i1=null; + Token i2=null; + Token i3=null; + Token n4=null; + Token char_literal114=null; + Token char_literal115=null; + Token char_literal116=null; + Token char_literal117=null; + functionCall_return fC5 = null; + + expression_return e6 = null; + + + Object i1_tree=null; + Object i2_tree=null; + Object i3_tree=null; + Object n4_tree=null; + Object char_literal114_tree=null; + Object char_literal115_tree=null; + Object char_literal116_tree=null; + Object char_literal117_tree=null; + + try { dbg.enterRule("factor"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(432, 1); + + try { + // C00.g:433:7: ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i2= Ident | ( '&' Ident )=> '&' i3= Ident | ( Number )=>n4= Number | ( functionCall )=>fC5= functionCall | '(' e6= expression ')' ) + int alt22=6; + try { dbg.enterDecision(22); + + switch ( input.LA(1) ) { + case Ident: + int LA22_1 = input.LA(2); + if ( (LA22_1==15) ) { + alt22=5; + } + else if ( (LA22_1==EOF||(LA22_1>=16 && LA22_1<=17)||(LA22_1>=20 && LA22_1<=21)||(LA22_1>=43 && LA22_1<=52)) ) { + alt22=1; + } + else { + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("432:1: factor returns [AST.Factor astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i2= Ident | ( '&' Ident )=> '&' i3= Ident | ( Number )=>n4= Number | ( functionCall )=>fC5= functionCall | '(' e6= expression ')' );", 22, 1, input); + + dbg.recognitionException(nvae); + throw nvae; + } + break; + case 21: + alt22=2; + break; + case 36: + alt22=3; + break; + case Number: + alt22=4; + break; + case 15: + alt22=6; + break; + default: + if (backtracking>0) {failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("432:1: factor returns [AST.Factor astTree] : ( ( Ident )=>i1= Ident | ( '*' Ident )=> '*' i2= Ident | ( '&' Ident )=> '&' i3= Ident | ( Number )=>n4= Number | ( functionCall )=>fC5= functionCall | '(' e6= expression ')' );", 22, 0, input); + + dbg.recognitionException(nvae); + throw nvae; + } + + } finally {dbg.exitDecision(22);} + + switch (alt22) { + case 1 : + dbg.enterAlt(1); + + // C00.g:433:7: ( Ident )=>i1= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(433,9); + i1=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_factor1932); if (failed) return retval; + if ( backtracking==0 ) { + i1_tree = (Object)adaptor.create(i1); + adaptor.addChild(root_0, i1_tree); + } + dbg.location(434,2); + if ( backtracking==0 ) { + if (i1 == null) {retval.astTree = null;} else + {retval.astTree = new AST.IdFactor(i1.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:437:7: ( '*' Ident )=> '*' i2= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(437,7); + char_literal114=(Token)input.LT(1); + match(input,21,FOLLOW_21_in_factor1943); if (failed) return retval; + if ( backtracking==0 ) { + char_literal114_tree = (Object)adaptor.create(char_literal114); + adaptor.addChild(root_0, char_literal114_tree); + } + dbg.location(437,13); + i2=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_factor1947); if (failed) return retval; + if ( backtracking==0 ) { + i2_tree = (Object)adaptor.create(i2); + adaptor.addChild(root_0, i2_tree); + } + dbg.location(438,2); + if ( backtracking==0 ) { + if (i2 == null) {retval.astTree = null;} else + {retval.astTree = new AST.RefIdFactor(i2.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:441:7: ( '&' Ident )=> '&' i3= Ident + { + root_0 = (Object)adaptor.nil(); + + dbg.location(441,7); + char_literal115=(Token)input.LT(1); + match(input,36,FOLLOW_36_in_factor1958); if (failed) return retval; + if ( backtracking==0 ) { + char_literal115_tree = (Object)adaptor.create(char_literal115); + adaptor.addChild(root_0, char_literal115_tree); + } + dbg.location(441,13); + i3=(Token)input.LT(1); + match(input,Ident,FOLLOW_Ident_in_factor1962); if (failed) return retval; + if ( backtracking==0 ) { + i3_tree = (Object)adaptor.create(i3); + adaptor.addChild(root_0, i3_tree); + } + dbg.location(442,2); + if ( backtracking==0 ) { + if (i3 == null) {retval.astTree = null;} else + {retval.astTree = new AST.AddIdFactor(i3.getText()); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 4 : + dbg.enterAlt(4); + + // C00.g:445:7: ( Number )=>n4= Number + { + root_0 = (Object)adaptor.nil(); + + dbg.location(445,9); + n4=(Token)input.LT(1); + match(input,Number,FOLLOW_Number_in_factor1975); if (failed) return retval; + if ( backtracking==0 ) { + n4_tree = (Object)adaptor.create(n4); + adaptor.addChild(root_0, n4_tree); + } + dbg.location(446,2); + if ( backtracking==0 ) { + if (n4 == null) {retval.astTree = null;} else + {retval.astTree = new AST.NumFactor(Integer.parseInt(n4.getText())); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 5 : + dbg.enterAlt(5); + + // C00.g:449:7: ( functionCall )=>fC5= functionCall + { + root_0 = (Object)adaptor.nil(); + + dbg.location(449,10); + pushFollow(FOLLOW_functionCall_in_factor1988); + fC5=functionCall(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, fC5.getTree()); + dbg.location(450,2); + if ( backtracking==0 ) { + if (fC5.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.FuncCallFactor(fC5.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 6 : + dbg.enterAlt(6); + + // C00.g:453:7: '(' e6= expression ')' + { + root_0 = (Object)adaptor.nil(); + + dbg.location(453,7); + char_literal116=(Token)input.LT(1); + match(input,15,FOLLOW_15_in_factor1999); if (failed) return retval; + if ( backtracking==0 ) { + char_literal116_tree = (Object)adaptor.create(char_literal116); + adaptor.addChild(root_0, char_literal116_tree); + } + dbg.location(453,13); + pushFollow(FOLLOW_expression_in_factor2003); + e6=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e6.getTree()); + dbg.location(453,25); + char_literal117=(Token)input.LT(1); + match(input,16,FOLLOW_16_in_factor2005); if (failed) return retval; + if ( backtracking==0 ) { + char_literal117_tree = (Object)adaptor.create(char_literal117); + adaptor.addChild(root_0, char_literal117_tree); + } + dbg.location(454,2); + if ( backtracking==0 ) { + if (e6.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.CompFactor(e6.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(457, 5); + + } + finally { + dbg.exitRule("factor"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end factor + + public static class boolExpression_return extends ParserRuleReturnScope { + public AST.BoolExpression astTree; + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start boolExpression + // C00.g:459:1: boolExpression returns [AST.BoolExpression astTree] : ( ( expression '==' expression )=>e11= expression '==' e12= expression | ( expression '!=' expression )=>e21= expression '!=' e22= expression | ( expression '<' expression )=>e31= expression '<' e32= expression | ( expression '>' expression )=>e41= expression '>' e42= expression | ( expression '<=' expression )=>e51= expression '<=' e52= expression | e61= expression '>=' e62= expression ); + public boolExpression_return boolExpression() throws RecognitionException { + boolExpression_return retval = new boolExpression_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token string_literal118=null; + Token string_literal119=null; + Token char_literal120=null; + Token char_literal121=null; + Token string_literal122=null; + Token string_literal123=null; + expression_return e11 = null; + + expression_return e12 = null; + + expression_return e21 = null; + + expression_return e22 = null; + + expression_return e31 = null; + + expression_return e32 = null; + + expression_return e41 = null; + + expression_return e42 = null; + + expression_return e51 = null; + + expression_return e52 = null; + + expression_return e61 = null; + + expression_return e62 = null; + + + Object string_literal118_tree=null; + Object string_literal119_tree=null; + Object char_literal120_tree=null; + Object char_literal121_tree=null; + Object string_literal122_tree=null; + Object string_literal123_tree=null; + + try { dbg.enterRule("boolExpression"); + if ( ruleLevel==0 ) {dbg.commence();} + ruleLevel++; + dbg.location(459, 1); + + try { + // C00.g:460:7: ( ( expression '==' expression )=>e11= expression '==' e12= expression | ( expression '!=' expression )=>e21= expression '!=' e22= expression | ( expression '<' expression )=>e31= expression '<' e32= expression | ( expression '>' expression )=>e41= expression '>' e42= expression | ( expression '<=' expression )=>e51= expression '<=' e52= expression | e61= expression '>=' e62= expression ) + int alt23=6; + try { dbg.enterDecision(23); + + try { + isCyclicDecision = true; + alt23 = dfa23.predict(input); + } + catch (NoViableAltException nvae) { + dbg.recognitionException(nvae); + throw nvae; + } + } finally {dbg.exitDecision(23);} + + switch (alt23) { + case 1 : + dbg.enterAlt(1); + + // C00.g:460:7: ( expression '==' expression )=>e11= expression '==' e12= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(460,10); + pushFollow(FOLLOW_expression_in_boolExpression2035); + e11=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e11.getTree()); + dbg.location(460,22); + string_literal118=(Token)input.LT(1); + match(input,47,FOLLOW_47_in_boolExpression2037); if (failed) return retval; + if ( backtracking==0 ) { + string_literal118_tree = (Object)adaptor.create(string_literal118); + adaptor.addChild(root_0, string_literal118_tree); + } + dbg.location(460,30); + pushFollow(FOLLOW_expression_in_boolExpression2041); + e12=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e12.getTree()); + dbg.location(461,2); + if ( backtracking==0 ) { + if (e11.astTree == null || e12.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.EqBoolExpr(e11.astTree, e12.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 2 : + dbg.enterAlt(2); + + // C00.g:464:7: ( expression '!=' expression )=>e21= expression '!=' e22= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(464,10); + pushFollow(FOLLOW_expression_in_boolExpression2054); + e21=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e21.getTree()); + dbg.location(464,22); + string_literal119=(Token)input.LT(1); + match(input,48,FOLLOW_48_in_boolExpression2056); if (failed) return retval; + if ( backtracking==0 ) { + string_literal119_tree = (Object)adaptor.create(string_literal119); + adaptor.addChild(root_0, string_literal119_tree); + } + dbg.location(464,30); + pushFollow(FOLLOW_expression_in_boolExpression2060); + e22=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e22.getTree()); + dbg.location(465,2); + if ( backtracking==0 ) { + if (e21.astTree == null || e22.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.NotEqBoolExpr(e21.astTree, e22.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 3 : + dbg.enterAlt(3); + + // C00.g:468:7: ( expression '<' expression )=>e31= expression '<' e32= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(468,10); + pushFollow(FOLLOW_expression_in_boolExpression2073); + e31=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e31.getTree()); + dbg.location(468,22); + char_literal120=(Token)input.LT(1); + match(input,49,FOLLOW_49_in_boolExpression2075); if (failed) return retval; + if ( backtracking==0 ) { + char_literal120_tree = (Object)adaptor.create(char_literal120); + adaptor.addChild(root_0, char_literal120_tree); + } + dbg.location(468,29); + pushFollow(FOLLOW_expression_in_boolExpression2079); + e32=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e32.getTree()); + dbg.location(469,2); + if ( backtracking==0 ) { + if (e31.astTree == null || e32.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.LessBoolExpr(e31.astTree, e32.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 4 : + dbg.enterAlt(4); + + // C00.g:472:7: ( expression '>' expression )=>e41= expression '>' e42= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(472,10); + pushFollow(FOLLOW_expression_in_boolExpression2092); + e41=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e41.getTree()); + dbg.location(472,22); + char_literal121=(Token)input.LT(1); + match(input,50,FOLLOW_50_in_boolExpression2094); if (failed) return retval; + if ( backtracking==0 ) { + char_literal121_tree = (Object)adaptor.create(char_literal121); + adaptor.addChild(root_0, char_literal121_tree); + } + dbg.location(472,29); + pushFollow(FOLLOW_expression_in_boolExpression2098); + e42=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e42.getTree()); + dbg.location(473,2); + if ( backtracking==0 ) { + if (e41.astTree == null || e42.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.GreatBoolExpr(e41.astTree, e42.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 5 : + dbg.enterAlt(5); + + // C00.g:476:7: ( expression '<=' expression )=>e51= expression '<=' e52= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(476,10); + pushFollow(FOLLOW_expression_in_boolExpression2111); + e51=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e51.getTree()); + dbg.location(476,22); + string_literal122=(Token)input.LT(1); + match(input,51,FOLLOW_51_in_boolExpression2113); if (failed) return retval; + if ( backtracking==0 ) { + string_literal122_tree = (Object)adaptor.create(string_literal122); + adaptor.addChild(root_0, string_literal122_tree); + } + dbg.location(476,30); + pushFollow(FOLLOW_expression_in_boolExpression2117); + e52=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e52.getTree()); + dbg.location(477,2); + if ( backtracking==0 ) { + if (e51.astTree == null || e52.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.LessEqBoolExpr(e51.astTree, e52.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + case 6 : + dbg.enterAlt(6); + + // C00.g:480:7: e61= expression '>=' e62= expression + { + root_0 = (Object)adaptor.nil(); + + dbg.location(480,10); + pushFollow(FOLLOW_expression_in_boolExpression2130); + e61=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e61.getTree()); + dbg.location(480,22); + string_literal123=(Token)input.LT(1); + match(input,52,FOLLOW_52_in_boolExpression2132); if (failed) return retval; + if ( backtracking==0 ) { + string_literal123_tree = (Object)adaptor.create(string_literal123); + adaptor.addChild(root_0, string_literal123_tree); + } + dbg.location(480,30); + pushFollow(FOLLOW_expression_in_boolExpression2136); + e62=expression(); + _fsp--; + if (failed) return retval; + if ( backtracking==0 ) adaptor.addChild(root_0, e62.getTree()); + dbg.location(481,2); + if ( backtracking==0 ) { + if (e61.astTree == null || e62.astTree == null) {retval.astTree = null;} else + {retval.astTree = new AST.GreatEqBoolExpr(e61.astTree, e62.astTree); + determineIndices(((Token)retval.start), retval.astTree);} + } + + } + break; + + } + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + } + finally { + retval.stop = input.LT(-1); + + if ( backtracking==0 ) { + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + dbg.location(484, 5); + + } + finally { + dbg.exitRule("boolExpression"); + ruleLevel--; + if ( ruleLevel==0 ) {dbg.terminate();} + } + + return retval; + } + // $ANTLR end boolExpression + + // $ANTLR start synpred2 + public void synpred2_fragment() throws RecognitionException { + // C00.g:58:7: ( functionHeading ';' globalDeclarations ) + dbg.enterAlt(1); + + // C00.g:58:7: functionHeading ';' globalDeclarations + { + dbg.location(58,10); + pushFollow(FOLLOW_functionHeading_in_synpred2141); + functionHeading(); + _fsp--; + if (failed) return ; + dbg.location(58,26); + match(input,17,FOLLOW_17_in_synpred2143); if (failed) return ; + dbg.location(58,34); + pushFollow(FOLLOW_globalDeclarations_in_synpred2147); + globalDeclarations(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred2 + + // $ANTLR start synpred34 + public void synpred34_fragment() throws RecognitionException { + // C00.g:268:7: ( 'else' statement ) + dbg.enterAlt(1); + + // C00.g:268:7: 'else' statement + { + dbg.location(268,7); + match(input,39,FOLLOW_39_in_synpred341151); if (failed) return ; + dbg.location(268,16); + pushFollow(FOLLOW_statement_in_synpred341155); + statement(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred34 + + // $ANTLR start synpred36 + public void synpred36_fragment() throws RecognitionException { + // C00.g:288:7: ( '{' caseSequence '}' ) + dbg.enterAlt(1); + + // C00.g:288:7: '{' caseSequence '}' + { + dbg.location(288,7); + match(input,23,FOLLOW_23_in_synpred361250); if (failed) return ; + dbg.location(288,15); + pushFollow(FOLLOW_caseSequence_in_synpred361254); + caseSequence(); + _fsp--; + if (failed) return ; + dbg.location(288,28); + match(input,24,FOLLOW_24_in_synpred361256); if (failed) return ; + + } + } + // $ANTLR end synpred36 + + // $ANTLR start synpred39 + public void synpred39_fragment() throws RecognitionException { + // C00.g:326:7: ( expression ) + dbg.enterAlt(1); + + // C00.g:326:7: expression + { + dbg.location(326,10); + pushFollow(FOLLOW_expression_in_synpred391439); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred39 + + // $ANTLR start synpred55 + public void synpred55_fragment() throws RecognitionException { + // C00.g:460:7: ( expression '==' expression ) + dbg.enterAlt(1); + + // C00.g:460:7: expression '==' expression + { + dbg.location(460,11); + pushFollow(FOLLOW_expression_in_synpred552035); + expression(); + _fsp--; + if (failed) return ; + dbg.location(460,22); + match(input,47,FOLLOW_47_in_synpred552037); if (failed) return ; + dbg.location(460,31); + pushFollow(FOLLOW_expression_in_synpred552041); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred55 + + // $ANTLR start synpred56 + public void synpred56_fragment() throws RecognitionException { + // C00.g:464:7: ( expression '!=' expression ) + dbg.enterAlt(1); + + // C00.g:464:7: expression '!=' expression + { + dbg.location(464,11); + pushFollow(FOLLOW_expression_in_synpred562054); + expression(); + _fsp--; + if (failed) return ; + dbg.location(464,22); + match(input,48,FOLLOW_48_in_synpred562056); if (failed) return ; + dbg.location(464,31); + pushFollow(FOLLOW_expression_in_synpred562060); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred56 + + // $ANTLR start synpred57 + public void synpred57_fragment() throws RecognitionException { + // C00.g:468:7: ( expression '<' expression ) + dbg.enterAlt(1); + + // C00.g:468:7: expression '<' expression + { + dbg.location(468,11); + pushFollow(FOLLOW_expression_in_synpred572073); + expression(); + _fsp--; + if (failed) return ; + dbg.location(468,22); + match(input,49,FOLLOW_49_in_synpred572075); if (failed) return ; + dbg.location(468,30); + pushFollow(FOLLOW_expression_in_synpred572079); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred57 + + // $ANTLR start synpred58 + public void synpred58_fragment() throws RecognitionException { + // C00.g:472:7: ( expression '>' expression ) + dbg.enterAlt(1); + + // C00.g:472:7: expression '>' expression + { + dbg.location(472,11); + pushFollow(FOLLOW_expression_in_synpred582092); + expression(); + _fsp--; + if (failed) return ; + dbg.location(472,22); + match(input,50,FOLLOW_50_in_synpred582094); if (failed) return ; + dbg.location(472,30); + pushFollow(FOLLOW_expression_in_synpred582098); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred58 + + // $ANTLR start synpred59 + public void synpred59_fragment() throws RecognitionException { + // C00.g:476:7: ( expression '<=' expression ) + dbg.enterAlt(1); + + // C00.g:476:7: expression '<=' expression + { + dbg.location(476,11); + pushFollow(FOLLOW_expression_in_synpred592111); + expression(); + _fsp--; + if (failed) return ; + dbg.location(476,22); + match(input,51,FOLLOW_51_in_synpred592113); if (failed) return ; + dbg.location(476,31); + pushFollow(FOLLOW_expression_in_synpred592117); + expression(); + _fsp--; + if (failed) return ; + + } + } + // $ANTLR end synpred59 + + public boolean synpred2() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred2_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred39() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred39_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred56() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred56_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred58() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred58_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred59() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred59_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred34() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred34_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred36() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred36_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred57() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred57_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + public boolean synpred55() { + backtracking++; + dbg.beginBacktrack(backtracking); + int start = input.mark(); + try { + synpred55_fragment(); // can never throw exception + } catch (RecognitionException re) { + throwException(re, "impossible: "+re); + } + boolean success = !failed; + input.rewind(start); + dbg.endBacktrack(backtracking, success); + backtracking--; + failed=false; + return success; + } + + + protected DFA17 dfa17 = new DFA17(this); + protected DFA23 dfa23 = new DFA23(this); + public static final String DFA17_eotS = + "\u016e\uffff"; + public static final String DFA17_eofS = + "\1\uffff\1\16\2\uffff\1\16\13\uffff\3\16\2\uffff\1\16\1\uffff\1"+ + "\16\2\uffff\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff"+ + "\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff"+ + "\1\16\2\uffff\1\16\5\uffff\2\16\4\uffff\2\16\1\uffff\2\16\1\uffff"+ + "\2\16\1\uffff\2\16\4\uffff\2\16\13\uffff\2\16\7\uffff\1\16\2\uffff"+ + "\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff"+ + "\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff"+ + "\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff\1\16\1\uffff"+ + "\1\16\2\uffff\1\16\15\uffff\1\16\2\uffff\1\16\1\uffff\1\16\2\uffff"+ + "\1\16\1\uffff\1\16\2\uffff\1\16\16\uffff\2\16\1\uffff\2\16\1\uffff"+ + "\2\16\1\uffff\2\16\1\uffff\2\16\1\uffff\2\16\1\uffff\2\16\10\uffff"+ + "\2\16\10\uffff\2\16\14\uffff\2\16\10\uffff\2\16\10\uffff\2\16\153"+ + "\uffff"; + public static final String DFA17_minS = + "\1\4\1\17\2\4\1\20\1\0\2\4\1\0\5\4\2\uffff\2\20\1\17\2\4\1\20\1"+ + "\0\1\17\2\4\1\20\1\0\1\17\2\4\1\20\1\0\1\17\2\4\1\20\1\0\1\17\2"+ + "\4\1\20\1\0\1\17\2\4\1\20\1\4\1\17\2\4\1\20\1\4\1\0\3\4\2\20\1\0"+ + "\3\4\2\20\1\0\2\20\1\0\2\20\1\0\2\20\1\0\3\4\2\20\1\0\2\4\2\0\2"+ + "\4\1\0\3\4\2\20\1\0\2\4\2\0\2\4\1\17\2\4\1\20\1\0\1\17\2\4\1\20"+ + "\1\0\1\17\2\4\1\20\1\0\1\17\2\4\1\20\1\0\1\17\2\4\1\20\1\0\1\17"+ + "\2\4\1\20\1\0\1\17\2\4\1\20\1\4\1\17\2\4\1\20\1\4\1\17\2\4\1\20"+ + "\1\4\3\0\2\4\3\0\2\4\2\0\1\17\2\4\1\20\1\4\1\17\2\4\1\20\1\4\1\17"+ + "\2\4\1\20\1\4\3\0\2\4\3\0\2\4\3\0\2\20\1\0\2\20\1\0\2\20\1\0\2\20"+ + "\1\0\2\20\1\0\2\20\1\0\2\20\1\0\2\4\2\0\2\4\1\0\2\20\1\0\2\4\2\0"+ + "\2\4\1\0\2\20\1\0\2\4\2\0\2\4\5\0\2\20\1\0\2\4\2\0\2\4\1\0\2\20"+ + "\1\0\2\4\2\0\2\4\1\0\2\20\1\0\2\4\2\0\2\4\7\0\2\4\3\0\2\4\5\0\2"+ + "\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2"+ + "\4\3\0\2\4\32\0"; + public static final String DFA17_maxS = + "\1\54\1\56\2\4\1\56\1\0\2\44\1\0\5\44\2\uffff\3\56\2\4\1\56\1\0"+ + "\1\56\2\4\1\56\1\0\1\56\2\4\1\56\1\0\1\56\2\4\1\56\1\0\1\56\2\4"+ + "\1\56\1\0\1\56\2\4\1\56\1\54\1\56\2\4\1\56\1\54\1\0\3\44\2\56\1"+ + "\0\3\44\2\56\1\0\2\56\1\0\2\56\1\0\2\56\1\0\3\44\2\56\1\0\2\4\2"+ + "\0\2\44\1\0\3\44\2\56\1\0\2\4\2\0\2\44\1\56\2\4\1\56\1\0\1\56\2"+ + "\4\1\56\1\0\1\56\2\4\1\56\1\0\1\56\2\4\1\56\1\0\1\56\2\4\1\56\1"+ + "\0\1\56\2\4\1\56\1\0\1\56\2\4\1\56\1\54\1\56\2\4\1\56\1\54\1\56"+ + "\2\4\1\56\1\54\3\0\2\4\3\0\2\4\2\0\1\56\2\4\1\56\1\54\1\56\2\4\1"+ + "\56\1\54\1\56\2\4\1\56\1\54\3\0\2\4\3\0\2\4\3\0\2\56\1\0\2\56\1"+ + "\0\2\56\1\0\2\56\1\0\2\56\1\0\2\56\1\0\2\56\1\0\2\4\2\0\2\44\1\0"+ + "\2\56\1\0\2\4\2\0\2\44\1\0\2\56\1\0\2\4\2\0\2\44\5\0\2\56\1\0\2"+ + "\4\2\0\2\44\1\0\2\56\1\0\2\4\2\0\2\44\1\0\2\56\1\0\2\4\2\0\2\44"+ + "\7\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4"+ + "\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\32\0"; + public static final String DFA17_acceptS = + "\16\uffff\1\1\1\2\u015e\uffff"; + public static final String DFA17_specialS = + "\5\uffff\1\u0083\2\uffff\1\41\15\uffff\1\31\4\uffff\1\0\4\uffff"+ + "\1\1\4\uffff\1\2\4\uffff\1\32\12\uffff\1\67\5\uffff\1\66\5\uffff"+ + "\1\65\2\uffff\1\40\2\uffff\1\64\2\uffff\1\141\5\uffff\1\12\2\uffff"+ + "\1\u008e\1\116\2\uffff\1\63\5\uffff\1\55\2\uffff\1\u008d\1\117\6"+ + "\uffff\1\33\4\uffff\1\34\4\uffff\1\3\4\uffff\1\4\4\uffff\1\35\4"+ + "\uffff\1\5\17\uffff\1\51\1\130\1\162\2\uffff\1\175\1\120\1\152\2"+ + "\uffff\1\171\1\121\17\uffff\1\52\1\131\1\u0092\2\uffff\1\u0082\1"+ + "\122\1\153\2\uffff\1\172\1\123\1\42\2\uffff\1\70\2\uffff\1\71\2"+ + "\uffff\1\37\2\uffff\1\62\2\uffff\1\36\2\uffff\1\61\2\uffff\1\54"+ + "\2\uffff\1\30\1\115\2\uffff\1\60\2\uffff\1\11\2\uffff\1\u008c\1"+ + "\114\2\uffff\1\140\2\uffff\1\10\2\uffff\1\u008b\1\113\2\uffff\1"+ + "\u0097\1\u0089\1\134\1\22\1\57\2\uffff\1\53\2\uffff\1\27\1\112\2"+ + "\uffff\1\137\2\uffff\1\7\2\uffff\1\26\1\111\2\uffff\1\56\2\uffff"+ + "\1\6\2\uffff\1\u008a\1\110\2\uffff\1\u0096\1\u0088\1\146\1\21\1"+ + "\50\1\136\1\u0091\2\uffff\1\u0081\1\107\1\156\2\uffff\1\106\1\105"+ + "\1\15\1\127\1\u0090\2\uffff\1\u0080\1\104\1\151\2\uffff\1\170\1"+ + "\103\1\14\1\126\1\161\2\uffff\1\174\1\102\1\150\2\uffff\1\167\1"+ + "\101\1\13\1\135\1\160\2\uffff\1\173\1\100\1\155\2\uffff\1\77\1\76"+ + "\1\47\1\125\1\u008f\2\uffff\1\177\1\75\1\154\2\uffff\1\166\1\74"+ + "\1\46\1\124\1\157\2\uffff\1\176\1\73\1\147\2\uffff\1\165\1\72\1"+ + "\45\1\164\1\145\1\20\1\u0095\1\u0087\1\144\1\17\1\44\1\u0086\1\133"+ + "\1\25\1\43\1\u0085\1\143\1\24\1\u0094\1\163\1\142\1\23\1\u0093\1"+ + "\u0084\1\132\1\16}>"; + public static final String[] DFA17_transition = { + "\1\1\1\4\11\uffff\1\5\5\uffff\1\2\16\uffff\1\3\6\uffff\1\6\1\7", + "\1\10\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\20", + "\1\21", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\22\1\25\11\uffff\1\26\5\uffff\1\23\16\uffff\1\24", + "\1\27\1\32\11\uffff\1\33\5\uffff\1\30\16\uffff\1\31", + "\1\uffff", + "\1\34\1\37\11\uffff\1\40\5\uffff\1\35\16\uffff\1\36", + "\1\41\1\44\11\uffff\1\45\5\uffff\1\42\16\uffff\1\43", + "\1\46\1\51\11\uffff\1\52\5\uffff\1\47\16\uffff\1\50", + "\1\53\1\56\11\uffff\1\57\5\uffff\1\54\16\uffff\1\55", + "\1\60\1\63\11\uffff\1\64\5\uffff\1\61\16\uffff\1\62", + "", + "", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\65\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\71", + "\1\72", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\73\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\77", + "\1\100", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\101\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\102", + "\1\103", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\104\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\105", + "\1\106", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\107\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\110", + "\1\111", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\112\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\116", + "\1\117", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\120\1\123\11\uffff\1\124\5\uffff\1\121\16\uffff\1\122\6\uffff"+ + "\1\125\1\126", + "\1\127\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\133", + "\1\134", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\135\1\140\11\uffff\1\141\5\uffff\1\136\16\uffff\1\137\6\uffff"+ + "\1\142\1\143", + "\1\uffff", + "\1\144\1\147\11\uffff\1\150\5\uffff\1\145\16\uffff\1\146", + "\1\151\1\154\11\uffff\1\155\5\uffff\1\152\16\uffff\1\153", + "\1\156\1\161\11\uffff\1\162\5\uffff\1\157\16\uffff\1\160", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\163\1\166\11\uffff\1\167\5\uffff\1\164\16\uffff\1\165", + "\1\170\1\173\11\uffff\1\174\5\uffff\1\171\16\uffff\1\172", + "\1\175\1\u0080\11\uffff\1\u0081\5\uffff\1\176\16\uffff\1\177", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\16\3\uffff\1\17\1\11\25\uffff\1\14\1\15\1\12\1\13", + "\1\uffff", + "\1\u0082\1\u0085\11\uffff\1\u0086\5\uffff\1\u0083\16\uffff\1\u0084", + "\1\u0087\1\u008a\11\uffff\1\u008b\5\uffff\1\u0088\16\uffff\1\u0089", + "\1\u008c\1\u008f\11\uffff\1\u0090\5\uffff\1\u008d\16\uffff\1\u008e", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\uffff", + "\1\u0091", + "\1\u0092", + "\1\uffff", + "\1\uffff", + "\1\u0093\1\u0096\11\uffff\1\u0097\5\uffff\1\u0094\16\uffff\1\u0095", + "\1\u0098\1\u009b\11\uffff\1\u009c\5\uffff\1\u0099\16\uffff\1\u009a", + "\1\uffff", + "\1\u009d\1\u00a0\11\uffff\1\u00a1\5\uffff\1\u009e\16\uffff\1\u009f", + "\1\u00a2\1\u00a5\11\uffff\1\u00a6\5\uffff\1\u00a3\16\uffff\1\u00a4", + "\1\u00a7\1\u00aa\11\uffff\1\u00ab\5\uffff\1\u00a8\16\uffff\1\u00a9", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\uffff", + "\1\u00ac", + "\1\u00ad", + "\1\uffff", + "\1\uffff", + "\1\u00ae\1\u00b1\11\uffff\1\u00b2\5\uffff\1\u00af\16\uffff\1\u00b0", + "\1\u00b3\1\u00b6\11\uffff\1\u00b7\5\uffff\1\u00b4\16\uffff\1\u00b5", + "\1\u00b8\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\u00b9", + "\1\u00ba", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\u00bb\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\u00bc", + "\1\u00bd", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\u00be\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\u00bf", + "\1\u00c0", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\u00c1\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\u00c2", + "\1\u00c3", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\u00c4\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\u00c5", + "\1\u00c6", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\u00c7\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\u00c8", + "\1\u00c9", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\u00ca\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00cb", + "\1\u00cc", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00cd\1\u00d0\11\uffff\1\u00d1\5\uffff\1\u00ce\16\uffff\1\u00cf"+ + "\6\uffff\1\u00d2\1\u00d3", + "\1\u00d4\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00d5", + "\1\u00d6", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00d7\1\u00da\11\uffff\1\u00db\5\uffff\1\u00d8\16\uffff\1\u00d9"+ + "\6\uffff\1\u00dc\1\u00dd", + "\1\u00de\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00df", + "\1\u00e0", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\u00e1\1\u00e4\11\uffff\1\u00e5\5\uffff\1\u00e2\16\uffff\1\u00e3"+ + "\6\uffff\1\u00e6\1\u00e7", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u00e8", + "\1\u00e9", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u00ea", + "\1\u00eb", + "\1\uffff", + "\1\uffff", + "\1\u00ec\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u00ed", + "\1\u00ee", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u00ef\1\u00f2\11\uffff\1\u00f3\5\uffff\1\u00f0\16\uffff\1\u00f1"+ + "\6\uffff\1\u00f4\1\u00f5", + "\1\u00f6\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u00f7", + "\1\u00f8", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u00f9\1\u00fc\11\uffff\1\u00fd\5\uffff\1\u00fa\16\uffff\1\u00fb"+ + "\6\uffff\1\u00fe\1\u00ff", + "\1\u0100\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u0101", + "\1\u0102", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\u0103\1\u0106\11\uffff\1\u0107\5\uffff\1\u0104\16\uffff\1\u0105"+ + "\6\uffff\1\u0108\1\u0109", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u010a", + "\1\u010b", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u010c", + "\1\u010d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\16\3\uffff\1\17\1\66\25\uffff\1\14\1\15\1\67\1\70", + "\1\uffff", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\16\3\uffff\1\17\1\74\25\uffff\1\14\1\15\1\75\1\76", + "\1\uffff", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\uffff", + "\1\u010e", + "\1\u010f", + "\1\uffff", + "\1\uffff", + "\1\u0110\1\u0113\11\uffff\1\u0114\5\uffff\1\u0111\16\uffff\1\u0112", + "\1\u0115\1\u0118\11\uffff\1\u0119\5\uffff\1\u0116\16\uffff\1\u0117", + "\1\uffff", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\uffff", + "\1\u011a", + "\1\u011b", + "\1\uffff", + "\1\uffff", + "\1\u011c\1\u011f\11\uffff\1\u0120\5\uffff\1\u011d\16\uffff\1\u011e", + "\1\u0121\1\u0124\11\uffff\1\u0125\5\uffff\1\u0122\16\uffff\1\u0123", + "\1\uffff", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\16\3\uffff\1\17\1\113\25\uffff\1\14\1\15\1\114\1\115", + "\1\uffff", + "\1\u0126", + "\1\u0127", + "\1\uffff", + "\1\uffff", + "\1\u0128\1\u012b\11\uffff\1\u012c\5\uffff\1\u0129\16\uffff\1\u012a", + "\1\u012d\1\u0130\11\uffff\1\u0131\5\uffff\1\u012e\16\uffff\1\u012f", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\uffff", + "\1\u0132", + "\1\u0133", + "\1\uffff", + "\1\uffff", + "\1\u0134\1\u0137\11\uffff\1\u0138\5\uffff\1\u0135\16\uffff\1\u0136", + "\1\u0139\1\u013c\11\uffff\1\u013d\5\uffff\1\u013a\16\uffff\1\u013b", + "\1\uffff", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\uffff", + "\1\u013e", + "\1\u013f", + "\1\uffff", + "\1\uffff", + "\1\u0140\1\u0143\11\uffff\1\u0144\5\uffff\1\u0141\16\uffff\1\u0142", + "\1\u0145\1\u0148\11\uffff\1\u0149\5\uffff\1\u0146\16\uffff\1\u0147", + "\1\uffff", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\16\3\uffff\1\17\1\130\25\uffff\1\14\1\15\1\131\1\132", + "\1\uffff", + "\1\u014a", + "\1\u014b", + "\1\uffff", + "\1\uffff", + "\1\u014c\1\u014f\11\uffff\1\u0150\5\uffff\1\u014d\16\uffff\1\u014e", + "\1\u0151\1\u0154\11\uffff\1\u0155\5\uffff\1\u0152\16\uffff\1\u0153", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0156", + "\1\u0157", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0158", + "\1\u0159", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015a", + "\1\u015b", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015c", + "\1\u015d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015e", + "\1\u015f", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0160", + "\1\u0161", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0162", + "\1\u0163", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0164", + "\1\u0165", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0166", + "\1\u0167", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0168", + "\1\u0169", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u016a", + "\1\u016b", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u016c", + "\1\u016d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff" + }; + + class DFA17 extends DFA { + public DFA17(BaseRecognizer recognizer) { + this.recognizer = recognizer; + this.decisionNumber = 17; + this.eot = DFA.unpackEncodedString(DFA17_eotS); + this.eof = DFA.unpackEncodedString(DFA17_eofS); + this.min = DFA.unpackEncodedStringToUnsignedChars(DFA17_minS); + this.max = DFA.unpackEncodedStringToUnsignedChars(DFA17_maxS); + this.accept = DFA.unpackEncodedString(DFA17_acceptS); + this.special = DFA.unpackEncodedString(DFA17_specialS); + int numStates = DFA17_transition.length; + this.transition = new short[numStates][]; + for (int i=0; ie1= expression | e2= expression ',' eL2= expressionList );"; + } + public void error(NoViableAltException nvae) { + dbg.recognitionException(nvae); + } + public int specialStateTransition(int s) throws NoViableAltException { + int _s = s; + switch ( s ) { + case 0 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 1 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 2 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 3 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 4 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 5 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 6 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 7 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 8 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 9 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 10 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 11 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 12 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 13 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 14 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 15 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 16 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 17 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 18 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 19 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 20 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 21 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 22 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 23 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 24 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 25 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 26 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 27 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 28 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 29 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 30 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 31 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 32 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 33 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 34 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 35 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 36 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 37 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 38 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 39 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 40 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 41 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 42 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 43 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 44 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 45 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 46 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 47 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 48 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 49 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 50 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 51 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 52 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 53 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 54 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 55 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 56 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 57 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 58 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 59 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 60 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 61 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 62 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 63 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 64 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 65 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 66 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 67 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 68 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 69 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 70 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 71 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 72 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 73 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 74 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 75 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 76 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 77 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 78 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 79 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 80 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 81 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 82 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 83 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 84 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 85 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 86 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 87 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 88 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 89 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 90 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 91 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 92 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 93 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 94 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 95 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 96 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 97 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 98 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 99 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 100 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 101 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 102 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 103 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 104 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 105 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 106 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 107 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 108 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 109 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 110 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 111 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 112 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 113 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 114 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 115 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 116 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 117 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 118 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 119 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 120 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 121 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 122 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 123 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 124 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 125 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 126 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 127 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 128 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 129 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 130 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 131 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 132 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 133 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 134 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 135 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 136 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 137 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 138 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 139 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 140 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 141 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 142 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 143 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 144 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 145 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 146 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 147 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 148 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 149 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 150 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + case 151 : + input.rewind(); + s = -1; + if ( (synpred39()) ) {s = 14;} + + else if ( (true) ) {s = 15;} + + if ( s>=0 ) return s; + break; + } + if (backtracking>0) {failed=true; return -1;} + NoViableAltException nvae = + new NoViableAltException(getDescription(), 17, _s, input); + error(nvae); + throw nvae; + } + } + public static final String DFA23_eotS = + "\u0172\uffff"; + public static final String DFA23_eofS = + "\u0172\uffff"; + public static final String DFA23_minS = + "\1\4\1\17\2\4\1\25\1\0\2\4\1\0\5\4\6\uffff\2\25\1\17\2\4\1\25\1"+ + "\0\1\17\2\4\1\25\1\0\1\17\2\4\1\25\1\0\1\17\2\4\1\25\1\0\1\17\2"+ + "\4\1\25\1\0\1\17\2\4\1\25\1\4\1\17\2\4\1\25\1\4\1\0\3\4\2\25\1\0"+ + "\3\4\2\25\1\0\2\25\1\0\2\25\1\0\2\25\1\0\3\4\2\25\1\0\2\4\2\0\2"+ + "\4\1\0\3\4\2\25\1\0\2\4\2\0\2\4\1\17\2\4\1\25\1\0\1\17\2\4\1\25"+ + "\1\0\1\17\2\4\1\25\1\0\1\17\2\4\1\25\1\0\1\17\2\4\1\25\1\0\1\17"+ + "\2\4\1\25\1\0\1\17\2\4\1\25\1\4\1\17\2\4\1\25\1\4\1\17\2\4\1\25"+ + "\1\4\3\0\2\4\3\0\2\4\2\0\1\17\2\4\1\25\1\4\1\17\2\4\1\25\1\4\1\17"+ + "\2\4\1\25\1\4\3\0\2\4\3\0\2\4\3\0\2\25\1\0\2\25\1\0\2\25\1\0\2\25"+ + "\1\0\2\25\1\0\2\25\1\0\2\25\1\0\2\4\2\0\2\4\1\0\2\25\1\0\2\4\2\0"+ + "\2\4\1\0\2\25\1\0\2\4\2\0\2\4\5\0\2\25\1\0\2\4\2\0\2\4\1\0\2\25"+ + "\1\0\2\4\2\0\2\4\1\0\2\25\1\0\2\4\2\0\2\4\7\0\2\4\3\0\2\4\5\0\2"+ + "\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2"+ + "\4\3\0\2\4\32\0"; + public static final String DFA23_maxS = + "\1\54\1\64\2\4\1\64\1\0\2\44\1\0\5\44\6\uffff\3\64\2\4\1\64\1\0"+ + "\1\64\2\4\1\64\1\0\1\64\2\4\1\64\1\0\1\64\2\4\1\64\1\0\1\64\2\4"+ + "\1\64\1\0\1\64\2\4\1\64\1\54\1\64\2\4\1\64\1\54\1\0\3\44\2\64\1"+ + "\0\3\44\2\64\1\0\2\64\1\0\2\64\1\0\2\64\1\0\3\44\2\64\1\0\2\4\2"+ + "\0\2\44\1\0\3\44\2\64\1\0\2\4\2\0\2\44\1\64\2\4\1\64\1\0\1\64\2"+ + "\4\1\64\1\0\1\64\2\4\1\64\1\0\1\64\2\4\1\64\1\0\1\64\2\4\1\64\1"+ + "\0\1\64\2\4\1\64\1\0\1\64\2\4\1\64\1\54\1\64\2\4\1\64\1\54\1\64"+ + "\2\4\1\64\1\54\3\0\2\4\3\0\2\4\2\0\1\64\2\4\1\64\1\54\1\64\2\4\1"+ + "\64\1\54\1\64\2\4\1\64\1\54\3\0\2\4\3\0\2\4\3\0\2\64\1\0\2\64\1"+ + "\0\2\64\1\0\2\64\1\0\2\64\1\0\2\64\1\0\2\64\1\0\2\4\2\0\2\44\1\0"+ + "\2\64\1\0\2\4\2\0\2\44\1\0\2\64\1\0\2\4\2\0\2\44\5\0\2\64\1\0\2"+ + "\4\2\0\2\44\1\0\2\64\1\0\2\4\2\0\2\44\1\0\2\64\1\0\2\4\2\0\2\44"+ + "\7\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4"+ + "\5\0\2\4\3\0\2\4\5\0\2\4\3\0\2\4\32\0"; + public static final String DFA23_acceptS = + "\16\uffff\1\5\1\4\1\2\1\1\1\3\1\6\u015e\uffff"; + public static final String DFA23_specialS = + "\5\uffff\1\40\2\uffff\1\u008b\21\uffff\1\123\4\uffff\1\130\4\uffff"+ + "\1\131\4\uffff\1\66\4\uffff\1\45\12\uffff\1\u008c\5\uffff\1\114"+ + "\5\uffff\1\110\2\uffff\1\u008a\2\uffff\1\113\2\uffff\1\127\5\uffff"+ + "\1\30\2\uffff\1\64\1\177\2\uffff\1\106\5\uffff\1\44\2\uffff\1\41"+ + "\1\u0080\6\uffff\1\146\4\uffff\1\115\4\uffff\1\147\4\uffff\1\67"+ + "\4\uffff\1\46\4\uffff\1\116\17\uffff\1\5\1\136\1\20\2\uffff\1\100"+ + "\1\u0081\1\141\2\uffff\1\32\1\u0082\17\uffff\1\10\1\137\1\21\2\uffff"+ + "\1\107\1\u0083\1\65\2\uffff\1\37\1\u0084\1\57\2\uffff\1\62\2\uffff"+ + "\1\u0089\2\uffff\1\u0088\2\uffff\1\56\2\uffff\1\55\2\uffff\1\126"+ + "\2\uffff\1\151\2\uffff\1\121\1\176\2\uffff\1\105\2\uffff\1\u0093"+ + "\2\uffff\1\120\1\175\2\uffff\1\125\2\uffff\1\43\2\uffff\1\63\1\174"+ + "\2\uffff\1\104\1\71\1\145\1\4\1\27\2\uffff\1\42\2\uffff\1\117\1"+ + "\173\2\uffff\1\26\2\uffff\1\150\2\uffff\1\6\1\172\2\uffff\1\124"+ + "\2\uffff\1\u0092\2\uffff\1\111\1\171\2\uffff\1\u008e\1\u0085\1\144"+ + "\1\133\1\3\1\u008d\1\73\2\uffff\1\112\1\170\1\53\2\uffff\1\u0091"+ + "\1\167\1\u0096\1\13\1\17\2\uffff\1\77\1\166\1\52\2\uffff\1\36\1"+ + "\165\1\33\1\132\1\101\2\uffff\1\14\1\164\1\140\2\uffff\1\31\1\163"+ + "\1\2\1\15\1\54\2\uffff\1\61\1\162\1\51\2\uffff\1\u0090\1\161\1\u0095"+ + "\1\135\1\72\2\uffff\1\76\1\160\1\122\2\uffff\1\u008f\1\157\1\154"+ + "\1\12\1\u0097\2\uffff\1\60\1\156\1\16\2\uffff\1\153\1\155\1\25\1"+ + "\23\1\50\1\u0087\1\11\1\35\1\143\1\7\1\134\1\22\1\75\1\1\1\103\1"+ + "\70\1\74\1\u0094\1\24\1\34\1\47\1\u0086\1\102\1\152\1\142\1\0}>"; + public static final String[] DFA23_transition = { + "\1\1\1\4\11\uffff\1\5\5\uffff\1\2\16\uffff\1\3\6\uffff\1\6\1\7", + "\1\10\5\uffff\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1"+ + "\17\1\16\1\23", + "\1\24", + "\1\25", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\26\1\31\11\uffff\1\32\5\uffff\1\27\16\uffff\1\30", + "\1\33\1\36\11\uffff\1\37\5\uffff\1\34\16\uffff\1\35", + "\1\uffff", + "\1\40\1\43\11\uffff\1\44\5\uffff\1\41\16\uffff\1\42", + "\1\45\1\50\11\uffff\1\51\5\uffff\1\46\16\uffff\1\47", + "\1\52\1\55\11\uffff\1\56\5\uffff\1\53\16\uffff\1\54", + "\1\57\1\62\11\uffff\1\63\5\uffff\1\60\16\uffff\1\61", + "\1\64\1\67\11\uffff\1\70\5\uffff\1\65\16\uffff\1\66", + "", + "", + "", + "", + "", + "", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\71\5\uffff\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1"+ + "\17\1\16\1\23", + "\1\75", + "\1\76", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\77\5\uffff\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\103", + "\1\104", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\105\5\uffff\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\106", + "\1\107", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\110\5\uffff\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\111", + "\1\112", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\113\5\uffff\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\114", + "\1\115", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\116\5\uffff\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1"+ + "\22\1\17\1\16\1\23", + "\1\122", + "\1\123", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\124\1\127\11\uffff\1\130\5\uffff\1\125\16\uffff\1\126\6\uffff"+ + "\1\131\1\132", + "\1\133\5\uffff\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1"+ + "\22\1\17\1\16\1\23", + "\1\137", + "\1\140", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\141\1\144\11\uffff\1\145\5\uffff\1\142\16\uffff\1\143\6\uffff"+ + "\1\146\1\147", + "\1\uffff", + "\1\150\1\153\11\uffff\1\154\5\uffff\1\151\16\uffff\1\152", + "\1\155\1\160\11\uffff\1\161\5\uffff\1\156\16\uffff\1\157", + "\1\162\1\165\11\uffff\1\166\5\uffff\1\163\16\uffff\1\164", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\167\1\172\11\uffff\1\173\5\uffff\1\170\16\uffff\1\171", + "\1\174\1\177\11\uffff\1\u0080\5\uffff\1\175\16\uffff\1\176", + "\1\u0081\1\u0084\11\uffff\1\u0085\5\uffff\1\u0082\16\uffff\1\u0083", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\11\25\uffff\1\14\1\15\1\12\1\13\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\u0086\1\u0089\11\uffff\1\u008a\5\uffff\1\u0087\16\uffff\1\u0088", + "\1\u008b\1\u008e\11\uffff\1\u008f\5\uffff\1\u008c\16\uffff\1\u008d", + "\1\u0090\1\u0093\11\uffff\1\u0094\5\uffff\1\u0091\16\uffff\1\u0092", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u0095", + "\1\u0096", + "\1\uffff", + "\1\uffff", + "\1\u0097\1\u009a\11\uffff\1\u009b\5\uffff\1\u0098\16\uffff\1\u0099", + "\1\u009c\1\u009f\11\uffff\1\u00a0\5\uffff\1\u009d\16\uffff\1\u009e", + "\1\uffff", + "\1\u00a1\1\u00a4\11\uffff\1\u00a5\5\uffff\1\u00a2\16\uffff\1\u00a3", + "\1\u00a6\1\u00a9\11\uffff\1\u00aa\5\uffff\1\u00a7\16\uffff\1\u00a8", + "\1\u00ab\1\u00ae\11\uffff\1\u00af\5\uffff\1\u00ac\16\uffff\1\u00ad", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u00b0", + "\1\u00b1", + "\1\uffff", + "\1\uffff", + "\1\u00b2\1\u00b5\11\uffff\1\u00b6\5\uffff\1\u00b3\16\uffff\1\u00b4", + "\1\u00b7\1\u00ba\11\uffff\1\u00bb\5\uffff\1\u00b8\16\uffff\1\u00b9", + "\1\u00bc\5\uffff\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\u00bd", + "\1\u00be", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\u00bf\5\uffff\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\u00c0", + "\1\u00c1", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\u00c2\5\uffff\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22"+ + "\1\17\1\16\1\23", + "\1\u00c3", + "\1\u00c4", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\u00c5\5\uffff\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00c6", + "\1\u00c7", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u00c8\5\uffff\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00c9", + "\1\u00ca", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u00cb\5\uffff\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00cc", + "\1\u00cd", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u00ce\5\uffff\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00cf", + "\1\u00d0", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u00d1\1\u00d4\11\uffff\1\u00d5\5\uffff\1\u00d2\16\uffff\1\u00d3"+ + "\6\uffff\1\u00d6\1\u00d7", + "\1\u00d8\5\uffff\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00d9", + "\1\u00da", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u00db\1\u00de\11\uffff\1\u00df\5\uffff\1\u00dc\16\uffff\1\u00dd"+ + "\6\uffff\1\u00e0\1\u00e1", + "\1\u00e2\5\uffff\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00e3", + "\1\u00e4", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u00e5\1\u00e8\11\uffff\1\u00e9\5\uffff\1\u00e6\16\uffff\1\u00e7"+ + "\6\uffff\1\u00ea\1\u00eb", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u00ec", + "\1\u00ed", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u00ee", + "\1\u00ef", + "\1\uffff", + "\1\uffff", + "\1\u00f0\5\uffff\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00f1", + "\1\u00f2", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u00f3\1\u00f6\11\uffff\1\u00f7\5\uffff\1\u00f4\16\uffff\1\u00f5"+ + "\6\uffff\1\u00f8\1\u00f9", + "\1\u00fa\5\uffff\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u00fb", + "\1\u00fc", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u00fd\1\u0100\11\uffff\1\u0101\5\uffff\1\u00fe\16\uffff\1\u00ff"+ + "\6\uffff\1\u0102\1\u0103", + "\1\u0104\5\uffff\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20"+ + "\1\22\1\17\1\16\1\23", + "\1\u0105", + "\1\u0106", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\u0107\1\u010a\11\uffff\1\u010b\5\uffff\1\u0108\16\uffff\1\u0109"+ + "\6\uffff\1\u010c\1\u010d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u010e", + "\1\u010f", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0110", + "\1\u0111", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\72\25\uffff\1\14\1\15\1\73\1\74\1\21\1\20\1\22\1\17\1\16\1\23", + "\1\uffff", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\100\25\uffff\1\14\1\15\1\101\1\102\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u0112", + "\1\u0113", + "\1\uffff", + "\1\uffff", + "\1\u0114\1\u0117\11\uffff\1\u0118\5\uffff\1\u0115\16\uffff\1\u0116", + "\1\u0119\1\u011c\11\uffff\1\u011d\5\uffff\1\u011a\16\uffff\1\u011b", + "\1\uffff", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u011e", + "\1\u011f", + "\1\uffff", + "\1\uffff", + "\1\u0120\1\u0123\11\uffff\1\u0124\5\uffff\1\u0121\16\uffff\1\u0122", + "\1\u0125\1\u0128\11\uffff\1\u0129\5\uffff\1\u0126\16\uffff\1\u0127", + "\1\uffff", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\117\25\uffff\1\14\1\15\1\120\1\121\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u012a", + "\1\u012b", + "\1\uffff", + "\1\uffff", + "\1\u012c\1\u012f\11\uffff\1\u0130\5\uffff\1\u012d\16\uffff\1\u012e", + "\1\u0131\1\u0134\11\uffff\1\u0135\5\uffff\1\u0132\16\uffff\1\u0133", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u0136", + "\1\u0137", + "\1\uffff", + "\1\uffff", + "\1\u0138\1\u013b\11\uffff\1\u013c\5\uffff\1\u0139\16\uffff\1\u013a", + "\1\u013d\1\u0140\11\uffff\1\u0141\5\uffff\1\u013e\16\uffff\1\u013f", + "\1\uffff", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u0142", + "\1\u0143", + "\1\uffff", + "\1\uffff", + "\1\u0144\1\u0147\11\uffff\1\u0148\5\uffff\1\u0145\16\uffff\1\u0146", + "\1\u0149\1\u014c\11\uffff\1\u014d\5\uffff\1\u014a\16\uffff\1\u014b", + "\1\uffff", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\134\25\uffff\1\14\1\15\1\135\1\136\1\21\1\20\1\22\1\17\1\16\1"+ + "\23", + "\1\uffff", + "\1\u014e", + "\1\u014f", + "\1\uffff", + "\1\uffff", + "\1\u0150\1\u0153\11\uffff\1\u0154\5\uffff\1\u0151\16\uffff\1\u0152", + "\1\u0155\1\u0158\11\uffff\1\u0159\5\uffff\1\u0156\16\uffff\1\u0157", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015a", + "\1\u015b", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015c", + "\1\u015d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u015e", + "\1\u015f", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0160", + "\1\u0161", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0162", + "\1\u0163", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0164", + "\1\u0165", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0166", + "\1\u0167", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0168", + "\1\u0169", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u016a", + "\1\u016b", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u016c", + "\1\u016d", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u016e", + "\1\u016f", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\u0170", + "\1\u0171", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff", + "\1\uffff" + }; + + class DFA23 extends DFA { + public DFA23(BaseRecognizer recognizer) { + this.recognizer = recognizer; + this.decisionNumber = 23; + this.eot = DFA.unpackEncodedString(DFA23_eotS); + this.eof = DFA.unpackEncodedString(DFA23_eofS); + this.min = DFA.unpackEncodedStringToUnsignedChars(DFA23_minS); + this.max = DFA.unpackEncodedStringToUnsignedChars(DFA23_maxS); + this.accept = DFA.unpackEncodedString(DFA23_acceptS); + this.special = DFA.unpackEncodedString(DFA23_specialS); + int numStates = DFA23_transition.length; + this.transition = new short[numStates][]; + for (int i=0; ie11= expression '==' e12= expression | ( expression '!=' expression )=>e21= expression '!=' e22= expression | ( expression '<' expression )=>e31= expression '<' e32= expression | ( expression '>' expression )=>e41= expression '>' e42= expression | ( expression '<=' expression )=>e51= expression '<=' e52= expression | e61= expression '>=' e62= expression );"; + } + public void error(NoViableAltException nvae) { + dbg.recognitionException(nvae); + } + public int specialStateTransition(int s) throws NoViableAltException { + int _s = s; + switch ( s ) { + case 0 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 1 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 2 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 3 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 4 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 5 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 6 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 7 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 8 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 9 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 10 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 11 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 12 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 13 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 14 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 15 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 16 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 17 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 18 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 19 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 20 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 21 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 22 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 23 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 24 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 25 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 26 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 27 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 28 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 29 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 30 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 31 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 32 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 33 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 34 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 35 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 36 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 37 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 38 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 39 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 40 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 41 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 42 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 43 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 44 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 45 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 46 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 47 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 48 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 49 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 50 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 51 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 52 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 53 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 54 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 55 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 56 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 57 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 58 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 59 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 60 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 61 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 62 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 63 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 64 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 65 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 66 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 67 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 68 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 69 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 70 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 71 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 72 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 73 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 74 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 75 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 76 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 77 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 78 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 79 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 80 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 81 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 82 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 83 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 84 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 85 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 86 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 87 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 88 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 89 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 90 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 91 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 92 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 93 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 94 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 95 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 96 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 97 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 98 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 99 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 100 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 101 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 102 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 103 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 104 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 105 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 106 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 107 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 108 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 109 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 110 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 111 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 112 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 113 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 114 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 115 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 116 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 117 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 118 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 119 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 120 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 121 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 122 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 123 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 124 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 125 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 126 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 127 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 128 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 129 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 130 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 131 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 132 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 133 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 134 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 135 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 136 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 137 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 138 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 139 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 140 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 141 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 142 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 143 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 144 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 145 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 146 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 147 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 148 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 149 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 150 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + case 151 : + input.rewind(); + s = -1; + if ( (synpred55()) ) {s = 17;} + + else if ( (synpred56()) ) {s = 16;} + + else if ( (synpred57()) ) {s = 18;} + + else if ( (synpred58()) ) {s = 15;} + + else if ( (synpred59()) ) {s = 14;} + + else if ( (true) ) {s = 19;} + + if ( s>=0 ) return s; + break; + } + if (backtracking>0) {failed=true; return -1;} + NoViableAltException nvae = + new NoViableAltException(getDescription(), 23, _s, input); + error(nvae); + throw nvae; + } + } + + + public static final BitSet FOLLOW_11_in_program70 = new BitSet(new long[]{0x0000000000001000L}); + public static final BitSet FOLLOW_12_in_program72 = new BitSet(new long[]{0x0000000000442000L}); + public static final BitSet FOLLOW_globalDeclarations_in_program76 = new BitSet(new long[]{0x0000000000402000L}); + public static final BitSet FOLLOW_functionImplementations_in_program80 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_13_in_program82 = new BitSet(new long[]{0x0000000000004000L}); + public static final BitSet FOLLOW_14_in_program84 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_program86 = new BitSet(new long[]{0x0000000000412000L}); + public static final BitSet FOLLOW_formalParameters_in_program90 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_program92 = new BitSet(new long[]{0x0000000000800000L}); + public static final BitSet FOLLOW_block_in_program96 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_declaration_in_globalDeclarations124 = new BitSet(new long[]{0x0000000000442000L}); + public static final BitSet FOLLOW_globalDeclarations_in_globalDeclarations128 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_functionHeading_in_globalDeclarations141 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_globalDeclarations143 = new BitSet(new long[]{0x0000000000442000L}); + public static final BitSet FOLLOW_globalDeclarations_in_globalDeclarations147 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_declaration_in_declarations183 = new BitSet(new long[]{0x0000000000042000L}); + public static final BitSet FOLLOW_declarations_in_declarations187 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_18_in_declaration221 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_13_in_declaration223 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_constDeclarations_in_declaration227 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_declaration229 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_declaration240 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_varDeclarations_in_declaration244 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_declaration246 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_constDeclarations274 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_constDeclarations276 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_constDeclarations280 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_constDeclarations293 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_constDeclarations295 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_constDeclarations299 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_constDeclarations301 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_constDeclarations_in_constDeclarations305 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations336 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_varDeclarations347 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations351 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations364 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_varDeclarations366 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_varDeclarations370 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations383 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_varDeclarations385 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_varDeclarations_in_varDeclarations389 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_varDeclarations400 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations404 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_varDeclarations406 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_varDeclarations_in_varDeclarations410 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_varDeclarations423 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_varDeclarations425 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_varDeclarations429 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_varDeclarations431 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_varDeclarations_in_varDeclarations435 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_functionHeading_in_functionImplementations465 = new BitSet(new long[]{0x0000000000800000L}); + public static final BitSet FOLLOW_block_in_functionImplementations469 = new BitSet(new long[]{0x0000000000402000L}); + public static final BitSet FOLLOW_functionImplementations_in_functionImplementations473 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_22_in_functionHeading515 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_functionHeading519 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_functionHeading521 = new BitSet(new long[]{0x0000000000412000L}); + public static final BitSet FOLLOW_formalParameters_in_functionHeading525 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_functionHeading527 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_functionHeading538 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_functionHeading542 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_functionHeading544 = new BitSet(new long[]{0x0000000000412000L}); + public static final BitSet FOLLOW_formalParameters_in_functionHeading548 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_functionHeading550 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_22_in_formalParameters578 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_paramSections_in_formalParameters591 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_paramSections628 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_paramSections632 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_paramSections643 = new BitSet(new long[]{0x0000000000200000L}); + public static final BitSet FOLLOW_21_in_paramSections645 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_paramSections649 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_paramSections660 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_paramSections664 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_paramSections666 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_paramSections_in_paramSections670 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_13_in_paramSections681 = new BitSet(new long[]{0x0000000000200000L}); + public static final BitSet FOLLOW_21_in_paramSections683 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_paramSections687 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_paramSections689 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_paramSections_in_paramSections693 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_23_in_block721 = new BitSet(new long[]{0x00000027FFA42010L}); + public static final BitSet FOLLOW_declarations_in_block725 = new BitSet(new long[]{0x00000027FFA00010L}); + public static final BitSet FOLLOW_statementSequence_in_block729 = new BitSet(new long[]{0x0000000001000000L}); + public static final BitSet FOLLOW_24_in_block731 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_statement_in_statementSequence762 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statementSequence_in_statementSequence766 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_assignment_in_statement806 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement808 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_25_in_statement819 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement821 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_boolExpression_in_statement825 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement827 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_statement831 = new BitSet(new long[]{0x0000008000000002L}); + public static final BitSet FOLLOW_elseClause_in_statement835 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_26_in_statement846 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement848 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_statement852 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement854 = new BitSet(new long[]{0x0000000000800000L}); + public static final BitSet FOLLOW_switchBlock_in_statement858 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_27_in_statement869 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement871 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_boolExpression_in_statement875 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement877 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_statement881 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_28_in_statement892 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_statement896 = new BitSet(new long[]{0x0000000008000000L}); + public static final BitSet FOLLOW_27_in_statement898 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement900 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_boolExpression_in_statement904 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement906 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement908 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_29_in_statement919 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement921 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_assignment_in_statement925 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement927 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_boolExpression_in_statement931 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement933 = new BitSet(new long[]{0x0000000000200010L}); + public static final BitSet FOLLOW_assignment_in_statement937 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement939 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_statement943 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_30_in_statement954 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement956 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_31_in_statement968 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement970 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_23_in_statement982 = new BitSet(new long[]{0x00000027FFA42010L}); + public static final BitSet FOLLOW_declarations_in_statement986 = new BitSet(new long[]{0x00000027FFA00010L}); + public static final BitSet FOLLOW_statementSequence_in_statement990 = new BitSet(new long[]{0x0000000001000000L}); + public static final BitSet FOLLOW_24_in_statement992 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_functionCall_in_statement1005 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1007 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_32_in_statement1018 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1020 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_32_in_statement1031 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_statement1035 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1037 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_33_in_statement1049 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement1051 = new BitSet(new long[]{0x0000000000000040L}); + public static final BitSet FOLLOW_String_in_statement1055 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement1057 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1059 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_33_in_statement1067 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement1069 = new BitSet(new long[]{0x0000000000000040L}); + public static final BitSet FOLLOW_String_in_statement1073 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_statement1075 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expressionList_in_statement1079 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement1081 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1083 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_34_in_statement1094 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_statement1096 = new BitSet(new long[]{0x0000000800000000L}); + public static final BitSet FOLLOW_35_in_statement1098 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_statement1100 = new BitSet(new long[]{0x0000001000000000L}); + public static final BitSet FOLLOW_36_in_statement1102 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_statement1106 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_statement1108 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_statement1110 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_37_in_statement1121 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_statement1125 = new BitSet(new long[]{0x0000004000000000L}); + public static final BitSet FOLLOW_38_in_statement1127 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_39_in_elseClause1151 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_elseClause1155 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_assignment1195 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_assignment1197 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_assignment1201 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_assignment1212 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_assignment1216 = new BitSet(new long[]{0x0000000000080000L}); + public static final BitSet FOLLOW_19_in_assignment1218 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_assignment1222 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_23_in_switchBlock1250 = new BitSet(new long[]{0x0000040001000000L}); + public static final BitSet FOLLOW_caseSequence_in_switchBlock1254 = new BitSet(new long[]{0x0000000001000000L}); + public static final BitSet FOLLOW_24_in_switchBlock1256 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_23_in_switchBlock1267 = new BitSet(new long[]{0x0000050000000000L}); + public static final BitSet FOLLOW_caseSequence_in_switchBlock1271 = new BitSet(new long[]{0x0000010000000000L}); + public static final BitSet FOLLOW_40_in_switchBlock1273 = new BitSet(new long[]{0x0000020000000000L}); + public static final BitSet FOLLOW_41_in_switchBlock1275 = new BitSet(new long[]{0x00000027FFA00010L}); + public static final BitSet FOLLOW_statementSequence_in_switchBlock1279 = new BitSet(new long[]{0x0000000001000000L}); + public static final BitSet FOLLOW_24_in_switchBlock1281 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_42_in_caseSequence1309 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_Number_in_caseSequence1313 = new BitSet(new long[]{0x0000020000000000L}); + public static final BitSet FOLLOW_41_in_caseSequence1315 = new BitSet(new long[]{0x00000427FEA00010L}); + public static final BitSet FOLLOW_statementSequence_in_caseSequence1319 = new BitSet(new long[]{0x0000040000000000L}); + public static final BitSet FOLLOW_caseSequence_in_caseSequence1323 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Ident_in_functionCall1362 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_15_in_functionCall1364 = new BitSet(new long[]{0x0000181000218030L}); + public static final BitSet FOLLOW_actualParameters_in_functionCall1368 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_functionCall1370 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expressionList_in_actualParameters1400 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_expressionList1439 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_expressionList1452 = new BitSet(new long[]{0x0000000000100000L}); + public static final BitSet FOLLOW_20_in_expressionList1454 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expressionList_in_expressionList1458 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_firstTerm_in_expression1493 = new BitSet(new long[]{0x0000180000000002L}); + public static final BitSet FOLLOW_expression2_in_expression1506 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_43_in_expression21543 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_term_in_expression21547 = new BitSet(new long[]{0x0000180000000002L}); + public static final BitSet FOLLOW_44_in_expression21560 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_term_in_expression21564 = new BitSet(new long[]{0x0000180000000002L}); + public static final BitSet FOLLOW_factor_in_firstTerm1613 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_firstTerm2_in_firstTerm1626 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_43_in_firstTerm1639 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_firstTerm1642 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_firstTerm2_in_firstTerm1655 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_44_in_firstTerm1668 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_firstTerm1671 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_firstTerm2_in_firstTerm1684 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_firstTerm21721 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_firstTerm21725 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_45_in_firstTerm21738 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_firstTerm21742 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_46_in_firstTerm21755 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_firstTerm21759 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_factor_in_term1804 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_term2_in_term1817 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_term21854 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_term21858 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_45_in_term21871 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_term21875 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_46_in_term21888 = new BitSet(new long[]{0x0000001000208030L}); + public static final BitSet FOLLOW_factor_in_term21892 = new BitSet(new long[]{0x0000600000200002L}); + public static final BitSet FOLLOW_Ident_in_factor1932 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_21_in_factor1943 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_factor1947 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_36_in_factor1958 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_Ident_in_factor1962 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_Number_in_factor1975 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_functionCall_in_factor1988 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_15_in_factor1999 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_factor2003 = new BitSet(new long[]{0x0000000000010000L}); + public static final BitSet FOLLOW_16_in_factor2005 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2035 = new BitSet(new long[]{0x0000800000000000L}); + public static final BitSet FOLLOW_47_in_boolExpression2037 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2041 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2054 = new BitSet(new long[]{0x0001000000000000L}); + public static final BitSet FOLLOW_48_in_boolExpression2056 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2060 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2073 = new BitSet(new long[]{0x0002000000000000L}); + public static final BitSet FOLLOW_49_in_boolExpression2075 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2079 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2092 = new BitSet(new long[]{0x0004000000000000L}); + public static final BitSet FOLLOW_50_in_boolExpression2094 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2098 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2111 = new BitSet(new long[]{0x0008000000000000L}); + public static final BitSet FOLLOW_51_in_boolExpression2113 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2117 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_boolExpression2130 = new BitSet(new long[]{0x0010000000000000L}); + public static final BitSet FOLLOW_52_in_boolExpression2132 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_boolExpression2136 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_functionHeading_in_synpred2141 = new BitSet(new long[]{0x0000000000020000L}); + public static final BitSet FOLLOW_17_in_synpred2143 = new BitSet(new long[]{0x0000000000442002L}); + public static final BitSet FOLLOW_globalDeclarations_in_synpred2147 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_39_in_synpred341151 = new BitSet(new long[]{0x00000027FEA00010L}); + public static final BitSet FOLLOW_statement_in_synpred341155 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_23_in_synpred361250 = new BitSet(new long[]{0x0000040001000000L}); + public static final BitSet FOLLOW_caseSequence_in_synpred361254 = new BitSet(new long[]{0x0000000001000000L}); + public static final BitSet FOLLOW_24_in_synpred361256 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred391439 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred552035 = new BitSet(new long[]{0x0000800000000000L}); + public static final BitSet FOLLOW_47_in_synpred552037 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_synpred552041 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred562054 = new BitSet(new long[]{0x0001000000000000L}); + public static final BitSet FOLLOW_48_in_synpred562056 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_synpred562060 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred572073 = new BitSet(new long[]{0x0002000000000000L}); + public static final BitSet FOLLOW_49_in_synpred572075 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_synpred572079 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred582092 = new BitSet(new long[]{0x0004000000000000L}); + public static final BitSet FOLLOW_50_in_synpred582094 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_synpred582098 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_expression_in_synpred592111 = new BitSet(new long[]{0x0008000000000000L}); + public static final BitSet FOLLOW_51_in_synpred592113 = new BitSet(new long[]{0x0000181000208030L}); + public static final BitSet FOLLOW_expression_in_synpred592117 = new BitSet(new long[]{0x0000000000000002L}); + + private void throwException(Exception e, String pre) { + if (ignoreExceptions) { + System.err.print(pre); + return; + } + + throw new ParseException(e.toString()); + } +} \ No newline at end of file diff --git a/src/c00/parser/CVS/Entries b/src/c00/parser/CVS/Entries new file mode 100644 index 0000000..a14e552 --- /dev/null +++ b/src/c00/parser/CVS/Entries @@ -0,0 +1,3 @@ +/C00Lexer.java/1.2/Mon Aug 16 12:05:49 2010// +/C00Parser.java/1.3/Mon Aug 16 12:05:49 2010// +/ParseException.java/1.1/Wed Jan 16 17:50:53 2008/-ko/ diff --git a/src/c00/parser/CVS/Repository b/src/c00/parser/CVS/Repository new file mode 100644 index 0000000..513b357 --- /dev/null +++ b/src/c00/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/c00/parser diff --git a/src/c00/parser/CVS/Root b/src/c00/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/c00/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/c00/parser/ParseException.java b/src/c00/parser/ParseException.java new file mode 100644 index 0000000..51d09ee --- /dev/null +++ b/src/c00/parser/ParseException.java @@ -0,0 +1,7 @@ +package c00.parser; + +public class ParseException extends RuntimeException { + public ParseException(String message) { + super(message); + } +} diff --git a/src/org/CVS/Entries b/src/org/CVS/Entries new file mode 100644 index 0000000..9b8af53 --- /dev/null +++ b/src/org/CVS/Entries @@ -0,0 +1 @@ +D/jalgo//// diff --git a/src/org/CVS/Repository b/src/org/CVS/Repository new file mode 100644 index 0000000..72b23fe --- /dev/null +++ b/src/org/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org diff --git a/src/org/CVS/Root b/src/org/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/CVS/Entries b/src/org/jalgo/CVS/Entries new file mode 100644 index 0000000..f09dcc5 --- /dev/null +++ b/src/org/jalgo/CVS/Entries @@ -0,0 +1,3 @@ +D/main//// +D/module//// +D/tests//// diff --git a/src/org/jalgo/CVS/Repository b/src/org/jalgo/CVS/Repository new file mode 100644 index 0000000..e53274c --- /dev/null +++ b/src/org/jalgo/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo diff --git a/src/org/jalgo/CVS/Root b/src/org/jalgo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/main/AbstractModuleConnector.java b/src/org/jalgo/main/AbstractModuleConnector.java new file mode 100644 index 0000000..13a04c6 --- /dev/null +++ b/src/org/jalgo/main/AbstractModuleConnector.java @@ -0,0 +1,237 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on May 18, 2004 + */ +package org.jalgo.main; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * The class AbstractModuleConnector defines the module side + * interface between the j-Algo main program and a module to be implemented.
      + * This class contains methods for cooperation between the main program and the + * module. Some methods the module programmer has to override, so + * {@link #init()}, {@link #run()}, + * {@link #setDataFromFile(ByteArrayInputStream)}, {@link #getDataForFile()} + * and {@link #print()}, because they are module specific. Other methods the + * module programmer can implement, when there is the need for higher + * sophisticated semantics, such as {@link #close()}. Finally some methods must + * have well defined semantics and are therefore implemented in this class and + * declared with final.
      + * Because the constructor of a module instance is invoked automatically and in + * interaction with creation of module's GUI components by the main program, + * subclasses doesn't have to declare a constructor. Initialization of the GUI + * of the module has to be placed in the init method. Furthermore + * the GUI components for the module aren't available yet at the time of the + * constructor call. + * + * @author Alexander Claus, Michael Pradel, Christopher Friedrich, Stephan + * Creutz + */ +public abstract class AbstractModuleConnector { + + private SaveStatus saveStatus; + private boolean savingBlocked; + private String openFileName; + + /** + * Constructs an AbstractModuleConnector. + */ + public AbstractModuleConnector() { + saveStatus = SaveStatus.NOTHING_TO_SAVE; + } + + /** + * Modules have to override this method to initialize their GUI. + */ + public abstract void init(); + + /** + * After the module has been initialized using the constructor (and maybe + * some methods), this method will be invoked by the main program. It should + * contain the code to start the module. This method should return soon. + */ + public abstract void run(); + + /** + * If the user opens a file saved with the specific module, this method is + * called with an input stream backed by the file. So the module programmer + * has to care, how to read from the file. + * + * @param data an input stream with the file content in the format saved by + * the module + */ + public abstract void setDataFromFile(ByteArrayInputStream data); + + /** + * If user wants to save the current module data, this method is called. The + * module programmer has to prepare the interesting data and to provide it + * as output stream in a format, which can be deserialized too! + * + * @return an output stream with the interesting data of the module + */ + public abstract ByteArrayOutputStream getDataForFile(); + + /** + * Printing is currently not supported, this method is only present for + * compatibility. + */ + public abstract void print(); + + /** + * This method is called, when module or program are intended to be closed. + * Here final operations can be performed, before closing the module, or, if + * the module is currently not ready to be closed, this method can return + * false. When this method returns true, the + * user will be asked for saving his work (if there is something to save). + * Otherwise the closing of the module / program is ignored. + * + * @return true, if module is ready to be closed, + * false otherwise + */ + public boolean close() { + return true; + } + + /** + * Retrieves the singleton instance of the IModuleInfo + * corresponding to this module. + * + * @return the corresponding IModuleInfo + * + * @see IModuleInfo + */ + public final IModuleInfo getModuleInfo() { + try { + return (IModuleInfo)Class.forName( + getClass().getPackage().getName() + ".ModuleInfo").getMethod( + "getInstance", new Class[] {}).invoke(null, new Object[] {}); + } + catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + /** + * The enum type SaveStatus is used by modules to indicate if + * module content has changed or not. This status is evaluated to set the + * enabled status of the save buttons in the main program. + */ + public enum SaveStatus { + /** Indicates, that there is no file open or nothing to save */ + NOTHING_TO_SAVE, + /** Indicates, that the current file was saved recently */ + NO_CHANGES, + /** Indicates, that the current file is 'dirty' and has to be saved */ + CHANGES_TO_SAVE + } + + /** + * This method retrieves the save status of the module. This method is + * necessary for correctly working of the enabled button status of the save + * buttons and several features. + * + * @return one of the {@link SaveStatus} enum constants: + *

        + *
      • NOTHING_TO_SAVE
      • - if there is no file + * open + *
      • NO_CHANGES
      • - if the open file was saved + * recently + *
      • CHANGES_TO_SAVE
      • - if there are changes + * to save + *
      + */ + public final SaveStatus getSaveStatus() { + return saveStatus; + } + + /** + * This method is called from main program during a save action. Furthermore + * this method can be used by the module to set the save status centrally. + * + * @param status the new save status + * + * @see #getSaveStatus() + * @see SaveStatus + */ + public final void setSaveStatus(SaveStatus status) { + saveStatus = status; + if (status == SaveStatus.NOTHING_TO_SAVE) setOpenFileName(null); + else if (status == SaveStatus.CHANGES_TO_SAVE && openFileName == null) setOpenFileName(""); + JAlgoGUIConnector.getInstance().saveStatusChanged(this); + } + + /** + * This method can be called, if the save buttons should be disabled for a + * while, e.g. during a running algorithm. So can be guaranteed, that only + * consistent states of module contents can be saved. Ensure to deblock the + * save buttons !!! + * + * @param blocked true, if the save buttons should be + * blocked, false otherwise + * + * @see #isSavingBlocked() + */ + public final void setSavingBlocked(boolean blocked) { + savingBlocked = blocked; + JAlgoGUIConnector.getInstance().saveStatusChanged(this); + } + + /** + * Retrieves, if saving mechanism is blocked or not, e.g. during a running + * algorithm. + * + * @return true if saving mechanism is blocked, + * false otherwise + */ + public final boolean isSavingBlocked() { + return savingBlocked; + } + + /** + * Retrieves the file name of the currently opened file. This file name is + * shown on the title bar of the main program. + * + * @return the file name of the currently opened file + */ + public final String getOpenFileName() { + return openFileName; + } + + /** + * Sets the file name of the currently opened file. This method is called by + * the main program, when a file is opened or when a file is saved with a + * new name (save as). + * + * @param filename the file name of the currently opened file. + */ + public final void setOpenFileName(String filename) { + openFileName = filename; + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/CVS/Entries b/src/org/jalgo/main/CVS/Entries new file mode 100644 index 0000000..a3dfc6e --- /dev/null +++ b/src/org/jalgo/main/CVS/Entries @@ -0,0 +1,11 @@ +/AbstractModuleConnector.java/1.6/Thu Jan 31 20:15:02 2008// +/IModuleInfo.java/1.8/Thu Jan 31 20:15:02 2008// +/InternalErrorException.java/1.6/Thu Jan 31 20:15:02 2008// +/JAlgoMain.java/1.5/Thu Jan 31 20:15:02 2008/-kk/ +/de.properties/1.19/Mon Feb 18 20:52:37 2008// +/en.properties/1.11/Mon Feb 18 20:52:37 2008// +D/gfx//// +D/gui//// +/res.properties/1.6/Fri Aug 11 16:39:26 2006// +D/trees//// +D/util//// diff --git a/src/org/jalgo/main/CVS/Repository b/src/org/jalgo/main/CVS/Repository new file mode 100644 index 0000000..608901b --- /dev/null +++ b/src/org/jalgo/main/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/main diff --git a/src/org/jalgo/main/CVS/Root b/src/org/jalgo/main/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/main/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/main/IModuleInfo.java b/src/org/jalgo/main/IModuleInfo.java new file mode 100644 index 0000000..5feefb4 --- /dev/null +++ b/src/org/jalgo/main/IModuleInfo.java @@ -0,0 +1,107 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 24.06.2004 + */ + +package org.jalgo.main; + +import java.net.URL; + +/** + * The interface IModuleInfo contains methods to get some + * information about a module, which is shown on a module chooser dialog or in + * an about frame.
      + * The interface IModuleInfo has to be implemented by each module. + * As convention the implementing classes have to be named + * org.jalgo.module.<moduleName>.ModuleInfo. The main program + * will search for that class when loading the module. + * For better performance and for the reason, that the interesting information + * are unique for one module, the implementing classes of + * IModuleInfo have to be modelled as singleton. The main program + * will call the the method getInstance(), which has to retrieve + * the singleton instance of IModuleInfo + * + * @author Alexander Claus, Stephan Creutz + */ +public interface IModuleInfo { + + /** + * Retrieves the name of the module, which is shown on a module chooser + * dialog, on the tab of the module and as the menu-name of the module menu. + * + * @return the name of the module + */ + public String getName(); + + /** + * Retrieves the current build version number of the module as string. + * + * @return the version number of the module + */ + public String getVersion(); + + /** + * Retrieves a comma-separated list of the authors of the module. + * + * @return tha author(s) of the module + */ + public String getAuthor(); + + /** + * Retrieves a (more or less) short description about the module. It is + * shown on the module chooser inter alia. So it should give a short, but + * detailled information about the module. + * + * @return a string representing a description of the module + */ + public String getDescription(); + + /** + * Retrieves an URL object pointing to the logo image of the + * module. The image has to be sized to 16 x 16 pixels. It is shown on the + * tab of the module and in the new-Menu. Also this logo image is shown on + * the module chooser dialog, but later versions may provide two icons, one + * small icon for menu and tab and a big icon for the module chooser dialog. + * + * @return an URL to the logo of the module + */ + public URL getLogoURL(); + + /** + * Retrieves a string describing the license, the module is distributed with. + * + * @return the license + */ + public String getLicense(); + + /** + * Retrieves an URL object pointing to the HelpSet file of the module. + * The HelpSet file is the major metafile of the JavaHelp system. + * The URL must point to a *.hs-file. + * + * @return the HelpSet filename + */ + public URL getHelpSetURL(); +} \ No newline at end of file diff --git a/src/org/jalgo/main/InternalErrorException.java b/src/org/jalgo/main/InternalErrorException.java new file mode 100644 index 0000000..84724b4 --- /dev/null +++ b/src/org/jalgo/main/InternalErrorException.java @@ -0,0 +1,59 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 02.06.2004 + */ + +package org.jalgo.main; + +import java.io.FileWriter; +import java.io.IOException; +import java.util.Calendar; +import java.util.GregorianCalendar; + +/** + * @author Michael Pradel + * + */ +public class InternalErrorException extends IllegalArgumentException { + + private static final long serialVersionUID = 4550324443173141861L; + + public InternalErrorException(String s) { + FileWriter errorFile = null; + + try { + errorFile = new FileWriter("error.log", true); // append to file //$NON-NLS-1$ + Calendar calendar = new GregorianCalendar(); + errorFile.write(calendar.getTime() + ": " + s + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (IOException e) { + System.err.println(e); + } finally { + try { + if (errorFile != null) errorFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/org/jalgo/main/JAlgoMain.java b/src/org/jalgo/main/JAlgoMain.java new file mode 100644 index 0000000..896e1c2 --- /dev/null +++ b/src/org/jalgo/main/JAlgoMain.java @@ -0,0 +1,308 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 13.04.2004 + */ +package org.jalgo.main; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.util.LinkedList; +import java.util.List; +import java.util.MissingResourceException; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.JAlgoWindow; +import org.jalgo.main.util.ErrorLog; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.main.util.Storage; + +/** + * The class JAlgoMain is the entry point for the application. This + * class implements the Singleton design pattern. It handles the management of + * open module instances and provides useful methods for file handling. + * + * @author Alexander Claus, Christopher Friedrich, Michael Pradel + */ +public class JAlgoMain { + + /** The singleton instance of JAlgoMain */ + private static JAlgoMain instance; + /** The singleton instance of JAlgoWindow */ + private JAlgoWindow appWin; + + private List> knownModules; + private List knownModuleInfos; + private AbstractModuleConnector currentInstance; + + /** + * Constructs an object of JalgoMain. This constructor is + * declared as private to avoid access from outside this class. This + * mechanism is part of the Singleton design pattern. + */ + private JAlgoMain() { + addKnownModules(); + } + + /** + * Retrieves the singleton instance of this class. This method is part of + * the Singleton design pattern. + * + * @return the singleton instance of JalgoMain + */ + public static JAlgoMain getInstance() { + // here no test to null is necessary, because instance was created in main() + return instance; + } + + /** + * Initializes the GUI of j-Algo. Opens the main frame. + */ + public void createGUI() { + // init main frame + appWin = new JAlgoWindow(); + // init gui connector + JAlgoGUIConnector.initInstance(appWin); + } + + /** + * Creates a new instance of the module with the given name. + * Returns null, if the given name does not match to any known + * module name. + * + * @param moduleName the name of the module to be created + * + * @return the AbstractModuleConnector instance of the module, + * if it is created, null otherwise + */ + public AbstractModuleConnector newInstanceByName(String moduleName) { + for (int i=0; iknownModules + * starting with 0. + * @return the new instance of AbstractModuleConnector + */ + public AbstractModuleConnector newInstance(int modNumber) { + // hides current modules toolbar and menubar + if (currentInstance != null) + appWin.setCurrentInstanceVisible(false); + currentInstance = null; + + try { + currentInstance = knownModules.get(modNumber).newInstance(); + } + catch (Exception ex) {ex.printStackTrace();} + + appWin.createNewModuleGUIComponents(); + currentInstance.init(); + appWin.activateNewInstance(); + + currentInstance.run(); + appWin.updateTitle(); + + return currentInstance; + } + + /** + * Retrieves a list of the IModuleInfos of the registered + * modules. This list ist used for module choosing mechanisms and for + * opening j-Algo files. + * + * @return a list of all registered IModuleInfos + */ + public List getKnownModuleInfos() { + return knownModuleInfos; + } + + /** + * Retrieves the AbstractModuleConnector of the currently + * active module instance. + * + * @return the currently active module instance + */ + public AbstractModuleConnector getCurrentInstance() { + return currentInstance; + } + + /** + * Takes content from module and stores it in currently used file. If no + * file is currently used, a filechooser dialog is opened to select a file + * to be saved. + */ + public boolean saveFile() { + if (currentInstance == null) return false; + if (currentInstance.getOpenFileName() == null || + currentInstance.getOpenFileName().length() == 0) { + //if no name was given to current module content, open a filechooser + return (appWin.showSaveDialog(true) != null); + } + return saveFileAs(currentInstance.getOpenFileName()); + } + + /** + * Takes content from module and stores it in a file with the given filename. + * + * @param filename the path to the file to be saved + */ + public boolean saveFileAs(String filename) { + currentInstance.setOpenFileName(filename); + currentInstance.setSaveStatus(SaveStatus.NO_CHANGES); + return Storage.save(filename); + } + + /** + * Opens file and gives content to module instance. + * + * @param filename the path to the file to be opened + * @param useCurrentInstance true, if file content should be + * delegated to the currently active module instance, + * false, if a new module instance should be opened + */ + public boolean openFile(String filename, boolean useCurrentInstance) { + if ((useCurrentInstance && Storage.load(filename, currentInstance)) || + !useCurrentInstance && Storage.load(filename, null)) { + currentInstance.setOpenFileName(filename); + currentInstance.setSaveStatus(SaveStatus.NO_CHANGES); + return true; + } + return false; + } + + /** + * Searches the folder runtime/modules for jar files with modules. + * Fills knownModules and knownModuleInfos + * with the found modules and registers resource and settings bundles, if + * they are supported by the modules.
      + * For detailled description of writing and registering a module, read the + * developers manual available as pdf. + */ + @SuppressWarnings("unchecked") + private void addKnownModules() { + knownModules = new LinkedList>(); + knownModuleInfos = new LinkedList(); + + String jarFileName, moduleName; + String fileSep = System.getProperty("file.separator"); + for (File file : new File(System.getProperty("user.dir") + fileSep + + "runtime" + fileSep + "modules").listFiles()) { + jarFileName = file.getName(); + if (file.isFile() && + jarFileName.endsWith(".jar") && + !jarFileName.equals("jalgo.jar")) { + moduleName = jarFileName.substring(0, jarFileName.length()-4); + try { + Class moduleConnector = Class.forName("org.jalgo.module." + + moduleName + ".ModuleConnector"); + Class moduleInfo = Class.forName("org.jalgo.module." + + moduleName + ".ModuleInfo"); + + if (moduleConnector.getSuperclass().equals( + AbstractModuleConnector.class) && + implementsInterface(moduleInfo, + "org.jalgo.main.IModuleInfo")) { + knownModules.add(moduleConnector); + knownModuleInfos.add((IModuleInfo) + moduleInfo.getMethod("getInstance", new Class[] {}). + invoke(null, new Object[] {})); + } + + Messages.registerResourceBundle(moduleName, + "org.jalgo.module."+moduleName); + Settings.registerSettingsBundle(moduleName, + "/"+moduleName+".prefs"); + } + catch (ClassNotFoundException ex) {ex.printStackTrace();} + catch (IllegalAccessException ex) {ex.printStackTrace();} + catch (MissingResourceException ex) { + //do nothing, that means only, that the current module has + //no strings externalized + } + catch (IllegalArgumentException ex) {ex.printStackTrace();} + catch (SecurityException ex) {ex.printStackTrace();} + catch (InvocationTargetException ex) {ex.printStackTrace();} + catch (NoSuchMethodException ex) {ex.printStackTrace();} + } + } + } + + /** + * Checks if a given class implements a specific interface. + * + * @param classObj Class object which should checked + * @param interfaceName the name of the interface the class should implement + * + * @return true if the interface is implemented, + * false otherwise + */ + private boolean implementsInterface(Class classObj, String interfaceName) { + Class [] interfaces = classObj.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + if (interfaces[i].getName().equals(interfaceName)) return true; + } + return false; + } + + /** + * The entry point of the j-Algo main program.
      + * When releasing the product, start the program with the flag "errorLogOn". + * So an error log file could be created for easy debugging. + * + * @param args the program arguments + * + * @see ErrorLog + */ + public static void main(String[] args) { + //saves exceptions to file +/* ErrorLog errorLog = null; + if (args.length > 0 && args[0].equalsIgnoreCase("errorlogon")) + errorLog = new ErrorLog();*/ + + JAlgoWindow.createSplashScreen(); + instance = new JAlgoMain(); + instance.createGUI(); + +// if (errorLog != null) errorLog.close(); + } + + /** + * Sets the currently active module instance to the given instance of + * AbstractModuleConnector. This is only for intern management + * and does not influence the GUI!
      + * Selecting another module is handled by JalgoWindow. + * + * @param instance the new module instance + */ + public void setCurrentInstance(AbstractModuleConnector instance) { + currentInstance = instance; + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/de.properties b/src/org/jalgo/main/de.properties new file mode 100644 index 0000000..a249274 --- /dev/null +++ b/src/org/jalgo/main/de.properties @@ -0,0 +1,71 @@ +General.name=j-Algo +General.version=1.01 + +ui.About=Über j-Algo +ui.About_mnemonic=A +ui.About_tooltip=Erfahren Sie mehr über j-Algo +ui.About_module=Über das j-Algo-Modul +ui.About_module_mnemonic=M +ui.About_module_tooltip=Erfahren Sie mehr über das j-Algo-Modul +ui.Close=Schliessen +ui.Close_mnemonic=C +ui.Close_tooltip=Schliesst das aktuell geöffnete Modul. +ui.Exit=Beenden +ui.Exit_mnemonic=B +ui.File=Datei +ui.File_mnemonic=D +ui.Help=Hilfe +ui.Help_mnemonic=H +ui.Help_contents=Inhalt +ui.Help_contents_mnemonic=I +ui.Help_tooltip=Öffnet die Hilfe. +ui.New=Neu +ui.New_mnemonic=N +ui.New_tooltip=Zeigt eine Liste der installierten Module zum Öffnen an. +ui.Open_file=Datei öffnen +ui.Open_file_mnemonic=F +ui.Open_file_tooltip=Öffnet einen Dateiauswahldialog zum Laden einer Datei. +ui.Prefs=Einstellungen +ui.Prefs_mnemonic=E +ui.Save_file=Datei speichern +ui.Save_file_mnemonic=S +ui.Save_file_tooltip=Speichert die aktuelle Arbeit. +ui.Save_as=Speichern unter +ui.Save_as_mnemonic=U +ui.Save_as_tooltip=Öffnet einen Dateiauswahldialog zum Speichern der Daten. +ui.Untitled=Unbenannt +ui.Wish_to_save=Möchten Sie Ihre Arbeit speichern? + +DialogConstants.Cancel=Abbrechen +DialogConstants.Error=Fehler +DialogConstants.Info=Hinweis +DialogConstants.No=Nein +DialogConstants.Ok=Ok +DialogConstants.Question=Frage +DialogConstants.Warning=Achtung +DialogConstants.Yes=Ja + +About.Copyright=(c) Copyright j-Algo-Team 2004-2008. Alle Rechte vorbehalten. +About.URL=Besuchen Sie http://j-algo.binaervarianz.de +About.Authors=Autoren: +About.Author_Names=Malte Blumberg, Alexander Claus, Stephan Creutz, Christopher Friedrich, Cornelius Hald, Anne Kersten, Hauke Menges, Michael Pradel, Babett Schalitz, Matthias Schmidt, Benjamin Scholz, Marco Zimmerling +About.License=Lizenz: +About.GPL=GNU General Public License +AboutModule.Version=\ - Version + +JalgoWindow.No_second_instance=Es ist nicht erlaubt, eine zweite Instanz zu öffnen. +JalgoWindow.Application_terminates=Die Applikation wird beendet! +Storage.Could_not_open_file_4=Datei kann nicht geöffnet werden. +Storage.File_not_valid_5=Die Datei ist keine korrekte j-Algo-Datei. +Storage.Could_not_write_the_file._8=Datei konnte nicht geschrieben werden. +Storage.Maybe_out_of_diskspace_9=Vielleicht haben Sie versucht, auf ein read-only Medium zu schreiben oder die Speicherkapazität reicht nicht mehr aus. +Storage.Module_not_present=Das angeforderte j-Algo-Modul ist nicht installiert. + +Prefs.ShowSplashOnStartup=Logo beim Start anzeigen +Prefs.ShowModuleChooserOnStartup=Modulauswahldialog beim Start anzeigen +Prefs.Language=Sprache (Neustart erforderlich) +Prefs.Skin=Oberfläche (Neustart erforderlich): + +New.Title=Modulauswahl +New.ModuleList=Modulliste +New.info=Modulbeschreibung: \ No newline at end of file diff --git a/src/org/jalgo/main/en.properties b/src/org/jalgo/main/en.properties new file mode 100644 index 0000000..3689746 --- /dev/null +++ b/src/org/jalgo/main/en.properties @@ -0,0 +1,71 @@ +General.name=j-Algo +General.version=1.01 + +ui.About=About j-Algo +ui.About_mnemonic=A +ui.About_tooltip=Get more information about j-Algo +ui.About_module=About the j-Algo-module +ui.About_module_mnemonic=M +ui.About_module_tooltip=Get more information about the j-Algo-module +ui.Close=Close +ui.Close_mnemonic=C +ui.Close_tooltip=Closes the currently opened module +ui.Exit=Exit +ui.Exit_mnemonic=X +ui.File=File +ui.File_mnemonic=F +ui.Help=Help +ui.Help_mnemonic=H +ui.Help_contents=Contents +ui.Help_contents_mnemonic=C +ui.Help_tooltip=Opens the help browser. +ui.New=New +ui.New_mnemonic=N +ui.New_tooltip=Shows a list of all installed modules to choose one. +ui.Open_file=Open file +ui.Open_file_mnemonic=O +ui.Open_file_tooltip=Opens a file chooser dialog for opening a file. +ui.Prefs=Preferences +ui.Prefs_mnemonic=E +ui.Save_file=Save file +ui.Save_file_mnemonic=S +ui.Save_file_tooltip=Saves the current module data. +ui.Save_as=Save as +ui.Save_as_mnemonic=A +ui.Save_as_tooltip=Opens a file chooser dialog for saving a file. +ui.Untitled=Untitled +ui.Wish_to_save=Do you wish to save your work? + +DialogConstants.Cancel=Cancel +DialogConstants.Error=Error +DialogConstants.No=No +DialogConstants.Info=Info +DialogConstants.Ok=Ok +DialogConstants.Question=Question +DialogConstants.Warning=Warning +DialogConstants.Yes=Yes + +About.Copyright=(c) Copyright j-Algo-Team 2004-2008. All rights reserved. +About.URL=Visit http://j-algo.binaervarianz.de +About.Authors=Authors: +About.Author_Names=Malte Blumberg, Alexander Claus, Stephan Creutz, Christopher Friedrich, Cornelius Hald, Anne Kersten, Hauke Menges, Michael Pradel, Babett Schalitz, Matthias Schmidt, Benjamin Scholz, Marco Zimmerling +About.License=License: +About.GPL=GNU General Public License +AboutModule.Version=\ - Version + +JalgoWindow.No_second_instance=It is not allowed to open a 2nd instance. +JalgoWindow.Application_terminates=The application will terminate! +Storage.Could_not_open_file_4=The file could not be opened. +Storage.File_not_valid_5=The file is not a valid j-Algo-file. +Storage.Could_not_write_the_file._8=The file could not be saved. +Storage.Maybe_out_of_diskspace_9=Maybe write protection or out of diskspace. +Storage.Module_not_present=The requested j-Algo-module is not installed. + +Prefs.ShowSplashOnStartup=Show splash screen on startup +Prefs.ShowModuleChooserOnStartup=Show module chooser on startup +Prefs.Language=Language (Restart necessary) +Prefs.Skin=Skin (Restart necessary): + +New.Title=Module Choose Dialog +New.ModuleList=Module liste +New.info=Module information: \ No newline at end of file diff --git a/src/org/jalgo/main/gui/CVS/Entries b/src/org/jalgo/main/gui/CVS/Entries new file mode 100644 index 0000000..1de49df --- /dev/null +++ b/src/org/jalgo/main/gui/CVS/Entries @@ -0,0 +1,7 @@ +/DialogConstants.java/1.3/Fri Mar 24 15:52:34 2006// +/JAlgoGUIConnector.java/1.4/Sat Mar 4 13:36:19 2006// +/JAlgoWindow.java/1.6/Tue Feb 12 16:02:08 2008/-kk/ +D/actions//// +D/components//// +D/event//// +D/widgets//// diff --git a/src/org/jalgo/main/gui/CVS/Repository b/src/org/jalgo/main/gui/CVS/Repository new file mode 100644 index 0000000..ba38e97 --- /dev/null +++ b/src/org/jalgo/main/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/main/gui diff --git a/src/org/jalgo/main/gui/CVS/Root b/src/org/jalgo/main/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/main/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/main/gui/DialogConstants.java b/src/org/jalgo/main/gui/DialogConstants.java new file mode 100644 index 0000000..53d397a --- /dev/null +++ b/src/org/jalgo/main/gui/DialogConstants.java @@ -0,0 +1,63 @@ +package org.jalgo.main.gui; + +import javax.swing.JOptionPane; + +import org.jalgo.main.util.Messages; + +/** + * The class DialogConstants contains some constant values used in dialog boxes. + * + * @author Alexander Claus + */ +public class DialogConstants { + + /** Return value from class method if YES is chosen. */ + public static final int YES_OPTION = JOptionPane.YES_OPTION;//SWT:0; + /** Return value from class method if NO is chosen. */ + public static final int NO_OPTION = JOptionPane.NO_OPTION;//SWT:1; + /** Return value from class method if CANCEL is chosen. */ + public static final int CANCEL_OPTION = JOptionPane.CANCEL_OPTION;//SWT:2; + /** Return value from class method if OK is chosen. */ + public static final int OK_OPTION = JOptionPane.OK_OPTION;//SWT:0; + + /** Option type for confirm dialogs. */ + public static final int YES_NO_OPTION = JOptionPane.YES_NO_OPTION;//SWT:1; + /** Option type for confirm dialogs. */ + public static final int YES_NO_CANCEL_OPTION = JOptionPane.YES_NO_CANCEL_OPTION;//SWT:2; + /** Option type for confirm dialogs. */ + public static final int OK_CANCEL_OPTION = JOptionPane.OK_CANCEL_OPTION;//SWT:3; + + /** + * Retrieves an array of Strings containing the option strings for a dialog + * box. What strings are in the array is specified by the + * option parameter. + * + * @param optionType one of the following constants: + *
        + *
      • YES_NO_OPTION
      • + *
      • YES_NO_CANCEL_OPTION
      • + *
      • OK_CANCEL_OPTION
      • + *
      + * + * @return a String array containing the requested option strings + */ + public static String[] getOptionStrings(int optionType) { + switch (optionType) { + case YES_NO_OPTION: + return new String[] { + Messages.getString("main", "DialogConstants.Yes"), + Messages.getString("main", "DialogConstants.No")}; + case YES_NO_CANCEL_OPTION: + return new String[] { + Messages.getString("main", "DialogConstants.Yes"), + Messages.getString("main", "DialogConstants.No"), + Messages.getString("main", "DialogConstants.Cancel")}; + case OK_CANCEL_OPTION: + return new String[] { + Messages.getString("main", "DialogConstants.Ok"), + Messages.getString("main", "DialogConstants.Cancel")}; + default: + return null; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/gui/JAlgoGUIConnector.java b/src/org/jalgo/main/gui/JAlgoGUIConnector.java new file mode 100644 index 0000000..9baf085 --- /dev/null +++ b/src/org/jalgo/main/gui/JAlgoGUIConnector.java @@ -0,0 +1,231 @@ +package org.jalgo.main.gui; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.JAlgoMain; + +/** + * Class JAlgoGUIConnector represents the counterpart to the + * AbstractModuleConnector interface. It contains methods to use + * from module instances or several non-GUI parts of the program. So it provides + * a kind of encapsulation and helps to split strictly the main program from the + * modules.
      + * This class is realized in the Singleton design pattern, because of easy + * management and the reason, that there is only one GUI, to connect with...
      + * This class contains methods for displaying several message boxes, for + * managing the save-button-enable-status, and for setting the status message. + * Also this class contains access methods for the GUI components of the opened + * module instances, such as the main GUI component, the menu or the toolbar. + * + * @author Alexander Claus + */ +public class JAlgoGUIConnector { + + /** The singleton instance of JAlgoGUIConnector */ + private static JAlgoGUIConnector instance; + /** The singleton instance of JalgoWindow */ + private JAlgoWindow appWin; + + /** + * Constructs an object of JAlgoGUIConnector. This constructor + * is declared as private to avoid access from outside this class. This + * mechanism is part of the Singleton design pattern. + * + * @param appWin the singleton instance of JalgoWindow + */ + private JAlgoGUIConnector(JAlgoWindow appWin) { + this.appWin = appWin; + } + + /** + * Initializes the singleton instance of JAlgoGUIConnector. + * This approach has been choosen to manage the singleton instance of + * JalgoWindow.
      + * This method should called only once by JalgoMain !!! + * + * @param appWin the singleton instance of JalgoWindow + */ + public static void initInstance(JAlgoWindow appWin) { + instance = new JAlgoGUIConnector(appWin); + } + + /** + * Retrieves the singleton instance of this class. + * + * @return the singleton instance of JAlgoGUIConnector + */ + public static JAlgoGUIConnector getInstance() { + return instance; + } + + /** + * This method has to be called, if the save status of a module instance + * changes. It guarantees, that the enabled status of the save buttons are + * controlled in the right way and so get the well known semantics of "save" + * and "save as".
      + * A module, which save status changes, has to call this method with the + * current instance of its AbstractModuleConnector as + * argument. If the current active module instance is not the relating + * module instance, this method has no effect. + * + * @param moduleInstance the instance of the + * AbstractModuleConnector of the relating module + */ + public void saveStatusChanged(AbstractModuleConnector moduleInstance) { + if (JAlgoMain.getInstance().getCurrentInstance() != moduleInstance) return; + appWin.updateSaveButtonEnableStatus(); + appWin.updateTitle(); + } + + /** + * Opens an error message with the given message string. + * + * @param msg the message string + * + * @see JAlgoWindow#showErrorMessage(String) + */ + public void showErrorMessage(String msg) { + appWin.showErrorMessage(msg); + } + + /** + * Opens a warning message with the given message string. + * + * @param msg the message string + * + * @see JAlgoWindow#showWarningMessage(String) + */ + public void showWarningMessage(String msg) { + appWin.showWarningMessage(msg); + } + + /** + * Opens an info message box with the given message string. + * + * @param msg the message string + * + * @see JAlgoWindow#showInfoMessage(String) + */ + public void showInfoMessage(String msg) { + appWin.showInfoMessage(msg); + } + + /** + * Opens a confirm dialog with the given question string. The type of option + * buttons can be selected using the second argument. It can be one of the + * following constants defined in {@link org.jalgo.main.gui.DialogConstants}: + *
        + *
      • YES_NO_OPTION
      • + *
      • YES_NO_CANCEL_OPTION
      • + *
      • OK_CANCEL_OPTION
      • + *
      + * The return value indicates, which button the user pressed. It can be one + * of the constants defined in {@link org.jalgo.main.gui.DialogConstants}: + *
        + *
      • OK_OPTION
      • + *
      • YES_OPTION
      • + *
      • NO_OPTION
      • + *
      • CANCEL_OPTION
      • + *
      + * + * @param question the question string + * @param optionType the type of the option buttons to be displayed + * + * @return an integer designating the option selected by the user + * + * @see JAlgoWindow#showConfirmDialog(String, int) + */ + public int showConfirmDialog(String question, int optionType) { + return appWin.showConfirmDialog(question, optionType); + } + + /** + * Sets the message at the status line of the main program to the given + * message string. + * + * @param msg the message string + */ + public void setStatusMessage(String msg) { + appWin.setStatusMessage(msg); + } + + /** + * Opens a filechooser for opening files. The file selected by the user can + * be opened automatically as j-Algo file. When selected this option the + * second parameter specifies, if the selected file should be opened in the + * current instance of the module or if a new module instance should be + * opened.
      + * If the file should not be opened automatically, e.g. for using the file + * in other ways, the file name is returned as string. + * + * @param openAsJAlgoFile true, if the file should be opened + * as j-Algo file, false otherwise + * @param useCurrentModuleInstance true, if the file should + * be opened in current module instance, false + * otherwise + * + * @return the file name of the selected file, if the first parameter is set + * to false + * + * @see JAlgoWindow#showOpenDialog(boolean, boolean) + */ + public String showOpenDialog(boolean openAsJAlgoFile, + boolean useCurrentModuleInstance) { + return appWin.showOpenDialog(openAsJAlgoFile, useCurrentModuleInstance); + } + + /** + * Creates a new instance of the module with the given name. Returns + * null, if the given name does not match to any known + * module name. + * + * @param moduleName the name of the module to be created + * + * @return the AbstractModuleConnector instance of the + * module, if it is created, null otherwise + * + * @see JAlgoMain#newInstanceByName(String) + */ + public AbstractModuleConnector newModuleInstanceByName(String moduleName) { + return JAlgoMain.getInstance().newInstanceByName(moduleName); + } + + /** + * Retrieves the main GUI component of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the main GUI component of the module instance + */ + public JComponent getModuleComponent(AbstractModuleConnector module) { + return appWin.getModuleComponent(module); + } + + /** + * Retrieves the menu of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the menu of the module instance + */ + public JMenu getModuleMenu(AbstractModuleConnector module) { + return appWin.getModuleMenu(module); + } + + /** + * Retrieves the toolbar of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the toolbar of the module instance + */ + public JToolBar getModuleToolbar(AbstractModuleConnector module) { + return appWin.getModuleToolbar(module); + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/gui/JAlgoWindow.java b/src/org/jalgo/main/gui/JAlgoWindow.java new file mode 100644 index 0000000..0a5e2fe --- /dev/null +++ b/src/org/jalgo/main/gui/JAlgoWindow.java @@ -0,0 +1,747 @@ +package org.jalgo.main.gui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.MediaTracker; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowStateListener; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.Box; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; +import javax.swing.SwingConstants; +import javax.swing.UIManager; +import javax.swing.WindowConstants; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.filechooser.FileFilter; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.components.HelpSystem; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.gui.components.ModuleChooseDialog; +import org.jalgo.main.gui.event.JAlgoWindowActionHandler; +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * The class JAlgoWindow represents the main frame of the j-Algo + * main program. + * + * @author Alexander Claus + */ +public class JAlgoWindow +extends JFrame { + + private static final long serialVersionUID = -5392277576384049416L; + + /** The singleton instance of JalgoWindow */ + private static JAlgoWindow instance; + + private static Window splash; + private JPanel contentPane; + private JPanel toolbarPane; + private JLabel statusLine; + private JTabbedPane tabbedPane; + private JButton closeButton; + private JMenuItem closeMenuItem; + + private JMenuBar menubar; + private LinkedList newModuleMenuItems; + private JButton saveButton; + private JMenuItem saveMenuItem; + private JButton saveAsButton; + private JMenuItem saveAsMenuItem; + private JMenuItem aboutModuleMenuItem; + + private static JFileChooser openFileChooser; + private static JFileChooser saveFileChooser; + + private JAlgoWindowActionHandler action; + + //management of module gui compontents + private List openModuleInstances; + private HashMap moduleComponents; + private HashMap moduleMenus; + private HashMap moduleToolbars; + + public JAlgoWindow() { + super("j-Algo"); + + if (instance != null) { + System.err.println(Messages.getString( + "main", "JalgoWindow.No_second_instance")); //$NON-NLS-1$ //$NON-NLS-2$ + System.err.println(Messages.getString( + "main", "JalgoWindow.Application_terminates")); //$NON-NLS-1$ //$NON-NLS-2$ + System.exit(1); + } + + setSize(800, 600); + setLocation(100, 100); + if (Settings.getBoolean("main", "MaximizeWindowOnStartup")) + setExtendedState(MAXIMIZED_BOTH); + addWindowStateListener(new WindowStateListener() { + public void windowStateChanged(WindowEvent e) { + switch (e.getNewState()) { + case NORMAL: + Settings.setBoolean("main", "MaximizeWindowOnStartup", false); + break; + case MAXIMIZED_BOTH: + Settings.setBoolean("main", "MaximizeWindowOnStartup", true); + break; + } + } + }); + + setIconImage(Toolkit.getDefaultToolkit().createImage( + Messages.getResourceURL("main", "ui.Logo_small"))); + + String lafClassName = Settings.getString("main", "LookAndFeel"); + if (lafClassName == null || + ((lafClassName.equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")) && + (! System.getProperty("os.name").startsWith("Windows")))) { + Settings.setString("main", "LookAndFeel", + UIManager.getSystemLookAndFeelClassName()); + lafClassName = Settings.getString("main", "LookAndFeel"); + } + setLookAndFeel(lafClassName); + + action = new JAlgoWindowActionHandler(this); + setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @SuppressWarnings("synthetic-access") + public void windowClosing(WindowEvent arg0) { + handleCloseEvent(); + } + }); + + createLayout(); + + openModuleInstances = new ArrayList(); + moduleComponents = new HashMap(); + moduleMenus = new HashMap(); + moduleToolbars = new HashMap(); + + setVisible(true); + + instance = this; + + hideSplash(); + + if (Settings.getBoolean("main", "ShowModuleChooserOnStartup")) + EventQueue.invokeLater(new Runnable() { + @SuppressWarnings("synthetic-access") + public void run() { + ModuleChooseDialog.open(instance); + } + }); + } + + /*--------------------------gui building------------------------------*/ + private void createLayout() { + setLayout(new BorderLayout()); + contentPane = new JPanel(new BorderLayout()); + add(contentPane, BorderLayout.CENTER); + + installMenu(); + installToolbar(); + installStatusLine(); + installTabbedPane(); + } + + private void installMenu() { + menubar = new JMenuBar(); + + JMenu fileMenu = createMenu("ui.File"); + + createNewModuleMenuItems(); + JMenu newMenu = createMenu("ui.New"); + for (JMenuItem item : newModuleMenuItems) newMenu.add(item); + fileMenu.add(newMenu); + fileMenu.addSeparator(); + + JMenuItem openMenuItem = createMenuItem("ui.Open_file"); + openMenuItem.setAccelerator( + KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)); + fileMenu.add(openMenuItem); + + saveMenuItem = createMenuItem("ui.Save_file"); + saveMenuItem.setAccelerator( + KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); + saveMenuItem.setEnabled(false); + fileMenu.add(saveMenuItem); + + saveAsMenuItem = createMenuItem("ui.Save_as"); + saveAsMenuItem.setEnabled(false); + fileMenu.add(saveAsMenuItem); + + closeMenuItem = createMenuItem("ui.Close"); + closeMenuItem.setEnabled(false); + fileMenu.add(closeMenuItem); + fileMenu.addSeparator(); + + JMenuItem prefsMenuItem = createMenuItem("ui.Prefs"); + fileMenu.add(prefsMenuItem); + fileMenu.addSeparator(); + + JMenuItem exitMenuItem = createMenuItem("ui.Exit"); + fileMenu.add(exitMenuItem); + + menubar.add(fileMenu); + + JMenu helpMenu = createMenu("ui.Help"); + + JMenuItem helpContentsMenuItem = createMenuItem("ui.Help_contents"); + helpContentsMenuItem.setAccelerator( + KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); + helpMenu.add(helpContentsMenuItem); + helpMenu.addSeparator(); + + JMenuItem aboutMenuItem = createMenuItem("ui.About"); + helpMenu.add(aboutMenuItem); + + aboutModuleMenuItem = createMenuItem("ui.About_module"); + aboutModuleMenuItem.setEnabled(false); + helpMenu.add(aboutModuleMenuItem); + + menubar.add(helpMenu); + + setJMenuBar(menubar); + } + + + /** + * Creates the JMenuItem objects for each registered module. + * This objects are later displayed as menu items in the "New" menu. + */ + private void createNewModuleMenuItems() { + newModuleMenuItems = new LinkedList(); + JAlgoMain main = JAlgoMain.getInstance(); + JMenuItem current; + for (int i=0; ifalse, if the user presses + * CANCEL during this process, true otherwise. + * + * @return true, if module data are saved or if the user closes + * all dialogs normally, false, if the user presses + * CANCEL during saving + */ + private boolean showFinalSaveDialog(AbstractModuleConnector moduleInstance) { + if (moduleInstance.getSaveStatus() == SaveStatus.NO_CHANGES || + moduleInstance.getSaveStatus() == SaveStatus.NOTHING_TO_SAVE) + return true; + switch (showConfirmDialog(Messages.getString("main", "ui.Wish_to_save"), //$NON-NLS-1$ //$NON-NLS-2$ + DialogConstants.YES_NO_CANCEL_OPTION)) { + case DialogConstants.YES_OPTION: + return JAlgoMain.getInstance().saveFile(); + case DialogConstants.NO_OPTION: + return true; + case DialogConstants.CANCEL_OPTION: + return false; + default: + return false; + } + } + + private void tabSelected() { + int tabIndex = tabbedPane.getSelectedIndex(); + + if (tabIndex < 0) {System.out.println("JAlgoWindow.tabSelected(): tabIndex="+tabIndex); return;} + setCurrentInstanceVisible(false); + JAlgoMain.getInstance().setCurrentInstance( + openModuleInstances.get(tabIndex)); + setCurrentInstanceVisible(true); + updateTitle(); + } + + public boolean tabClosed() { + AbstractModuleConnector currentInstance = + JAlgoMain.getInstance().getCurrentInstance(); + if (!currentInstance.close() || + !showFinalSaveDialog(currentInstance)) return false; + + int tabIndex = tabbedPane.getSelectedIndex(); + setCurrentInstanceVisible(false); + ChangeListener tabbedPaneListener = tabbedPane.getChangeListeners()[0]; + tabbedPane.removeChangeListener(tabbedPaneListener); + tabbedPane.removeTabAt(openModuleInstances.indexOf(currentInstance)); + + moduleComponents.remove(currentInstance); + moduleMenus.remove(currentInstance); + moduleToolbars.remove(currentInstance); + openModuleInstances.remove(currentInstance); + + if (openModuleInstances.isEmpty()) { + closeButton.setVisible(false); + closeMenuItem.setEnabled(false); + aboutModuleMenuItem.setEnabled(false); + JAlgoMain.getInstance().setCurrentInstance(null); + updateSaveButtonEnableStatus(); + updateTitle(); + } + else { + tabbedPane.setSelectedIndex(Math.max(0, tabIndex-1)); + //JTabbedPane.setSelectedIndex() doesn't fire a change event! + // since ChangeListener is temporarily deactivated - AC + JAlgoMain.getInstance().setCurrentInstance( + openModuleInstances.get(tabbedPane.getSelectedIndex())); + setCurrentInstanceVisible(true); + updateTitle(); + } + tabbedPane.addChangeListener(tabbedPaneListener); + return true; + } + + /** + * Implements the standard behaviour of the title text of the main program. + * This means, that the save status and file name of the current work are + * shown and the currently opened module is mentioned. + */ + public void updateTitle() { + AbstractModuleConnector currentInstance = + JAlgoMain.getInstance().getCurrentInstance(); + StringBuffer title = new StringBuffer(); + if (currentInstance != null) { + if (currentInstance.getOpenFileName() != null) { + if (currentInstance.getOpenFileName().length() == 0) + title.append(Messages.getString("main", "ui.Untitled")); + else title.append(currentInstance.getOpenFileName()); + if (currentInstance.getSaveStatus() == + SaveStatus.CHANGES_TO_SAVE) title.append("* - "); + else title.append(" - "); + } + title.append(currentInstance.getModuleInfo().getName()); + title.append(" - "); + } + title.append(Messages.getString("main", "General.name")); //$NON-NLS-1$ //$NON-NLS-2$ + setTitle(title.toString()); + } + + public void showErrorMessage(String msg) { + JOptionPane.showOptionDialog(this, msg, + Messages.getString("main", "DialogConstants.Error"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, + DialogConstants.getOptionStrings(DialogConstants.OK_OPTION), null); + } + + public void showWarningMessage(String msg) { + JOptionPane.showOptionDialog(this, msg, + Messages.getString("main", "DialogConstants.Warning"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, + DialogConstants.getOptionStrings(DialogConstants.OK_OPTION), null); + } + + public void showInfoMessage(String msg) { + JOptionPane.showOptionDialog(this, msg, + Messages.getString("main", "DialogConstants.Info"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, + DialogConstants.getOptionStrings(DialogConstants.OK_OPTION), null); + } + + public int showConfirmDialog(String question, int optionType) { + return JOptionPane.showOptionDialog(this, question, + Messages.getString("main", "DialogConstants.Question"), //$NON-NLS-1$ //$NON-NLS-2$ + optionType, JOptionPane.QUESTION_MESSAGE, null, + DialogConstants.getOptionStrings(optionType), null); + } + + /** + * Sets the message at the status line to the given message string. + * + * @param msg the message string + */ + public void setStatusMessage(String msg) { + statusLine.setText(msg); + } + + public String showOpenDialog(boolean openAsJAlgoFile, + boolean useCurrentModuleInstance) { + if (openFileChooser == null) { + openFileChooser = new JFileChooser(System.getProperty("user.dir")); + openFileChooser.setFileFilter(new FileFilter() { + public String getDescription() { + return "j-Algo Dateien"; + } + public boolean accept(File f) { + if (f.isDirectory()) return true; + if (f.getName().toLowerCase().endsWith(".jalgo")) + return true; + return false; + } + }); + } + String fileName = null; + if (openFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) + try { + fileName = openFileChooser.getSelectedFile().getCanonicalPath(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + if (openAsJAlgoFile && fileName != null) + JAlgoMain.getInstance().openFile( + fileName, useCurrentModuleInstance); + return fileName; + } + + public String showSaveDialog(boolean saveAsJAlgoFile) { + if (saveFileChooser == null) { + saveFileChooser = new JFileChooser(System.getProperty("user.dir")); + saveFileChooser.setFileFilter(new FileFilter() { + public String getDescription() { + return "j-Algo Dateien"; + } + public boolean accept(File f) { + if (f.isDirectory()) return true; + if (f.getName().toLowerCase().endsWith(".jalgo")) + return true; + return false; + } + }); + } + String fileName = null; + if (saveFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) + try { + fileName = saveFileChooser.getSelectedFile().getCanonicalPath(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + if (saveAsJAlgoFile && fileName != null) { + if (!fileName.toLowerCase().endsWith(".jalgo")) + fileName = fileName.concat(".jalgo"); + if (!JAlgoMain.getInstance().saveFileAs(fileName)) fileName = null; + } + return fileName; + } + + /** + * Updates the enabled status of the buttons "Save" and "Save as" to provide + * correct semantics. The necessary information to do so is taken from the + * currently opened module instance. + */ + public void updateSaveButtonEnableStatus() { + AbstractModuleConnector currentInstance = + JAlgoMain.getInstance().getCurrentInstance(); + if (currentInstance == null || + currentInstance.isSavingBlocked()) { + saveMenuItem.setEnabled(false); + saveButton.setEnabled(false); + saveAsMenuItem.setEnabled(false); + saveAsButton.setEnabled(false); + } + else switch (currentInstance.getSaveStatus()) { + case NOTHING_TO_SAVE: + saveMenuItem.setEnabled(false); + saveButton.setEnabled(false); + saveAsMenuItem.setEnabled(false); + saveAsButton.setEnabled(false); + break; + case NO_CHANGES: + saveMenuItem.setEnabled(false); + saveButton.setEnabled(false); + saveAsMenuItem.setEnabled(true); + saveAsButton.setEnabled(true); + break; + case CHANGES_TO_SAVE: + saveMenuItem.setEnabled(true); + saveButton.setEnabled(true); + saveAsMenuItem.setEnabled(true); + saveAsButton.setEnabled(true); + break; + } + } + + /*--------------Management of module's GUI components---------------*/ + + /** + * Retrieves the main GUI component of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the main GUI component of the module instance + */ + protected JComponent getModuleComponent(AbstractModuleConnector module) { + return moduleComponents.get(module); + } + + /** + * Retrieves the menu of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the menu of the module instance + */ + protected JMenu getModuleMenu(AbstractModuleConnector module) { + return moduleMenus.get(module); + } + + /** + * Retrieves the toolbar of the module instance, having the given + * AbstractModuleConnector. + * + * @param module the AbstractModuleConnector instance of module + * + * @return the toolbar of the module instance + */ + protected JToolBar getModuleToolbar(AbstractModuleConnector module) { + return moduleToolbars.get(module); + } + + public void setCurrentInstanceVisible(boolean visible) { + AbstractModuleConnector currentInstance = + JAlgoMain.getInstance().getCurrentInstance(); + + if (getModuleMenu(currentInstance).isEnabled()) + getModuleMenu(currentInstance).setVisible(visible); + if (getModuleToolbar(currentInstance).isEnabled()) + getModuleToolbar(currentInstance).setVisible(visible); + if (visible) updateSaveButtonEnableStatus(); + } + + public void activateNewInstance() { + // Set tab selected + tabbedPane.setSelectedComponent(moduleComponents.get( + JAlgoMain.getInstance().getCurrentInstance())); + // Set module visible + setCurrentInstanceVisible(true); + // Enable 'About module' + aboutModuleMenuItem.setEnabled(true); + // Enable 'Close' + closeButton.setVisible(true); + closeMenuItem.setEnabled(true); + } + + public void createNewModuleGUIComponents() { + AbstractModuleConnector module = + JAlgoMain.getInstance().getCurrentInstance(); + + JMenu moduleMenu = new JMenu(module.getModuleInfo().getName()); + moduleMenus.put(module, moduleMenu); + moduleMenu.setVisible(false); + menubar.add(moduleMenu, 1); + + JToolBar moduleToolbar = new JToolBar(); + moduleToolbars.put(module, moduleToolbar); + moduleToolbar.setFloatable(false); + moduleToolbar.setVisible(false); + toolbarPane.add(moduleToolbar, 1); + + moduleComponents.put(module, new JPanel(new BorderLayout())); + + ChangeListener tabbedPaneListener = tabbedPane.getChangeListeners()[0]; + tabbedPane.removeChangeListener(tabbedPaneListener); + tabbedPane.addTab( + module.getModuleInfo().getName(), + new ImageIcon(module.getModuleInfo().getLogoURL()), + moduleComponents.get(module)); + tabbedPane.addChangeListener(tabbedPaneListener); + + openModuleInstances.add(module); + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/gui/components/AboutFrame.java b/src/org/jalgo/main/gui/components/AboutFrame.java new file mode 100644 index 0000000..ef1c673 --- /dev/null +++ b/src/org/jalgo/main/gui/components/AboutFrame.java @@ -0,0 +1,105 @@ +package org.jalgo.main.gui.components; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingConstants; +import javax.swing.border.EmptyBorder; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.util.Messages; + +/** + * The class AboutFrame represents an "About" - frame for a short + * information about j-Algo and its modules. It contains also a logo image.
      + * This class has two class methods, which open the requested frame. Internally + * a singleton instance of AboutFrame is managed for better + * performance. + * + * @author Alexander Claus + */ +public class AboutFrame +extends JDialog { + + private static final long serialVersionUID = -4496899775387570794L; + private static AboutFrame instance; + private JLabel contentLabel; + + private AboutFrame(JFrame parent) { + super(parent, "", true); + setAlwaysOnTop(true); + + setLayout(new BorderLayout()); + + JLabel imageLabel = new JLabel(new ImageIcon( + Messages.getResourceURL("main", "About.header"))); //$NON-NLS-1$ //$NON-NLS-2$ + add("North", imageLabel); + + JButton okButton = new JButton("OK"); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + setVisible(false); + } + }); + JPanel southPane = new JPanel(new FlowLayout(FlowLayout.CENTER)); + southPane.add(okButton); + add("South", southPane); + + contentLabel = new JLabel("", SwingConstants.CENTER); + // the following is for optimizing layout under linux, otherwise + // some of the text does not fit into dialog + contentLabel.setFont(new Font( + contentLabel.getFont().getName(), + contentLabel.getFont().getStyle(), + 11)); + contentLabel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createCompoundBorder( + new EmptyBorder(5, 5, 5, 5), + new EtchedBorder()), + new EmptyBorder(5, 5, 5, 5))); + add("Center", contentLabel); + } + + /** + * Opens an "About" - frame for the currently opened module instance. + * + * @param parent the JAlgoWindow instance + */ + public static void openAboutModuleFrame(JFrame parent) { + openAboutFrame(parent, Messages.getString("main", "ui.About_module") + //$NON-NLS-1$ //$NON-NLS-2$ + " \"" + //$NON-NLS-1$ + JAlgoMain.getInstance().getCurrentInstance().getModuleInfo().getName() + + "\"", Messages.getModuleInfoAsHTML(-1)); + } + + /** + * Opens an "About" - frame for general informations about j-Algo. + * + * @param parent the JAlgoWindow instance + */ + public static void openAboutJAlgoFrame(JFrame parent) { + openAboutFrame(parent, Messages.getString("main", "ui.About"), //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getJAlgoInfoAsHTML()); + } + + private synchronized static void openAboutFrame(JFrame parent, + String title, String contentLabelText) { + if (instance == null) instance = new AboutFrame(parent); + instance.setSize(558, 320); + instance.setLocationRelativeTo(parent); + instance.setTitle(title); + instance.contentLabel.setText(contentLabelText); + instance.setVisible(true); + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/gui/components/CVS/Entries b/src/org/jalgo/main/gui/components/CVS/Entries new file mode 100644 index 0000000..146d2af --- /dev/null +++ b/src/org/jalgo/main/gui/components/CVS/Entries @@ -0,0 +1,5 @@ +/AboutFrame.java/1.3/Mon Mar 27 10:29:14 2006/-kk/ +/HelpSystem.java/1.7/Thu Jan 31 20:15:07 2008// +/JToolbarButton.java/1.4/Mon Mar 27 10:29:14 2006/-kk/ +/ModuleChooseDialog.java/1.9/Mon Oct 16 16:52:29 2006// +/PreferencesDialog.java/1.5/Mon Mar 27 10:29:14 2006/-kk/ diff --git a/src/org/jalgo/main/gui/components/CVS/Repository b/src/org/jalgo/main/gui/components/CVS/Repository new file mode 100644 index 0000000..1ade606 --- /dev/null +++ b/src/org/jalgo/main/gui/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/main/gui/components diff --git a/src/org/jalgo/main/gui/components/CVS/Root b/src/org/jalgo/main/gui/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/main/gui/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/main/gui/components/HelpSystem.java b/src/org/jalgo/main/gui/components/HelpSystem.java new file mode 100644 index 0000000..e84aab6 --- /dev/null +++ b/src/org/jalgo/main/gui/components/HelpSystem.java @@ -0,0 +1,88 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Feb 15, 2006 + */ +package org.jalgo.main.gui.components; + +import java.awt.event.ActionListener; +import java.net.URL; +import java.util.List; + +import javax.help.CSH; +import javax.help.HelpBroker; +import javax.help.HelpSet; +import javax.help.HelpSetException; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.util.Messages; + +/** + * + * @author Matthias Schmidt + */ +public class HelpSystem { + + private List knownModuleInfos; + + public HelpSystem() { + knownModuleInfos = JAlgoMain.getInstance().getKnownModuleInfos(); + } + + /** + * Retrieves an JavaHelp specific ActionListener which launches the JavaHelpDialog. + * @return an ActionListener + */ + public ActionListener getJavaHelpActionListener() { + + //Initialise the HelpSet with the help data from JAlgoMain + HelpSet mainHS = getHSByURL(Messages.getResourceURL("main", "Main_HelpSet")); + + //Merge the Module HelpSets + URL path = null; + + for (IModuleInfo element : knownModuleInfos) { + path = element.getHelpSetURL(); + if (path == null) + System.out.println("HelpSetURL from " + element.getName() + " is null!"); + else mainHS.add(getHSByURL(path)); + } + + //Create a HelpBroker object + HelpBroker hb = mainHS.createHelpBroker(); + + return new CSH.DisplayHelpFromSource(hb); + } + + private HelpSet getHSByURL(URL path) { + try { + return new HelpSet(null, path); + } catch (HelpSetException ee) { + //Say what the exception really is + System.err.println("HelpSet " + ee.getMessage()); + } + return null; + } +} diff --git a/src/org/jalgo/main/gui/components/JToolbarButton.java b/src/org/jalgo/main/gui/components/JToolbarButton.java new file mode 100644 index 0000000..593691f --- /dev/null +++ b/src/org/jalgo/main/gui/components/JToolbarButton.java @@ -0,0 +1,85 @@ +package org.jalgo.main.gui.components; + +import java.awt.Color; +import java.awt.SystemColor; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.border.BevelBorder; +import javax.swing.border.Border; +import javax.swing.border.EmptyBorder; + +/** + * This class defines a JButton, which is specialized for + * JToolbars. This means, that the standard JButton + * has a border, which is not appropriate for creating nice toolbars ;o) + * Furthermore the native look&feel doesn't support the rollover mechanism. + * + * @author Alexander Claus + */ +public class JToolbarButton +extends JButton { + + private static final long serialVersionUID = 1764614541666747667L; + static Border oneLineRaisedBevelBorder = + BorderFactory.createBevelBorder( + BevelBorder.RAISED, Color.white, SystemColor.control, + Color.gray, SystemColor.control); + static Border oneLineLoweredBevelBorder = + BorderFactory.createBevelBorder( + BevelBorder.LOWERED, Color.white, SystemColor.control, + Color.gray, SystemColor.control); + static Border emptyBorder = new EmptyBorder(2, 2, 2, 2); + + RolloverHandler rolloverHandler; + + public JToolbarButton(Icon icon, String tooltipText, String actionCommand) { + super(icon); + setBorder(emptyBorder); + setActionCommand(actionCommand); + setToolTipText(tooltipText); + //implementation of the standard rollover behaviour + rolloverHandler = new RolloverHandler(); + if (isEnabled()) addMouseListener(rolloverHandler); + addPropertyChangeListener("enabled", new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + if ((Boolean)evt.getNewValue()) addMouseListener(rolloverHandler); + else { + removeMouseListener(rolloverHandler); + setBorder(emptyBorder); + } + } + }); + } + + private class RolloverHandler + extends MouseAdapter { + boolean mouseOver = false; + boolean mouseDown = false; + public void mouseExited(MouseEvent e) { + mouseOver = false; + setBorder(emptyBorder); + } + public void mouseEntered(MouseEvent e) { + mouseOver = true; + if (mouseDown) setBorder(oneLineLoweredBevelBorder); + else setBorder(oneLineRaisedBevelBorder); + } + public void mousePressed(MouseEvent e) { + mouseDown = true; + setBorder(oneLineLoweredBevelBorder); + } + public void mouseReleased(MouseEvent e) { + mouseDown = false; + //check for isEnabled here, because, sometimes a click on a button + //disables the button + if (mouseOver && isEnabled()) setBorder(oneLineRaisedBevelBorder); + else setBorder(emptyBorder); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/gui/components/ModuleChooseDialog.java b/src/org/jalgo/main/gui/components/ModuleChooseDialog.java new file mode 100644 index 0000000..933d402 --- /dev/null +++ b/src/org/jalgo/main/gui/components/ModuleChooseDialog.java @@ -0,0 +1,265 @@ +package org.jalgo.main.gui.components; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Iterator; +import java.util.List; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingConstants; +import javax.swing.border.EmptyBorder; +import javax.swing.border.EtchedBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.gui.JAlgoWindow; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * The dialog to open a new module. + * @author Matthias Schmidt + */ +public class ModuleChooseDialog +extends JDialog { + + private static final long serialVersionUID = -4607723819515165988L; + private JAlgoWindow appWin; + private static ModuleChooseDialog instance; + + private JLabel contentLabel; + private JList moduleList; + private JButton okButton; + private JCheckBox mcdOnStartup; + + private ModuleChooseDialog(JFrame parent) { + super(parent, Messages.getString("main", "New.Title"), true); + + if (!(parent instanceof JAlgoWindow)) + System.err.println("The ModuleChooseDialog needs to be opened by the JAlgoWindow."); + else appWin = (JAlgoWindow) parent; + + int space = 5; + + setLayout(new BorderLayout()); + + JPanel overlayPane = new JPanel(); + overlayPane.setLayout(new BorderLayout()); + + JPanel westPane = new JPanel(); + westPane.setLayout(new BoxLayout(westPane, BoxLayout.Y_AXIS)); + + JLabel listLabel = new JLabel(Messages.getString("main", "New.ModuleList")); + listLabel.setAlignmentX(Component.RIGHT_ALIGNMENT); + westPane.add(Box.createVerticalStrut(space)); + westPane.add(listLabel); + + moduleList = new JList(getModuleList()); + moduleList.setCellRenderer(new MyCellRenderer()); + moduleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + moduleList.addListSelectionListener(new ListSelectionListener() { + @SuppressWarnings("synthetic-access") + public void valueChanged(ListSelectionEvent e) { + updateInfo(moduleList.getSelectedIndex()); + okButton.setEnabled(true); + } + }); + moduleList.addMouseListener(new MouseAdapter() { + @SuppressWarnings("synthetic-access") + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) moduleSelected(); + } + }); + moduleList.addKeyListener(new KeyAdapter() { + @SuppressWarnings("synthetic-access") + public void keyTyped(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) moduleSelected(); + } + }); + + + JScrollPane listScrollPane = new JScrollPane(moduleList, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + westPane.add(listScrollPane); + westPane.add(Box.createVerticalStrut(space)); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new GridLayout(3,1)); + //ok-button + okButton = new JButton(Messages.getString("main", "DialogConstants.Ok")); + okButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + moduleSelected(); + } + }); + okButton.setEnabled(false); + okButton.setAlignmentX(Component.LEFT_ALIGNMENT); + //open-button + JButton openButton = new JButton(Messages.getString("main", "ui.Open_file")); + openButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + dispose(); + appWin.showOpenDialog(true, false); + } + }); + openButton.setAlignmentX(Component.LEFT_ALIGNMENT); + //cancel-button + JButton cancelButton = new JButton(Messages.getString("main", "DialogConstants.Cancel")); + cancelButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + dispose(); + } + }); + cancelButton.setAlignmentX(Component.LEFT_ALIGNMENT); + cancelButton.setFocusCycleRoot(true); + + buttonPane.add(okButton); + buttonPane.add(openButton); + buttonPane.add(cancelButton); + westPane.add(buttonPane); + overlayPane.add(westPane,BorderLayout.WEST); + + contentLabel = new JLabel("", SwingConstants.CENTER); + // the following is for optimizing layout under linux, otherwise + // some of the text does not fit into dialog + contentLabel.setFont(new Font(contentLabel.getFont().getName(),contentLabel.getFont().getStyle(), 11)); + contentLabel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createCompoundBorder( + new EmptyBorder(5, 5, 0, 5), + new EtchedBorder()), + new EmptyBorder(5, 5, 5, 5))); + contentLabel.setText(Messages.getJAlgoInfoAsHTML()); + + overlayPane.add(contentLabel, BorderLayout.CENTER); + + mcdOnStartup = new JCheckBox( + Messages.getString("main", "Prefs.ShowModuleChooserOnStartup")); + mcdOnStartup.setAlignmentX(Component.LEFT_ALIGNMENT); + + mcdOnStartup.addActionListener(new ActionListener(){ + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + Settings.setBoolean("main", "ShowModuleChooserOnStartup", + mcdOnStartup.isSelected()); + } + }); + overlayPane.add(mcdOnStartup, BorderLayout.SOUTH); + + overlayPane.setBorder(new EmptyBorder(0,5,0,0)); + + add(overlayPane, BorderLayout.CENTER); + pack(); + setLocationRelativeTo(parent); + } + + /** + * Starts a new module out of the moduleList. + */ + private void moduleSelected() { + if (! moduleList.isSelectionEmpty()){ + dispose(); + JAlgoMain.getInstance().newInstance(moduleList.getSelectedIndex()); + } + } + + public synchronized static void open(JFrame parent) { + if (instance == null) instance = new ModuleChooseDialog(parent); + instance.setSize(430, 330); + instance.setLocationRelativeTo(parent); + instance.mcdOnStartup.setSelected(Settings.getBoolean("main", "ShowModuleChooserOnStartup")); + instance.setVisible(true); + } + + /** + * Retrieves a String array filled with the installed modules. + * @return module list + */ + private static String[] getModuleList() { + String[] back = new String[JAlgoMain.getInstance().getKnownModuleInfos().size()]; + int index = 0; + Iterator it = JAlgoMain.getInstance().getKnownModuleInfos().iterator(); + + while(it.hasNext()) { + back[index] = it.next().getName(); + index++; + } + return back; + } + + /** + * Updates the InfoPane when a new module is choosen. + * @param index of the choosen module + */ + private static void updateInfo(int index) { + instance.contentLabel.removeAll(); + instance.contentLabel.setText(Messages.getModuleInfoAsHTML(index)); + //contentLabel.updateUI(); + } + + + /** + * A special ListCellRenderer to add images in the moduleList. + * @author Matthias Schmidt + */ + class MyCellRenderer extends JLabel implements ListCellRenderer { + private List knownModules; + + public MyCellRenderer() { + setOpaque(true); + knownModules = JAlgoMain.getInstance().getKnownModuleInfos(); + } + public Component getListCellRendererComponent( + JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + setText(value.toString()); + setBackground(isSelected ? Color.blue : Color.white); + setForeground(isSelected ? Color.white : Color.black); + setIcon(getIconForValue(value)); + setBorder(new EmptyBorder(2,2,2,0)); + return this; + } + + // Retrieves to module specific Icon for the JList entry. + private Icon getIconForValue(Object value){ + for (IModuleInfo element : knownModules) { + if (element.getName().equals(value)) + return new ImageIcon(element.getLogoURL()); + } + return null; + } + } +} diff --git a/src/org/jalgo/main/gui/components/PreferencesDialog.java b/src/org/jalgo/main/gui/components/PreferencesDialog.java new file mode 100644 index 0000000..1dfc49a --- /dev/null +++ b/src/org/jalgo/main/gui/components/PreferencesDialog.java @@ -0,0 +1,255 @@ +package org.jalgo.main.gui.components; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; +import java.beans.PropertyVetoException; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; +import javax.swing.ScrollPaneConstants; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import org.jalgo.main.gui.JAlgoWindow; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * This class represents the preferences dialog of j-Algo. It holds some + * checkboxes and such stuff for relevant persistent settings.
      + * For performance improvement, this class implements the singleton design + * pattern. + * + * @author Alexander Claus + */ +public class PreferencesDialog +extends JDialog { + + private static final long serialVersionUID = -6396848149904196575L; + private static PreferencesDialog instance; + private JCheckBox showSplash; + private JCheckBox showModuleChooser; + private JComboBox language; + private JPanel previewPane; + private JList lafList; + private JComponent[] prevFrames; + private static LookAndFeelInfo[] installedLAFs; + + private PreferencesDialog(JFrame parent) { + super(parent, Messages.getString("main", "ui.Prefs"), true); + setModal(true); + + setLayout(new BorderLayout()); + JPanel centerPane = new JPanel(); + centerPane.setLayout(new BoxLayout(centerPane, BoxLayout.PAGE_AXIS)); + + showSplash = new JCheckBox( + Messages.getString("main", "Prefs.ShowSplashOnStartup")); + showSplash.setAlignmentX(Component.LEFT_ALIGNMENT); + centerPane.add(showSplash); + + showModuleChooser = new JCheckBox( + Messages.getString("main", "Prefs.ShowModuleChooserOnStartup")); + showModuleChooser.setAlignmentX(Component.LEFT_ALIGNMENT); + centerPane.add(showModuleChooser); + add(centerPane, BorderLayout.CENTER); + + JPanel langPane = new JPanel(); + langPane.setLayout(new BoxLayout(langPane, BoxLayout.LINE_AXIS)); + langPane.setBorder(new EmptyBorder(4,4,2,4)); + language = new JComboBox(getAvailableLanguages()); + langPane.add(language); + langPane.add(Box.createHorizontalStrut(5)); + JLabel langLabel = new JLabel( + Messages.getString("main", "Prefs.Language")); + langPane.add(langLabel); + langPane.setAlignmentX(Component.LEFT_ALIGNMENT); + centerPane.add(langPane); + centerPane.add(Box.createVerticalStrut(5)); + + JLabel lafLabel = new JLabel(Messages.getString("main", "Prefs.Skin")); + lafLabel.setBorder(new EmptyBorder(2,4,0,0)); + lafLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + centerPane.add(lafLabel); + centerPane.add(Box.createVerticalStrut(5)); + JPanel lafPane = new JPanel(); + lafPane.setLayout(new BoxLayout(lafPane, BoxLayout.LINE_AXIS)); + lafPane.setBorder(new EmptyBorder(0,4,0,2)); + lafList = new JList(getAvailableLookAndFeelNames()); + lafList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + lafList.addListSelectionListener(new ListSelectionListener() { + @SuppressWarnings("synthetic-access") + public void valueChanged(ListSelectionEvent e) { + previewPane.removeAll(); + previewPane.add(prevFrames[lafList.getSelectedIndex()]); + previewPane.updateUI(); + } + }); + JScrollPane lafScrollPane = new JScrollPane(lafList, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + lafPane.add(lafScrollPane); + + previewPane = new JPanel(); + previewPane.setPreferredSize(new Dimension(120, 120)); + lafPane.add(previewPane); + lafPane.setAlignmentX(Component.LEFT_ALIGNMENT); + centerPane.add(lafPane); + prevFrames = buildPreviews(); + + JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + JButton okButton = new JButton( + Messages.getString("main", "DialogConstants.Ok")); + okButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + Settings.setBoolean("main", "ShowSplashOnStartup", + showSplash.isSelected()); + Settings.setBoolean("main", "ShowModuleChooserOnStartup", + showModuleChooser.isSelected()); + Settings.setString("main", "Language", Messages.getString("main_res", + "Available_languages.short").split(",") + [language.getSelectedIndex()]); + dispose(); + Settings.setString("main", "LookAndFeel", + installedLAFs[lafList.getSelectedIndex()].getClassName()); + } + }); + JButton cancelButton = new JButton( + Messages.getString("main", "DialogConstants.Cancel")); + cancelButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + dispose(); + } + }); + buttonPane.add(okButton); + buttonPane.add(cancelButton); + add(buttonPane, BorderLayout.SOUTH); + + pack(); + setLocationRelativeTo(parent); + } + + /** + * Opens the preferences dialog and updates the control elements with the + * saved settings. + * + * @param parent the j-Algo main frame for constructing the dialog + */ + public static void open(JFrame parent) { + if (instance == null) instance = new PreferencesDialog(parent); + // update settings + instance.showSplash.setSelected( + Settings.getBoolean("main", "ShowSplashOnStartup")); + instance.showModuleChooser.setSelected( + Settings.getBoolean("main", "ShowModuleChooserOnStartup")); + String[] shortLangNames = Messages.getString("main_res", + "Available_languages.short").split(","); + String selectedLanguage = Settings.getString("main", "Language"); + for (int i=0; iStatusLineUpdater as a mouse listener. + * + * @author Alexander Claus + */ +public class StatusLineUpdater +extends MouseAdapter { + + private static StatusLineUpdater instance; + + private StatusLineUpdater() { + // no initialization neccessary + } + + public static StatusLineUpdater getInstance() { + if (instance == null) instance = new StatusLineUpdater(); + return instance; + } + + @Override + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getToolTipText()); + } + + @Override + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/res.properties b/src/org/jalgo/main/res.properties new file mode 100644 index 0000000..37e43cc --- /dev/null +++ b/src/org/jalgo/main/res.properties @@ -0,0 +1,37 @@ +ui.About=/main_pix/about.gif +ui.About_module=/main_pix/about.gif +ui.Close=/main_pix/close.gif +ui.Exit=/main_pix/exit.gif +ui.Help_contents=/main_pix/help.gif +ui.Logo=/main_pix/jalgo.png +ui.Logo_small=/main_pix/logo_small.gif +ui.Open_file=/main_pix/open.gif +ui.Prefs=/main_pix/prefs.gif +ui.Save_file=/main_pix/save.gif +ui.Save_as=/main_pix/save_as.gif +ui.Splash=/main_pix/splash.png +ui.New=/main_pix/new.gif +About.header=/main_pix/aboutHeader.png + +Icon.Redo=/main_pix/redo.gif +Icon.Undo=/main_pix/undo.gif +Icon.Advice=/main_pix/advice.gif +Icon.Advice_Selected=/main_pix/advice_selected.gif +Icon.Abort_algorithm=/main_pix/abortAlg.gif +Icon.Undo_step=/main_pix/undoStep.gif +Icon.Undo_blockstep=/main_pix/undoBlockStep.gif +Icon.Undo_all=/main_pix/undoAll.gif +Icon.Perform_step=/main_pix/performStep.gif +Icon.Perform_blockstep=/main_pix/performBlockStep.gif +Icon.Perform_all=/main_pix/performAll.gif +Icon.Finish_algorithm=/main_pix/finishAlg.gif +Icon.Beamer_mode=/main_pix/beamer.gif +Icon.Clear=/main_pix/clear.gif +Icon.Msg_error=/main_pix/msgError.gif +Icon.Msg_info=/main_pix/msgInfo.gif + +Available_languages.short=de,en +Available_languages.full=Deutsch,English + +Main_HelpSet=/help/jhelp/main_help.hs +Main_DummyHS=/help/jhelp/main_dummy.hs \ No newline at end of file diff --git a/src/org/jalgo/main/util/CVS/Entries b/src/org/jalgo/main/util/CVS/Entries new file mode 100644 index 0000000..07b1556 --- /dev/null +++ b/src/org/jalgo/main/util/CVS/Entries @@ -0,0 +1,4 @@ +/ErrorLog.java/1.2/Thu Jan 31 20:15:10 2008// +/Messages.java/1.13/Thu Jan 31 20:15:10 2008// +/Settings.java/1.4/Wed Mar 29 07:04:37 2006/-kk/ +/Storage.java/1.14/Thu Jan 31 20:15:10 2008// diff --git a/src/org/jalgo/main/util/CVS/Repository b/src/org/jalgo/main/util/CVS/Repository new file mode 100644 index 0000000..c6b8a3b --- /dev/null +++ b/src/org/jalgo/main/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/main/util diff --git a/src/org/jalgo/main/util/CVS/Root b/src/org/jalgo/main/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/main/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/main/util/ErrorLog.java b/src/org/jalgo/main/util/ErrorLog.java new file mode 100644 index 0000000..d803d2e --- /dev/null +++ b/src/org/jalgo/main/util/ErrorLog.java @@ -0,0 +1,100 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 11.06.2005 */ +package org.jalgo.main.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Map; + +/** + * The class ErrorLog is a helper class for easy debugging, when the + * program is running at the users computer. It writes system properties and + * occured exceptions in a textfile. The file is created when the module starts and + * is successive filled with exceptions. If there were no exceptions during runtime, + * the file is deleted from the disk. That mechanism guarantees, that only useful + * error logfiles are stored. + * These logfiles the user can send to the programmers to fix the bugs, if there + * were any... + * + * @author Alexander Claus + */ +public class ErrorLog { + + private PrintStream stderr; + private FileOutputStream out; + private String fileName; + private static final String lineSep = System.getProperty("line.separator"); + private static final String testString = "Error Log"+lineSep+lineSep; + private boolean writeProtected = false; + + /** + * Constructs an ErrorLog object. The standard error stream is + * redirected to a file "error\.log" and the available system + * properties are written to the file. + * Finally a well-defined string is written, which can be used to determine, + * if an exception occured. + */ + public ErrorLog() { + try { + fileName = "error"+System.currentTimeMillis()+".log"; + out = new FileOutputStream(fileName); + stderr = System.err; + System.setErr(new PrintStream(out)); + System.err.println("Properties:"); + System.err.println(); + for (Map.Entry property : System.getProperties().entrySet()) { + System.err.println(property); + } + System.err.println(); + System.err.print(testString); + } + catch (FileNotFoundException e) { + System.err.println("Konnte keine Logdatei anlegen..."); + writeProtected = true; + } + } + + /** + * Closes the created logfile and redirects the standard error stream back. + * Tests if there were exceptions occured, and if not, deletes the logfile. + * (If the program starts in write protected mode, e.g. from cd, there is + * nothing to close...) + */ + public void close() { + if (writeProtected) return; + try { + out.close(); + File log = new File(fileName); + FileReader testReader = new FileReader(log); + testReader.skip(log.length()-testString.length()); + char[] streamEnd = new char[testString.length()]; + testReader.read(streamEnd); + testReader.close(); + if (String.valueOf(streamEnd).equals(testString)) log.delete(); + System.setErr(stderr); + } + catch (IOException e) {e.printStackTrace();} + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/util/Messages.java b/src/org/jalgo/main/util/Messages.java new file mode 100644 index 0000000..5c8515f --- /dev/null +++ b/src/org/jalgo/main/util/Messages.java @@ -0,0 +1,198 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Jun 29, 2004 + */ + +package org.jalgo.main.util; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JAlgoMain; + +/** + * This class manages string externalization. The j-Algo main program and each + * module has its own resource bundles of externalized strings. The names of + * these resource bundle files have to follow the naming convention described in + * the developers manual of j-Algo. + * + * @author Alexander Claus + */ +public abstract class Messages { + + private final static Map RESOURCE_BUNDLES = + new HashMap(); + + static { + registerResourceBundle("main", "org.jalgo.main"); + } + + /** + * Loads and registers a resource bundle with the given path name. The + * resource bundle will be accessible under the given key calling
      + * Messages.getString(bundleKey, messageKey).
      + * If the key is already assigned, an IllegalArgumentException + * is thrown. + * + * @param key the access key for the resource bundle + * @param bundlePath the file path name of the bundle data base + */ + public static void registerResourceBundle(String key, String bundlePath) { + if (RESOURCE_BUNDLES.containsKey(key) || + RESOURCE_BUNDLES.containsKey(key+"_res")) + throw new IllegalArgumentException("Key already assigned: "+key); + + try { + RESOURCE_BUNDLES.put(key, ResourceBundle.getBundle( + bundlePath + "." + Settings.getString("main", "Language"))); + } + catch (MissingResourceException ex) { + //do nothing, that means only, that the current module has + //no strings externalized + } + try { + RESOURCE_BUNDLES.put(key + "_res", ResourceBundle.getBundle( + bundlePath + ".res")); + } + catch (MissingResourceException ex) { + //do nothing, that means only, that the current module has + //no resources externalized + } + } + + /** + * Retrieves an externalized string message with the given key from the + * specified resource bundle. + * + * @param bundleKey the key for accessing the resource bundle + * @param messageKey the key identifying the string message + * + * @return the externalized string message, if it was found. + */ + public static String getString(String bundleKey, String messageKey) { + try { + return RESOURCE_BUNDLES.get(bundleKey).getString(messageKey); + } + catch (MissingResourceException e) { + // if the messageKey could not found in resource bundle + return '!' + messageKey + '!'; + } + catch (NullPointerException ex) { + // if the resource bundle not exists + return '!' + messageKey + '!'; + } + } + + /** + * Retrieves an URL object backed by an externalized string of + * the interesting path name. A call to this method will have the same + * effect as
      + * getClass().getResource(Messages.getString(bundleKey+"_res", key)) + * + * + * @param bundleKey the key to the resource bundle + * @param key the key to the externalized string + * + * @return the requested URL object, if it exists, + * null otherwise + */ + public static URL getResourceURL(String bundleKey, String key) { + try { + return Messages.class.getResource( + RESOURCE_BUNDLES.get(bundleKey+"_res").getString(key)); + } + catch (MissingResourceException ex) { + // if the messageKey could not found in resource bundle + return null; + } + catch (NullPointerException ex) { + // if the resource bundle not exists + return null; + } + } + + /** + * Retrieves a String object, which contains the informations + * about j-Algo with the right layout. + */ + public static String getJAlgoInfoAsHTML(){ + StringBuffer content = new StringBuffer(); + content.append(""); ////$NON-NLS-1$ + content.append(Messages.getString("main", "General.name")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(" - "); //$NON-NLS-1$ + content.append(Messages.getString("main", "General.version")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.Copyright")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.URL")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.Authors")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.Author_Names")); //$NON-N //$NON-NLS-2$LS-1$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.License")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(Messages.getString("main", "About.GPL")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(""); //$NON-NLS-1$ + return content.toString(); + } + + /** + * Retrieves a String object, which contains the informations + * about the module with the specified index with the right layout.
      + * For informations about the currently opened module, the parameter has to + * be -1. + * + * @param index the index of the module or -1 for the current module + */ + public static String getModuleInfoAsHTML(int index) { + IModuleInfo module; + if (index < 0) + module = JAlgoMain.getInstance().getCurrentInstance().getModuleInfo(); + else module = JAlgoMain.getInstance().getKnownModuleInfos().get(index); + + StringBuffer content = new StringBuffer(); + content.append(""); //$NON-NLS-1$ + content.append(module.getName()); + content.append(Messages.getString("main", "AboutModule.Version")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(" ").append(module.getVersion()); + content.append("

      ").append("

      "); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(module.getDescription()); + content.append("

      "); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(Messages.getString("main", "About.Authors")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(module.getAuthor()); + content.append("

      "); //$NON-NLS-1$ //$NON-NLS-2$ + content.append(Messages.getString("main", "About.License")); //$NON-NLS-1$ //$NON-NLS-2$ + content.append("

      "); //$NON-NLS-1$ + content.append(module.getLicense()); + content.append(""); //$NON-NLS-1$ + return content.toString(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/util/Settings.java b/src/org/jalgo/main/util/Settings.java new file mode 100644 index 0000000..9ee5527 --- /dev/null +++ b/src/org/jalgo/main/util/Settings.java @@ -0,0 +1,158 @@ +package org.jalgo.main.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * This class defines some methods for the handling of persistent settings. + * For the j-Algo main program and for each module, a separate map of setting- + * value-pairs is held. This guarantees, that no naming conflicts between + * setting keys of different program units occur.
      + * To support this, the main program and each module, which should support + * persistent settings, has to offer a file where the default values of this + * settings are declared. This file must follow the naming conventions described + * in the developers manual of j-Algo! + * + * @author Alexander Claus + */ +public class Settings { + + private static String fileSep = System.getProperty("file.separator"); + private static Map PROPERTIES = + new HashMap(); + private static String prefsPath = + System.getProperty("user.home")+fileSep+".jalgo"+fileSep; + + static { + registerSettingsBundle("main", "/main.prefs"); + } + + /** + * Loads and registers a settings bundle with the given resource path. The + * settings bundle will be accessible under the given key.
      + * If the key is already assigned, an IllegalArgumentException + * is thrown.
      + * If a module doesn't support persistent settings, this call will be + * ignored. If no user settings file is saved or the version of the default + * settings file changes, the default settings are saved in a user settings + * file. + * + * @param key the access key for the settings bundle + * @param path the path name of the default settings file + */ + public static void registerSettingsBundle(String key, String path) { + if (PROPERTIES.containsKey(key)) + throw new IllegalArgumentException("Key already assigned: "+key); + // if module does not support persistent settings, ignore this call + if (Settings.class.getResourceAsStream(path) == null) return; + + // load defaults + Properties defaults = new Properties(); + try {defaults.load(Settings.class.getResourceAsStream(path));} + catch (IOException ex) {ex.printStackTrace();} + String defaultVersion = defaults.getProperty("Version"); + + Properties properties; + // check if user settings file exists, load user settings + if (!new File(prefsPath+key+".prefs").exists()) properties = defaults; + else { + properties = new Properties(defaults); + try {properties.load(new FileInputStream(prefsPath+key+".prefs"));} + catch (IOException ex) {ex.printStackTrace();} + if (!properties.getProperty("Version").equals(defaultVersion)) + properties = defaults; + } + + // store possible changes in user settings file + PROPERTIES.put(key, properties); + store(key); + } + + /** + * Retrieves the setting with the given settingKey from the + * settings bundle with the given resourceKey as boolean value. + * If the settingKey not exists or it doesn't represent a + * boolean value, false is returned. + * + * @param resourceKey the key to the settings bundle + * @param settingKey the key of the setting + * @return the value of the setting + */ + public static boolean getBoolean(String resourceKey, String settingKey) { + return Boolean.parseBoolean( + (String)PROPERTIES.get(resourceKey).get(settingKey)); + } + + /** + * Sets the value of the setting with the given settingKey from + * the settings bundle with the given resourceKey to the given + * value. + * + * @param resourceKey the key to the settings bundle + * @param key the key of the setting + * @param value the new value + */ + public static void setBoolean(String resourceKey, String key, boolean value) { + PROPERTIES.get(resourceKey).put(key, String.valueOf(value)); + store(resourceKey); + } + + /** + * Retrieves the setting with the given settingKey from the + * settings bundle with the given resourceKey as string. + * If the settingKey not exists, null is returned. + * + * @param resourceKey the key to the settings bundle + * @param settingKey the key of the setting + * @return the value of the setting + */ + public static String getString(String resourceKey, String key) { + return PROPERTIES.get(resourceKey).getProperty(key); + } + + /** + * Sets the value of the setting with the given settingKey from + * the settings bundle with the given resourceKey to the given + * value. + * + * @param resourceKey the key to the settings bundle + * @param key the key of the setting + * @param value the new value + */ + public static void setString(String resourceKey, String key, String value) { + PROPERTIES.get(resourceKey).put(key, value); + store(resourceKey); + } + + /** + * Stores the settings with the given resourceKey in a user + * settings file. Each settings bundle is saved in a separate user file. + * + * @param resourceKey the key to the settings bundle + */ + private static void store(String resourceKey) { + try { + File folder = new File(prefsPath); + if (!folder.exists()) folder.mkdir(); + FileOutputStream out = + new FileOutputStream(prefsPath+resourceKey+".prefs"); + String comment; + if (resourceKey.equals("main")) comment = "j-Algo Settings"; + else comment = "Settings for the "+resourceKey+" module"; + PROPERTIES.get(resourceKey).store(out, comment); + out.close(); + } + catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/main/util/Storage.java b/src/org/jalgo/main/util/Storage.java new file mode 100644 index 0000000..05d432c --- /dev/null +++ b/src/org/jalgo/main/util/Storage.java @@ -0,0 +1,180 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 19.04.2004 + */ + +package org.jalgo.main.util; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.gui.JAlgoGUIConnector; + + +/** + * @author Hauke Menges, Michael Pradel + */ +public class Storage { + + public static boolean load(String filename, + AbstractModuleConnector currentInstance) { + byte[] buf = null; + + // Create InputStream + FileInputStream in = null; + try { + in = new FileInputStream(filename); + } + catch (FileNotFoundException e) { + e.printStackTrace(); + } + + try { + // is it a valid jalgo-file? + buf = new byte["jalgo".getBytes().length]; //$NON-NLS-1$ + in.read(buf, 0, "jalgo".getBytes().length); //$NON-NLS-1$ + if (!(new String(buf).equals("jalgo"))) { //$NON-NLS-1$ + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("main", "Storage.Could_not_open_file_4") + //$NON-NLS-1$ + System.getProperty("line.separator") + + Messages.getString("main", "Storage.File_not_valid_5")); //$NON-NLS-1$ + return false; + } + buf = null; + + // Get Header length + int nameLength = in.read(); + int versionLength = in.read(); + + // Read Header + buf = new byte[nameLength]; + in.read(buf, 0, nameLength); + String name = new String(buf); + buf = new byte[versionLength]; + in.read(buf, 0, versionLength); + buf = null; + + // get modNumber of module corresponding to this file + int modNumber = -1; + List moduleInfos = + JAlgoMain.getInstance().getKnownModuleInfos(); + for (int i = 0; i < moduleInfos.size(); i++) { + if (((IModuleInfo)moduleInfos.get(i)).getName().equals(name)) + modNumber = i; + } + if (modNumber < 0) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("main", "Storage.Could_not_open_file_4") + //$NON-NLS-1$ + System.getProperty("line.separator") + + Messages.getString("main", "Storage.Module_not_present")); //$NON-NLS-1$ + return false; + } + + if (currentInstance == null) + currentInstance = JAlgoMain.getInstance().newInstance(modNumber); //$NON-NLS-1$ + + // Read module data + buf = new byte[in.available()]; + in.read(buf, 0, in.available()); + + // give outStream to Module + ByteArrayInputStream outStream = new ByteArrayInputStream(buf); + if (currentInstance == null) + throw new NullPointerException("currentInstance is null"); + currentInstance.setDataFromFile(outStream); + } + catch (IOException e) { + e.printStackTrace(); + } + finally { + try { + in.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + return true; + } + + public static boolean save(String filename) { + // Generate Headers + int nameLength = JAlgoMain.getInstance().getCurrentInstance(). + getModuleInfo().getName().getBytes().length; + int versionLength = JAlgoMain.getInstance().getCurrentInstance(). + getModuleInfo().getVersion().getBytes().length; + + // Create OutputStream + FileOutputStream out = null; + try { + out = new FileOutputStream(filename); + } + catch (FileNotFoundException e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString( + "main", "Storage.Could_not_write_the_file._8") + //$NON-NLS-1$ + System.getProperty("line.separator") + + Messages.getString("main", "Storage.Maybe_out_of_diskspace_9")); //$NON-NLS-1$ + e.printStackTrace(); + } + + try { + // Write Header + out.write("jalgo".getBytes()); //$NON-NLS-1$ + out.write(nameLength); + out.write(versionLength); + out.write(JAlgoMain.getInstance().getCurrentInstance(). + getModuleInfo().getName().getBytes()); + out.write(JAlgoMain.getInstance().getCurrentInstance(). + getModuleInfo().getVersion().getBytes()); + + // Write module data + out.write(JAlgoMain.getInstance().getCurrentInstance(). + getDataForFile().toByteArray()); + + } + catch (IOException e) { + e.printStackTrace(); + } + finally { + try { + out.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + } + + return true; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/CVS/Entries b/src/org/jalgo/module/CVS/Entries new file mode 100644 index 0000000..3c19210 --- /dev/null +++ b/src/org/jalgo/module/CVS/Entries @@ -0,0 +1,21 @@ +D/am0c0//// +D/am1simulator//// +D/app//// +D/avl//// +D/bTree//// +D/bellmanFord//// +D/bfsdfs//// +D/c0h0//// +D/dijkstra//// +D/dijkstraModule//// +D/ebnf//// +D/em//// +D/heapsort//// +D/hoare//// +D/kmp//// +D/lambda//// +D/pulsemem//// +D/startup//// +D/synDiaEBNF//// +D/testModule//// +D/unifikation//// diff --git a/src/org/jalgo/module/CVS/Repository b/src/org/jalgo/module/CVS/Repository new file mode 100644 index 0000000..21d323d --- /dev/null +++ b/src/org/jalgo/module/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module diff --git a/src/org/jalgo/module/CVS/Root b/src/org/jalgo/module/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/CVS/Entries b/src/org/jalgo/module/am0c0/CVS/Entries new file mode 100644 index 0000000..12334a8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/CVS/Entries @@ -0,0 +1,11 @@ +/ModuleConnector.java/1.1/Mon Aug 16 12:05:48 2010// +/ModuleInfo.java/1.2/Wed Dec 8 13:01:52 2010// +D/core//// +/de.properties/1.1/Wed Dec 8 13:01:52 2010// +/en.properties/1.1/Wed Dec 8 13:01:52 2010// +D/gui//// +D/model//// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// +D/parser//// +/res.properties/1.1/Wed Dec 8 13:01:52 2010// +D/tests//// diff --git a/src/org/jalgo/module/am0c0/CVS/Repository b/src/org/jalgo/module/am0c0/CVS/Repository new file mode 100644 index 0000000..b23935d --- /dev/null +++ b/src/org/jalgo/module/am0c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0 diff --git a/src/org/jalgo/module/am0c0/CVS/Root b/src/org/jalgo/module/am0c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/ModuleConnector.java b/src/org/jalgo/module/am0c0/ModuleConnector.java new file mode 100644 index 0000000..529fd1b --- /dev/null +++ b/src/org/jalgo/module/am0c0/ModuleConnector.java @@ -0,0 +1,62 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.am0c0.core.Controller; + +public class ModuleConnector extends AbstractModuleConnector { + + public void buildGUI() { + new Controller( + JAlgoGUIConnector.getInstance().getModuleComponent(this), + JAlgoGUIConnector.getInstance().getModuleToolbar(this), + JAlgoGUIConnector.getInstance().getModuleMenu(this)); + } + + @Override + public void init() { + this.buildGUI(); + } + + @Override + public void run() { + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + } + + @Override + public ByteArrayOutputStream getDataForFile() { + return null; + } + + @Override + public void print() { + } +} diff --git a/src/org/jalgo/module/am0c0/ModuleInfo.java b/src/org/jalgo/module/am0c0/ModuleInfo.java new file mode 100644 index 0000000..bb6edec --- /dev/null +++ b/src/org/jalgo/module/am0c0/ModuleInfo.java @@ -0,0 +1,82 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) + instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "AM0/C0"; //$NON-NLS-1$ + } + + public String getVersion() { + return "1.0"; //$NON-NLS-1$ + } + + public String getAuthor() { + return Messages.getString("am0c0", "ModuleInfo.2") //$NON-NLS-1$ + + Messages.getString("am0c0", "ModuleInfo.3"); //$NON-NLS-1$ + } + + public String getDescription() { + return Messages.getString("am0c0", "ModuleInfo.5"); //$NON-NLS-1$ + } + + public URL getLogoURL() { + return Messages.getResourceURL("am0c0", "Main_Icon"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public String getLicense() { + return Messages.getString("am0c0", "ModuleInfo.8"); //$NON-NLS-1$ + } + + public URL getHelpSetURL() { + return Messages.getResourceURL("am0c0", "HelpSet_Name"); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/core/CVS/Entries b/src/org/jalgo/module/am0c0/core/CVS/Entries new file mode 100644 index 0000000..aaf1e85 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/CVS/Entries @@ -0,0 +1,8 @@ +/Controller.java/1.1/Thu Jun 18 13:39:40 2015// +/Editor.java/1.1/Mon Aug 16 12:05:48 2010// +/ILoveCandy.java/1.2/Wed Dec 8 13:01:52 2010// +/PresentationAction.java/1.2/Wed Dec 8 13:01:52 2010// +/Simulator.java/1.1/Mon Aug 16 12:05:48 2010// +/Subcontroller.java/1.1/Mon Aug 16 12:05:48 2010// +/Transformator.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/core/CVS/Repository b/src/org/jalgo/module/am0c0/core/CVS/Repository new file mode 100644 index 0000000..ae8ac70 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/core diff --git a/src/org/jalgo/module/am0c0/core/CVS/Root b/src/org/jalgo/module/am0c0/core/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/core/Controller.java b/src/org/jalgo/module/am0c0/core/Controller.java new file mode 100644 index 0000000..12ec7be --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/Controller.java @@ -0,0 +1,157 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.core; + +import java.awt.BorderLayout; +import java.awt.CardLayout; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JPanel; +import javax.swing.JToolBar; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.am0c0.gui.EditorView; +import org.jalgo.module.am0c0.gui.SimulationView; +import org.jalgo.module.am0c0.gui.TransformationView; + +/** + * Main controller. Handles all components and supports switching between them. + * + * @author Franz Gregor + * @author Max Leuthäuser + */ +public class Controller { + private JComponent rootPanel; + @SuppressWarnings("unused") + private JToolBar toolbarPanel; + private JMenu menuPanel; + private JPanel panelLayers; + + private Editor editor; + private Simulator simulator; + private Transformator transformator; + + private static final String EDITOR = "e"; + private static final String SIMULATION = "s"; + private static final String TRANSFORMATION = "t"; + + public Controller(JComponent rootPanel, JToolBar toolbarPanel, + JMenu menuPanel) { + this.rootPanel = rootPanel; + this.toolbarPanel = toolbarPanel; + this.menuPanel = menuPanel; + + editor = new Editor(this); + simulator = new Simulator(this); + transformator = new Transformator(this); + + setViews(); + showEditor(); + createMenuBar(); + } + + /** + * Create the menu bar entries. + */ + private void createMenuBar() { + menuPanel.add(new PresentationAction(this)); + } + + /** + * Add all views in a {@link CardLayout} to switch them easily. + */ + private void setViews() { + rootPanel.setLayout(new BorderLayout()); + panelLayers = new JPanel(new CardLayout()); + panelLayers.add(editor.getView(), EDITOR); + panelLayers.add(transformator.getView(), TRANSFORMATION); + panelLayers.add(simulator.getView(), SIMULATION); + rootPanel.add(panelLayers); + } + + /** + * Switch to the {@link EditorView}. + */ + public void showEditor() { + CardLayout cl = (CardLayout) (panelLayers.getLayout()); + cl.show(panelLayers, EDITOR); + } + + /** + * Switch to the {@link SimulationView}. + */ + public void showSimulator() { + CardLayout cl = (CardLayout) (panelLayers.getLayout()); + cl.show(panelLayers, SIMULATION); + } + + /** + * Switch to the {@link TransformationView}. + */ + public void showTransformator() { + CardLayout cl = (CardLayout) (panelLayers.getLayout()); + cl.show(panelLayers, TRANSFORMATION); + } + + /** + * @return the {@link Editor} + */ + public Editor getEditor() { + return editor; + } + + /** + * @return the {@link Simulator} + */ + public Simulator getSimulator() { + return simulator; + } + + /** + * @return the {@link Transformator} + */ + public Transformator getTransformator() { + return transformator; + } + + /** + * Write a message to the j-Algo statusbar. + * + * @param message + */ + public void writeOnStatusbar(String message) { + JAlgoGUIConnector.getInstance().setStatusMessage(message); + } + + /** + * Set all views in presentation mode or not. + * + * @param presentation + */ + public void setPresentationMode(boolean presentation) { + editor.setPresentationMode(presentation); + simulator.setPresentationMode(presentation); + transformator.setPresentationMode(presentation); + } +} diff --git a/src/org/jalgo/module/am0c0/core/Editor.java b/src/org/jalgo/module/am0c0/core/Editor.java new file mode 100644 index 0000000..ade9e61 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/Editor.java @@ -0,0 +1,449 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/** + * + */ +package org.jalgo.module.am0c0.core; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.model.c0.C0Program; +import org.jalgo.module.am0c0.parser.Parser; +import org.jalgo.module.am0c0.parser.am0.AM0Parser; +import org.jalgo.module.am0c0.parser.c0.C0Parser; +import org.jalgo.module.am0c0.gui.EditorView; +import org.jalgo.module.am0c0.gui.jeditor.JEditor; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.AM0TokenMarker; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.CTokenMarker; + +/** + * The Editor SubController, containing the EditorView (with JEditor component). + * It controls code parsing/validation through its states and can return parsed + * code as AM0/C0Programs. + * + * @author Felix Schmitt + * @author Franz Gregor + * + */ +public class Editor extends Subcontroller { + public final static int AM0 = 0; + public final static int C0 = 1; + + /** + * abstract static base class for all states of this Editor controller + * + * @author Felix Schmitt + * + */ + public abstract static class EditorState { + protected Parser parser; + + /** + * validates the current code and returns the next {@link EditorState} + * (which can be the last one, too) depending on the last state and the + * validation result. + * + * @return the next {@link EditorState} + */ + public EditorState validate(String code) { + return this; + } + + /** + * Returns the parsed {@link C0Program}. Calling this method in an + * invalid state will cause a {@link IllegalStateException}. + * + * @return the parsed {@link C0Program} + * @throws IllegalStateException + * if this method is invoked on instances of + * {@link StateNotValidated} and {@link StateValidatedAM0} + */ + public abstract C0Program getC0Program(); + + /** + * Returns the parsed {@link AM0Program}. Calling this method in an + * invalid state will cause a {@link IllegalStateException}. + * + * @return the parsed {@link AM0Program} + * @throws IllegalStateException + * if this method is invoked on instances of + * {@link StateNotValidated} and {@link StateValidatedC0} + */ + public abstract AM0Program getAM0Program(); + + /** + * abstract method for returning text with current validation status + * + * @return a String with current validation status + */ + public abstract String getValidationResult(); + } + + /** + * abstract base class for not-validated states + * + * @author Felix Schmitt + * + */ + public abstract static class StateNotValidated extends EditorState { + + /** + * parses the code in {@link JEditor} an returns the result. used by + * subclasses + * + * @return the parsing result + */ + protected boolean isValid(String code) { + return parser.parse(code); + } + + /** + * returns the error text/validation text returned by the parser + * + * @return a String with the error text + */ + @Override + public String getValidationResult() { + return parser.getErrorText(); + } + + /** + * Invoking this method on instances of this class results in a + * {@link IllegalStateException}. + */ + @Override + public C0Program getC0Program() { + throw new IllegalStateException(); + } + + /** + * Invoking this method on instances of this class results in a + * {@link IllegalStateException}. + */ + @Override + public AM0Program getAM0Program() { + throw new IllegalStateException(); + } + } + + /** + * state with invalidated AM0 code in the editor + * + * @author Felix Schmitt + * + */ + public static class StateNotValidatedAM0 extends StateNotValidated { + + /** + * constructor + */ + public StateNotValidatedAM0() { + parser = new AM0Parser(); + } + + @Override + public EditorState validate(String code) { + if (isValid(code)) + return new StateValidatedAM0((AM0Parser) parser); + else + return this; + } + } + + /** + * state with invalidated C0 code in the editor + * + * @author Felix Schmitt + * + */ + public static class StateNotValidatedC0 extends StateNotValidated { + + /** + * constructor + */ + public StateNotValidatedC0() { + parser = new C0Parser(); + } + + @Override + public EditorState validate(String code) { + if (isValid(code)) + return new StateValidatedC0((C0Parser) parser); + else + return this; + } + } + + /** + * abstract base class for validated states + * + * @author Felix Schmitt + * + */ + public abstract static class StateValidated extends EditorState { + + /** + * constructor + * + * @param parser + * a {@link Parser} used for validating code + */ + public StateValidated(Parser parser) { + if (parser == null) + throw new IllegalArgumentException("Parser must not be null."); //$NON-NLS-1$ + this.parser = parser; + } + + @Override + public String getValidationResult() { + return Messages.getString("am0c0", "Editor.3") //$NON-NLS-1$ + + Messages.getString("am0c0", "Editor.4"); //$NON-NLS-1$ + } + } + + /** + * state with validated AM0 code in the editor + * + * @author Felix Schmitt + * + */ + public static class StateValidatedAM0 extends StateValidated { + + /** + * constructor + * + * @param parser + * see {@link StateValidated } + */ + public StateValidatedAM0(AM0Parser parser) { + super(parser); + } + + /** + * returns the {@link AM0Program } when parsing finished successfully, + * null otherwise + * + * @return the {@link AM0Program } or null + */ + @Override + public AM0Program getAM0Program() { + return ((AM0Parser) parser).getProgram(); + } + + /** + * Invoking this method on instances of this class results in a + * {@link IllegalStateException}. + */ + @Override + public C0Program getC0Program() { + throw new IllegalStateException(); + } + } + + /** + * state with validated C0 code in the editor + * + * @author Felix Schmitt + * + */ + public static class StateValidatedC0 extends StateValidated { + + /** + * constructor + * + * @param parser + * see {@link StateValidated } + */ + public StateValidatedC0(C0Parser parser) { + super(parser); + } + + /** + * returns the {@link C0Program } when parsing finished successfully, + * null otherwise + * + * @return the {@link C0Program } or null + */ + @Override + public C0Program getC0Program() { + return ((C0Parser) parser).getProgram(); + } + + /** + * Invoking this method on instances of this class results in a + * {@link IllegalStateException}. + */ + @Override + public AM0Program getAM0Program() { + throw new IllegalStateException(); + } + } + + @SuppressWarnings("unused") + private boolean autoValidate; + private EditorState state; + + /** + * constructor + * + * @param controller + * the {@link Controller } for this {@link Subcontroller} + */ + public Editor(Controller controller) { + this.controller = controller; + view = new EditorView(this); + setAutoValidate(false); + } + + @Override + public EditorView getView() { + return (EditorView) (super.getView()); + } + + /** + * Loads code file to the {@link JEditor} component and sets the editor + * state corresponding to the file extension. + * + * @return the path of the file loaded or an empty String the user aborted + * the load dialog. + */ + public String loadCode() { + String filepath = ((EditorView) view).getJEditor().loadCode(); + + if (filepath.endsWith(".am0")) { //$NON-NLS-1$ + setState(new StateNotValidatedAM0()); + } + + if (filepath.endsWith(".c0")) { //$NON-NLS-1$ + setState(new StateNotValidatedC0()); + } + + return filepath; + } + + /** + * saves code from {@link JEditor } to a file + * + * @return the absolut patch if the user confirmed the save dialog or "" if not + */ + public String saveCode() { + return ((EditorView) view).getJEditor().saveCode(); + } + + /** + * sets the {@link EditorState } + * + * @param state + * the new {@link EditorState}. must not be null + */ + public void setState(EditorState state) throws IllegalArgumentException { + if (state == null) + throw new IllegalArgumentException("EditorState must not be null"); //$NON-NLS-1$ + + if (state instanceof StateNotValidatedAM0 + || state instanceof StateValidatedAM0) { + getView().codeField.setTokenMarker(new AM0TokenMarker()); + getView().codeField.repaint(); + getView().am0Button.setSelected(true); + } + + if (state instanceof StateNotValidatedC0 + || state instanceof StateValidatedC0) { + getView().codeField.setTokenMarker(new CTokenMarker()); + getView().codeField.repaint(); + getView().c0Button.setSelected(true); + } + + this.state = state; + } + + /** + * returns the current {@link EditorState } + * + * @return the current {@link EditorState } + */ + public EditorState getState() { + return state; + } + + /** + * returns text with current validation status + * + * @return a String with validation status + */ + public String getValidationResult() { + return state.getValidationResult(); + } + + /** + * calls validation and updated the {@link EditorState }. the validation + * result will be logged to the GUI + * + * @param type + * either {@link Editor#AM0} or {@link Editor#C0}. + * @return true if the code was successfully validated (new state is a + * {@link StateValidated }) + */ + public boolean validate(final int type) { + if (type == AM0) { + setState(new StateNotValidatedAM0()); + } + if (type == C0) { + setState(new StateNotValidatedC0()); + } + + setState(state + .validate(((EditorView) getView()).getJEditor().getText())); + + ((EditorView) view).setConsoleText(getValidationResult()); + + return getState() instanceof StateValidatedAM0 + || getState() instanceof StateValidatedC0; + } + + /** + * calls validation and updated the {@link EditorState }. + */ + @SuppressWarnings("unused") + private void autoValidate() { + setState(state + .validate(((EditorView) getView()).getJEditor().getText())); + } + + /** + * sets auto validation. if autoValidate is true, a timer will try to + * validate the code in {@link JEditor } in intervals + * + * @param autoValidate + * new value for auto-validation + */ + public void setAutoValidate(boolean autoValidate) { + this.autoValidate = autoValidate; + } + + public void setAM0Program(AM0Program am0program) { + getView().codeField.updateModel(am0program); + getView().tabPane.setTitleAt(0, Messages.getString("am0c0", "Editor.5")); + setState(new StateNotValidatedAM0()); + } +} diff --git a/src/org/jalgo/module/am0c0/core/ILoveCandy.java b/src/org/jalgo/module/am0c0/core/ILoveCandy.java new file mode 100644 index 0000000..c17231f --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/ILoveCandy.java @@ -0,0 +1,633 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.core; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Event; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.Timer; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.gui.EditorView; + +public class ILoveCandy extends JPanel implements ActionListener { + private static final long serialVersionUID = 1L; + private EditorView editorView; + private Dimension d; + private Font smallfont = new Font("Helvetica", Font.BOLD, 14); + + @SuppressWarnings("unused") + private FontMetrics fmsmall, fmlarge; + private Image ii; + private Color dotcolor = new Color(192, 192, 0); + private Color mazecolor; + + private boolean ingame = false; + private boolean dying = false; + + private final int blocksize = 24; + private final int nrofblocks = 15; + private final int scrsize = nrofblocks * blocksize; + private final int pacanimdelay = 2; + private final int pacmananimcount = 4; + private final int maxghosts = 12; + private final int pacmanspeed = 6; + + private int pacanimcount = pacanimdelay; + private int pacanimdir = 1; + private int pacmananimpos = 0; + private int nrofghosts = 6; + private int pacsleft, score; + @SuppressWarnings("unused") + private int deathcounter; + private int[] dx, dy; + private int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed; + + private Image ghost; + private Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down; + private Image pacman3up, pacman3down, pacman3left, pacman3right; + private Image pacman4up, pacman4down, pacman4left, pacman4right; + + private int pacmanx, pacmany, pacmandx, pacmandy; + private int reqdx, reqdy, viewdx, viewdy; + /*private final short level1data[] = { 19, 26, 26, 22, 9, 12, 19, 26, 22, 9, + 12, 19, 26, 26, 22, 37, 11, 14, 17, 26, 26, 20, 15, 17, 26, 26, 20, + 11, 14, 37, 17, 26, 26, 20, 11, 6, 17, 26, 20, 3, 14, 17, 26, 26, + 20, 21, 3, 6, 25, 22, 5, 21, 7, 21, 5, 19, 28, 3, 6, 21, 21, 9, 8, + 14, 21, 13, 21, 5, 21, 13, 21, 11, 8, 12, 21, 25, 18, 26, 18, 24, + 18, 28, 5, 25, 18, 24, 18, 26, 18, 28, 6, 21, 7, 21, 7, 21, 11, 8, + 14, 21, 7, 21, 7, 21, 03, 4, 21, 5, 21, 5, 21, 11, 10, 14, 21, 5, + 21, 5, 21, 1, 12, 21, 13, 21, 13, 21, 11, 10, 14, 21, 13, 21, 13, + 21, 9, 19, 24, 26, 24, 26, 16, 26, 18, 26, 16, 26, 24, 26, 24, 22, + 21, 3, 2, 2, 6, 21, 15, 21, 15, 21, 3, 2, 2, 06, 21, 21, 9, 8, 8, + 4, 17, 26, 8, 26, 20, 1, 8, 8, 12, 21, 17, 26, 26, 22, 13, 21, 11, + 2, 14, 21, 13, 19, 26, 26, 20, 37, 11, 14, 17, 26, 24, 22, 13, 19, + 24, 26, 20, 11, 14, 37, 25, 26, 26, 28, 3, 6, 25, 26, 28, 3, 6, 25, + 26, 26, 28 };*/ + + private final short leveldata[] = { 19, 26, 26, 26, 18, 18, 18, 18, 18, + 18, 18, 18, 18, 18, 22, 21, 0, 0, 0, 17, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 20, 21, 0, 0, 0, 17, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 20, 21, 0, 0, 0, 17, 16, 16, 24, 16, 16, 16, 16, 16, 16, 20, + 17, 18, 18, 18, 16, 16, 20, 0, 17, 16, 16, 16, 16, 16, 20, 17, 16, + 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, 16, 24, 20, 25, 16, 16, 16, + 24, 24, 28, 0, 25, 24, 24, 16, 20, 0, 21, 1, 17, 16, 20, 0, 0, 0, + 0, 0, 0, 0, 17, 20, 0, 21, 1, 17, 16, 16, 18, 18, 22, 0, 19, 18, + 18, 16, 20, 0, 21, 1, 17, 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, + 20, 0, 21, 1, 17, 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, 20, 0, 21, + 1, 17, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 20, 0, 21, 1, 17, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 0, 21, 1, 25, 24, 24, + 24, 24, 24, 24, 24, 24, 16, 16, 16, 18, 20, 9, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 25, 24, 24, 24, 28 }; + + private final int validspeeds[] = { 1, 2, 3, 4, 6, 8 }; + private final int maxspeed = 6; + + private int currentspeed = 3; + private short[] screendata; + private Timer timer; + private JButton end; + + public ILoveCandy(EditorView e) { + editorView = e; + end = new JButton("Stop"); + end.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + timer.stop(); + ingame = false; + editorView.stopCandy(); + } + }); + add(end); + getImages(); + + addKeyListener(new TAdapter()); + + screendata = new short[nrofblocks * nrofblocks]; + mazecolor = new Color(5, 100, 5); + setFocusable(true); + + d = new Dimension(400, 400); + + setBackground(Color.black); + setDoubleBuffered(true); + + ghostx = new int[maxghosts]; + ghostdx = new int[maxghosts]; + ghosty = new int[maxghosts]; + ghostdy = new int[maxghosts]; + ghostspeed = new int[maxghosts]; + dx = new int[4]; + dy = new int[4]; + timer = new Timer(40, this); + timer.start(); + } + + @Override + public void addNotify() { + super.addNotify(); + gameInit(); + } + + public void doAnim() { + pacanimcount--; + if (pacanimcount <= 0) { + pacanimcount = pacanimdelay; + pacmananimpos = pacmananimpos + pacanimdir; + if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0) + pacanimdir = -pacanimdir; + } + } + + public void playGame(Graphics2D g2d) { + if (dying) { + death(); + } else { + movePacMan(); + drawPacMan(g2d); + moveGhosts(g2d); + checkMaze(); + } + } + + public void showIntroScreen(Graphics2D g2d) { + + g2d.setColor(new Color(0, 32, 48)); + g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50); + g2d.setColor(Color.white); + g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50); + + String s = "Press s to start."; + Font small = new Font("Helvetica", Font.BOLD, 14); + FontMetrics metr = this.getFontMetrics(small); + + g2d.setColor(Color.white); + g2d.setFont(small); + g2d.drawString(s, (scrsize - metr.stringWidth(s)) / 2, scrsize / 2); + } + + public void drawScore(Graphics2D g) { + int i; + String s; + + g.setFont(smallfont); + g.setColor(new Color(96, 128, 255)); + s = "Score: " + score; + g.drawString(s, scrsize / 2 + 96, scrsize + 16); + for (i = 0; i < pacsleft; i++) { + g.drawImage(pacman3left, i * 28 + 8, scrsize + 1, this); + } + } + + public void checkMaze() { + short i = 0; + boolean finished = true; + + while (i < nrofblocks * nrofblocks && finished) { + if ((screendata[i] & 48) != 0) + finished = false; + i++; + } + + if (finished) { + score += 50; + + if (nrofghosts < maxghosts) + nrofghosts++; + if (currentspeed < maxspeed) + currentspeed++; + levelInit(); + } + } + + public void death() { + + pacsleft--; + if (pacsleft == 0) + ingame = false; + levelContinue(); + } + + public void moveGhosts(Graphics2D g2d) { + short i; + int pos; + int count; + + for (i = 0; i < nrofghosts; i++) { + if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) { + pos = ghostx[i] / blocksize + nrofblocks + * (int) (ghosty[i] / blocksize); + + count = 0; + if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) { + dx[count] = -1; + dy[count] = 0; + count++; + } + if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) { + dx[count] = 0; + dy[count] = -1; + count++; + } + if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) { + dx[count] = 1; + dy[count] = 0; + count++; + } + if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) { + dx[count] = 0; + dy[count] = 1; + count++; + } + + if (count == 0) { + if ((screendata[pos] & 15) == 15) { + ghostdx[i] = 0; + ghostdy[i] = 0; + } else { + ghostdx[i] = -ghostdx[i]; + ghostdy[i] = -ghostdy[i]; + } + } else { + count = (int) (Math.random() * count); + if (count > 3) + count = 3; + ghostdx[i] = dx[count]; + ghostdy[i] = dy[count]; + } + + } + ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]); + ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]); + drawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1); + + if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) + && pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12) + && ingame) { + + dying = true; + deathcounter = 64; + + } + } + } + + public void drawGhost(Graphics2D g2d, int x, int y) { + g2d.drawImage(ghost, x, y, this); + } + + public void movePacMan() { + int pos; + short ch; + + if (reqdx == -pacmandx && reqdy == -pacmandy) { + pacmandx = reqdx; + pacmandy = reqdy; + viewdx = pacmandx; + viewdy = pacmandy; + } + if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) { + pos = pacmanx / blocksize + nrofblocks + * (int) (pacmany / blocksize); + ch = screendata[pos]; + + if ((ch & 16) != 0) { + screendata[pos] = (short) (ch & 15); + score++; + } + + if (reqdx != 0 || reqdy != 0) { + if (!((reqdx == -1 && reqdy == 0 && (ch & 1) != 0) + || (reqdx == 1 && reqdy == 0 && (ch & 4) != 0) + || (reqdx == 0 && reqdy == -1 && (ch & 2) != 0) || (reqdx == 0 + && reqdy == 1 && (ch & 8) != 0))) { + pacmandx = reqdx; + pacmandy = reqdy; + viewdx = pacmandx; + viewdy = pacmandy; + } + } + + // Check for standstill + if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) + || (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) + || (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) + || (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) { + pacmandx = 0; + pacmandy = 0; + } + } + pacmanx = pacmanx + pacmanspeed * pacmandx; + pacmany = pacmany + pacmanspeed * pacmandy; + } + + public void drawPacMan(Graphics2D g2d) { + if (viewdx == -1) + drawPacManLeft(g2d); + else if (viewdx == 1) + drawPacManRight(g2d); + else if (viewdy == -1) + drawPacManUp(g2d); + else + drawPacManDown(g2d); + } + + public void drawPacManUp(Graphics2D g2d) { + switch (pacmananimpos) { + case 1: + g2d.drawImage(pacman2up, pacmanx + 1, pacmany + 1, this); + break; + case 2: + g2d.drawImage(pacman3up, pacmanx + 1, pacmany + 1, this); + break; + case 3: + g2d.drawImage(pacman4up, pacmanx + 1, pacmany + 1, this); + break; + default: + g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); + break; + } + } + + public void drawPacManDown(Graphics2D g2d) { + switch (pacmananimpos) { + case 1: + g2d.drawImage(pacman2down, pacmanx + 1, pacmany + 1, this); + break; + case 2: + g2d.drawImage(pacman3down, pacmanx + 1, pacmany + 1, this); + break; + case 3: + g2d.drawImage(pacman4down, pacmanx + 1, pacmany + 1, this); + break; + default: + g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); + break; + } + } + + public void drawPacManLeft(Graphics2D g2d) { + switch (pacmananimpos) { + case 1: + g2d.drawImage(pacman2left, pacmanx + 1, pacmany + 1, this); + break; + case 2: + g2d.drawImage(pacman3left, pacmanx + 1, pacmany + 1, this); + break; + case 3: + g2d.drawImage(pacman4left, pacmanx + 1, pacmany + 1, this); + break; + default: + g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); + break; + } + } + + public void drawPacManRight(Graphics2D g2d) { + switch (pacmananimpos) { + case 1: + g2d.drawImage(pacman2right, pacmanx + 1, pacmany + 1, this); + break; + case 2: + g2d.drawImage(pacman3right, pacmanx + 1, pacmany + 1, this); + break; + case 3: + g2d.drawImage(pacman4right, pacmanx + 1, pacmany + 1, this); + break; + default: + g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); + break; + } + } + + public void drawMaze(Graphics2D g2d) { + short i = 0; + int x, y; + + for (y = 0; y < scrsize; y += blocksize) { + for (x = 0; x < scrsize; x += blocksize) { + g2d.setColor(mazecolor); + g2d.setStroke(new BasicStroke(2)); + + if ((screendata[i] & 1) != 0) // draws left + { + g2d.drawLine(x, y, x, y + blocksize - 1); + } + if ((screendata[i] & 2) != 0) // draws top + { + g2d.drawLine(x, y, x + blocksize - 1, y); + } + if ((screendata[i] & 4) != 0) // draws right + { + g2d.drawLine(x + blocksize - 1, y, x + blocksize - 1, y + + blocksize - 1); + } + if ((screendata[i] & 8) != 0) // draws bottom + { + g2d.drawLine(x, y + blocksize - 1, x + blocksize - 1, y + + blocksize - 1); + } + if ((screendata[i] & 16) != 0) // draws point + { + g2d.setColor(dotcolor); + g2d.fillRect(x + 11, y + 11, 2, 2); + } + i++; + } + } + } + + public void gameInit() { + pacsleft = 3; + score = 0; + levelInit(); + nrofghosts = 6; + currentspeed = 3; + } + + public void levelInit() { + int i; + /*if (currentspeed == 4 || currentspeed == 6) { + for (i = 0; i < nrofblocks * nrofblocks; i++) + screendata[i] = level1data[i]; + } else { + for (i = 0; i < nrofblocks * nrofblocks; i++) + screendata[i] = level2data[i]; + }*/ + for (i = 0; i < nrofblocks * nrofblocks; i++) + screendata[i] = leveldata[i]; + levelContinue(); + } + + public void levelContinue() { + short i; + int dx = 1; + int random; + + for (i = 0; i < nrofghosts; i++) { + ghosty[i] = 4 * blocksize; + ghostx[i] = 4 * blocksize; + ghostdy[i] = 0; + ghostdx[i] = dx; + dx = -dx; + random = (int) (Math.random() * (currentspeed + 1)); + if (random > currentspeed) + random = currentspeed; + ghostspeed[i] = validspeeds[random]; + } + + pacmanx = 7 * blocksize; + pacmany = 11 * blocksize; + pacmandx = 0; + pacmandy = 0; + reqdx = 0; + reqdy = 0; + viewdx = -1; + viewdy = 0; + dying = false; + } + + public void getImages() { + + ghost = new ImageIcon(Messages.getResourceURL("am0c0", "ghost")) + .getImage(); + pacman1 = new ImageIcon(Messages.getResourceURL("am0c0", "pacman")) + .getImage(); + pacman2up = new ImageIcon(Messages.getResourceURL("am0c0", "up1")) + .getImage(); + pacman3up = new ImageIcon(Messages.getResourceURL("am0c0", "up2")) + .getImage(); + pacman4up = new ImageIcon(Messages.getResourceURL("am0c0", "up3")) + .getImage(); + pacman2down = new ImageIcon(Messages.getResourceURL("am0c0", "down1")) + .getImage(); + pacman3down = new ImageIcon(Messages.getResourceURL("am0c0", "down2")) + .getImage(); + pacman4down = new ImageIcon(Messages.getResourceURL("am0c0", "down3")) + .getImage(); + pacman2left = new ImageIcon(Messages.getResourceURL("am0c0", "left1")) + .getImage(); + pacman3left = new ImageIcon(Messages.getResourceURL("am0c0", "left2")) + .getImage(); + pacman4left = new ImageIcon(Messages.getResourceURL("am0c0", "left3")) + .getImage(); + pacman2right = new ImageIcon(Messages.getResourceURL("am0c0", "right1")) + .getImage(); + pacman3right = new ImageIcon(Messages.getResourceURL("am0c0", "right2")) + .getImage(); + pacman4right = new ImageIcon(Messages.getResourceURL("am0c0", "right3")) + .getImage(); + + } + + @Override + public void paint(Graphics g) { + super.paint(g); + + Graphics2D g2d = (Graphics2D) g; + + g2d.setColor(Color.black); + g2d.fillRect(0, 0, d.width, d.height); + + drawMaze(g2d); + drawScore(g2d); + doAnim(); + if (ingame) + playGame(g2d); + else + showIntroScreen(g2d); + + g.drawImage(ii, 5, 5, this); + Toolkit.getDefaultToolkit().sync(); + g.dispose(); + } + + class TAdapter extends KeyAdapter { + @Override + public void keyPressed(KeyEvent e) { + + int key = e.getKeyCode(); + + if (ingame) { + if (key == KeyEvent.VK_LEFT) { + reqdx = -1; + reqdy = 0; + } else if (key == KeyEvent.VK_RIGHT) { + reqdx = 1; + reqdy = 0; + } else if (key == KeyEvent.VK_UP) { + reqdx = 0; + reqdy = -1; + } else if (key == KeyEvent.VK_DOWN) { + reqdx = 0; + reqdy = 1; + } else if (key == KeyEvent.VK_ESCAPE && timer.isRunning()) { + ingame = false; + } else if (key == KeyEvent.VK_PAUSE || key == KeyEvent.VK_P) { + if (timer.isRunning()) + timer.stop(); + else + timer.start(); + } + } else { + if (key == 's' || key == 'S') { + ingame = true; + gameInit(); + } + } + } + + @Override + public void keyReleased(KeyEvent e) { + int key = e.getKeyCode(); + + if (key == Event.LEFT || key == Event.RIGHT || key == Event.UP + || key == Event.DOWN) { + reqdx = 0; + reqdy = 0; + } + } + } + + @Override + public void actionPerformed(ActionEvent e) { + repaint(); + } +} diff --git a/src/org/jalgo/module/am0c0/core/PresentationAction.java b/src/org/jalgo/module/am0c0/core/PresentationAction.java new file mode 100644 index 0000000..aa375fc --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/PresentationAction.java @@ -0,0 +1,59 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.core; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; + +import org.jalgo.main.util.Messages; + +/** + * Handle the presentation mode. + * + * @author Max Leuthäuser + */ +public class PresentationAction extends JCheckBoxMenuItem implements + ActionListener { + private static final long serialVersionUID = 1L; + private Controller controller; + + public PresentationAction(Controller controller) { + super(Messages.getString("am0c0", "PresentationAction.0"), new ImageIcon(Messages //$NON-NLS-1$ + .getResourceURL("main", "Icon.Beamer_mode")), false); //$NON-NLS-1$ //$NON-NLS-2$ + this.controller = controller; + addActionListener(this); + } + + /** + * Toggles the presentation mode. + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + controller.setPresentationMode(isSelected()); + } +} diff --git a/src/org/jalgo/module/am0c0/core/Simulator.java b/src/org/jalgo/module/am0c0/core/Simulator.java new file mode 100644 index 0000000..e94cd79 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/Simulator.java @@ -0,0 +1,366 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.core; + +import javax.swing.JOptionPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.gui.SimulationView; +import org.jalgo.module.am0c0.model.AM0History; +import org.jalgo.module.am0c0.model.am0.*; + +/** + * Controller to handle the AM0 simulation. + * + * @author Max Leuthäuser + */ +public class Simulator extends Subcontroller { + private AM0History history; + private int currentStep; + private AM0Program am0Program; + private MachineConfiguration currentMc; + /** + * Flag to allow or disallow scrolling, printing descriptions and + * highlighting. This flag is set to false during a simulation in one single + * step to avoid performance issues. + */ + private boolean drawAddon = true; + /** + * Flag which is used to handle jump command failures. + */ + private boolean jumpFails = false; + + public Simulator(Controller controller) { + this.controller = controller; + view = new SimulationView(this); + history = new AM0History(); + currentStep = 0; + } + + @Override + public SimulationView getView() { + return (SimulationView) (super.getView()); + } + + /** + * @return the maximal available program counter; + */ + public int getMaxPC() { + return am0Program.size(); + } + + /** + * @return the history of the simulation. + */ + public AM0History getHistory() { + return history; + } + + /** + * @param m + * {@link MachineConfiguration} which is used here. + */ + public void setCurrentMachineConfiguration(MachineConfiguration m) { + currentMc = m; + } + + /** + * Show an error message to the user because an command could not be + * executed. + * + * @param reason + */ + private void showError(String reason) { + JOptionPane + .showMessageDialog( + null, + Messages.getString("am0c0", "Simulator.0") //$NON-NLS-1$ + + Messages.getString("am0c0", "Simulator.1") //$NON-NLS-1$ + + am0Program + .get(currentMc.getProgramCounter() + .get() - 1).getCodeText() + + "\n\n" + Messages.getString("am0c0", "Simulator.3") + reason); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Show an info message to the user because an jump command could not be + * executed. + * + * @param reason + */ + @SuppressWarnings("unused") + private void showInformation(String reason) { + JOptionPane + .showMessageDialog( + null, + Messages.getString("am0c0", "Simulator.4") //$NON-NLS-1$ + + am0Program + .get(currentMc.getProgramCounter() + .get() - 1).getCodeText() + + "\n\n" + Messages.getString("am0c0", "Simulator.6") + reason); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * @param program + * The {@link AM0Program} which should be used during the + * simulation. + * + * @throws IllegalArgumentException + */ + public void setAM0Program(AM0Program program) + throws IllegalArgumentException { + if (program != null) { + am0Program = program; + ((SimulationView) view).setAM0Program(program); + getView().resetSimulation(); + } else + throw new IllegalArgumentException( + "Null argument is not allowed for AM0Program."); //$NON-NLS-1$ + } + + /** + * Show the description for the corresponding statement. + * + * @param i + * Position of the statement in the {@link AM0Program}. + */ + private void showDescription(int i) { + if (drawAddon) { + if (am0Program.size() < 1) { + return; + } + + if (i <= 0) { + i = 1; + } + + if (i > am0Program.size()) { + i = am0Program.size(); + } + + ((SimulationView) view).showDescription(am0Program.get(i - 1) + .getCodeText() + "

      " //$NON-NLS-1$ + + am0Program.get(i - 1).getDescription() + "

      "); //$NON-NLS-1$ + } + } + + /** + * Show the currently visible page range. + */ + private void showRange() { + ((SimulationView) view) + .getRangeLabel() + .setText( + Messages.getString("am0c0", "Simulator.12") //$NON-NLS-1$ + + (((SimulationView) view).getTableModel() + .getPageOffset() == 0 ? 1 + : (((SimulationView) view) + .getTableModel().getPageSize() * ((SimulationView) view) + .getTableModel() + .getPageOffset())) + + Messages.getString("am0c0", "Simulator.13") //$NON-NLS-1$ + + (((SimulationView) view).getTableModel() + .getPageSize() * (((SimulationView) view) + .getTableModel().getPageOffset() + 1)) + + Messages.getString("am0c0", "Simulator.14")); //$NON-NLS-1$ + } + + /** + * @param m + * The {@link MachineConfiguration} to draw in the + * {@link SimulationView}. + */ + public void addResultToTable(MachineConfiguration m, int position) { + ((SimulationView) view).getTableModel().addRow(m); + if (drawAddon) { + if (position >= 1) { + ((SimulationView) view) + .getStepLabel() + .setText( + Messages.getString("am0c0", "Simulator.10") + (position + 1) + " "); //$NON-NLS-1$ //$NON-NLS-2$ + showRange(); + ((SimulationView) view).scroll(currentMc.getProgramCounter() + .get()); + } + if (currentMc.getProgramCounter().get() <= getMaxPC() + && currentMc.getProgramCounter().get() >= 1) { + showDescription(currentMc.getProgramCounter().get()); + } + } + } + + /** + * Removes the last line in the table. + */ + public void removeLastTableEntry(int position) { + ((SimulationView) view).getTableModel().removeLastRow(); + ((SimulationView) view) + .getStepLabel() + .setText( + Messages.getString("am0c0", "Simulator.15") + (position + 1) + " "); //$NON-NLS-1$ //$NON-NLS-2$ + if (drawAddon) { + ((SimulationView) view).scroll(currentMc.getProgramCounter().get()); + showDescription(currentMc.getProgramCounter().get()); + } + } + + /** + * Do the next step and draw the result in the {@link SimulationView} using + * {@link SimulationView#getTableModel()}. We only calculate something new + * if the step is not already in the {@link AM0History}. + * + * @return true if the next step could executed correctly, false otherwise. + */ + public boolean nextStep() { + if (currentMc.getProgramCounter().get() > getMaxPC() + || currentMc.getProgramCounter().get() < 1) { + jumpFails = true; + if (!jumpFails) { + addResultToTable(currentMc, currentStep + 1); + jumpFails = true; + } + // ok, this sucks really... + // JOptionPane.showMessageDialog(getView(), + // "The simulation finished successfully.", + // "Simulation finished", JOptionPane.INFORMATION_MESSAGE); + return false; + } + currentStep++; + if (!history.stepExists(currentStep)) { + jumpFails = false; + try { + currentMc = am0Program.get( + currentMc.getProgramCounter().get() - 1).apply( + new MachineConfiguration(currentMc)); + history.add(currentMc); + } catch (IllegalArgumentException e) { + // If an am0 command will fail we show this: + showError(e.getMessage()); + return false; + } catch (ArithmeticException e) { + // In the special case of DIV with 0 we will crash here: + showError(e.getMessage()); + return false; + } + } else { + currentMc = history.getAtStep(currentStep); + } + addResultToTable(currentMc, currentStep); + return true; + } + + /** + * Do the previous step and draw the result in the {@link SimulationView} + * using {@link SimulationView#getTableModel()}. Nothing is calculated here, + * we just using the {@link AM0History}. + * + * @return true if the previous step could executed correctly, false + * otherwise. + */ + public boolean previousStep() { + if (currentStep >= 1) { + currentStep--; + currentMc = history.getAtStep(currentStep); + removeLastTableEntry(currentStep); + jumpFails = false; + return true; + } + return false; + } + + /** + * Do the full (remaining) simulation in one single step. Basically we just + * use {@link Simulator#nextStep()}. + * + * @return true if all steps could executed correctly, false otherwise. + */ + public boolean stepToEnd() { + drawAddon = false; + boolean result = true; + while (result) { + result = nextStep(); + if (currentStep % ((SimulationView) view).getStepsToStopAfter() == 0) { + drawAddon = true; + showDescription(currentMc.getProgramCounter().get()); + ((SimulationView) view) + .getStepLabel() + .setText( + Messages.getString("am0c0", "Simulator.17") + currentStep + " "); //$NON-NLS-1$ //$NON-NLS-2$ + ((SimulationView) view).scroll(currentMc.getProgramCounter() + .get()); + drawAddon = false; + int s = JOptionPane + .showConfirmDialog( + null, + currentStep + + Messages.getString( + "am0c0", "Simulator.19") //$NON-NLS-1$ + + Messages.getString( + "am0c0", "Simulator.20") //$NON-NLS-1$ + + Messages.getString( + "am0c0", "Simulator.21"), //$NON-NLS-1$ + Messages.getString("am0c0", "Simulator.22"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ + if (s == JOptionPane.NO_OPTION + || s == JOptionPane.CANCEL_OPTION) { + result = true; + break; + } + } + } + drawAddon = true; + ((SimulationView) view) + .getStepLabel() + .setText( + Messages.getString("am0c0", "Simulator.23") + (currentStep + 1) + " "); //$NON-NLS-1$ //$NON-NLS-2$ + ((SimulationView) view).scroll(currentMc.getProgramCounter().get()); + // We want to show the description of the jump command which failed so + // we can not use '- 1' always. + showDescription(currentMc.getProgramCounter().get() + - (jumpFails ? 0 : 1)); + showRange(); + return result; + } + + /** + * Clear the whole simulation. + */ + public void clear() { + ((SimulationView) view).getTableModel().clear(); + history.clear(); + ((SimulationView) view).getStepLabel().setText( + Messages.getString("am0c0", "Simulator.25")); //$NON-NLS-1$ + ((SimulationView) view).showDescription(""); //$NON-NLS-1$ + currentStep = 0; + } + + /** + * @return true if the simulation needs an initial configuration. + */ + public boolean simulatorNeedsInitialConfig() { + return history.getCount() == 0; + } + + public AM0Program getAM0Program() { + return am0Program; + } +} diff --git a/src/org/jalgo/module/am0c0/core/Subcontroller.java b/src/org/jalgo/module/am0c0/core/Subcontroller.java new file mode 100644 index 0000000..1bdeee0 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/Subcontroller.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/** + * + */ +package org.jalgo.module.am0c0.core; + +import org.jalgo.module.am0c0.gui.View; + +/** + * Abstract controller class which defines the basic functionality for: + *

      + *

    • {@link Simulator}
    • + *
    • {@link Editor}
    • + *
    • {@link Transformator}
    • + *

      + *
      + * + * @author Franz Gregor + * @author Max Leuthäuser + */ +public abstract class Subcontroller { + protected View view; + protected Controller controller; + + /** + * @return the {@link View} which is used to handle user input und show + * calculation results. + */ + public View getView() { + return view; + } + + /** + * Set the presentation mode for the {@link View} which is used by this + * {@link Subcontroller}. + * + * @param presentationMode + * True will activate the presentation mode which + * increases font sizes, false will turn it off. + */ + public void setPresentationMode(boolean presentationMode) { + view.setPresentationMode(presentationMode); + } + + /** + * @return the {@link Controller} + */ + public Controller getController() { + return controller; + } +} diff --git a/src/org/jalgo/module/am0c0/core/Transformator.java b/src/org/jalgo/module/am0c0/core/Transformator.java new file mode 100644 index 0000000..b91578e --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/Transformator.java @@ -0,0 +1,455 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/** + * + */ +package org.jalgo.module.am0c0.core; + +import java.util.List; +import java.util.Map; + +import javax.activity.InvalidActivityException; +import javax.swing.JOptionPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.gui.TransformationView; +import org.jalgo.module.am0c0.gui.View; +import org.jalgo.module.am0c0.model.AddressException; +import org.jalgo.module.am0c0.model.C0History; +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.model.c0.C0Program; +import org.jalgo.module.am0c0.model.c0.ast.Program; +import org.jalgo.module.am0c0.model.c0.trans.AddressSolver; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans; +import org.jalgo.module.am0c0.model.c0.trans.BlockTrans; +import org.jalgo.module.am0c0.model.c0.trans.C0TransProgram; +import org.jalgo.module.am0c0.model.c0.trans.StubTrans; +import org.jalgo.module.am0c0.model.c0.trans.SymbolTable; +import org.jalgo.module.am0c0.model.c0.trans.Trans; +import org.jalgo.module.am0c0.model.c0.trans.TransException; +import org.jalgo.module.am0c0.model.c0.trans.TransformFunction; + +/** + * Controller to handle the c0 -> am0 transformation. + * + * @author Felix Schmitt + * @author Franz Gregor + * + */ +public class Transformator extends Subcontroller { + + protected C0TransProgram functions; + + public static enum TransformationState { + TS_WAITING, TS_PREVIEW, TS_FINISHED, TS_WAITING_FIRST, TS_PREVIEW_FIRST + }; + + private TransformationState state; + private SymbolTable symbolTable; + + private C0History functionsHistory; + + @Override + public TransformationView getView() { + return (TransformationView) (super.getView()); + } + + /** + * inits or resets the histories + */ + private void newHistory() { + functionsHistory = new C0History(); + } + + /** + * constructor + * + * @param controller + * the {@link Controller} for this {@link Subcontroller} + */ + public Transformator(Controller controller) { + this.controller = controller; + this.view = new TransformationView(this); + state = TransformationState.TS_WAITING_FIRST; + + functions = new C0TransProgram(); + + newHistory(); + } + + /** + * returns the current {@link TransformationState} + * + * @return the current {@link TransformationState} + */ + public TransformationState getState() { + return state; + } + + /** + * sets the current {@link TransformationState} + * + * @param state + * new {@link TransformationState} + */ + public void setState(TransformationState state) { + this.state = state; + } + + /** + * returns the current {@link SymbolTable} + * + * @return the current {@link SymbolTable} + */ + public SymbolTable getSymbolTable() { + return symbolTable; + } + + /** + * previews the results of applying the {@link TransformFunction} at index + * + * @param index + * index of the {@link TransformFunction} to preview + * @return if the preview could be generated successfully + */ + public boolean previewStatement(int index) throws IllegalStateException { + if (state == TransformationState.TS_FINISHED) + throw new IllegalStateException("Preview is not permitted in state FINISHED."); //$NON-NLS-1$ + + TransformFunction func = functions.get(index); + + if (func instanceof StubTrans) + return false; + + if (func instanceof AtomicTrans) { + JOptionPane.showMessageDialog(getView(), + Messages.getString("am0c0", "Transformator.1"), //$NON-NLS-1$ + Messages.getString("am0c0", "Transformator.2"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$ + return false; + } + + try { + getView().setPreviewText(getPreviewText(index)); + getView().setRuleText(getRuleText(index)); + if (getState() == TransformationState.TS_WAITING + || getState() == TransformationState.TS_PREVIEW) { + setState(TransformationState.TS_PREVIEW); + } else { + setState(TransformationState.TS_PREVIEW_FIRST); + } + return true; + } catch (TransException e) { + JOptionPane.showMessageDialog(getView(), e.getMessage(), Messages.getString("am0c0", "Transformator.0"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + return false; + } + } + + /* + * protected boolean internalTranslateNextStatement() { int nextIndex = -1; + * for (int i = 0; i < functions.size(); i++) { TransformFunction func = + * functions.get(i); if (!((func instanceof AtomicTrans) || (func instanceof + * StubTrans))) { nextIndex = i; break; } } + * + * if (nextIndex == -1) { return false; } else { try { applyFunc(nextIndex); + * return true; } catch (TransException e) { return false; } } } + */ + + /** + * translates the {@link TransformFunction} at index and applies the results + * to the {@link C0TransProgram} + * + * @param index + * index of the {@link TransformFunction} to translate/apply + * @return if the translation was successful + */ + public boolean translateStatement(int index) throws IllegalStateException { + if (state == TransformationState.TS_FINISHED) + throw new IllegalStateException("Translation is not permitted in state FINISHED."); //$NON-NLS-1$ + + try { + TransformFunction func = functions.get(index); + + if (func instanceof AtomicTrans || func instanceof StubTrans) { + JOptionPane.showMessageDialog(getView(), + Messages.getString("am0c0", "Transformator.5"), //$NON-NLS-1$ + Messages.getString("am0c0", "Transformator.6"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$ + return false; + } + + applyFunc(index); + } catch (TransException e) { + JOptionPane.showMessageDialog(getView(), e.getMessage(), Messages.getString("am0c0", "Transformator.7"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + return false; + } + + getView().updateModel(functions); + if (transformationFinished()) { + setState(TransformationState.TS_FINISHED); + JOptionPane.showMessageDialog(getView(), Messages.getString("am0c0", "Transformator.8"), //$NON-NLS-1$ + Messages.getString("am0c0", "Transformator.9"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$ + } else + setState(TransformationState.TS_WAITING); + return true; + + } + + /** + * translates the next available {@link TransformFunction} and applies the + * results to the {@link C0TransProgram} + * + * @param updateView + * if the {@link View} should be updated after translation + * @return if the translation was successful. returns false if there was no + * next available {@link TransformFunction} + */ + public boolean translateNextStatement(boolean updateView) throws IllegalStateException { + if (state == TransformationState.TS_FINISHED) + throw new IllegalStateException("Translation is not permitted in state FINISHED."); //$NON-NLS-1$ + + int nextIndex = -1; + for (int i = 0; i < functions.size(); i++) { + TransformFunction func = functions.get(i); + if (!((func instanceof AtomicTrans) || (func instanceof StubTrans))) { + nextIndex = i; + break; + } + } + + if (nextIndex == -1) { + return false; + } else + try { + applyFunc(nextIndex); + } catch (TransException e) { + JOptionPane.showMessageDialog(getView(), e.getMessage(), Messages.getString("am0c0", "Transformator.11"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + return false; + } + + if (updateView) + getView().updateModel(functions); + + if (transformationFinished()) { + setState(TransformationState.TS_FINISHED); + JOptionPane.showMessageDialog(getView(), Messages.getString("am0c0", "Transformator.12"), //$NON-NLS-1$ + Messages.getString("am0c0", "Transformator.13"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$ + return false; + + } else { + setState(TransformationState.TS_WAITING); + return true; + } + } + + /** + * translates the complete {@link C0TransProgram} and updated the + * {@link View} afterwards + */ + public void translateAll() throws IllegalStateException { + while (translateNextStatement(false)) { + } + ; + getView().updateModel(functions); + } + + /** + * creates a new {@link C0TransProgram} using program. The current + * {@link C0TransProgram}, {@link SymbolTable} and {@link View} will be + * cleared + * + * @param program + * the new {@link C0Program}. must not be null + */ + public void setC0Program(C0Program program) throws IllegalArgumentException { + if (program != null) { + functions.clear(); + symbolTable = new SymbolTable(); + functions.add(new Trans((Program) program.get(0), null)); + setState(TransformationState.TS_WAITING_FIRST); + getView().updateModel(functions); + getView().updateSymbolTable(); + newHistory(); + } else + throw new IllegalArgumentException("C0Program must not be null."); //$NON-NLS-1$ + } + + /** + * returns the current {@link C0TransProgram} + * + * @return the current {@link C0TransProgram} + */ + public C0TransProgram getC0TransProgram() { + return functions; + } + + /** + * checks if the transformation is complete. returns true if there are only + * {@link AtomicTrans} or {@link StubTrans} functions remaining + * + * @return whether the transformation is finished + */ + protected boolean transformationFinished() { + boolean result = true; + for (TransformFunction func : functions) + if (!((func instanceof AtomicTrans) || (func instanceof StubTrans))) + return false; + + return result && functions.size() != 0; + } + + /** + * applies the {@link TransformFunction} at index by inserting the results + * to the list and updating symbolTable + * + * @param index + * the index of the functions to apply + * @throws TransException + */ + protected void applyFunc(int index) throws TransException { + List resultFunctions = null; + try { + resultFunctions = getResultFunctions(index, false); + } catch (IllegalArgumentException e) { + throw new TransException(e.getMessage()); + } + + functionsHistory.add(functions.clone()); + functions.remove(index); + functions.addAll(index, resultFunctions); + } + + /** + * goes one step back in the transformation + * + * @throws InvalidActivityException + */ + public void stepBack() throws InvalidActivityException { + if (!functionsHistory.hasPrevious()) + throw new InvalidActivityException(); + + functions = functionsHistory.previous(); + getView().updateModel(functions); + + if (functions.get(0) instanceof BlockTrans) + symbolTable.clear(); + + if (functionsHistory.hasPrevious()) { + setState(TransformationState.TS_WAITING); + } else { + setState(TransformationState.TS_WAITING_FIRST); + } + } + + /** + * returns the list of resulting functions when applying + * {@link TransformFunction} at index + * + * @param index + * the index of the function to apply + * @param preview + * set true if results should be previewed but not inserted into + * the list + * @return the list of resulting {@link TransformFunction}s + * @throws TransException + */ + protected List getResultFunctions(int index, boolean preview) + throws TransException { + TransformFunction func = functions.get(index); + + if (func instanceof AtomicTrans || func instanceof StubTrans) + throw new TransException( + Messages.getString("am0c0", "Transformator.15") //$NON-NLS-1$ + + func.getCodeText()); + + if (preview && func instanceof BlockTrans) + return ((BlockTrans) func).applyPreview(); + else + try { + return func.apply(symbolTable); + } catch (TransException e) { + throw new TransException(e.getMessage() + "\n" + func.getCodeText()); //$NON-NLS-1$ + } + } + + /** + * returns the preview text associated with the {@link TransformFunction} at + * index + * + * @param index + * the index of the function + * @return the preview text + * @throws TransException + */ + protected String getPreviewText(int index) throws TransException { + StringBuilder resultText = new StringBuilder(); + + List resultFunctions = getResultFunctions(index, true); + + for (TransformFunction resultFunc : resultFunctions) { + resultText.append(resultFunc.getCodeText()); + resultText.append("\n"); + } + + return resultText.toString(); + } + + /** + * returns the rule text associated with the {@link TransformFunction} at + * index (their description) + * + * @param index + * the index of the function + * @return the rule text + * @throws IllegalArgumentException + */ + protected String getRuleText(int index) throws IllegalArgumentException { + if (index >= 0 && index < functions.size()) + return functions.get(index).getDescription(); + else + throw new IllegalArgumentException(Messages.getString("am0c0", "Transformator.3") + index); //$NON-NLS-1$ + } + + public AM0Program getAM0Program() throws NullPointerException, AddressException { + Map addresses; + + addresses = AddressSolver.solve(getC0TransProgram()); + + AM0Program am0program = new AM0Program(); + + int line = 1; + for (TransformFunction func : getC0TransProgram()) { + if (!(func instanceof StubTrans)) { + AtomicTrans atomFunc = (AtomicTrans) func; + + am0program.add(atomFunc.getStatement(new LineAddress(line), addresses)); + + line++; + } + } + + return am0program; + } +} diff --git a/src/org/jalgo/module/am0c0/core/package-info.java b/src/org/jalgo/module/am0c0/core/package-info.java new file mode 100644 index 0000000..55ee540 --- /dev/null +++ b/src/org/jalgo/module/am0c0/core/package-info.java @@ -0,0 +1,5 @@ +/** + * Classes which control the whole program. + */ +package org.jalgo.module.am0c0.core; + diff --git a/src/org/jalgo/module/am0c0/de.properties b/src/org/jalgo/module/am0c0/de.properties new file mode 100644 index 0000000..1ae6961 --- /dev/null +++ b/src/org/jalgo/module/am0c0/de.properties @@ -0,0 +1,301 @@ +Add.0=Der Datenkeller enthält weniger als zwei Elemente! +Add.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2+d.1):d.3: ... :d.n,h, inp, out) +AddressSolver.0=StubTrans Addresse darf nicht NULL sein! +AM0InputDialog.0=Neue AM Konfiguration +AM0InputDialog.1=Befehlszähler +AM0InputDialog.12=+ +AM0InputDialog.13=- +AM0InputDialog.14=Gib hier eine neue AM Konfiguration ein.
      Benutze ':' um die Werte im Datenkeller zu trennen
      und ',' auf dem Ein- und Ausgabeband.

      +AM0InputDialog.15=OK +AM0InputDialog.16=Abbrechen +AM0InputDialog.17=Intitiale Konfiguration +AM0InputDialog.18=Diese Eingabe für den Hauptspeicher ist nicht korrekt. Er darf nicht leer sein!\n +AM0InputDialog.19=Diese Eingabe für den Hauptspeicher ist nicht korrekt.\n +AM0InputDialog.2=Datenkeller (mit ':' getrennt) +AM0InputDialog.20=Bitte überprüfe folgende Zahlen:\n +AM0InputDialog.21=Adresse: +AM0InputDialog.24=Diese Eingabe für den Hauptspeicher ist nicht korrekt.\n +AM0InputDialog.25=Die Adresse darf nicht negtiv oder 0 sein, aber sie war:\n +AM0InputDialog.26=Diese Hauptspeicheradresse ist nicht korrekt.\n +AM0InputDialog.27=\ Bitte überprüfe folgende Adresse: +AM0InputDialog.28=Diese Hauptspeicheradresse ist nicht korrekt.\n +AM0InputDialog.29=\ Die Adresse darf nicht negativ oder 0 sein, aber sie war:\n +AM0InputDialog.3=Hauptspeicher (Adresse, Wert) +AM0InputDialog.4=Eingabeband (mit Kommata getrennt) +AM0InputDialog.43=es muss mindestens eine Zahl +AM0InputDialog.44=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.45=Dieses Eingabeband ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.46=es muss mindestens eine Zahl +AM0InputDialog.47=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.48=Dieser Datenkeller ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.49=es muss mindestens eine Zahl +AM0InputDialog.5=Ausgabeband (mit Kommata getrennt) +AM0InputDialog.50=oder mehr mit ',' getrennt eingegeben werden, aber es war:\n +AM0InputDialog.51=Dieser Befehlszähler ist nicht korrekt.\nEr muss >=1 sein, aber es war:\n +AM0InputDialog.52=Der Befehlszähler darf nicht leer sein!\n +AM0InputDialog.6=Wert: +AM0InputDialog.7=Dieses Ausgabeband ist nicht korrekt. Es ist nur ein '-' zugelassen und\n +AM0InputDialog.74=Hauptspeicherkonfiguration +AM0InputDialog.8=Diese Adresse existiert bereits. Soll der Wert an dieser Adresse überschrieben werden? +AM0InputDialog.87=Datenkellerkonfiguration +AM0InputDialog.9=Diese Adresse existiert nicht:\n +AM0PagingTableModel.0=Befehlszähler +AM0PagingTableModel.1=Datenkeller +AM0PagingTableModel.10=  Zeige Schritte von +AM0PagingTableModel.11= bis +AM0PagingTableModel.12= +AM0PagingTableModel.2=Hauptspeicher +AM0PagingTableModel.3=Eingabeband +AM0PagingTableModel.4=Ausgabeband +AM0PagingTableModel.7=  Zeige Schritte von +AM0PagingTableModel.8= bis +AM0PagingTableModel.9= +AM0Scanner.0=Unbekannter interner Scanner Fehler +AM0Scanner.1=Fehler: konnte Eingabe nicht in Übereinstimmung bringen +AM0Scanner.2=Fehler: Rückgabewert ist zu groß +AtomicTrans.0=Dieser AtomicType ist nicht gültig +AtomicTrans.5=Token muss für AtomicTrans Funktionen NULL sein +AtomicTrans.6=Eine Sprungbefehl muss eine Sprungadresse haben +AtomicTrans.7=Anwenden von AtomicTrans ist nicht erlaubt +BlockTrans.0=blocktrans: W() \u2212 \u2192 bProg0\n\n +BlockTrans.1=blocktrans({ decl statseq return 0;}) := stseqtrans(statseq, update(decl, tab \u2205 ), 1) +BlockTrans.2=für alle decl \u2208 W() und statseq \u2208 W(), +BlockTrans.3=tab \u2205 \u2208 Tab mit graph(tab \u2205 ) = \u2205 +BoolExpTrans.0=boolexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0\n\n +BoolExpTrans.1=boolexptrans(se 1 rel se 2 , tab) :=\n +BoolExpTrans.2=\tsimpleexptrans(se 1 , tab)\n +BoolExpTrans.3=\tsimpleexptrans(se 2 , tab)\n +BoolExpTrans.4=\tREL;\n +BoolExpTrans.5=für alle se 1 , se 2 \u2208 W(), rel \u2208 {==, \!=, <, >, <=, >=} und tab \u2208 Tab +C0Scanner.0=Fehler: Rückgabewert ist zu groß +C0Scanner.177=Unbekannter interner Scanner Fehler +C0Scanner.178=Fehler: konnte Eingabe nicht in Übereinstimmung bringen +Div.0=Der Datenkeller enthält weniger als zwei Elemente! +Div.1=Division mit 0! +Div.2=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2/d.1):d.3: ... :d.n,h, inp, out) +Editor.3=

      Die Syntaxüberprüfung war +Editor.4=erfolgreich. Klicke nun auf Start.

      +Editor.5=Transformiertes Programm +EditorView.10=AM0-Code +EditorView.12=Konsole +EditorView.13=Optionen +EditorView.14=Editor +EditorView.15=Soll das Programm vor der Transformation gespeichert werden? +EditorView.16=Speichern +EditorView.17=Lädt Code in den Editor +EditorView.18=Speichere den soeben editierten Code. +EditorView.19=Verwende den Code für die Simulation oder Transformation. +EditorView.2=Laden +EditorView.20=Validiere den Code. +EditorView.21=Verwende AM0 Code. +EditorView.22=Verwende C0 Code. +EditorView.23=Zeile: +EditorView.24=\ Spalte: +EditorView.25=Neue Datei +EditorView.4=Speichern +EditorView.6=Validiere +EditorView.7=Start +EditorView.9=C0-Code +Equal.0=Der Datenkeller enthält weniger als zwei Elemente! +Equal.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, falls d.2=d.1, und b=0, falls d.2\!=d.1,
      d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +ErrorEvents.RemoveThisToken=Entferne es, um diesen Fehler zu beseitigen. +ErrorEvents.LexicalAnalysis=Lexikalische Analyse +ErrorEvents.SyntacticAnalysis=Syntaktische Analyse +ErrorEvents.FollowingErrors=Folgende Fehler traten während der Validierung auf: +ErrorEvents.FollowingError=Folgender Fehler trat während der Validierung auf: +ErrorEvents.NumberTooLarge=Die eingegebene Zahl %s in Zeile %d, Spalte %d ist zu groß: der maximal erlaubte Wert ist %d. +ErrorEvents.UnexpectedTokenAt=Unerwartetes Terminalsymbol "%s" in Zeile %d, Spalte %d. +ErrorEvents.DontKnowWhatToDo=Kann die Eingabe "%s" auf Zeile %d nicht verarbeiten. +ErrorEvents.UnexpectedEOF=Unerwartetes Dateiende in Zeile %d, Spalte %d. +ErrorEvents.UnexpectedEOL=Unerwartetes Zeilenende in Zeile %d, Spalte %d. +ErrorEvents.InsertRelation=Füge eine der Relationen "==", "!=", ">=", "<=", ">" oder "<" ein, um diesen booleschen Ausdruck zu komplettieren. +ErrorEvents.InsertAmp=Füge "&" ein, um dieses scanf-Statement zu komplettieren. +ErrorEvents.InsertComma=Füge "," ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertAssign=Füge "=" ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertSemicolon=Füge ";" ein, um das vorhergehende Statement zu komplettieren. +ErrorEvents.InsertIdent=Füge einen Variablennamen ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertNumber=Füge eine Zahl ein, um diesen Fehler zu beseitigen. +ErrorEvents.InsertNumber_AM0=Füge eine Zahl ein, um dieses AM0-Statement zu komplettieren. +ErrorEvents.InsertSemicolon_AM0=Füge ";" ein, um dieses AM0-Statement zu komplettieren. +GreaterEqual.0=Der Datenkeller enthält weniger als zwei Elemente! +GreaterEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, wenn d.2\u2265d.1, und b=0, wenn d.2<d.1,
      d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +GreaterThen.0=Der Datenkeller enthält weniger als zwei Elemente! +GreaterThen.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, wenn d.2>d.1, und b=0, wenn d.2\u2264d.1,
      d.h. für den Wert true (oder false) wird 1 (oder 0) auf den Datenkeller gelegt. +JEditor.0=Eingabe/Ausgabe Fehler +JEditor.1=AM0 Programm (*.am0) +JEditor.13=Eingabe/Ausgabe Fehler +JEditor.3=C0 Programm (*.c0) +JEditor.8=Der Programmcode wurde modifiziert.\nMöchtest du ihn speichern? +JEditor.9=Bestätigen +Jmc.0=Der Datenkeller enthält kein Element! +Jmc.1=Falls d=0:d.2: ... :d.n mit n \u2265 1, dann (e,d.2: ... :d.n,h, inp, out)
      sonst (m+1,d.2: ... :d.n,h, inp, out)
      Falls das erste Datenkellerelement 0 (logisch falsch) ist wird der PC auf e gesetzt.
      Sonst wird er inkrementiert. +Jmp.0=(e,d,h, inp, out) +LesserEqual.0=Der Datenkeller enthält weniger als zwei Elemente. +LesserEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, wenn d.2\u2264d.1, und b=0, wenn d.2>d.1,
      , d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +LesserThen.0=Der Datenkeller enthält weniger als zwei Elemente. +LesserThen.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, wenn d.2<d.1, und b=0, wenn d.2\u2265d.1,
      , d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +Lit.0=(m+1,z:d,h, inp, out) +Load.0=Diese Hauptspeicherzelle ist nicht definiert. +Load.1=Falls h(n) \u220A \u2115, dann (m+1,h(n):d,h, inp, out) +Mod.0=Der Datenkeller enthält weniger als zwei Elemente. +Mod.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2%.1):d.3: ... :d.n,h, inp, out) +ModuleInfo.2=Franz Gregor, Martin Morgenstern,\n +ModuleInfo.3=\ Max Leuth\u00E4user, David Voigt, Felix Schmitt +ModuleInfo.5=Dieses Modul übersetzt schrittweise C0- in AM0-Programme und simuliert AM0-Programme. +ModuleInfo.8=GNU General Public License. Grafiken vom Tango Desktop Project. +Mul.0=Der Datenkeller enthält weniger als zwei Elemente. +Mul.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,(d.2*d.1):d.3: ... :d.n,h, inp, out) +NotEqual.0=Der Datenkeller enthält weniger als zwei Elemente. +NotEqual.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2, dann (m+1,b:d.3: ... :d.n,h, inp, out)
      und b=1, wenn d.2\!=d.1, und b=0, wenn d.2=d.1,
      , d.h. für den Wert True (False) wird 1 (0) auf den Datenkeller gelegt. +PresentationAction.0=Präsentationsmodus +Read.0=Ziel < 0 ist nicht erlaubt\! +Read.1=Das Eingabeband ist leer\! +Read.2=Falls inp=first(inp).rest(inp), dann (m+1,d,h[n/first(inp)], rest(inp), out)
      und für jedes n \u220A \u2124 und w \u220A \u2124*: first(n:w)=n und rest(n:w)=w +SimpleExpTrans.0=simpleexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0 +SimulationView.11=Zurück +SimulationView.13=Weiter +SimulationView.15=Leeren +SimulationView.17=Alles in einem Schritt +SimulationView.19=Initiale Konfiguration +SimulationView.23=Die Simulation wird nach maximal +SimulationView.24= Schritten nachfragen, ob sie weiter laufen soll. +SimulationView.26=Die Simulation wird nach maximal +SimulationView.27= Schritten nachfragen, ob sie weiter laufen soll. +SimulationView.28=\ \ Nachfragen nach: +SimulationView.29=\ Schritten +SimulationView.3=AM0-Tabelle +SimulationView.31=Befehls Hilfe +SimulationView.32=Zum Anfang der Simulation springen. +SimulationView.33=Ans Ende der Simulation springen. +SimulationView.34=Zurück zum Editor. +SimulationView.35=Einen Schritt zurück gehen. +SimulationView.36=Einen Schritt weiter gehen. +SimulationView.37=Simulation in einem Schritt. +SimulationView.38=Eine Maschinenkonfiguration eingeben. +SimulationView.39=Alles bereinigen. Diese Aktion wird die aktuelle Maschinenkonfiguration sowie alle Übersetzungsschritte entfernen\! +SimulationView.4=AM0-Animation +SimulationView.5=Tabellenanfang +SimulationView.6=Tabellenende +SimulationView.7=Noch nicht gestartet. +SimulationView.9=Zum Editor +Simulator.0=Es tratt ein Fehler bei der Simulation auf.\n +Simulator.1=Der folgende Befehl konnte nicht ausgeführt werden:\n +Simulator.10=Letzter Schritt: +Simulator.12=  Zeige Schritte von +Simulator.13= bis +Simulator.14= +Simulator.15=\ \ Letzter Schritt: +Simulator.17=\ \ Letzter Schritt: +Simulator.19=\ Schritte berechnet.\n +Simulator.20=Möchtest du fortfahren?\n\n +Simulator.21=Wähle 'Nein' zum Stoppen oder 'Ja' zum Fortsetzen der Simulation +Simulator.22=Simulation +Simulator.23=\ \ Letzter Schritt: +Simulator.25=Noch nicht gestartet. +Simulator.3=Grund:\n +Simulator.4=Dieser Sprungbefehl konnte nicht ausgeführt werden:\n +Simulator.6=Grund:\n +Store.0=Der Datenkeller enthält kein Element. +Store.1=Falls d=d.1:d', dann (m+1,d',h[n/d.1], inp, out)
      und h[n/d.1](k)={d.1
      h(k)
      wenn k=n
      sonst
      +STSeqTrans.0=stseqtrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STSeqTrans.1=stseqtrans(stat 1 stat 2 . . . stat n , tab, a) :=\n +STSeqTrans.2=\tsttrans(stat 1 , tab, a.1)\n +STSeqTrans.3=\tsttrans(stat 2 , tab, a.2)\n +STSeqTrans.4=\t...\n +STSeqTrans.5=\tsttrans(stat n , tab, a.n)\n +STSeqTrans.6=für alle stat 1 , stat 2 , . . . , stat n \u2208 W(), tab \u2208 Tab und a \u2208 N\u2217 +STSeqTrans.7=Es wurde versucht, eine leere statement sequence zu transformieren. +STTrans.AssignError=Das Symbol auf der linken Seite der Zuweisung existiert nicht oder ist ein Konstantensymbol! +STTrans.ScanfError=Das Symbol in diesem scanf-Statement existiert nicht oder ist ein Konstantensymbol! +STTrans.PrintfError=Das Symbol in diesem printf-Statement existiert nicht oder ist ein Konstantensymbol! +STTrans.0=sttrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STTrans.1=sttrans({ stat 1 stat 2 . . . stat n }, tab, a) :=\n +STTrans.10=sttrans(printf("%d",id);, tab, a) :=\n +STTrans.11=\twenn tab(id ) = (var, n) dann WRITE n;\n +STTrans.12=\tfür alle id \u2208 W( Ident ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.13=sttrans(if ( exp ) stat, tab, a) :=\n +STTrans.14=\tboolexptrans(exp, tab)\n +STTrans.15=\tJMC a.1;\n +STTrans.16=\tsttrans(stat , tab, a.2)\n +STTrans.17=\ta.1:\n +STTrans.18=\tfür alle exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.19=\tund a \u2208 N\u2217 +STTrans.2=\tstseqtrans(stat 1, stat 2 . . . stat n , tab, a)\n +STTrans.20=sttrans(if ( exp ) stat 1 else stat 2 , tab, a) :=\n +STTrans.21=\tboolexptrans(exp, tab)\n +STTrans.22=\tJMC a.1;\n +STTrans.23=\tsttrans(stat 1 , tab, a.2)\n +STTrans.24=\tJMP a.3;\n +STTrans.25=\ta.1: sttrans(stat 2 , tab, a.4)\n +STTrans.26=\ta.3:\n +STTrans.27=\tfür alle exp \u2208 W( BoolExpression ), stat 1 , stat 2 \u2208 W( Statement ),\n +STTrans.28=\ttab \u2208 Tab und a \u2208 N\u2217 +STTrans.29=sttrans(while ( exp ) stat, tab, a) :=\n +STTrans.3=\tfür alle stat 1 , stat 2 , . . . , stat n \u2208 W( statement ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.30=\ta.1 : boolexptrans(exp, tab)\n +STTrans.31=\tJMC a.2;\n +STTrans.32=\tsttrans(stat , tab, a.3)\n +STTrans.33=\tJMP a.1;\n +STTrans.34=\ta.2:\n +STTrans.35=\tfür alle exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.36=\tund a \u2208 N\u2217 +STTrans.4=sttrans(id = exp;, tab, a) :=\n +STTrans.5=\twenn tab(id ) = (var, n) dann simpleexptrans(exp, tab) STORE n; +STTrans.6=\tfür alle id \u2208 W( Ident ), exp \u2208 W( SimpleExpression ), tab \u2208 Tab und a \u2208 N\u2217 +STTrans.7=sttrans(scanf("%i",&id);, tab, a) :=\n +STTrans.8=\twenn tab(id ) = (var, n) dann READ n;\n +STTrans.9=\tfür alle id \u2208 W( Ident ), tab \u2208 Tab und a \u2208 N\u2217 +Symbol.0=Ungültige Speicheradresse < +Symbol.1=Der Zugriff auf Adressen von Konstanten ist ungültig. +SymbolTable.0=Ein symbol mit id +SymbolTable.1=\ existiert bereits. +SymbolTable.10=Es wurde versucht, den Wert eines nicht existierenden Symbols auszulesen +SymbolTable.11=Es wurde versucht, den SymbolType eines nicht existierenden Symbols auszulesen +SymbolTable.2=Eine Variable it Speicheradresse +SymbolTable.3=\ existiert bereits +SymbolTable.9=Es wurde versucht, den SymbolType eines nicht existierenden Symbols auszulesen +Trans.0=trans: W() \u2212 \u2192 bProg0\n\n +Trans.1=trans( \#include int main() block ) := blocktrans(block) für alle block \u2208 W() +TransformationView.0=Typ +TransformationView.1=ID +TransformationView.10=Anwenden +TransformationView.12=Fertig transformieren +TransformationView.14=Simulieren +TransformationView.16=Zurück zum Editor +TransformationView.18=Definition / Regel +TransformationView.19=Vorschau +TransformationView.2=Adresse +TransformationView.25=Wollen Sie das transformatierte Programm an den Editor schicken? +TransformationView.26=übertrage +TransformationView.3=tab(ID) +TransformationView.32=Fehler +TransformationView.33=Alle anwenden ist im Zustand FINISHED nicht möglich. Internal program error\! +TransformationView.34=Fehler +TransformationView.35=Fehler +TransformationView.4=Fehler +TransformationView.40=Zurück zum Editor. +TransformationView.41=Den letzten Schritt rückgängig machen. +TransformationView.42=Die ausgewählte Transformationsfunktion anwenden. +TransformationView.43=In einem Schritt übersetzen. +TransformationView.44=Übertrage das übersetzte Programm zum Simulator. +TransformationView.5=Fehler +TransformationView.6=Fehler +TransformationView.8=Rückgängig +Transformator.0=Fehler +Transformator.1=Diese Funktion kann nicht weiter transformiert werden, sie ist bereits atomar. +Transformator.11=Fehler +Transformator.12=Die Transformation wurde erfolgreich abgeschlossen. +Transformator.13=Transformation abgeschlossen +Transformator.15=Dieser Index zeigt auf eine nicht anwendbare Transformationsfunktion.\n +Transformator.2=Ungültige Transformation +Transformator.3=Keine Transformationsfunktion am Index +Transformator.5=Diese Funktion kann nicht weiter transformiert werden, sie ist bereits atomar. +Transformator.6=Ungültige Transformation +Transformator.7=Fehler +Transformator.8=Die Transformation wurde erfolgreich abgeschlossen. +Transformator.9=Transformation abgeschlossen +TransformFunction.0=abstrakte transformationsfunktion +Write.0=Diese Ramzelle ist nicht definiert! +Write.1=Falls h \u220A \u2124, dann (m+1,d,h, inp, out:h(n)) +Sub.0=Der Datenkeller enthält weniger als zwei Elemente! +Sub.1=Falls d=d.1:d.2:d.3: ... :d.n mit n \u2265 2 dann (m+1,(d.2-d.1):d.3: ... :d.n,h, inp, out) diff --git a/src/org/jalgo/module/am0c0/en.properties b/src/org/jalgo/module/am0c0/en.properties new file mode 100644 index 0000000..115162e --- /dev/null +++ b/src/org/jalgo/module/am0c0/en.properties @@ -0,0 +1,301 @@ +Add.0=Stack does not contain 2 or more values. +Add.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2+d.1):d.3: ... :d.n,h, inp, out) +AddressSolver.0=A StubTrans must not have a null address +AM0InputDialog.0=New abstract machine configuration +AM0InputDialog.1=PC +AM0InputDialog.12=Add +AM0InputDialog.13=Delete +AM0InputDialog.14=Enter a new machine configuration here.
      Use ':' to separate values in the stack
      and ',' to seperate values in the input- and output stream.

      +AM0InputDialog.15=OK +AM0InputDialog.16=Cancel +AM0InputDialog.17=Initial configuration +AM0InputDialog.18=This ram element is not valid. It should not be empty\! +AM0InputDialog.19=This ram element is not valid.\n +AM0InputDialog.2=Stack (Separated with ':') +AM0InputDialog.20=Please check this numbers:\n +AM0InputDialog.21=Address: +AM0InputDialog.24=This ram element is not valid.\n +AM0InputDialog.25=The address should not be negative or 0 but it was:\n +AM0InputDialog.26=This ram address is not valid.\n +AM0InputDialog.27=\ Please check this address: +AM0InputDialog.28=This ram address is not valid.\n +AM0InputDialog.29=\ The address should not be negative or 0 but it was:\n +AM0InputDialog.3=RAM (Address, Value) +AM0InputDialog.4=Input (Separated with ',') +AM0InputDialog.43=at least there should be one number +AM0InputDialog.44=or more separated with ',' but it was:\n +AM0InputDialog.45=This input stream is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.46=at least there should be one number +AM0InputDialog.47=or more separated with ',' but it was:\n +AM0InputDialog.48=This stack is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.49=at least there should be one number +AM0InputDialog.5=Output (Separated with ',') +AM0InputDialog.50=or more separated with ':' but it was:\n +AM0InputDialog.51=This program counter is not valid.\nIt has to be a number greater or equals 1 but it was:\n +AM0InputDialog.52=It is not allowed to the leave the program counter empty\! +AM0InputDialog.6=Value: +AM0InputDialog.7=This output stream is not valid. Multiple '-' per number are not allowed and\n +AM0InputDialog.74=RAM Configuration +AM0InputDialog.8=This address exists already. Do you want to override the value for this address? +AM0InputDialog.87=Stack Configuration +AM0InputDialog.9=This address did not exists:\n +AM0PagingTableModel.0=PC +AM0PagingTableModel.1=Stack +AM0PagingTableModel.10=  Showing steps from +AM0PagingTableModel.11= to +AM0PagingTableModel.12= +AM0PagingTableModel.2=Ram +AM0PagingTableModel.3=Input +AM0PagingTableModel.4=Output +AM0PagingTableModel.7=  Showing steps from +AM0PagingTableModel.8= to +AM0PagingTableModel.9= +AM0Scanner.0=Unknown internal scanner error +AM0Scanner.1=Error: could not match input +AM0Scanner.2=Error: pushback value was too large +AtomicTrans.0=This AtomicType is not valid +AtomicTrans.5=token must be null for AtomicTrans functions +AtomicTrans.6=A jump statement must have a jumpAddress +AtomicTrans.7=Applying AtomicTrans is not allowed. +BlockTrans.0=blocktrans: W() \u2212 \u2192 bProg0\n\n +BlockTrans.1=blocktrans({ decl statseq return 0;}) := stseqtrans(statseq, update(decl, tab \u2205 ), 1) +BlockTrans.2=for all decl \u2208 W() and statseq \u2208 W(), +BlockTrans.3=tab \u2205 \u2208 Tab with graph(tab \u2205 ) = \u2205 +BoolExpTrans.0=boolexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0\n\n +BoolExpTrans.1=boolexptrans(se 1 rel se 2 , tab) :=\n +BoolExpTrans.2=\tsimpleexptrans(se 1 , tab)\n +BoolExpTrans.3=\tsimpleexptrans(se 2 , tab)\n +BoolExpTrans.4=\tREL;\n +BoolExpTrans.5=for all se 1 , se 2 \u2208 W(), rel \u2208 {==, \!=, <, >, <=, >=} and tab \u2208 Tab +C0Scanner.0=Error: pushback value was too large +C0Scanner.177=Unknown internal scanner error +C0Scanner.178=Error: could not match input +Div.0=Stack does not contain 2 or more values. +Div.1=Division by zero. +Div.2=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2/d.1):d.3: ... :d.n,h, inp, out) +Editor.3=

      The syntax validation was +Editor.4=successful. Now press the Run button.

      +Editor.5=Transformed Program +EditorView.10=AM0-Code +EditorView.12=Console +EditorView.13=Options +EditorView.14=Editor +EditorView.15=Do you want to save your program before translation? +EditorView.16=Save +EditorView.17=Load some code to the editor. +EditorView.18=Save your currently edited code. +EditorView.19=Use the code for simulating or tranformating. +EditorView.2=Load +EditorView.20=Validate your code. +EditorView.21=Use AM0 code now. +EditorView.22=Use C0 code now. +EditorView.23=Line: +EditorView.24=\ Column: +EditorView.25=New file +EditorView.4=Save +EditorView.6=Validate +EditorView.7=Run +EditorView.9=C0-Code +Equal.0=Stack does not contain 2 or more values. +Equal.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2=d.1, and b=0, if d.2\!=d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +ErrorEvents.RemoveThisToken=Delete it to correct this error. +ErrorEvents.LexicalAnalysis=Lexical Analysis +ErrorEvents.SyntacticAnalysis=Syntactic Analysis +ErrorEvents.FollowingErrors=The following errors occured during validation: +ErrorEvents.FollowingError=The following error occured during validation: +ErrorEvents.NumberTooLarge=The number %s at line %d, column %d is too large: the maximum possible value is %d. +ErrorEvents.UnexpectedTokenAt=Unexpected token "%s" at line %d, column %d. +ErrorEvents.DontKnowWhatToDo=Can't process input "%s" on line %d. +ErrorEvents.UnexpectedEOF=Unexpected end-of-file at line %d, column %d. +ErrorEvents.UnexpectedEOL=Unexpected end-of-line at line %d, column %d. +ErrorEvents.InsertRelation=Insert one of the relations "==", "!=", ">=", "<=", ">" or "<" to complete this boolean expression. +ErrorEvents.InsertAmp=Insert "&" to complete this scanf statement. +ErrorEvents.InsertComma=Insert "," to correct this error. +ErrorEvents.InsertAssign=Insert "=" to correct this error. +ErrorEvents.InsertSemicolon=Insert ";" to complete the previous statement. +ErrorEvents.InsertIdent=Insert an identifier to correct this error. +ErrorEvents.InsertNumber=Insert a number to correct this error. +ErrorEvents.InsertNumber_AM0=Insert a number to complete this AM0 statement. +ErrorEvents.InsertSemicolon_AM0=Insert ";" to complete this AM0 statement. +GreaterEqual.0=Stack does not contain 2 or more values. +GreaterEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\u2265d.1, and b=0, if d.2<d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +GreaterThen.0=Stack does not contain 2 or more values. +GreaterThen.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2>d.1, and b=0, if d.2\u2264d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +JEditor.0=IO Error +JEditor.1=AM0 Program (*.am0) +JEditor.13=IO Error +JEditor.3=C0 Program (*.c0) +JEditor.8=The current code has been modified.\nDo you want to save it? +JEditor.9=Confirm +Jmc.0=Stack does not contain 1 or more values. +Jmc.1=if d=0:d.2: ... :d.n with n \u2265 1 then (e,d.2: ... :d.n,h, inp, out)
      else (m+1,d.2: ... :d.n,h, inp, out)
      If the first stack element is 0 (logic false), then the program counter will be set to e.
      Otherwise the first stack element has an other value (logic true), then the program counter will be incremented. +Jmp.0=(e,d,h, inp, out) +LesserEqual.0=Stack does not contain 2 or more values. +LesserEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\u2264d.1, and b=0, if d.2>d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +LesserThen.0=Stack does not contain 2 or more values. +LesserThen.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2<d.1, and b=0, if d.2\u2265d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +Lit.0=(m+1,z:d,h, inp, out) +Load.0=This ram cell is not defined. +Load.1=if h(n) \u220A \u2115 then (m+1,h(n):d,h, inp, out) +Mod.0=Stack does not contain 2 or more values. +Mod.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2%.1):d.3: ... :d.n,h, inp, out) +ModuleInfo.2=Franz Gregor, Martin Morgenstern,\n +ModuleInfo.3=\ Max Leuth\u00E4user, David Voigt, Felix Schmitt +ModuleInfo.5=This module step by step compiles C0 programs to AM0 programs and simulates AM0 programs. +ModuleInfo.8=GNU General Public License. Using icons from the Tango Desktop Project. +Mul.0=Stack does not contain 2 or more values. +Mul.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2*d.1):d.3: ... :d.n,h, inp, out) +NotEqual.0=Stack does not contain 2 or more values. +NotEqual.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\!=d.1, and b=0, if d.2=d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack +PresentationAction.0=Toggle presentation mode +Read.0=Target < 0 is not allowed\! +Read.1=Input stream is empty. +Read.2=if inp=first(inp).rest(inp) then (m+1,d,h[n/first(inp)], rest(inp), out)
      and for every n \u220A \u2124 and w \u220A \u2124*: first(n:w)=n and rest(n:w)=w +SimpleExpTrans.0=simpleexptrans: W() \u00D7 Tab\u2212 \u2192 bProg0 +SimulationView.11=Previous +SimulationView.13=Next +SimulationView.15=Clear +SimulationView.17=All in one step +SimulationView.19=Initial Configuration +SimulationView.23=The simulation will stop after a maximum of +SimulationView.24= steps and you have the choice to continue. +SimulationView.26=The simulation will stop after a maximum of +SimulationView.27= steps and you have the choice to continue. +SimulationView.28=\ \ Ask after: +SimulationView.29=\ steps +SimulationView.3=AM0-Table +SimulationView.31=Command-Hint +SimulationView.32=Show the first few steps of the simulation +SimulationView.33=Show the last final steps of the simulation +SimulationView.34=Return to the editor. +SimulationView.35=Go one step back. +SimulationView.36=Go one step forward +SimulationView.37=Do the whole simulation in one single step. +SimulationView.38=Enter a specific machine configuration. +SimulationView.39=Clear everything. This will delete your current machine configuration and remove every simulation step\! +SimulationView.4=AM0-Animation +SimulationView.5=To the top of the table +SimulationView.6=To the bottom of the table +SimulationView.7=Not started yet. +SimulationView.9=Back to Editor +Simulator.0=The was an error while simulating.\n +Simulator.1=The following command could not be executed:\n +Simulator.10=Latest step: +Simulator.12=  Showing steps from +Simulator.13= to +Simulator.14= +Simulator.15=\ \ Latest step: +Simulator.17=\ \ Latest step: +Simulator.19=\ steps are calculated.\n +Simulator.20=Do you want to continue?\n\n +Simulator.21=Choose 'no' to stop the simulation or 'yes' if you want to go on. +Simulator.22=Simulation +Simulator.23=\ \ Latest step: +Simulator.25=Not started yet. +Simulator.3=Reason:\n +Simulator.4=This jump command could not be executed:\n +Simulator.6=Reason:\n +Store.0=Stack does not contain 1 or more values. +Store.1=if d=d.1:d' then (m+1,d',h[n/d.1], inp, out)
      and h[n/d.1](k)={d.1
      h(k)
      if k=n
      otherwise
      +STSeqTrans.0=stseqtrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STSeqTrans.1=stseqtrans(stat 1 stat 2 . . . stat n , tab, a) :=\n +STSeqTrans.2=\tsttrans(stat 1 , tab, a.1)\n +STSeqTrans.3=\tsttrans(stat 2 , tab, a.2)\n +STSeqTrans.4=\t...\n +STSeqTrans.5=\tsttrans(stat n , tab, a.n)\n +STSeqTrans.6=for all stat 1 , stat 2 , . . . , stat n \u2208 W(), tab \u2208 Tab and a \u2208 N\u2217 +STSeqTrans.7=It was attempted to translate an empty statement sequence. +STTrans.AssignError=The symbol on the left side of this assignment does not exist or is a constant symbol! +STTrans.ScanfError=The symbol in this scanf statement does not exist or is a constant symbol! +STTrans.PrintfError=The symbol in this printf statement does not exist or is a constant symbol! +STTrans.0=sttrans: W() \u00D7 Tab \u00D7 N\u2217 \u2212 \u2192 bProg0\n\n +STTrans.1=sttrans({ stat 1 stat 2 . . . stat n }, tab, a) :=\n +STTrans.10=sttrans(printf("%d",id);, tab, a) :=\n +STTrans.11=\tif tab(id ) = (var, n) then WRITE n;\n +STTrans.12=\tfor all id \u2208 W( Ident ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.13=sttrans(if ( exp ) stat, tab, a) :=\n +STTrans.14=\tboolexptrans(exp, tab)\n +STTrans.15=\tJMC a.1;\n +STTrans.16=\tsttrans(stat , tab, a.2)\n +STTrans.17=\ta.1:\n +STTrans.18=\tfor all exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.19=\tand a \u2208 N\u2217 +STTrans.2=\tstseqtrans(stat 1 stat 2 . . . stat n , tab, a)\n +STTrans.20=sttrans(if ( exp ) stat 1 else stat 2 , tab, a) :=\n +STTrans.21=\tboolexptrans(exp, tab)\n +STTrans.22=\tJMC a.1;\n +STTrans.23=\tsttrans(stat 1 , tab, a.2)\n +STTrans.24=\tJMP a.3;\n +STTrans.25=\ta.1: sttrans(stat 2 , tab, a.4)\n +STTrans.26=\ta.3:\n +STTrans.27=\tfor all exp \u2208 W( BoolExpression ), stat 1 , stat 2 \u2208 W( Statement ),\n +STTrans.28=\ttab \u2208 Tab and a \u2208 N\u2217 +STTrans.29=sttrans(while ( exp ) stat, tab, a) :=\n +STTrans.3=\tfor all stat 1 , stat 2 , . . . , stat n \u2208 W( statement ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.30=\ta.1 : boolexptrans(exp, tab)\n +STTrans.31=\tJMC a.2;\n +STTrans.32=\tsttrans(stat , tab, a.3)\n +STTrans.33=\tJMP a.1;\n +STTrans.34=\ta.2:\n +STTrans.35=\tfor all exp \u2208 W( BoolExpression ), stat \u2208 W( Statement ), tab \u2208 Tab\n +STTrans.36=\tand a \u2208 N\u2217 +STTrans.4=sttrans(id = exp;, tab, a) :=\n +STTrans.5=\tif tab(id ) = (var, n) then simpleexptrans(exp, tab) STORE n; +STTrans.6=\tfor all id \u2208 W( Ident ), exp \u2208 W( SimpleExpression ), tab \u2208 Tab and a \u2208 N\u2217 +STTrans.7=sttrans(scanf("%i",&id);, tab, a) :=\n +STTrans.8=\tif tab(id ) = (var, n) then READ n;\n +STTrans.9=\tfor all id \u2208 W( Ident ), tab \u2208 Tab and a \u2208 N\u2217 +Symbol.0=The memory address must not be < +Symbol.1=Retrieving the address of a constant symbol is forbidden. +SymbolTable.0=A symbol with id +SymbolTable.1=\ already exists. +SymbolTable.10=It was attempted to retrieve the value of a non-existent symbol +SymbolTable.11=It was attempted to retrieve the SymbolType of an non-existent symbol +SymbolTable.2=A variable with address +SymbolTable.3=\ already exists +SymbolTable.9=It was attempted to retrieve the SymbolType of a non-existent symbol +Trans.0=trans: W() \u2212 \u2192 bProg0\n\n +Trans.1=trans( \#include int main() block ) := blocktrans(block) for all block \u2208 W() +TransformationView.0=Type +TransformationView.1=ID +TransformationView.10=Apply +TransformationView.12=Apply all +TransformationView.14=Simulate +TransformationView.16=Back to Editor +TransformationView.18=Definition / Rule +TransformationView.19=Preview +TransformationView.2=Address +TransformationView.25=Do you want to transmit the even translated program into the editor? +TransformationView.26=Transmit +TransformationView.3=tab(ID) +TransformationView.32=Error +TransformationView.33=Applying all is not possible in state FINISHED. Internal program error\! +TransformationView.34=Error +TransformationView.35=Error +TransformationView.4=Error +TransformationView.40=Return to the editor. +TransformationView.41=Go one step back. +TransformationView.42=Go one step forward and apply the selected transform function +TransformationView.43=Do the whole transformation in one single step. +TransformationView.44=Transfer the resulting AM0 code to the simulator. +TransformationView.5=Error +TransformationView.6=Error +TransformationView.8=One step back +Transformator.0=Error +Transformator.1=This functions is atomic and cannot be transformed anymore. +Transformator.11=Error +Transformator.12=The transformation finished successfully. +Transformator.13=Transformation finished +Transformator.15=This index points to a TransformFunction which cannot be applied.\n +Transformator.2=Invalid transformation +Transformator.3=There is no TransformFunction at index +Transformator.5=This functions is atomic and cannot be transformed anymore. +Transformator.6=Invalid transformation +Transformator.7=Error +Transformator.8=The transformation finished successfully. +Transformator.9=Transformation finished +TransformFunction.0=abstract transform function +Write.0=This ram cell is not defined. +Write.1=if h \u220A \u2124 then (m+1,d,h, inp, out:h(n)) +Sub.0=Stack does not contain 2 or more values. +Sub.1=if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2-d.1):d.3: ... :d.n,h, inp, out) diff --git a/src/org/jalgo/module/am0c0/gui/AM0InputDialog.java b/src/org/jalgo/module/am0c0/gui/AM0InputDialog.java new file mode 100644 index 0000000..348bf0c --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/AM0InputDialog.java @@ -0,0 +1,548 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.LinkedList; +import java.util.TreeMap; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.core.Simulator; +import org.jalgo.module.am0c0.model.SimulationSet; +import org.jalgo.module.am0c0.model.am0.MachineConfiguration; + +/** + * Simple modal dialog to allow the user to type in a new AM configuration. + * Returns a valid {@link MachineConfiguration} + * + * @see AM0InputDialog#showAndWaitForReturn() + * + * @author Max Leuthäuser + */ +public class AM0InputDialog extends JComponent implements ActionListener { + private static final long serialVersionUID = 1L; + private static MachineConfiguration machineConfiguration = null; + private JButton ok, cancel, ramAdd, ramDel; + private JLabel pcDesc, stackDesc, ramDesc, inDesc, outDesc, ramInput; + private JTextField pcInput, stackInput, inInput, outInput, ramAdInput, + ramValueInput; + private JPanel inputs, buttons; + private JDialog dialog; + private TreeMap ramMap = new TreeMap(); + private static JSlider steps; + private Simulator simController; + + static final int STEPS_MIN = 2000; + /** + * Constants to stop the presentation after the given number of steps and + * ask the user if he wants to go on. + */ + static final int STEPS_MAX = 10000; + static final int STEPS_INIT = 8000; + + private AM0InputDialog(Simulator s) { + simController = s; + dialog = new JDialog(); + dialog.setTitle(Messages.getString("am0c0", "AM0InputDialog.0")); //$NON-NLS-1$ + dialog.setResizable(false); + dialog.setModal(true); + dialog.setLayout(new BorderLayout()); + ((JPanel) dialog.getContentPane()).setBorder(BorderFactory + .createEmptyBorder(10, 10, 10, 10)); + createBaseLayout(); + createInputLayout(); + + dialog.pack(); + dialog.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width + / 2 - (dialog.getSize().width / 2), Toolkit.getDefaultToolkit() + .getScreenSize().height / 2 - (dialog.getSize().height / 2)); + dialog.setVisible(true); + } + + /** + * Create the input layout including text fields and description to enter a + * new AM0 configuration. + */ + private void createInputLayout() { + inputs = new JPanel(); + inputs.setLayout(new BoxLayout(inputs, BoxLayout.Y_AXIS)); + pcDesc = new JLabel(Messages.getString("am0c0", "AM0InputDialog.1")); //$NON-NLS-1$ + pcDesc.setFont(new Font(pcDesc.getFont().getFontName(), Font.BOLD, + pcDesc.getFont().getSize())); + stackDesc = new JLabel(Messages.getString("am0c0", "AM0InputDialog.2")); //$NON-NLS-1$ + stackDesc.setFont(new Font(stackDesc.getFont().getFontName(), + Font.BOLD, stackDesc.getFont().getSize())); + ramDesc = new JLabel(Messages.getString("am0c0", "AM0InputDialog.3")); //$NON-NLS-1$ + ramDesc.setFont(new Font(ramDesc.getFont().getFontName(), Font.BOLD, + ramDesc.getFont().getSize())); + inDesc = new JLabel(Messages.getString("am0c0", "AM0InputDialog.4")); //$NON-NLS-1$ + inDesc.setFont(new Font(inDesc.getFont().getFontName(), Font.BOLD, + inDesc.getFont().getSize())); + outDesc = new JLabel(Messages.getString("am0c0", "AM0InputDialog.5")); //$NON-NLS-1$ + outDesc.setFont(new Font(outDesc.getFont().getFontName(), Font.BOLD, + outDesc.getFont().getSize())); + + pcInput = new JTextField(); + pcInput.setHorizontalAlignment(JTextField.CENTER); + pcInput.setText(" 1 "); //$NON-NLS-1$ + pcInput.setCaretPosition(3); + stackInput = new JTextField(); + stackInput.setText("Æ"); //$NON-NLS-1$ + ramInput = new JLabel(); + ramInput.setBackground(Color.white); + char o = '\u00D8'; + ramInput.setText("h" + o + "= [ ]"); //$NON-NLS-1$ //$NON-NLS-2$ + inInput = new JTextField(); + inInput.setText("Æ"); //$NON-NLS-1$ + outInput = new JTextField(); + outInput.setText("Æ"); //$NON-NLS-1$ + + ramAdInput = new JTextField("1"); + ramValueInput = new JTextField(); + + ramAdd = new JButton(Messages.getString("am0c0", "AM0InputDialog.12")); //$NON-NLS-1$ + ramAdd.addActionListener(this); + ramDel = new JButton(Messages.getString("am0c0", "AM0InputDialog.13")); //$NON-NLS-1$ + ramDel.addActionListener(this); + + JPanel pc = new JPanel(); + pc.setLayout(new BorderLayout(5, 5)); + pc.add(pcDesc, BorderLayout.NORTH); + pc.add(pcInput, BorderLayout.WEST); + + JPanel stack = new JPanel(); + stack.setLayout(new BorderLayout(5, 5)); + stack.add(stackDesc, BorderLayout.NORTH); + stack.add(stackInput, BorderLayout.CENTER); + + JPanel ram = new JPanel(); + JPanel holdA = new JPanel(); + holdA.setLayout(new GridLayout(1, 4)); + holdA.add(ramAdInput); + holdA.add(ramValueInput); + holdA.add(ramAdd); + holdA.add(ramDel); + JPanel holdB = new JPanel(); + holdB.setLayout(new BorderLayout()); + holdB.add(ramInput, BorderLayout.CENTER); + ram.setLayout(new GridLayout(3, 1, 5, 0)); + ram.add(ramDesc); + ram.add(holdA); + ram.add(holdB); + + JPanel in = new JPanel(); + in.setLayout(new BorderLayout(5, 5)); + in.add(inDesc, BorderLayout.NORTH); + in.add(inInput, BorderLayout.CENTER); + + JPanel out = new JPanel(); + out.setLayout(new BorderLayout(5, 5)); + out.add(outDesc, BorderLayout.NORTH); + out.add(outInput, BorderLayout.CENTER); + + inputs.add(pc); + inputs.add(Box.createRigidArea(new Dimension(10, 15))); + inputs.add(stack); + inputs.add(Box.createRigidArea(new Dimension(10, 15))); + inputs.add(ram); + inputs.add(Box.createRigidArea(new Dimension(10, 15))); + inputs.add(in); + inputs.add(Box.createRigidArea(new Dimension(10, 15))); + inputs.add(out); + + dialog.add(inputs, BorderLayout.CENTER); + + JLabel desc = new JLabel(Messages.getString( + "am0c0", "AM0InputDialog.14")); //$NON-NLS-1$ + dialog.add(desc, BorderLayout.NORTH); + + steps = new JSlider(JSlider.HORIZONTAL, STEPS_MIN, STEPS_MAX, + STEPS_INIT); + steps.setMajorTickSpacing(2000); + steps.setMinorTickSpacing(1000); + steps.setPaintTicks(true); + steps.setPaintLabels(true); + + steps.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.23") //$NON-NLS-1$ + + steps.getValue() + + Messages.getString( + "am0c0", "SimulationView.24")); //$NON-NLS-1$ + } + }); + steps.addMouseListener(new MouseListener() { + + @Override + public void mouseReleased(MouseEvent e) { + + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + simController.getController().writeOnStatusbar(""); //$NON-NLS-1$ + } + + @Override + public void mouseEntered(MouseEvent e) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.26") //$NON-NLS-1$ + + steps.getValue() + + Messages.getString( + "am0c0", "SimulationView.27")); //$NON-NLS-1$ + } + + @Override + public void mouseClicked(MouseEvent e) { + } + }); + JPanel holder = new JPanel(); + holder.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), "Option")); + holder.setLayout(new BorderLayout()); + holder.add( + new JLabel(Messages.getString("am0c0", "SimulationView.28")), BorderLayout.WEST); //$NON-NLS-1$ + holder.add(steps, BorderLayout.CENTER); + holder.add( + new JLabel(Messages.getString("am0c0", "SimulationView.29")), BorderLayout.EAST); //$NON-NLS-1$ + inputs.add(Box.createRigidArea(new Dimension(10, 15))); + inputs.add(holder); + } + + /** + * Create the base layout including the 'OK' and 'Cancel' button. + */ + private void createBaseLayout() { + buttons = new JPanel(); + buttons.setLayout(new GridLayout(1, 3)); + + ok = new JButton(Messages.getString("am0c0", "AM0InputDialog.15")); //$NON-NLS-1$ + ok.addActionListener(this); + cancel = new JButton(Messages.getString("am0c0", "AM0InputDialog.16")); //$NON-NLS-1$ + cancel.addActionListener(this); + + buttons.add(new JPanel()); + buttons.add(ok); + buttons.add(cancel); + buttons.add(new JPanel()); + + buttons.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); + + dialog.add(buttons, BorderLayout.SOUTH); + } + + /** + * Use this method to show this dialog and wait for the result. + * + * @return a new valid {@link MachineConfiguration} or null if the + * user cancel this dialog. + */ + public static SimulationSet showAndWaitForReturn(Simulator s) { + new AM0InputDialog(s); + return new SimulationSet(machineConfiguration, steps.getValue()); + } + + /** + * Show an error dialog if the am0 configuration is not valid. + * + * @param description + */ + private void showError(String description) { + JOptionPane + .showMessageDialog( + null, + description, + Messages.getString("am0c0", "AM0InputDialog.17"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ + } + + /** + * Checks the numbers the users wants to type in as new ram elements. + * + * @param add + * the address which should be checked + * @param val + * the value at the given address which should be checked + * @return true if both numbers are valid, false otherwise. + */ + private boolean checkRamInput(String add, String val) { + if (add.isEmpty() || val.isEmpty()) { + showError(Messages.getString("am0c0", "AM0InputDialog.18")); //$NON-NLS-1$ + return false; + } + + @SuppressWarnings("unused") + int value; + int address = 0; + try { + address = Integer.parseInt(add); + value = Integer.parseInt(val); + } catch (NumberFormatException e) { + showError(Messages.getString("am0c0", "AM0InputDialog.19") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.20") + Messages.getString("am0c0", "AM0InputDialog.21") + add + "\n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + Messages.getString("am0c0", "AM0InputDialog.6") + val); //$NON-NLS-1$ + return false; + } + if (address <= 0) { + showError(Messages.getString("am0c0", "AM0InputDialog.24") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.25") //$NON-NLS-1$ + + address); + return false; + } + return true; + } + + /** + * Checks the address the users wants to type in as new ram address. + * + * @param add + * @return true if address is valid, false otherwise. + */ + private boolean checkRamAddress(String add) { + int address = 0; + try { + address = Integer.parseInt(add); + } catch (NumberFormatException e) { + showError(Messages.getString("am0c0", "AM0InputDialog.26") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.27") + add); //$NON-NLS-1$ + return false; + } + if (address <= 0) { + showError(Messages.getString("am0c0", "AM0InputDialog.28") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.29") //$NON-NLS-1$ + + address); + return false; + } + return true; + } + + /** + * Checks the elements the users wants to type in as new ram configuration. + * + * @param pc + * @param stack + * @param in + * @param out + * @return true if everything is valid, false otherwise. + */ + private boolean checkInput(String pc, String stack, String in, String out) { + if (pc.trim().replaceAll(" ", "").matches("[0-9]+")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + if (stack.trim().isEmpty() + || stack.trim().replaceAll(" ", "").matches( //$NON-NLS-1$ //$NON-NLS-2$ + "Æ|(-?[0-9]+:{1})*-?[0-9]+")) { //$NON-NLS-1$ + if (in.trim().isEmpty() + || in.trim().replaceAll(" ", "").matches( //$NON-NLS-1$ //$NON-NLS-2$ + "Æ|(-?[0-9]+,{1})*-?[0-9]+")) { //$NON-NLS-1$ + if (out.trim().isEmpty() + || out.trim().replaceAll(" ", "").matches( //$NON-NLS-1$ //$NON-NLS-2$ + "Æ|(-?[0-9]+,{1})*-?[0-9]+")) { //$NON-NLS-1$ + return true; + } else { + showError(Messages.getString( + "am0c0", "AM0InputDialog.7") //$NON-NLS-1$ + + Messages.getString( + "am0c0", "AM0InputDialog.43") //$NON-NLS-1$ + + Messages.getString( + "am0c0", "AM0InputDialog.44") //$NON-NLS-1$ + + out); + } + } else { + showError(Messages.getString("am0c0", "AM0InputDialog.45") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.46") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.47") + in); //$NON-NLS-1$ + } + } else { + showError(Messages.getString("am0c0", "AM0InputDialog.48") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.49") //$NON-NLS-1$ + + Messages.getString("am0c0", "AM0InputDialog.50") + stack); //$NON-NLS-1$ + } + } else { + if (!pc.isEmpty()) { + showError(Messages.getString("am0c0", "AM0InputDialog.51") //$NON-NLS-1$ + + pc); + } else { + showError(Messages.getString("am0c0", "AM0InputDialog.52")); //$NON-NLS-1$ + } + } + return false; + } + + /** + * Handle 'OK' and 'Cancel' click and handle RAM input/delete buttons + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent arg0) { + if (arg0.getSource() == ok) { + if (checkInput(pcInput.getText(), stackInput.getText(), + inInput.getText(), outInput.getText())) { + if (stackInput.getText().replaceAll(" ", "").isEmpty() //$NON-NLS-1$ //$NON-NLS-2$ + && inInput.getText().replaceAll(" ", "").isEmpty() //$NON-NLS-1$ //$NON-NLS-2$ + && outInput.getText().replaceAll(" ", "").isEmpty() //$NON-NLS-1$ //$NON-NLS-2$ + && ramInput.getText().startsWith("h")) { //$NON-NLS-1$ + machineConfiguration = new MachineConfiguration(); + } else { + int pc = Integer.parseInt(pcInput.getText().replaceAll(" ", //$NON-NLS-1$ + "")); //$NON-NLS-1$ + LinkedList stack = null; + LinkedList in = null; + LinkedList out = null; + String delims = "[:]"; //$NON-NLS-1$ + String[] tokens; + + if (!stackInput.getText().equals("Æ")) { //$NON-NLS-1$ + stack = new LinkedList(); + tokens = stackInput.getText().replaceAll(" ", "") //$NON-NLS-1$ //$NON-NLS-2$ + .split(delims); + for (String s : tokens) { + if (!s.isEmpty()) + stack.add(Integer.parseInt(s)); + } + } + + delims = "[,]"; //$NON-NLS-1$ + if (!inInput.getText().equals("Æ")) { //$NON-NLS-1$ + in = new LinkedList(); + tokens = inInput.getText().replaceAll(" ", "").split( //$NON-NLS-1$ //$NON-NLS-2$ + delims); + for (String s : tokens) { + if (!s.isEmpty()) + in.add(Integer.parseInt(s)); + } + } + + if (!outInput.getText().equals("Æ")) { //$NON-NLS-1$ + out = new LinkedList(); + tokens = outInput.getText().replaceAll(" ", "").split( //$NON-NLS-1$ //$NON-NLS-2$ + delims); + for (String s : tokens) { + if (!s.isEmpty()) + out.add(Integer.parseInt(s)); + } + } + + if (ramMap.isEmpty()) { + machineConfiguration = new MachineConfiguration(pc, + stack, null, in, out); + } else { + machineConfiguration = new MachineConfiguration(pc, + stack, ramMap, in, out); + } + } + dialog.setVisible(false); + dialog.dispose(); + } + } + if (arg0.getSource() == cancel) { + machineConfiguration = null; + dialog.setVisible(false); + dialog.dispose(); + } + if (arg0.getSource() == ramAdd) { + if (checkRamInput(ramAdInput.getText(), ramValueInput.getText())) { + if (ramMap.containsKey(Integer.parseInt(ramAdInput.getText()))) { + if (JOptionPane + .showConfirmDialog(dialog, Messages.getString( + "am0c0", "AM0InputDialog.8"), //$NON-NLS-1$ + Messages.getString( + "am0c0", "AM0InputDialog.74"), 0) == JOptionPane.OK_OPTION) { //$NON-NLS-1$ + ramMap.put(Integer.parseInt(ramAdInput.getText()), + Integer.parseInt(ramValueInput.getText())); + } + } else { + ramMap.put(Integer.parseInt(ramAdInput.getText()), + Integer.parseInt(ramValueInput.getText())); + } + String result = "["; //$NON-NLS-1$ + for (int i : ramMap.keySet()) { + result += ", " + i + "/" + ramMap.get(i); //$NON-NLS-1$ //$NON-NLS-2$ + } + ramInput.setText(result.replaceFirst(", ", "") + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ramInput.setToolTipText(result.replaceFirst(", ", "") + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ramValueInput.setText(""); //$NON-NLS-1$ + ramAdInput.setText("" + (ramMap.lastKey() + 1)); //$NON-NLS-1$ + } + } + if (arg0.getSource() == ramDel) { + if (!ramAdInput.getText().isEmpty() + && checkRamAddress(ramAdInput.getText())) { + if (!ramMap.containsKey(Integer.parseInt(ramAdInput.getText()))) { + JOptionPane + .showMessageDialog( + null, + Messages.getString( + "am0c0", "AM0InputDialog.9") //$NON-NLS-1$ + + ramAdInput.getText(), + Messages.getString( + "am0c0", "AM0InputDialog.87"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ + } else { + ramMap.remove(Integer.parseInt(ramAdInput.getText())); + if (ramMap.isEmpty()) { + char o = '\u00D8'; + String result = "h" + o + "= [ ]"; //$NON-NLS-1$ //$NON-NLS-2$ + ramInput.setText(result); + ramInput.setToolTipText(result); + } else { + String result = "["; //$NON-NLS-1$ + for (int i : ramMap.keySet()) { + result += ", " + i + "/" + ramMap.get(i); //$NON-NLS-1$ //$NON-NLS-2$ + } + ramInput.setText(result.replaceFirst(", ", "") + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ramInput.setToolTipText(result.replaceFirst(", ", "") //$NON-NLS-1$ //$NON-NLS-2$ + + "]"); //$NON-NLS-1$ + } + + } + } + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/AMTableRenderer.java b/src/org/jalgo/module/am0c0/gui/AMTableRenderer.java new file mode 100644 index 0000000..e061af3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/AMTableRenderer.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.Color; +import java.awt.Component; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; + +/** + * Custom table renderer to show rows in different colors. + * + * @author Max Leuthäuser + */ +class AMTableRenderer extends DefaultTableCellRenderer { + private static final long serialVersionUID = 1L; + private final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + Component cell; + cell = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, + isSelected, hasFocus, row, column); + + cell.setForeground(Color.BLACK); + if (!isSelected) { + if (row % 2 == 0) { + cell.setBackground(GuiConstants.TABLE_EVEN); + } else { + cell.setBackground(GuiConstants.TABLE_ODD); + } + } else { + if (row % 2 == 0) { + cell.setBackground(Color.YELLOW); + } else { + cell.setBackground(Color.ORANGE); + } + } + if (column == 0) { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.CENTER); + return cell; + } else { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.LEFT); + } + if (column == 1) { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.RIGHT); + return cell; + //cell.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + } else { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.LEFT); + //cell.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); + } + return cell; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/CVS/Entries b/src/org/jalgo/module/am0c0/gui/CVS/Entries new file mode 100644 index 0000000..373d47c --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/CVS/Entries @@ -0,0 +1,9 @@ +/AM0InputDialog.java/1.2/Wed Dec 8 13:01:52 2010// +/AMTableRenderer.java/1.1/Mon Aug 16 12:05:47 2010// +/EditorView.java/1.2/Thu Jun 18 13:39:41 2015// +/GuiConstants.java/1.1/Mon Aug 16 12:05:47 2010// +/SimulationView.java/1.2/Thu Jun 18 13:39:41 2015// +/TransformationView.java/1.2/Thu Jun 18 13:39:41 2015// +/View.java/1.1/Thu Jun 18 13:39:41 2015// +D/jeditor//// +/package-info.java/1.1/Mon Aug 16 12:05:47 2010// diff --git a/src/org/jalgo/module/am0c0/gui/CVS/Repository b/src/org/jalgo/module/am0c0/gui/CVS/Repository new file mode 100644 index 0000000..f4f8860 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/gui diff --git a/src/org/jalgo/module/am0c0/gui/CVS/Root b/src/org/jalgo/module/am0c0/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/gui/EditorView.java b/src/org/jalgo/module/am0c0/gui/EditorView.java new file mode 100644 index 0000000..b7521b0 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/EditorView.java @@ -0,0 +1,422 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.core.Editor; +import org.jalgo.module.am0c0.core.ILoveCandy; +import org.jalgo.module.am0c0.gui.GuiConstants; +import org.jalgo.module.am0c0.gui.View; +import org.jalgo.module.am0c0.gui.jeditor.JEditor; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.CTokenMarker; + +/** + * This class represents the Editor in the JAlgo module C0/AM0. + * + * @author Max Leuthäuser + * @author Felix Schmitt + */ +public class EditorView extends View { + private static final long serialVersionUID = 1L; + private JPanel buttonFields, buttonPanel, buttonPanel2, contentPanel; + public JEditor codeField; + private JEditorPane logConsole; + private JButton loadButton; + private JButton saveButton; + private JButton runButton; + private JButton validateButton; + public ButtonGroup codeSelector; + public JRadioButton c0Button, am0Button; + private JSplitPane hSplitPane; + private ButtonHandler buttonHandler; + private Editor editorController; + public JTabbedPane tabPane; + + public EditorView(Editor editorController) { + this.editorController = editorController; + initComponents(); + initComponentAttributs(); + attachButtonHandler(); + add(contentPanel); + } + + /** + * Set the text of the console. + * + * @param text + * the text which should be printed + */ + public void setConsoleText(String text) { + logConsole.setText("" //$NON-NLS-1$ + + text + ""); //$NON-NLS-1$ + } + + /** + * Delete the current content of the console. + */ + public void clearConsoleText() { + logConsole.setText(null); + } + + /** + * @return the {@link JEditor} from this {@link EditorView}. + */ + public JEditor getJEditor() { + return codeField; + } + + @Override + protected void initComponents() { + buttonHandler = new ButtonHandler(); + loadButton = new JButton(Messages.getString("am0c0", "EditorView.2")); //$NON-NLS-1$ + loadButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.OPEN_ICON))); + saveButton = new JButton(Messages.getString("am0c0", "EditorView.4")); //$NON-NLS-1$ + saveButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.SAVE_ICON))); + + validateButton = new JButton( + Messages.getString("am0c0", "EditorView.6")); //$NON-NLS-1$ + + runButton = new JButton(Messages.getString("am0c0", "EditorView.7")); //$NON-NLS-1$ + runButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.RUN_ICON))); + runButton.setEnabled(false); + + codeSelector = new ButtonGroup(); + c0Button = new JRadioButton(Messages.getString("am0c0", "EditorView.9")); //$NON-NLS-1$ + c0Button.setSelected(true); + am0Button = new JRadioButton(Messages.getString( + "am0c0", "EditorView.10")); //$NON-NLS-1$ + + buttonPanel = new JPanel(); + buttonPanel2 = new JPanel(); + + buttonFields = new JPanel(); + + codeField = new JEditor(new Observer() { + public void update(Observable arg0, Object arg1) { + if (((JEditor) arg1).isModified()) { + tabPane.setForeground(Color.RED); + tabPane.setFont(tabPane.getFont().deriveFont(Font.ITALIC)); + if (c0Button.isSelected()) + editorController.setState(new Editor.StateNotValidatedC0()); + else + editorController + .setState(new Editor.StateNotValidatedAM0()); + runButton.setEnabled(false); + } + ; + } + }, null); + codeField.setTokenMarker(new CTokenMarker()); + codeField.setCaretVisible(false); + + codeField.addCaretListener(new CaretListener() { + @Override + public void caretUpdate(CaretEvent arg0) { + int cPos = codeField.getCaretPosition(); + int lineNumber = codeField.getLineOfOffset(cPos); + int startOffset = codeField.getLineStartOffset(lineNumber); + String str = codeField.getText(startOffset, + (cPos - startOffset)); + int len = str.length() + 1; + + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.23") + + (lineNumber + 1) + + Messages.getString("am0c0", "EditorView.24") + + len); + } + }); + + logConsole = new JEditorPane("text/html", null); //$NON-NLS-1$ + logConsole.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); + logConsole.setFont(GuiConstants.STANDARDFONT_SERIF); + JTabbedPane tab = new JTabbedPane(); + JScrollPane logScrollPane = getScrollPane(logConsole); + logScrollPane + .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + tab.addTab(Messages.getString("am0c0", "EditorView.12"), logScrollPane); //$NON-NLS-1$ + tabPane = new JTabbedPane(); + tabPane.addTab(Messages.getString("am0c0", "EditorView.25"), codeField); + hSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, tabPane, + tab); + + contentPanel = new JPanel(); + contentPanel.setLayout(new BorderLayout()); + contentPanel.add(hSplitPane, BorderLayout.CENTER); + contentPanel.add(buttonFields, BorderLayout.EAST); + } + + @Override + protected void attachButtonHandler() { + loadButton.addActionListener(buttonHandler); + saveButton.addActionListener(buttonHandler); + runButton.addActionListener(buttonHandler); + validateButton.addActionListener(buttonHandler); + am0Button.addActionListener(buttonHandler); + c0Button.addActionListener(buttonHandler); + + loadButton.addMouseListener(buttonHandler); + saveButton.addMouseListener(buttonHandler); + runButton.addMouseListener(buttonHandler); + validateButton.addMouseListener(buttonHandler); + am0Button.addMouseListener(buttonHandler); + c0Button.addMouseListener(buttonHandler); + } + + @Override + protected void initComponentAttributs() { + setLayout(new BorderLayout()); + + codeSelector.add(am0Button); + codeSelector.add(c0Button); + + buttonPanel.setLayout(new BorderLayout()); + buttonPanel.add(loadButton, BorderLayout.NORTH); + buttonPanel.add(saveButton, BorderLayout.CENTER); + JPanel p = new JPanel(); + p.add(c0Button); + p.add(am0Button); + buttonPanel.add(p, BorderLayout.SOUTH); + + buttonFields.setLayout(new BorderLayout()); + buttonFields.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "EditorView.13"))); //$NON-NLS-1$ + + buttonPanel2.setLayout(new BorderLayout()); + buttonPanel2.add(this.validateButton, BorderLayout.NORTH); + buttonPanel2.add(this.runButton, BorderLayout.SOUTH); + + buttonFields.add(buttonPanel, BorderLayout.PAGE_START); + buttonFields.add(buttonPanel2, BorderLayout.PAGE_END); + + logConsole.setEditable(false); + + hSplitPane.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "EditorView.14"))); //$NON-NLS-1$ + + hSplitPane + .setDividerLocation(GuiConstants.getJAlgoWindow().getSize().height / 2); + + hSplitPane.setOneTouchExpandable(true); + } + + private void startCandy() { + loadButton.setEnabled(false); + saveButton.setEnabled(false); + runButton.setEnabled(false); + validateButton.setEnabled(false); + hSplitPane.setLeftComponent(new ILoveCandy(this)); + hSplitPane + .setDividerLocation(GuiConstants.getJAlgoWindow().getHeight() / 2); + hSplitPane.getLeftComponent().requestFocus(); + } + + public void stopCandy() { + loadButton.setEnabled(true); + saveButton.setEnabled(true); + validateButton.setEnabled(true); + hSplitPane.setLeftComponent(codeField); + } + + private class ButtonHandler implements ActionListener, MouseListener { + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == loadButton) { + String s = editorController.loadCode(); + if (!s.isEmpty()) { + tabPane.setForeground(Color.BLACK); + tabPane.setFont(tabPane.getFont().deriveFont(Font.PLAIN)); + tabPane.setTitleAt(0, s); + } + runButton.setEnabled(false); + } + if (e.getSource() == saveButton) { + String s = editorController.saveCode(); + if (!s.isEmpty()) { + if (c0Button.isSelected()) + editorController + .setState(new Editor.StateNotValidatedC0()); + else + editorController + .setState(new Editor.StateNotValidatedAM0()); + tabPane.setForeground(Color.BLACK); + tabPane.setFont(tabPane.getFont().deriveFont(Font.PLAIN)); + tabPane.setTitleAt(0, s); + } + runButton.setEnabled(false); + } + + if (e.getSource() == validateButton) { + if (codeField.getText().toLowerCase().equals("ilovecandy")) { + startCandy(); + } else { + clearConsoleText(); + if (!codeField.getText().trim().isEmpty()) { + if (codeSelector.isSelected(am0Button.getModel())) { + runButton.setEnabled(editorController + .validate(Editor.AM0)); + } + + if (codeSelector.isSelected(c0Button.getModel())) { + runButton.setEnabled(editorController + .validate(Editor.C0)); + } + } + } + } + + if (e.getSource() == runButton) { + if (!codeField.getText().trim().isEmpty()) { + if (codeSelector.isSelected(am0Button.getModel())) { + editorController + .getController() + .getSimulator() + .setAM0Program( + editorController.getState() + .getAM0Program()); + editorController.getController().showSimulator(); + } + + if (codeSelector.isSelected(c0Button.getModel())) { + if (codeField.isModified()) { + int choice = JOptionPane.NO_OPTION; + choice = JOptionPane + .showConfirmDialog( + editorController.getView(), + Messages.getString( + "am0c0", "EditorView.15"), //$NON-NLS-1$ + Messages.getString( + "am0c0", "EditorView.16"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ + if (choice == JOptionPane.YES_OPTION) { + codeField.saveCode(); + } + } + editorController + .getController() + .getTransformator() + .setC0Program( + editorController.getState() + .getC0Program()); + + editorController.getController().showTransformator(); + } + } + } + if (e.getSource() == am0Button) { + runButton.setEnabled(false); + editorController.setState(new Editor.StateNotValidatedAM0()); + } + if (e.getSource() == c0Button) { + runButton.setEnabled(false); + editorController.setState(new Editor.StateNotValidatedC0()); + } + } + + @Override + public void mouseClicked(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + if (e.getSource() == loadButton) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.17")); //$NON-NLS-1$ + } + if (e.getSource() == saveButton) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.18")); //$NON-NLS-1$ + } + if (e.getSource() == runButton) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.19")); //$NON-NLS-1$ + + } + if (e.getSource() == validateButton) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.20")); //$NON-NLS-1$ + } + if (e.getSource() == am0Button) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.21")); //$NON-NLS-1$ + } + if (e.getSource() == c0Button) { + editorController.getController().writeOnStatusbar( + Messages.getString("am0c0", "EditorView.22")); //$NON-NLS-1$ + } + } + + @Override + public void mouseExited(MouseEvent e) { + editorController.getController().writeOnStatusbar(""); //$NON-NLS-1$ + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseReleased(MouseEvent e) { + } + } + + @Override + public void setPresentationMode(boolean presentationMode) { + if (presentationMode) { + codeField.setFont(GuiConstants.PRESENTATIONFONT); + logConsole.setFont(GuiConstants.PRESENTATIONFONT_SERIF); + } else { + codeField.setFont(GuiConstants.STANDARDFONT); + logConsole.setFont(GuiConstants.STANDARDFONT_SERIF); + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/GuiConstants.java b/src/org/jalgo/module/am0c0/gui/GuiConstants.java new file mode 100644 index 0000000..4ebe6a3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/GuiConstants.java @@ -0,0 +1,78 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Frame; + +import org.jalgo.main.gui.JAlgoWindow; + +/** + * All constants for GUI elements are defined here. + * + * @author Max Leuthäuser + */ +public class GuiConstants { + /** The presentation font */ + public static final Font PRESENTATIONFONT = new Font("Courier", Font.BOLD, + 16); + /** The standard font */ + public static final Font STANDARDFONT = new Font("Courier", Font.PLAIN, 14); + + public static final Font STANDARDFONT_SERIF = new Font(Font.SERIF, Font.PLAIN, 14); + public static final Font PRESENTATIONFONT_SERIF = new Font(Font.SERIF, Font.PLAIN, 16); + + public static final String BACK_TO_EDITOR_ICON = "back_to_editor_Icon"; //$NON-NLS-1$ + public static final String CLEAR_ICON = "clear_Icon"; //$NON-NLS-1$ + public static final String INITIAL_CONFIG_ICON = "initial_config_Icon"; //$NON-NLS-1$ + public static final String LAST_ICON = "last_Icon"; //$NON-NLS-1$ + public static final String NEXT_ICON = "next_Icon"; //$NON-NLS-1$ + public static final String OPEN_ICON = "open_Icon"; //$NON-NLS-1$ + public static final String PREVIOUS_ICON = "previous_Icon"; //$NON-NLS-1$ + public static final String RUN_ICON = "run_Icon"; //$NON-NLS-1$ + public static final String SAVE_ICON = "save_Icon"; //$NON-NLS-1$ + + /** + * Standard grey for our am0 table + */ + public static final Color TABLE_ODD = new Color(237, 237, 237); + /** + * Standard white for our am0 table + */ + public static final Color TABLE_EVEN = new Color(255, 255, 255); + + /** + * This method returns the {@link JAlgoWindow} or throw a + * {@link RuntimeException} if it was unable to find it. + * + * @return the {@link JAlgoWindow} + */ + public static JAlgoWindow getJAlgoWindow() { + for (Frame f : Frame.getFrames()) + if (f instanceof JAlgoWindow) + return (JAlgoWindow) f; + + throw new RuntimeException("JAlgoWindow not found"); //$NON-NLS-1$ + } +} diff --git a/src/org/jalgo/module/am0c0/gui/SimulationView.java b/src/org/jalgo/module/am0c0/gui/SimulationView.java new file mode 100644 index 0000000..ba9f897 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/SimulationView.java @@ -0,0 +1,557 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSplitPane; +import javax.swing.JTable; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.AM0PagingTableModel; +import org.jalgo.module.am0c0.model.SimulationSet; +import org.jalgo.module.am0c0.core.Simulator; +import org.jalgo.module.am0c0.gui.GuiConstants; +import org.jalgo.module.am0c0.gui.View; +import org.jalgo.module.am0c0.gui.jeditor.JEditor; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.AM0TokenMarker; +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.model.am0.MachineConfiguration; +import org.jalgo.module.am0c0.model.am0.SimulationStatement; + +/** + * This class shows the simulation in the JAlgo module C0/AM0. + * + * @author Max Leuthäuser + */ +public class SimulationView extends View { + private static final long serialVersionUID = 1L; + private ButtonHandler bh; + private JSplitPane vSplitPane, hSplitPane; + private JEditor am0code; + private JEditorPane commandHint; + private JPanel am0Pane, codeTablePane, commandHintPane, buttonsPanel, + navigationPane; + private JTable codeTable; + private AM0PagingTableModel amTableModel; + private JButton back, prev, doIt, next, config, clear, jumpUp, jumpDown; + private JLabel step; + private JLabel range; + private int steps; + + private Simulator simController; + + public SimulationView(Simulator simController) { + initComponents(); + initComponentAttributs(); + attachButtonHandler(); + add(vSplitPane); + this.simController = simController; + } + + /** + * @return {@link AM0PagingTableModel} which is used to show the machine + * configurations. + */ + public AM0PagingTableModel getTableModel() { + return amTableModel; + } + + /** + * Show a am0 statement description. + * + * + * @param s + * Description that should be printed. + */ + public void showDescription(String s) { + if (s.isEmpty()) { + commandHint.setText(""); //$NON-NLS-1$ + } else + commandHint + .setText("" //$NON-NLS-1$ + + s + ""); //$NON-NLS-1$ + commandHint.setCaretPosition(0); + } + + /** + * @return the {@link JLabel} which is used to show the current step. + */ + public JLabel getStepLabel() { + return step; + } + + /** + * @return the {@link JLabel} which is used to show the current step range. + */ + public JLabel getRangeLabel() { + return range; + } + + /** + * @param am + * The new am0 program to show in simulation. + */ + public void setAM0Program(AM0Program am) { + am0code.updateModel(am); + am0code.setCaretPosition(am0code.getLineStartOffset(0)); + am0code.setLineMarker(0, 0); + } + + /** + * Scrolls to the current line. + * + * @param pc + * The program counter which indicates the program line that + * should be highlighted. + */ + public void scroll(int pc) { + codeTable.scrollRectToVisible(codeTable.getCellRect( + codeTable.getRowCount() - 1, codeTable.getColumnCount(), true)); + + if (pc >= 1 && pc <= am0code.getLineCount()) { + am0code.setCaretPosition(am0code.getLineStartOffset(pc - 1)); + am0code.setLineMarker(pc - 1, pc - 1); + } + } + + /** + * Create and use the simulation table. + */ + private void useCodeTablePane() { + codeTablePane = new JPanel(); + codeTablePane.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "SimulationView.3"))); //$NON-NLS-1$ + codeTablePane.setLayout(new BorderLayout(5, 10)); + JPanel p = new JPanel(); + p.setLayout(new BorderLayout()); + + JPanel a = new JPanel(); + a.setLayout(new GridLayout(1, 3)); + a.add(step); + a.add(jumpUp); + a.add(jumpDown); + + p.add(range, BorderLayout.WEST); + p.add(a, BorderLayout.EAST); + codeTablePane.add( + AM0PagingTableModel.createPagingScrollPaneForTable(codeTable), + BorderLayout.CENTER); + + navigationPane = new JPanel(); + navigationPane.setLayout(new BorderLayout(5, 10)); + navigationPane.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), "Navigation")); + navigationPane.add(p, BorderLayout.NORTH); + navigationPane.add(buttonsPanel, BorderLayout.SOUTH); + } + + /** + * Create and use the simulation panel. All animations are visible here. + * + * @deprecated + */ + @SuppressWarnings("unused") + private void useAm0Pane() { + am0Pane = new JPanel(); + am0Pane.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "SimulationView.4"))); //$NON-NLS-1$ + am0Pane.setMinimumSize(new Dimension(550, 0)); + am0Pane.setLayout(new BorderLayout()); + am0Pane.add(buttonsPanel, BorderLayout.SOUTH); + } + + @Override + protected void initComponents() { + bh = new ButtonHandler(); + am0code = new JEditor(new Observer() { + @Override + public void update(Observable arg0, Object arg1) { + // Modified flag could be ignored here. + } + }, null); + + jumpUp = new JButton(Messages.getString("am0c0", "SimulationView.5")); //$NON-NLS-1$ + jumpDown = new JButton(Messages.getString("am0c0", "SimulationView.6")); //$NON-NLS-1$ + step = new JLabel(Messages.getString("am0c0", "SimulationView.7")); //$NON-NLS-1$ + range = new JLabel(""); //$NON-NLS-1$ + back = new JButton(Messages.getString("am0c0", "SimulationView.9")); //$NON-NLS-1$ + back.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.BACK_TO_EDITOR_ICON))); + prev = new JButton(Messages.getString("am0c0", "SimulationView.11")); //$NON-NLS-1$ + prev.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.PREVIOUS_ICON))); + next = new JButton(Messages.getString("am0c0", "SimulationView.13")); //$NON-NLS-1$ + next.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.NEXT_ICON))); + clear = new JButton(Messages.getString("am0c0", "SimulationView.15")); //$NON-NLS-1$ + clear.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.CLEAR_ICON))); + doIt = new JButton(Messages.getString("am0c0", "SimulationView.17")); //$NON-NLS-1$ + doIt.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.LAST_ICON))); + config = new JButton(Messages.getString("am0c0", "SimulationView.19")); //$NON-NLS-1$ + config.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", //$NON-NLS-1$ + GuiConstants.INITIAL_CONFIG_ICON))); + buttonsPanel = new JPanel(); + + commandHint = new JEditorPane(); + commandHint.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, + true); + commandHint.setFont(GuiConstants.STANDARDFONT_SERIF); + + amTableModel = new AM0PagingTableModel(this); + codeTable = new JTable(amTableModel); + + useCodeTablePane(); + + commandHintPane = new JPanel(); + + hSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, am0code, + commandHintPane); + + JPanel a = new JPanel(); + a.setLayout(new BorderLayout()); + a.add(codeTablePane, BorderLayout.CENTER); + a.add(navigationPane, BorderLayout.SOUTH); + vSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, + hSplitPane, a); + } + + @Override + protected void attachButtonHandler() { + back.addActionListener(bh); + prev.addActionListener(bh); + next.addActionListener(bh); + doIt.addActionListener(bh); + config.addActionListener(bh); + clear.addActionListener(bh); + jumpUp.addActionListener(bh); + jumpDown.addActionListener(bh); + jumpUp.addMouseListener(bh); + jumpDown.addMouseListener(bh); + back.addMouseListener(bh); + prev.addMouseListener(bh); + next.addMouseListener(bh); + doIt.addMouseListener(bh); + config.addMouseListener(bh); + clear.addMouseListener(bh); + } + + /** + * @return the steps the user want to execute until he is asked for more. + */ + public int getStepsToStopAfter() { + return steps; + } + + @Override + protected void initComponentAttributs() { + setLayout(new BorderLayout()); + am0code.setTokenMarker(new AM0TokenMarker()); + am0code.setCodeHighlightMode(false); + am0code.getPainter().setLineHighlightEnabled(false); + am0code.showLineMarker(true); + am0code.setEnabled(false); + am0code.setMinimumSize(new Dimension(160, 300)); + + setAM0CodeListeners(); + + prev.setEnabled(false); + clear.setEnabled(false); + + buttonsPanel.setLayout(new GridLayout(1, 5)); + + buttonsPanel.add(config); + buttonsPanel.add(clear); + buttonsPanel.add(prev); + buttonsPanel.add(next); + buttonsPanel.add(doIt); + + commandHint.setEditable(false); + commandHint.setContentType("text/html"); //$NON-NLS-1$ + commandHintPane.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "SimulationView.31"))); //$NON-NLS-1$ + commandHintPane.setLayout(new BorderLayout()); + commandHintPane.add(getScrollPane(commandHint), BorderLayout.CENTER); + commandHintPane.add(back, BorderLayout.SOUTH); + commandHintPane.setMinimumSize(new Dimension(250, 150)); + + hSplitPane + .setDividerLocation(GuiConstants.getJAlgoWindow().getSize().height / 2); + + hSplitPane.setOneTouchExpandable(true); + vSplitPane.setOneTouchExpandable(true); + + codeTable.setEnabled(true); + codeTable.setRowHeight(codeTable.getRowHeight() + 8); + codeTable.setDefaultRenderer(Object.class, new AMTableRenderer()); + codeTable.setShowGrid(false); + codeTable.setIntercellSpacing(new Dimension(15, 2)); + codeTable.getTableHeader().setReorderingAllowed(false); + } + + private void setAM0CodeListeners() { + am0code.getPainter().addMouseListener(new MouseListener() { + + private void setDescription(int y) { + int line = am0code.yToLine(y); + SimulationStatement statement = (SimulationStatement) am0code + .getCodeFromLine(line, null, null); + if (statement != null) { + String description = statement.getCodeText() + "

      " //$NON-NLS-1$ + + statement.getDescription() + "

      "; //$NON-NLS-1$ + + showDescription(description); + } + } + + @Override + public void mouseReleased(MouseEvent e) { + setDescription(e.getY()); + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseExited(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + } + + @Override + public void mouseClicked(MouseEvent e) { + setDescription(e.getY()); + } + }); + } + + private class ButtonHandler implements ActionListener, MouseListener { + @Override + public void actionPerformed(ActionEvent arg0) { + if (arg0.getSource() == back) { + simController.getController().showEditor(); + } + if (arg0.getSource() == prev) { + amTableModel.showLastPage(); + if (!simController.previousStep()) { + prev.setEnabled(false); + } else { + next.setEnabled(true); + doIt.setEnabled(true); + } + } + if (arg0.getSource() == next) { + if (simController.simulatorNeedsInitialConfig()) { + SimulationSet s = AM0InputDialog + .showAndWaitForReturn(simController); + MachineConfiguration m = s.getMachineConfiguration(); + if (m != null) { + steps = s.getSteps(); + config.setEnabled(false); + simController.getHistory().add( + new MachineConfiguration(m)); + simController.setCurrentMachineConfiguration(m); + simController.addResultToTable(m, 0); + amTableModel.showLastPage(); + clear.setEnabled(true); + if (!simController.nextStep()) { + next.setEnabled(false); + doIt.setEnabled(false); + prev.setEnabled(true); + } + } + } else { + amTableModel.showLastPage(); + if (!simController.nextStep()) { + next.setEnabled(false); + doIt.setEnabled(false); + } + prev.setEnabled(true); + clear.setEnabled(true); + } + } + if (arg0.getSource() == doIt) { + if (simController.simulatorNeedsInitialConfig()) { + SimulationSet s = AM0InputDialog + .showAndWaitForReturn(simController); + MachineConfiguration m = s.getMachineConfiguration(); + if (m != null) { + steps = s.getSteps(); + simController.getHistory().add( + new MachineConfiguration(m)); + simController.setCurrentMachineConfiguration(m); + simController.addResultToTable(m, 0); + next.setEnabled(false); + doIt.setEnabled(false); + config.setEnabled(false); + prev.setEnabled(true); + clear.setEnabled(true); + simController.stepToEnd(); + amTableModel.showLastPage(); + } + } else { + next.setEnabled(false); + doIt.setEnabled(false); + config.setEnabled(false); + clear.setEnabled(true); + simController.stepToEnd(); + prev.setEnabled(true); + amTableModel.showLastPage(); + } + } + if (arg0.getSource() == config) { + SimulationSet s = AM0InputDialog + .showAndWaitForReturn(simController); + MachineConfiguration m = s.getMachineConfiguration(); + if (m != null) { + steps = s.getSteps(); + simController.getHistory().add(new MachineConfiguration(m)); + simController.setCurrentMachineConfiguration(m); + simController.addResultToTable(m, 0); + clear.setEnabled(true); + config.setEnabled(false); + } + } + if (arg0.getSource() == clear) { + resetSimulation(); + clear.setEnabled(false); + } + + if (arg0.getSource() == jumpUp) { + amTableModel.showFirstPage(); + codeTable.scrollRectToVisible(codeTable.getCellRect(0, + codeTable.getColumnCount(), true)); + } + + if (arg0.getSource() == jumpDown) { + amTableModel.showLastPage(); + codeTable.scrollRectToVisible(codeTable.getCellRect( + codeTable.getRowCount() - 1, + codeTable.getColumnCount(), true)); + } + } + + @Override + public void mouseClicked(MouseEvent e) { + } + + @Override + public void mouseEntered(MouseEvent e) { + if (e.getSource() == jumpUp) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.32")); //$NON-NLS-1$ + } + if (e.getSource() == jumpDown) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.33")); //$NON-NLS-1$ + } + if (e.getSource() == back) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.34")); //$NON-NLS-1$ + } + if (e.getSource() == prev) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.35")); //$NON-NLS-1$ + } + if (e.getSource() == next) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.36")); //$NON-NLS-1$ + + } + if (e.getSource() == doIt) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.37")); //$NON-NLS-1$ + } + if (e.getSource() == config) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.38")); //$NON-NLS-1$ + } + if (e.getSource() == clear) { + simController.getController().writeOnStatusbar( + Messages.getString("am0c0", "SimulationView.39")); //$NON-NLS-1$ + } + } + + @Override + public void mouseExited(MouseEvent e) { + simController.getController().writeOnStatusbar(""); //$NON-NLS-1$ + } + + @Override + public void mousePressed(MouseEvent e) { + } + + @Override + public void mouseReleased(MouseEvent e) { + } + } + + /** + * Resets the whole simulation. Use this carefully. + */ + public void resetSimulation() { + config.setEnabled(true); + am0code.setCaretPosition(am0code.getLineStartOffset(0)); + am0code.setLineMarker(0, 0); + simController.clear(); + next.setEnabled(true); + prev.setEnabled(false); + doIt.setEnabled(true); + } + + @Override + public void setPresentationMode(boolean presentationMode) { + if (presentationMode) { + am0code.setFont(GuiConstants.PRESENTATIONFONT); + commandHint.setFont(GuiConstants.PRESENTATIONFONT_SERIF); + codeTable.setFont(GuiConstants.PRESENTATIONFONT); + } else { + am0code.setFont(GuiConstants.STANDARDFONT); + commandHint.setFont(GuiConstants.STANDARDFONT_SERIF); + codeTable.setFont(GuiConstants.STANDARDFONT); + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/TransformationView.java b/src/org/jalgo/module/am0c0/gui/TransformationView.java new file mode 100644 index 0000000..67d66af --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/TransformationView.java @@ -0,0 +1,581 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Observable; +import java.util.Observer; + +import javax.activity.InvalidActivityException; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.core.Editor; +import org.jalgo.module.am0c0.core.Transformator; +import org.jalgo.module.am0c0.core.Transformator.TransformationState; +import org.jalgo.module.am0c0.gui.jeditor.JEditor; +import org.jalgo.module.am0c0.gui.jeditor.JEditor.ExInteger; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.CTransTokenMarker; +import org.jalgo.module.am0c0.model.AddressException; +import org.jalgo.module.am0c0.model.CodeObject; +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.model.c0.ast.Statement; +import org.jalgo.module.am0c0.model.c0.trans.C0TransProgram; +import org.jalgo.module.am0c0.model.c0.trans.SymbolException; +import org.jalgo.module.am0c0.model.c0.trans.SymbolTable; + +/** + * This class shows the transformation in the JAlgo module C0/AM0. + * + * @author Max Leuthäuser + * @author Felix Schmitt + */ +public class TransformationView extends View { + private static final long serialVersionUID = 1L; + private JButton backToEditorButton, stepBackButton, applyButton, stepToEndButton, simulateButton; + private JSplitPane hSplitPane, vSplitPane; + private JPanel leftPanel, rightPanel, buttonPanel, allButtons; + private JTable symbolTable; + private DefaultTableModel symbolTableModel; + private JEditorPane previewText, ruleText; + private JEditor codeEditor; + private ButtonHandler buttonHandler; + private JScrollPane ruleScrollPane, previewScrollPane; + private Transformator transController; + + private int markingStart; + private int markingEnd; + private ExInteger markingIndex; + + /** + * see {@link View} + * + * @param transController + * the {@link Transformator} associated with this + * {@link TransformationView} + */ + public TransformationView(Transformator transController) { + markingStart = -1; + markingEnd = -1; + markingIndex = new ExInteger(-1); + + initComponents(); + initComponentAttributs(); + attachButtonHandler(); + add(vSplitPane); + this.transController = transController; + } + + @Override + /** + * creates and initializes components, attaches handlers and sets attributes + */ + protected void initComponents() { + buttonHandler = new ButtonHandler(); + leftPanel = new JPanel(); + leftPanel.setLayout(new BorderLayout()); + + rightPanel = new JPanel(); + + buttonHandler = new ButtonHandler(); + String[] x = { Messages.getString("am0c0", "TransformationView.1"), Messages.getString("am0c0", "TransformationView.3") }; //$NON-NLS-1$ //$NON-NLS-2$ + String[][] y = { { "", "" } }; //$NON-NLS-1$ //$NON-NLS-2$ + symbolTable = new JTable(); + symbolTable.setEnabled(false); + symbolTableModel = new DefaultTableModel(y, x); + symbolTable.setModel(symbolTableModel); + + ruleText = new JEditorPane(); + ruleText.setFont(GuiConstants.STANDARDFONT_SERIF); + + ruleScrollPane = getScrollPane(ruleText); + + rightPanel.add(getScrollPane(symbolTable)); + rightPanel.add(ruleScrollPane); + + buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridLayout(1, 3)); + + stepBackButton = new JButton(Messages.getString("am0c0", "TransformationView.8")); //$NON-NLS-1$ + stepBackButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", GuiConstants.PREVIOUS_ICON))); //$NON-NLS-1$ + + applyButton = new JButton(Messages.getString("am0c0", "TransformationView.10")); //$NON-NLS-1$ + applyButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", GuiConstants.NEXT_ICON))); //$NON-NLS-1$ + applyButton.setEnabled(false); + + stepToEndButton = new JButton(Messages.getString("am0c0", "TransformationView.12")); //$NON-NLS-1$ + stepToEndButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", GuiConstants.LAST_ICON))); //$NON-NLS-1$ + stepToEndButton.setEnabled(false); + + simulateButton = new JButton(Messages.getString("am0c0", "TransformationView.14")); //$NON-NLS-1$ + simulateButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", GuiConstants.RUN_ICON))); //$NON-NLS-1$ + + backToEditorButton = new JButton(Messages.getString("am0c0", "TransformationView.16")); //$NON-NLS-1$ + backToEditorButton.setIcon(new ImageIcon(Messages.getResourceURL("am0c0", GuiConstants.BACK_TO_EDITOR_ICON))); //$NON-NLS-1$ + + allButtons = new JPanel(); + allButtons.setLayout(new GridLayout(1, 3)); + + buttonPanel.add(stepBackButton); + buttonPanel.add(applyButton); + buttonPanel.add(stepToEndButton); + + allButtons.add(backToEditorButton, BorderLayout.WEST); + allButtons.add(new JPanel()); + allButtons.add(simulateButton, BorderLayout.EAST); + + previewText = new JEditorPane(); + previewText.setFont(GuiConstants.STANDARDFONT); + + previewScrollPane = getScrollPane(previewText); + + codeEditor = new JEditor(new Observer() { + + @Override + public void update(Observable arg0, Object arg1) { + // modified flag can be ignored here + } + }, null); + + codeEditor.setMinimumSize(new Dimension(200, 200)); + + setCodeEditorListeners(); + + JPanel p = new JPanel(); + p.setLayout(new BorderLayout()); + p.add(codeEditor, BorderLayout.CENTER); + p.add(buttonPanel, BorderLayout.SOUTH); + hSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, p, previewScrollPane); + + leftPanel.add(hSplitPane, BorderLayout.CENTER); + leftPanel.add(allButtons, BorderLayout.SOUTH); + + vSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, leftPanel, rightPanel); + } + + private void setCodeEditorListeners() { + codeEditor.getPainter().addMouseListener(new MouseListener() { + + @Override + public void mouseReleased(MouseEvent arg0) { + + } + + @Override + public void mousePressed(MouseEvent arg0) { + } + + @Override + public void mouseExited(MouseEvent arg0) { + } + + @Override + public void mouseEntered(MouseEvent arg0) { + } + + @Override + public void mouseClicked(MouseEvent arg0) { + int line = codeEditor.yToLine(arg0.getY()); + + if (transController.getState() != TransformationState.TS_FINISHED) { + ExInteger startLine = new ExInteger(-1); + ExInteger tmpIndex = new ExInteger(-1); + + CodeObject codeObject = codeEditor.getCodeFromLine(line, startLine, tmpIndex); + + if (codeObject != null) { + try { + if (line >= markingStart && line <= markingEnd) { + applyMarkedStatement(); + } else { + + if (transController.previewStatement(tmpIndex.getValue())) { + markingIndex.set(tmpIndex.getValue()); + markingStart = startLine.getValue(); + markingEnd = startLine.getValue() + codeObject.getLinesCount() - 1; + updateGUI(); + } + + } + } catch (IllegalArgumentException e) { + updateGUI(); + } + } else { + + if (transController.getState() == TransformationState.TS_PREVIEW + || transController.getState() == TransformationState.TS_WAITING) { + transController.setState(TransformationState.TS_WAITING); + } else { + transController.setState(TransformationState.TS_WAITING_FIRST); + } + + updateGUI(); + } + } + } + }); + } + + @Override + protected void attachButtonHandler() { + backToEditorButton.addActionListener(buttonHandler); + stepBackButton.addActionListener(buttonHandler); + applyButton.addActionListener(buttonHandler); + stepToEndButton.addActionListener(buttonHandler); + simulateButton.addActionListener(buttonHandler); + + backToEditorButton.addMouseListener(buttonHandler); + stepBackButton.addMouseListener(buttonHandler); + applyButton.addMouseListener(buttonHandler); + stepToEndButton.addMouseListener(buttonHandler); + simulateButton.addMouseListener(buttonHandler); + } + + @Override + protected void initComponentAttributs() { + setLayout(new BorderLayout()); + + rightPanel.setLayout(new GridLayout(2, 1)); + ruleText.setEditable(false); + + ruleScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "TransformationView.18"))); //$NON-NLS-1$ + + simulateButton.setEnabled(false); + + previewText.setEditable(false); + + previewScrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), + Messages.getString("am0c0", "TransformationView.19"))); //$NON-NLS-1$ + + codeEditor.setTokenMarker(new CTransTokenMarker()); + codeEditor.setEditable(false); + codeEditor.getPainter().setLineHighlightEnabled(false); + codeEditor.setCodeHighlightMode(true); + + hSplitPane.setOneTouchExpandable(true); + hSplitPane.setDividerLocation(400); + + vSplitPane.setOneTouchExpandable(true); + } + + /** + * Update the {@link SymbolTable}. + */ + public void updateSymbolTable() { + while (symbolTableModel.getRowCount() > 0) + symbolTableModel.removeRow(0); + + if (transController.getSymbolTable().size() == 0) { + String[] emptyRow = { "", "" }; //$NON-NLS-1$ //$NON-NLS-2$ + symbolTableModel.addRow(emptyRow); + } else { + try { + String[][] tableStr = transController.getSymbolTable().toStringTable(); + for (int i = 0; i < transController.getSymbolTable().size(); i++) + symbolTableModel.addRow(tableStr[i]); + } catch (SymbolException e) { + JOptionPane.showMessageDialog(transController.getView(), e.getMessage(), Messages.getString("am0c0", "TransformationView.4"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + } + } + } + + /** + * Update the model in the {@link Editor}. + * + * @param c0TransProgram + * of type {@link C0TransProgram}. + */ + public void updateModel(C0TransProgram c0TransProgram) { + /** + * TODO: clear/revert everything here + */ + codeEditor.updateModel(c0TransProgram); + updateGUI(); + } + + @Override + /** + * see {@link View} + */ + public void setPresentationMode(boolean presentationMode) { + if (presentationMode) { + codeEditor.setFont(GuiConstants.PRESENTATIONFONT); + previewText.setFont(GuiConstants.PRESENTATIONFONT); + ruleText.setFont(GuiConstants.PRESENTATIONFONT_SERIF); + symbolTable.setFont(GuiConstants.PRESENTATIONFONT); + } else { + codeEditor.setFont(GuiConstants.STANDARDFONT); + previewText.setFont(GuiConstants.STANDARDFONT); + ruleText.setFont(GuiConstants.STANDARDFONT_SERIF); + symbolTable.setFont(GuiConstants.STANDARDFONT); + } + } + + private class ButtonHandler implements ActionListener, MouseListener { + public void actionPerformed(ActionEvent e) { + if (e.getSource() == backToEditorButton) { + int choice = JOptionPane.NO_OPTION; + + if (transController.getState() == TransformationState.TS_FINISHED) { + choice = JOptionPane.showConfirmDialog(transController.getView(), Messages.getString("am0c0", "TransformationView.25"), //$NON-NLS-1$ + Messages.getString("am0c0", "TransformationView.26"), JOptionPane.YES_NO_OPTION); //$NON-NLS-1$ + } + if (choice == JOptionPane.YES_OPTION) { + try { + AM0Program am0program = transController.getAM0Program(); + transController.getController().getEditor().setAM0Program(am0program); + // this must be done to remove the model from JEditor and make it editable + transController.getController().getEditor().getView().getJEditor().updateModel(null); + } catch (AddressException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg + .getMessage(), "Error", JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ + } + } + transController.getController().showEditor(); + } + + if (e.getSource() == applyButton) { + if (transController.getState() != TransformationState.TS_PREVIEW + && transController.getState() != TransformationState.TS_PREVIEW_FIRST) { + JOptionPane.showMessageDialog(transController.getView(), + "Transformator should be in state PREVIEW or PREVIEW_FIRST.", "Error", //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.ERROR_MESSAGE); + throw new IllegalStateException("Transformator should be in state PREVIEW."); //$NON-NLS-1$ + } + + if (markingStart >= 0 && markingEnd < codeEditor.getLineCount()) { + try { + applyMarkedStatement(); + } catch (IllegalArgumentException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg.getMessage(), Messages.getString("am0c0", "TransformationView.5"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + updateGUI(); + } catch (IllegalStateException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg.getMessage(), Messages.getString("am0c0", "TransformationView.32"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + updateGUI(); + } + } + } + + if (e.getSource() == stepToEndButton) { + if (transController.getState() == TransformationState.TS_FINISHED) + throw new IllegalStateException( + Messages.getString("am0c0", "TransformationView.33")); //$NON-NLS-1$ + + try { + applyAllStatements(); + } catch (IllegalArgumentException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg.getMessage(), Messages.getString("am0c0", "TransformationView.34"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + updateGUI(); + } catch (IllegalStateException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg.getMessage(), Messages.getString("am0c0", "TransformationView.35"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + updateGUI(); + } + + } + + if (e.getSource() == stepBackButton) { + try { + transController.stepBack(); + } catch (InvalidActivityException error) { + JOptionPane.showMessageDialog(transController.getView(), "There is no previous step!", "Error", //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.ERROR_MESSAGE); + } + updateSymbolTable(); + updateGUI(); + } + + if (e.getSource() == simulateButton) { + if (transController.getState() != TransformationState.TS_FINISHED) + throw new IllegalStateException( + "Simulation is only possible in state FINISHED. Internal program error!"); //$NON-NLS-1$ + + try { + AM0Program am0program = transController.getAM0Program(); + transController.getController().getSimulator().setAM0Program(am0program); + } catch (AddressException arg) { + JOptionPane.showMessageDialog(transController.getView(), arg + .getMessage(), Messages.getString("am0c0", "TransformationView.6"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ + } + transController.getController().showSimulator(); + } + } + + @Override + public void mouseClicked(MouseEvent arg0) { + } + + @Override + public void mouseEntered(MouseEvent arg0) { + if (arg0.getSource() == backToEditorButton) { + transController.getController().writeOnStatusbar(Messages.getString("am0c0", "TransformationView.40")); //$NON-NLS-1$ + } + if (arg0.getSource() == stepBackButton) { + transController.getController().writeOnStatusbar(Messages.getString("am0c0", "TransformationView.41")); //$NON-NLS-1$ + } + if (arg0.getSource() == applyButton) { + transController.getController().writeOnStatusbar( + Messages.getString("am0c0", "TransformationView.42")); //$NON-NLS-1$ + + } + if (arg0.getSource() == stepToEndButton) { + transController.getController().writeOnStatusbar(Messages.getString("am0c0", "TransformationView.43")); //$NON-NLS-1$ + } + if (arg0.getSource() == simulateButton) { + transController.getController().writeOnStatusbar(Messages.getString("am0c0", "TransformationView.44")); //$NON-NLS-1$ + } + } + + @Override + public void mouseExited(MouseEvent arg0) { + transController.getController().writeOnStatusbar(""); //$NON-NLS-1$ + } + + @Override + public void mousePressed(MouseEvent arg0) { + } + + @Override + public void mouseReleased(MouseEvent arg0) { + } + } + + /** + * Update the whole {@link TransformationView}. + */ + protected void updateGUI() { + switch (transController.getState()) { + case TS_FINISHED: + codeEditor.setCodeHighlightMode(false); + setPreviewText(""); //$NON-NLS-1$ + setRuleText(""); //$NON-NLS-1$ + markingStart = -1; + markingEnd = -1; + applyButton.setEnabled(false); + stepToEndButton.setEnabled(false); + simulateButton.setEnabled(true); + stepBackButton.setEnabled(true); + break; + case TS_PREVIEW: + codeEditor.setCodeHighlightMode(false); + applyButton.setEnabled(true); + stepToEndButton.setEnabled(true); + simulateButton.setEnabled(false); + stepBackButton.setEnabled(true); + break; + case TS_WAITING: + codeEditor.setCodeHighlightMode(true); + setPreviewText(""); //$NON-NLS-1$ + setRuleText(""); //$NON-NLS-1$ + markingStart = -1; + markingEnd = -1; + applyButton.setEnabled(false); + stepToEndButton.setEnabled(true); + simulateButton.setEnabled(false); + stepBackButton.setEnabled(true); + break; + case TS_WAITING_FIRST: + codeEditor.setCodeHighlightMode(true); + setPreviewText(""); //$NON-NLS-1$ + setRuleText(""); //$NON-NLS-1$ + markingStart = -1; + markingEnd = -1; + applyButton.setEnabled(false); + stepToEndButton.setEnabled(true); + simulateButton.setEnabled(false); + stepBackButton.setEnabled(false); + break; + case TS_PREVIEW_FIRST: + codeEditor.setCodeHighlightMode(false); + applyButton.setEnabled(true); + stepToEndButton.setEnabled(true); + simulateButton.setEnabled(false); + stepBackButton.setEnabled(false); + break; + + } + codeEditor.setLineMarker(markingStart, markingEnd); + } + + /** + * Apply a marked {@link Statement} using + * {@link TransformationView#updateSymbolTable()} and + * {@link TransformationView#updateGUI()}. + */ + protected void applyMarkedStatement() { + if (transController.translateStatement(markingIndex.getValue())) { + updateSymbolTable(); + updateGUI(); + } else + applyButton.setEnabled(false); + } + + /** + * Apply all {@link Statement}s in one single step. + */ + protected void applyAllStatements() throws IllegalStateException { + transController.translateAll(); + updateSymbolTable(); + } + + /** + * Set a new preview text. + * + * @param text + */ + public void setPreviewText(String text) { + previewText.setText(text); + previewText.setCaretPosition(0); + } + + /** + * Set a new rule text. + * + * @param text + */ + public void setRuleText(String text) { + ruleText.setText(text); + ruleText.setCaretPosition(0); + } +} diff --git a/src/org/jalgo/module/am0c0/gui/View.java b/src/org/jalgo/module/am0c0/gui/View.java new file mode 100644 index 0000000..75079f9 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/View.java @@ -0,0 +1,85 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.gui; + +import java.awt.Dimension; + +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.module.am0c0.gui.EditorView; +import org.jalgo.module.am0c0.gui.SimulationView; +import org.jalgo.module.am0c0.gui.TransformationView; + +/** + * Simple view class. All views implementing this: + * + *

      + *

    • {@link EditorView}
    • + *
    • {@link SimulationView}
    • + *
    • {@link TransformationView}
    • + *

      + *
      + * + * @author Max Leuthäuser + */ +public abstract class View extends JPanel { + private static final long serialVersionUID = 1L; + + /** + * Set the presentation mode which sets bigger fonts. + * + * @param presentationMode + */ + abstract public void setPresentationMode(boolean presentationMode); + + /** + * Create all compontents. + */ + abstract protected void initComponents(); + + /** + * Add a ButtonHandler to all important components. Implement this handler + * by yourself. + */ + abstract protected void attachButtonHandler(); + + /** + * Set all attributes to the components of this view. + */ + abstract protected void initComponentAttributs(); + + /** + * @param c + * {@link JComponent} to embed in the {@link JScrollPane}. + * @return a new {@link JScrollPane} with the {@link JComponent} c + * embedded. + */ + protected JScrollPane getScrollPane(JComponent c) { + JScrollPane scrollPane = new JScrollPane(c); + scrollPane.setMinimumSize(new Dimension(100, 100)); + scrollPane.setMaximumSize(new Dimension(200, 200)); + return scrollPane; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Entries b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Entries new file mode 100644 index 0000000..3a0e6dc --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Entries @@ -0,0 +1,4 @@ +/EnhancedPainter.java/1.1/Mon Aug 16 12:05:48 2010// +/JEditor.java/1.2/Wed Dec 8 13:01:52 2010// +D/jedit//// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Repository b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Repository new file mode 100644 index 0000000..8603f82 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/gui/jeditor diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Root b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.java b/src/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.java new file mode 100644 index 0000000..8422d29 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/EnhancedPainter.java @@ -0,0 +1,486 @@ +package org.jalgo.module.am0c0.gui.jeditor; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; + +import javax.swing.text.Segment; + +import org.jalgo.module.am0c0.gui.jeditor.JEditor.ExInteger; +import org.jalgo.module.am0c0.gui.jeditor.jedit.*; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.*; +import org.jalgo.module.am0c0.model.CodeObject; + +/** + * Improved TextAreaPainter for JEditor component which features line numbers, + * marked lines and more. + * + * @author Felix Schmitt + * + */ + +public class EnhancedPainter extends TextAreaPainter { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Class used for marking a range of lines with a specific color + * + * @author Felix Schmitt + * + */ + public static class Marker { + private Color color; + private int start; + private int end; + + /** + * sets the line range to mark + * + * @param lineStart + * index of the first line + * @param lineEnd + * index of the last line + */ + public void setLines(int lineStart, int lineEnd) throws IllegalArgumentException { + this.start = lineStart; + this.end = lineEnd; + + if (lineEnd < lineStart) + throw new IllegalArgumentException("last line should be >= first line"); + } + + /** + * returns the start line + * @return the start line + */ + public int getStartLine() { + return start; + } + + /** + * returns the end line + * @return the end line + */ + public int getEndLine() { + return end; + } + + /** + * sets the {@link Color} of the Marker + * + * @param color + * the new {@link Color} + */ + public void setColor(Color color) { + this.color = color; + } + + /** + * returns the {@link Color} of this Marker + * + * @return the current {@link Color} + */ + public Color getColor() { + return color; + } + + /** + * checks if line is in marking range + * + * @param line + * index of the line to check + * @return if line is in marking range + */ + public boolean isMarked(int line) { + return line >= start && line <= end; + } + + /** + * constructor + * + * @param lineStart + * index of the first line + * @param lineEnd + * index of the last line + */ + public Marker(int lineStart, int lineEnd) { + color = new Color(246, 206, 136); + setLines(lineStart, lineEnd); + } + } + + /** + * offset in pixels from line numbers to the seperating line between numbers + * and text + */ + private static final int LINE_NUMBERS_OFFSET = 5; + + private int lineNumbersWidth; + private int LINE_NUMBERS_WIDTH; + private boolean lineNumbersVisible; + private Marker marker; + private boolean markerVisible; + Segment currentLine; + + /** + * constructor + * + * @param textArea + * the {@link JEditor} for this painter + * @param defaults + * the {@link TextAreaDefaults} to use + */ + public EnhancedPainter(JEditor textArea, TextAreaDefaults defaults) { + super(textArea, defaults); + + setTextArea(textArea); + marker = new Marker(-1, -1); + markerVisible = false; + lineNumbersVisible = true; + LINE_NUMBERS_WIDTH = getFm().stringWidth("000"); + lineNumbersWidth = LINE_NUMBERS_WIDTH + LINE_NUMBERS_OFFSET; + } + + /** + * sets visibility of line numbers. calls repaint + * + * @param visible + * new line numbers visibility + */ + public void setLineNumbersVisible(boolean visible) { + lineNumbersVisible = visible; + if (visible) + lineNumbersWidth = LINE_NUMBERS_WIDTH + LINE_NUMBERS_OFFSET; + else + lineNumbersWidth = 0; + repaint(); + } + + /** + * sets the line range which should be marked. calls repaint + * + * @param lineStart + * index of first line + * @param lineEnd + * index of last line + */ + public void setLineMarker(int lineStart, int lineEnd) { + marker.setLines(lineStart, lineEnd); + repaint(); + } + + /** + * returns the range marked by the line marker + * @param lineStart returns the start line index. pass null to ignore + * @param lineEnd returns the end line index. pass null to ignore + */ + public void getLineMarker(ExInteger lineStart, ExInteger lineEnd) { + if (lineStart != null) + lineStart.set(marker.getStartLine()); + if (lineEnd != null) + lineEnd.set(marker.getEndLine()); + } + + /** + * sets visibility of the line marker. calls repaint + * + * @param visible + * new line marker visibility + */ + public void showLineMarker(boolean visible) { + markerVisible = visible; + repaint(); + } + + /** + * returns the line marker's visibility + * @return if the line marker is visible + */ + public boolean isLineMarkerVisible() { + return markerVisible; + } + + /** + * updates the line numbers width to be large enough for {@link String} s + * + * @param s + * the {@link String} which has to fit in line numbers width + */ + public void updateLineNumbersWidth(String s) { + FontMetrics fm = getFm(); + if (getLineNumbersWidth() - LINE_NUMBERS_OFFSET < fm.stringWidth(s)) + setLineNumbersWidth(fm.stringWidth(s)); + } + + /** + * sets new line numbers width + * + * @param width + * new width in pixels + */ + public void setLineNumbersWidth(int width) { + this.LINE_NUMBERS_WIDTH = width; + setLineNumbersVisible(lineNumbersVisible); + } + + /** + * returns the current line numbers width + * + * @return current line numbers width + */ + public int getLineNumbersWidth() { + return lineNumbersWidth; + } + + /** + * returns the index of the current line + * + * @return index of current line + */ + public int getCurrentLineIndex() { + return currentLineIndex; + } + + /** + * sets the index of the current line + * + * @param index + * index of new current line + */ + public void setCurrentLineIndex(int index) { + this.currentLineIndex = index; + } + + /** + * return cached tokens of current line + * + * @return the cached {@link Token} + */ + public Token getCurrentLineTokens() { + return currentLineTokens; + } + + /** + * sets the tokens for current line + * + * @param token + * new {@link Token} for current line + */ + public void setCurrentLineTokens(Token token) { + this.currentLineTokens = token; + } + + /** + * refreshed the width of line numbers area to fit the largest line number + * available + */ + public void refreshLineNumbersWidth() { + // update to the largest necessary line number width before + // painting lines + setLineNumbersWidth(0); + for (int line = 1; line <= textArea.getLineCount(); line++) { + if (!((JEditor) textArea).hasModel()) { + String lineNumber = String.valueOf(line); + updateLineNumbersWidth(lineNumber); + } else { + ExInteger startLine = new ExInteger(0); + CodeObject codeObject = ((JEditor) textArea).getCodeFromLine(line - 1, startLine, null); + + // if the codeObject is null, we might be at the last line + // which does not have to have a codeObject + // so it is fine not to print a line number here + if (codeObject != null && line - 1 == startLine.getValue() && codeObject.getAddress() != null + && codeObject.getAddress().isVisible()) { + String lineAddress = codeObject.getAddress().toString(); + updateLineNumbersWidth(lineAddress); + } + } + } + } + + @Override + /** + * see {@link TextAreaPainter} + */ + public void paint(Graphics gfx) { + tabSize = getFm().charWidth(' ') * 4; + //* ((Integer) textArea.getDocument().getProperty(PlainDocument.tabSizeAttribute)).intValue(); + + Rectangle clipRect = gfx.getClipBounds(); + + gfx.setColor(getBackground()); + gfx.fillRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height); + + // We don't use yToLine() here because that method doesn't + // return lines past the end of the document + int height = getFm().getHeight(); + int firstLine = textArea.getFirstLine(); + int firstInvalid = firstLine + clipRect.y / height; + // Because the clipRect's height is usually an even multiple + // of the font height, we subtract 1 from it, otherwise one + // too many lines will always be painted. + int lastInvalid = firstLine + (clipRect.y + clipRect.height - 1) / height; + + try { + TokenMarker tokenMarker = textArea.getDocument().getTokenMarker(); + int x = textArea.getHorizontalOffset() + lineNumbersWidth; + + // paint the actual lines + for (int line = firstInvalid; line <= lastInvalid + 1; line++) { + paintLine(gfx, tokenMarker, line, x); + } + + if (tokenMarker != null && tokenMarker.isNextLineRequested()) { + int h = clipRect.y + clipRect.height; + repaint(0, h, getWidth(), getHeight() - h); + } + } catch (Exception e) { + System.err.println("Error repainting line" + " range {" + firstInvalid + "," + (lastInvalid + 1) + "}:"); + e.printStackTrace(); + } + } + + protected void paintLineNumber(Graphics gfx, int line, int y) { + Color color = gfx.getColor(); + Font defaultFont = gfx.getFont(); + + gfx.setFont(defaultFont.deriveFont(Font.PLAIN)); + + gfx.setColor(getBackground()); + gfx.fillRect(0, y, lineNumbersWidth, getFm().getHeight()); + + gfx.setColor(Color.LIGHT_GRAY); + gfx.drawLine(lineNumbersWidth - 1, y, lineNumbersWidth - 1, y + getFm().getHeight()); + + gfx.setColor(new Color(100, 100, 100)); + + // prints default line numbers or CodeObject addresses + if (!((JEditor) textArea).hasModel()) { + if (line <= textArea.getLineCount()) { + String lineNumber = String.valueOf(line); + + gfx.drawString(lineNumber, lineNumbersWidth - LINE_NUMBERS_OFFSET - getFm().stringWidth(lineNumber), y); + } + } else { + ExInteger startLine = new ExInteger(0); + CodeObject codeObject = ((JEditor) textArea).getCodeFromLine(line - 1, startLine, null); + + // if the codeObject is null, we might be at the last line which + // does not have to have a codeObject + // so it is fine not to print a line number here + if (codeObject != null && line - 1 == startLine.getValue() && codeObject.getAddress() != null + && codeObject.getAddress().isVisible()) { + String lineAddress = codeObject.getAddress().toString(); + + gfx.drawString(lineAddress, lineNumbersWidth - LINE_NUMBERS_OFFSET - getFm().stringWidth(lineAddress), + y); + } + } + + gfx.setFont(defaultFont); + gfx.setColor(color); + } + + @Override + /** + * see {@link TextAreaPainter} + */ + protected void paintLine(Graphics gfx, TokenMarker tokenMarker, int line, int x) { + Font defaultFont = getFont(); + ((Graphics2D) gfx).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); + Color defaultColor = getForeground(); + + currentLineIndex = line; + int y = textArea.lineToY(line); + + if (markerVisible && marker.isMarked(line)) + paintLineMarker(gfx, line, y); + + if (line < 0 || line >= textArea.getLineCount()) { + if (paintInvalid) { + paintHighlight(gfx, line, y); + + styles[Token.INVALID].setGraphicsFlags(gfx, defaultFont); + gfx.drawString("~", 0, y + getFm().getHeight()); + } + } else if (tokenMarker == null) { + paintPlainLine(gfx, line, defaultFont, defaultColor, x, y); + } else { + paintSyntaxLine(gfx, tokenMarker, line, defaultFont, defaultColor, x, y); + } + + // draw line numbers + if (lineNumbersVisible) + paintLineNumber(gfx, line, y); + gfx.setFont(defaultFont); + } + + protected void paintLineMarker(Graphics gfx, int line, int y) { + int height = getFm().getHeight(); + y += getFm().getLeading() + getFm().getMaxDescent(); + + gfx.setColor(marker.getColor()); + gfx.fillRect(lineNumbersWidth, y, getWidth() - lineNumbersWidth, height); + } + + @Override + /** + * see {@link TextAreaPainter} + */ + protected void paintLineHighlight(Graphics gfx, int line, int y) { + int height = getFm().getHeight(); + y += getFm().getLeading() + getFm().getMaxDescent(); + + int selectionStart = textArea.getSelectionStart(); + int selectionEnd = textArea.getSelectionEnd(); + + if (lineHighlight && line == textArea.getCaretLine()) { + gfx.setColor(lineHighlightColor); + gfx.fillRect(lineNumbersWidth, y, getWidth() - lineNumbersWidth, height); + } + + if (selectionStart != selectionEnd) { + if (textArea.isEnabled()) { + gfx.setColor(selectionColor); + + int selectionStartLine = textArea.getSelectionStartLine(); + int selectionEndLine = textArea.getSelectionEndLine(); + int lineStart = textArea.getLineStartOffset(line); + + int x1, x2; + if (textArea.isSelectionRectangular()) { + int lineLen = textArea.getLineLength(line); + x1 = textArea._offsetToX(line, Math.min(lineLen, selectionStart + - textArea.getLineStartOffset(selectionStartLine))); + x2 = textArea._offsetToX(line, Math.min(lineLen, selectionEnd + - textArea.getLineStartOffset(selectionEndLine))); + if (x1 == x2) + x2++; + } else if (selectionStartLine == selectionEndLine) { + x1 = textArea._offsetToX(line, selectionStart - lineStart); + x2 = textArea._offsetToX(line, selectionEnd - lineStart); + } else if (line == selectionStartLine) { + x1 = textArea._offsetToX(line, selectionStart - lineStart); + x2 = getWidth(); + } else if (line == selectionEndLine) { + x1 = lineNumbersWidth; + x2 = textArea._offsetToX(line, selectionEnd - lineStart); + } else { + x1 = lineNumbersWidth; + x2 = getWidth(); + } + + // "inlined" min/max() + gfx.fillRect(x1 > x2 ? (x2) : (x1), y, x1 > x2 ? (x1 - x2) : (x2 - x1), height); + } + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/JEditor.java b/src/org/jalgo/module/am0c0/gui/jeditor/JEditor.java new file mode 100644 index 0000000..2e72ee5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/JEditor.java @@ -0,0 +1,725 @@ +package org.jalgo.module.am0c0.gui.jeditor; + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Observer; + +import javax.print.attribute.IntegerSyntax; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.event.DocumentEvent; +import javax.swing.filechooser.FileFilter; +import javax.swing.text.Utilities; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.gui.jeditor.jedit.JEditTextArea; +import org.jalgo.module.am0c0.gui.jeditor.jedit.SyntaxDocument; +import org.jalgo.module.am0c0.gui.jeditor.jedit.SyntaxStyle; +import org.jalgo.module.am0c0.gui.jeditor.jedit.TextAreaDefaults; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.Token; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.TokenMarker; +import org.jalgo.module.am0c0.model.CodeObject; +import org.jalgo.module.am0c0.model.GenericProgram; + +/** + * Improved {@link JEditTextArea} with support for line numbers, an underlying code + * model, automatic code highlighting and a marker. + * + * @author Felix Schmitt + * + */ +public class JEditor extends JEditTextArea { + + /** + * Implementation of IntegerSyntax with set() feature. + * + * @author Felix Schmitt + * + */ + public static class ExInteger extends IntegerSyntax { + + /** + * + */ + private static final long serialVersionUID = 1L; + protected int val; + + public ExInteger(int value) { + super(value); + val = value; + } + + /** + * sets new integer value + * + * @param value + * new value + */ + public final void set(int value) { + val = value; + } + + /** + * returns integer value + * + * @return the value + */ + @Override + public int getValue() { + return val; + } + } + + /** + * + */ + private static final long serialVersionUID = 1L; + + protected boolean beamerMode; + protected boolean modified; + protected boolean codeHighlightMode; + protected GenericProgram model; + protected JFileChooser fileChooser; + + protected EnhancedPainter enhancedPainter; + + protected Observer observer; + + /** + * constructor creates a new JEditor instance with optional code model + * + * @param model + * the underlying code model. if model is null, no code model + * will be used + */ + public JEditor(Observer observer, GenericProgram model) { + this(observer, TextAreaDefaults.getDefaults(), model); + } + + /** + * constructor creates a new JEditor instance with default values for the + * TextArea and an optional code model + * + * @param defaults + * default values for the TextArea, see documentation for + * {@link JEditTextArea} for further info + * @param model + * the underlying code model. if model is null, no code model + * will be used + */ + public JEditor(Observer observer, TextAreaDefaults defaults, + GenericProgram model) { + super(defaults); + setDocument(new SyntaxDocument()); + setCaretBlinkEnabled(false); + + this.observer = observer; + if (observer == null) + throw new IllegalArgumentException("The observer should not be null"); //$NON-NLS-1$ + + fileChooser = new JFileChooser(System.getProperty("user.dir")); + + fileChooser.addChoosableFileFilter(new FileFilter() { + + @Override + public String getDescription() { + return Messages.getString("am0c0", "JEditor.1"); //$NON-NLS-1$ + } + + @Override + public boolean accept(File f) { + return f.isDirectory() || f.getName().endsWith(".am0"); //$NON-NLS-1$ + } + }); + + fileChooser.addChoosableFileFilter(new FileFilter() { + + @Override + public String getDescription() { + return Messages.getString("am0c0", "JEditor.3"); //$NON-NLS-1$ + } + + @Override + public boolean accept(File f) { + return f.isDirectory() || f.getName().endsWith(".c0"); //$NON-NLS-1$ + } + }); + + enhancedPainter = new EnhancedPainter(this, defaults); + setPainter(enhancedPainter); + setMouseListener(); + + setModified(false); + setBeamerMode(false); + + setCodeHighlightMode(model != null); + + updateModel(model); + } + + private void setMouseListener() { + enhancedPainter.addMouseMotionListener(new MouseMotionListener() { + + @Override + public void mouseMoved(MouseEvent arg0) { + int line = yToLine(arg0.getPoint().y); + updateCodeHighlight(line); + } + + @Override + public void mouseDragged(MouseEvent arg0) { + } + }); + } + + @Override + protected void documentChanged(DocumentEvent evt) { + super.documentChanged(evt); + setModified(true); + + } + + /** + * sets the beamer mode + * + * @param beamerMode + * value for beamer mode + */ + public void setBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + repaint(); + } + + /** + * returns if code has been altered since last save + * + * @return the modified flag + */ + public boolean isModified() { + return modified; + } + + /** + * sets the modified flag + * + * @param modified + * new value for modified flag + */ + public void setModified(boolean modified) { + this.modified = modified; + observer.update(null, this); + repaint(); + } + + /** + * sets line numbers visibility + * + * @param visible + * line numbers visibility + */ + public void showLineNumbers(boolean visible) { + enhancedPainter.setLineNumbersVisible(visible); + } + + /** + * sets the range for the line marker. marked lines will be highlighted if + * the line marker is visible + * + * @param lineStart + * index of the first marked line. set to -1 to mark no line + * @param lineEnd + * index of the last marked line + */ + public void setLineMarker(int lineStart, int lineEnd) { + enhancedPainter.setLineMarker(lineStart, lineEnd); + } + + /** + * sets visibility of line marker + * + * @param visible + * line marker visibility + */ + public void showLineMarker(boolean visible) { + enhancedPainter.showLineMarker(visible); + } + + /** + * sets if selected code should be highlighted automatically. needs an + * underlying code model + * + * @param codeHighlight + * if selected code should be highlighted + */ + public void setCodeHighlightMode(boolean codeHighlight) { + this.codeHighlightMode = codeHighlight; + if (codeHighlight) + showLineMarker(true); + repaint(); + } + + /** + * updates the highlighted code if codeHighlightMode == true and there is a model + * @param line the line to check highlighting for + */ + private void updateCodeHighlight(int line) { + if (model != null && codeHighlightMode) { + ExInteger startLine = new ExInteger(0); + CodeObject codeObject = getCodeFromLine(line, startLine, null); + if (codeObject != null) + setLineMarker(startLine.getValue(), startLine.getValue() + + codeObject.getLinesCount() - 1); + else + setLineMarker(-1, -1); + repaint(); + } + } + + /** + * enables/disabled the component for editing. sets caret's visibility and + * line highlights + * + * @param enabled + * enables/disables the component + */ + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + + setCaretVisible(enabled); + getPainter().setLineHighlightEnabled(enabled); + } + + /** + * updates the underlying code model using a {@link GenericProgram} + * + * @param model + * new value for the code model. null will disable the underlying + * code model + */ + public void updateModel(GenericProgram model) { + this.model = model; + + if (model != null) { + StringBuffer buf = new StringBuffer(); + for (CodeObject codeObj : model) + buf.append(codeObj.getCodeText() + "\n"); //$NON-NLS-1$ + setText(buf.toString()); + } + + setEditable(model == null); + enhancedPainter.refreshLineNumbersWidth(); + + repaint(); + } + + /** + * checks whether an underlying code model has been set or not + * + * @return true if the code model != null + */ + public boolean hasModel() { + return model != null; + } + + /** + * saves the entered code if the user confirms the respective dialog and + * sets modified to false + * + * @return the path if the user confirmed the dialog or "" if not + */ + public String saveCode() { + boolean result = fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION; + String ret = ""; + if (result) { + File file = fileChooser.getSelectedFile(); + ret = file.getAbsolutePath(); + PrintWriter printWriter; + try { + printWriter = new PrintWriter(new FileWriter(file)); + + printWriter.print(getText()); + printWriter.close(); + + setModified(false); + } catch (IOException e) { + JOptionPane.showMessageDialog(this, e.getMessage(), Messages.getString("am0c0", "JEditor.0"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + return ""; + } + } + + return ret; + } + + /** + * loads new code if the user confirms the respective dialog and sets + * modified to false. if there is remaining modified code, the user will be + * questioned whether or not to save it. + * + * @return the path to the selected file or a empty string if no file was selected + */ + public String loadCode() { + if (isModified()) { + int saveBeforeClose = JOptionPane.showConfirmDialog(this, + Messages.getString("am0c0", "JEditor.8"), Messages.getString("am0c0", "JEditor.9"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.YES_NO_CANCEL_OPTION); + + switch (saveBeforeClose) { + case JOptionPane.YES_OPTION: + saveCode(); + setModified(false); + break; + case JOptionPane.CANCEL_OPTION: + return ""; //$NON-NLS-1$ + default: + break; + } + } + + boolean result = fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION; + + if (result) { + File file = fileChooser.getSelectedFile(); + + BufferedReader reader; + try { + reader = new BufferedReader(new FileReader(file)); + + setText(""); //$NON-NLS-1$ + boolean firstLine = true; + + for (String line; (line = reader.readLine()) != null;) { + if (firstLine) { + setText(line); + firstLine = false; + } else + setText(getText() + "\n" + line); //$NON-NLS-1$ + } + + reader.close(); + + updateModel(null); + setModified(false); + + return fileChooser.getSelectedFile().getAbsolutePath(); + } catch (IOException e) { + JOptionPane.showMessageDialog(this, e.getMessage(), Messages.getString("am0c0", "JEditor.13"), //$NON-NLS-1$ + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + return ""; //$NON-NLS-1$ + } + + } + + return ""; //$NON-NLS-1$ + } + + /** + * returns the {@link CodeObject} referenced by lineIndex if there is an + * underlying code model + * + * @param lineIndex + * the lineIndex to check + * @param startLine + * returns the first line of the code object as an + * {@link ExInteger}. pass null to ignore this. + * @param objectIndex + * returns the list index of the code object as an + * {@link ExInteger}. pass null to ignore this. + * @return the referenced {@link CodeObject} or null if there is no such (or + * no code model) + */ + public CodeObject getCodeFromLine(int lineIndex, ExInteger startLine, ExInteger objectIndex) { + if (model == null || lineIndex < 0) + return null; + + int currentLine = 0; + for (CodeObject codeObj : model) { + if (lineIndex < currentLine + codeObj.getLinesCount()) { + if (startLine != null) + // pass currentLine to startLine here... + // I hate Java + startLine.set(currentLine); + if (objectIndex != null) + objectIndex.set(model.indexOf(codeObj)); + return codeObj; + } + currentLine += codeObj.getLinesCount(); + } + + return null; + } + + @Override + /** + * sets the font for this component (and its painter) + * refreshed line number width + * @param font the new {@link Font} + */ + public void setFont(Font font) { + super.setFont(font); + + // save attributes and MouseListeners + ExInteger lineStart = new ExInteger(0); + ExInteger lineEnd = new ExInteger(0); + enhancedPainter.getLineMarker(lineStart, lineEnd); + + MouseListener[] mouseListeners = (MouseListener[])enhancedPainter.getListeners(MouseListener.class); + + boolean markerVisible = enhancedPainter.isLineMarkerVisible(); + boolean lineHighlightEnabled = enhancedPainter.isLineHighlightEnabled(); + boolean enabled = isEnabled(); + + int currentLineIndex = enhancedPainter.getCurrentLineIndex(); + Token currentLineToken = enhancedPainter.getCurrentLineTokens(); + + // reset the painter with new font + enhancedPainter = new EnhancedPainter(this, TextAreaDefaults.getDefaults()); + setPainter(enhancedPainter); + getPainter().setFont(font); + + // restore MouseListeners and attributes + setMouseListener(); + enhancedPainter.setLineMarker(lineStart.getValue(), lineEnd.getValue()); + enhancedPainter.showLineMarker(markerVisible); + enhancedPainter.setCurrentLineIndex(currentLineIndex); + enhancedPainter.setCurrentLineTokens(currentLineToken); + enhancedPainter.setLineHighlightEnabled(lineHighlightEnabled); + + for (MouseListener ml : mouseListeners) + enhancedPainter.addMouseListener(ml); + + setEnabled(enabled); + + updateScrollBars(); + enhancedPainter.refreshLineNumbersWidth(); + } + + @Override + /** + * returns the current {@link Font} of this component (and its painter) + * @return the current {@link Font} + */ + public Font getFont() { + return getPainter().getFont(); + } + + @Override + public void updateScrollBars() + { + if(vertical != null && visibleLines != 0) + { + vertical.setValues(firstLine,visibleLines,0,getLineCount()); + vertical.setUnitIncrement(2); + vertical.setBlockIncrement(visibleLines); + } + + int width = getPainter().getWidth(); + if(horizontal != null && width != 0) + { + horizontal.setValues(-horizontalOffset,width,0,width * 5); + horizontal.setUnitIncrement(enhancedPainter.getFontMetrics() + .charWidth('w')); + horizontal.setBlockIncrement(width / 2); + } + } + + @Override + public boolean scrollTo(int line, int offset) { + // visibleLines == 0 before the component is realized + // we can't do any proper scrolling then, so we have + // this hack... + if (visibleLines == 0) { + setFirstLine(Math.max(0, line - electricScroll)); + return true; + } + + int newFirstLine = firstLine; + int newHorizontalOffset = getHorizontalOffset(); + + if (line < firstLine + electricScroll) { + newFirstLine = Math.max(0, line - electricScroll); + } else if (line + electricScroll >= firstLine + visibleLines) { + newFirstLine = (line - visibleLines) + electricScroll + 1; + if (newFirstLine + visibleLines >= getLineCount()) + newFirstLine = getLineCount() - visibleLines; + if (newFirstLine < 0) + newFirstLine = 0; + } + + int x = _offsetToX(line, offset) - enhancedPainter.getLineNumbersWidth(); + int width = enhancedPainter.getFontMetrics().charWidth('w'); + + if (x < 0) { + newHorizontalOffset = Math.min(0, horizontalOffset - x + width + 5); + } else if (x + width >= enhancedPainter.getWidth()) { + newHorizontalOffset = horizontalOffset + (enhancedPainter.getWidth() - x) - width - 5; + } + + enhancedPainter.refreshLineNumbersWidth(); + + return setOrigin(newFirstLine, newHorizontalOffset); + } + + @Override + /** + * TODO: there is a bug in this method which generates wring results when TokenMarkers are applied + */ + public int _offsetToX(int line, int offset) { + TokenMarker tokenMarker = getTokenMarker(); + + FontMetrics fm = enhancedPainter.getFontMetrics(); + + getLineText(line, lineSegment); + + int segmentOffset = lineSegment.offset; + int lineNumbersWidth = enhancedPainter.getLineNumbersWidth(); + int x = getHorizontalOffset() + lineNumbersWidth; + + if (tokenMarker == null) { + lineSegment.count = offset; + return x + Utilities.getTabbedTextWidth(lineSegment, fm, x, enhancedPainter, 0); + } + + else { + Token tokens; + if (enhancedPainter.getCurrentLineIndex() == line && enhancedPainter.getCurrentLineTokens() != null) + tokens = enhancedPainter.getCurrentLineTokens(); + else { + enhancedPainter.setCurrentLineIndex(line); + enhancedPainter.setCurrentLineTokens(tokenMarker.markTokens(lineSegment, line)); + tokens = enhancedPainter.getCurrentLineTokens(); + } + + Font defaultFont = enhancedPainter.getFont(); + SyntaxStyle[] styles = enhancedPainter.getStyles(); + + for (;;) { + byte id = tokens.id; + if (id == Token.END) { + return x; + } + + if (id == Token.NULL) + fm = enhancedPainter.getFontMetrics(); + else + fm = styles[id].getFontMetrics(defaultFont); + + int length = tokens.length; + + if (offset + segmentOffset < lineSegment.offset + length) { + lineSegment.count = offset - (lineSegment.offset - segmentOffset); + return x + Utilities.getTabbedTextWidth(lineSegment, fm, x, enhancedPainter, 0); + } else { + lineSegment.count = length; + x += Utilities.getTabbedTextWidth(lineSegment, fm, x, enhancedPainter, 0); + lineSegment.offset += length; + } + tokens = tokens.next; + } + } + } + + @Override + public int xToOffset(int line, int x) { + TokenMarker tokenMarker = getTokenMarker(); + + FontMetrics fm = enhancedPainter.getFontMetrics(); + + getLineText(line, lineSegment); + + char[] segmentArray = lineSegment.array; + int segmentOffset = lineSegment.offset; + int segmentCount = lineSegment.count; + + int width = getHorizontalOffset() + enhancedPainter.getLineNumbersWidth(); + + if (tokenMarker == null) { + for (int i = 0; i < segmentCount; i++) { + char c = segmentArray[i + segmentOffset]; + int charWidth; + if (c == '\t') + charWidth = (int) enhancedPainter.nextTabStop(width, i) - width; + else + charWidth = fm.charWidth(c); + + if (enhancedPainter.isBlockCaretEnabled()) { + if (x - charWidth <= width) { + return i; + } + } else { + if (x - charWidth / 2 <= width) { + return i; + } + } + + width += charWidth; + } + + return segmentCount; + } else { + Token tokens; + if (enhancedPainter.getCurrentLineIndex() == line && enhancedPainter.getCurrentLineTokens() != null) + tokens = enhancedPainter.getCurrentLineTokens(); + else { + enhancedPainter.setCurrentLineIndex(line); + enhancedPainter.setCurrentLineTokens(tokenMarker.markTokens(lineSegment, line)); + tokens = enhancedPainter.getCurrentLineTokens(); + } + + int offset = 0; + Font defaultFont = enhancedPainter.getFont(); + SyntaxStyle[] styles = enhancedPainter.getStyles(); + + for (;;) { + byte id = tokens.id; + if (id == Token.END){ + return offset; + } + + if (id == Token.NULL) + fm = enhancedPainter.getFontMetrics(); + else + fm = styles[id].getFontMetrics(defaultFont); + + int length = tokens.length; + + for (int i = 0; i < length; i++) { + char c = segmentArray[segmentOffset + offset + i]; + int charWidth; + if (c == '\t') { + charWidth = (int) enhancedPainter.nextTabStop(width, offset + i) - width; + } + else + charWidth = fm.charWidth(c); + + if (enhancedPainter.isBlockCaretEnabled()) { + if (x - charWidth <= width) { + return offset + i; + } + } else { + if (x - charWidth / 2 <= width) { + return offset + i; + } + } + + width += charWidth; + } + + offset += length; + tokens = tokens.next; + } + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Entries b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Entries new file mode 100644 index 0000000..2b028d0 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Entries @@ -0,0 +1,12 @@ +/DefaultInputHandler.java/1.2/Wed Dec 8 13:01:52 2010// +/InputHandler.java/1.2/Wed Dec 8 13:01:52 2010// +/JEditTextArea.java/1.2/Wed Dec 8 13:01:52 2010// +/KeywordMap.java/1.2/Wed Dec 8 13:01:52 2010// +/SyntaxDocument.java/1.2/Wed Dec 8 13:01:52 2010// +/SyntaxStyle.java/1.2/Wed Dec 8 13:01:52 2010// +/SyntaxUtilities.java/1.2/Wed Dec 8 13:01:52 2010// +/TextAreaDefaults.java/1.1/Mon Aug 16 12:05:48 2010// +/TextAreaPainter.java/1.2/Wed Dec 8 13:01:52 2010// +/TextUtilities.java/1.2/Wed Dec 8 13:01:52 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// +D/tokenmarker//// diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Repository b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Repository new file mode 100644 index 0000000..e4fdd20 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/gui/jeditor/jedit diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Root b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.java new file mode 100644 index 0000000..9651d33 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/DefaultInputHandler.java @@ -0,0 +1,353 @@ +/* + * DefaultInputHandler.java - Default implementation of an input handler + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.KeyStroke; +import java.awt.event.*; +import java.awt.Toolkit; +import java.util.Hashtable; +import java.util.StringTokenizer; + +/** + * The default input handler. It maps sequences of keystrokes into actions + * and inserts key typed events into the text area. + * @author Slava Pestov + */ +public class DefaultInputHandler extends InputHandler +{ + /** + * Creates a new input handler with no key bindings defined. + */ + public DefaultInputHandler() + { + bindings = currentBindings = new Hashtable(); + } + + /** + * Sets up the default key bindings. + */ + public void addDefaultKeyBindings() + { + addKeyBinding("BACK_SPACE",BACKSPACE); + addKeyBinding("C+BACK_SPACE",BACKSPACE_WORD); + addKeyBinding("DELETE",DELETE); + addKeyBinding("C+DELETE",DELETE_WORD); + + addKeyBinding("ENTER",INSERT_BREAK); + addKeyBinding("TAB",INSERT_TAB); + + addKeyBinding("INSERT",OVERWRITE); + addKeyBinding("C+\\",TOGGLE_RECT); + + addKeyBinding("HOME",HOME); + addKeyBinding("END",END); + addKeyBinding("C+A",SELECT_ALL); + addKeyBinding("S+HOME",SELECT_HOME); + addKeyBinding("S+END",SELECT_END); + addKeyBinding("C+HOME",DOCUMENT_HOME); + addKeyBinding("C+END",DOCUMENT_END); + addKeyBinding("CS+HOME",SELECT_DOC_HOME); + addKeyBinding("CS+END",SELECT_DOC_END); + + addKeyBinding("PAGE_UP",PREV_PAGE); + addKeyBinding("PAGE_DOWN",NEXT_PAGE); + addKeyBinding("S+PAGE_UP",SELECT_PREV_PAGE); + addKeyBinding("S+PAGE_DOWN",SELECT_NEXT_PAGE); + + addKeyBinding("LEFT",PREV_CHAR); + addKeyBinding("S+LEFT",SELECT_PREV_CHAR); + addKeyBinding("C+LEFT",PREV_WORD); + addKeyBinding("CS+LEFT",SELECT_PREV_WORD); + addKeyBinding("RIGHT",NEXT_CHAR); + addKeyBinding("S+RIGHT",SELECT_NEXT_CHAR); + addKeyBinding("C+RIGHT",NEXT_WORD); + addKeyBinding("CS+RIGHT",SELECT_NEXT_WORD); + addKeyBinding("UP",PREV_LINE); + addKeyBinding("S+UP",SELECT_PREV_LINE); + addKeyBinding("DOWN",NEXT_LINE); + addKeyBinding("S+DOWN",SELECT_NEXT_LINE); + + addKeyBinding("C+ENTER",REPEAT); + + // Clipboard + addKeyBinding("C+C", CLIP_COPY); + addKeyBinding("C+V", CLIP_PASTE); + addKeyBinding("C+X", CLIP_CUT); + } + + /** + * Adds a key binding to this input handler. The key binding is + * a list of white space separated key strokes of the form + * [modifiers+]key where modifier is C for Control, A for Alt, + * or S for Shift, and key is either a character (a-z) or a field + * name in the KeyEvent class prefixed with VK_ (e.g., BACK_SPACE) + * @param keyBinding The key binding + * @param action The action + */ + public void addKeyBinding(String keyBinding, ActionListener action) + { + Hashtable current = bindings; + + StringTokenizer st = new StringTokenizer(keyBinding); + while(st.hasMoreTokens()) + { + KeyStroke keyStroke = parseKeyStroke(st.nextToken()); + if(keyStroke == null) + return; + + if(st.hasMoreTokens()) + { + Object o = current.get(keyStroke); + if(o instanceof Hashtable) + current = (Hashtable)o; + else + { + o = new Hashtable(); + current.put(keyStroke,o); + current = (Hashtable)o; + } + } + else + current.put(keyStroke,action); + } + } + + /** + * Removes a key binding from this input handler. This is not yet + * implemented. + * @param keyBinding The key binding + */ + public void removeKeyBinding(String keyBinding) + { + throw new InternalError("Not yet implemented"); + } + + /** + * Removes all key bindings from this input handler. + */ + public void removeAllKeyBindings() + { + bindings.clear(); + } + + /** + * Returns a copy of this input handler that shares the same + * key bindings. Setting key bindings in the copy will also + * set them in the original. + */ + public InputHandler copy() + { + return new DefaultInputHandler(this); + } + + /** + * Handle a key pressed event. This will look up the binding for + * the key stroke and execute it. + */ + public void keyPressed(KeyEvent evt) + { + int keyCode = evt.getKeyCode(); + int modifiers = evt.getModifiers(); + + if(keyCode == KeyEvent.VK_CONTROL || + keyCode == KeyEvent.VK_SHIFT || + keyCode == KeyEvent.VK_ALT || + keyCode == KeyEvent.VK_META) + return; + + if((modifiers & ~KeyEvent.SHIFT_MASK) != 0 + || evt.isActionKey() + || keyCode == KeyEvent.VK_BACK_SPACE + || keyCode == KeyEvent.VK_DELETE + || keyCode == KeyEvent.VK_ENTER + || keyCode == KeyEvent.VK_TAB + || keyCode == KeyEvent.VK_ESCAPE) + { + if(grabAction != null) + { + handleGrabAction(evt); + return; + } + + KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, + modifiers); + Object o = currentBindings.get(keyStroke); + if(o == null) + { + // Don't beep if the user presses some + // key we don't know about unless a + // prefix is active. Otherwise it will + // beep when caps lock is pressed, etc. + if(currentBindings != bindings) + { + Toolkit.getDefaultToolkit().beep(); + // F10 should be passed on, but C+e F10 + // shouldn't + repeatCount = 0; + repeat = false; + evt.consume(); + } + currentBindings = bindings; + return; + } + else if(o instanceof ActionListener) + { + currentBindings = bindings; + + executeAction(((ActionListener)o), + evt.getSource(),null); + + evt.consume(); + return; + } + else if(o instanceof Hashtable) + { + currentBindings = (Hashtable)o; + evt.consume(); + return; + } + } + } + + /** + * Handle a key typed event. This inserts the key into the text area. + */ + public void keyTyped(KeyEvent evt) + { + int modifiers = evt.getModifiers(); + char c = evt.getKeyChar(); + if(c != KeyEvent.CHAR_UNDEFINED && + (modifiers & KeyEvent.ALT_MASK) == 0) + { + if(c >= 0x20 && c != 0x7f) + { + KeyStroke keyStroke = KeyStroke.getKeyStroke( + Character.toUpperCase(c)); + Object o = currentBindings.get(keyStroke); + + if(o instanceof Hashtable) + { + currentBindings = (Hashtable)o; + return; + } + else if(o instanceof ActionListener) + { + currentBindings = bindings; + executeAction((ActionListener)o, + evt.getSource(), + String.valueOf(c)); + return; + } + + currentBindings = bindings; + + if(grabAction != null) + { + handleGrabAction(evt); + return; + } + + // 0-9 adds another 'digit' to the repeat number + if(repeat && Character.isDigit(c)) + { + repeatCount *= 10; + repeatCount += (c - '0'); + return; + } + + executeAction(INSERT_CHAR,evt.getSource(), + String.valueOf(evt.getKeyChar())); + + repeatCount = 0; + repeat = false; + } + } + } + + /** + * Converts a string to a keystroke. The string should be of the + * form modifiers+shortcut where modifiers + * is any combination of A for Alt, C for Control, S for Shift + * or M for Meta, and shortcut is either a single character, + * or a keycode name from the KeyEvent class, without + * the VK_ prefix. + * @param keyStroke A string description of the key stroke + */ + public static KeyStroke parseKeyStroke(String keyStroke) + { + if(keyStroke == null) + return null; + int modifiers = 0; + int index = keyStroke.indexOf('+'); + if(index != -1) + { + for(int i = 0; i < index; i++) + { + switch(Character.toUpperCase(keyStroke + .charAt(i))) + { + case 'A': + modifiers |= InputEvent.ALT_MASK; + break; + case 'C': + modifiers |= InputEvent.CTRL_MASK; + break; + case 'M': + modifiers |= InputEvent.META_MASK; + break; + case 'S': + modifiers |= InputEvent.SHIFT_MASK; + break; + } + } + } + String key = keyStroke.substring(index + 1); + if(key.length() == 1) + { + char ch = Character.toUpperCase(key.charAt(0)); + if(modifiers == 0) + return KeyStroke.getKeyStroke(ch); + else + return KeyStroke.getKeyStroke(ch,modifiers); + } + else if(key.length() == 0) + { + System.err.println("Invalid key stroke: " + keyStroke); + return null; + } + else + { + int ch; + + try + { + ch = KeyEvent.class.getField("VK_".concat(key)) + .getInt(null); + } + catch(Exception e) + { + System.err.println("Invalid key stroke: " + + keyStroke); + return null; + } + + return KeyStroke.getKeyStroke(ch,modifiers); + } + } + + // private members + private Hashtable bindings; + private Hashtable currentBindings; + + private DefaultInputHandler(DefaultInputHandler copy) + { + bindings = currentBindings = copy.bindings; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.java new file mode 100644 index 0000000..eb15215 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/InputHandler.java @@ -0,0 +1,1113 @@ +/* + * InputHandler.java - Manages key bindings and executes actions + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.text.*; +import javax.swing.JPopupMenu; +import java.awt.event.*; +import java.awt.Component; +import java.util.*; + +/** + * An input handler converts the user's key strokes into concrete actions. + * It also takes care of macro recording and action repetition.

      + * + * This class provides all the necessary support code for an input + * handler, but doesn't actually do any key binding logic. It is up + * to the implementations of this class to do so. + * + * @author Slava Pestov + * @see org.jalgo.module.testModule.editor.jedit.DefaultInputHandler + * + * 08/12/2002 Clipboard actions (Oliver Henning) + */ +public abstract class InputHandler extends KeyAdapter +{ + /** + * If this client property is set to Boolean.TRUE on the text area, + * the home/end keys will support 'smart' BRIEF-like behaviour + * (one press = start/end of line, two presses = start/end of + * viewscreen, three presses = start/end of document). By default, + * this property is not set. + */ + public static final String SMART_HOME_END_PROPERTY = "InputHandler.homeEnd"; + + public static final ActionListener BACKSPACE = new Backspace(); + public static final ActionListener BACKSPACE_WORD = new backspace_word(); + public static final ActionListener DELETE = new Delete(); + public static final ActionListener DELETE_WORD = new delete_word(); + public static final ActionListener END = new End(false); + public static final ActionListener DOCUMENT_END = new document_end(false); + public static final ActionListener SELECT_ALL = new select_all(); + public static final ActionListener SELECT_END = new End(true); + public static final ActionListener SELECT_DOC_END = new document_end(true); + public static final ActionListener INSERT_BREAK = new insert_break(); + public static final ActionListener INSERT_TAB = new insert_tab(); + public static final ActionListener HOME = new Home(false); + public static final ActionListener DOCUMENT_HOME = new document_home(false); + public static final ActionListener SELECT_HOME = new Home(true); + public static final ActionListener SELECT_DOC_HOME = new document_home(true); + public static final ActionListener NEXT_CHAR = new next_char(false); + public static final ActionListener NEXT_LINE = new next_line(false); + public static final ActionListener NEXT_PAGE = new next_page(false); + public static final ActionListener NEXT_WORD = new next_word(false); + public static final ActionListener SELECT_NEXT_CHAR = new next_char(true); + public static final ActionListener SELECT_NEXT_LINE = new next_line(true); + public static final ActionListener SELECT_NEXT_PAGE = new next_page(true); + public static final ActionListener SELECT_NEXT_WORD = new next_word(true); + public static final ActionListener OVERWRITE = new overwrite(); + public static final ActionListener PREV_CHAR = new prev_char(false); + public static final ActionListener PREV_LINE = new prev_line(false); + public static final ActionListener PREV_PAGE = new prev_page(false); + public static final ActionListener PREV_WORD = new prev_word(false); + public static final ActionListener SELECT_PREV_CHAR = new prev_char(true); + public static final ActionListener SELECT_PREV_LINE = new prev_line(true); + public static final ActionListener SELECT_PREV_PAGE = new prev_page(true); + public static final ActionListener SELECT_PREV_WORD = new prev_word(true); + public static final ActionListener REPEAT = new Repeat(); + public static final ActionListener TOGGLE_RECT = new toggle_rect(); + // Clipboard + public static final ActionListener CLIP_COPY = new clip_copy(); + public static final ActionListener CLIP_PASTE = new clip_paste(); + public static final ActionListener CLIP_CUT = new clip_cut(); + + // Default action + public static final ActionListener INSERT_CHAR = new insert_char(); + + private static Hashtable actions; + + static + { + actions = new Hashtable(); + actions.put("backspace",BACKSPACE); + actions.put("backspace-word",BACKSPACE_WORD); + actions.put("delete",DELETE); + actions.put("delete-word",DELETE_WORD); + actions.put("end",END); + actions.put("select-all",SELECT_ALL); + actions.put("select-end",SELECT_END); + actions.put("document-end",DOCUMENT_END); + actions.put("select-doc-end",SELECT_DOC_END); + actions.put("insert-break",INSERT_BREAK); + actions.put("insert-tab",INSERT_TAB); + actions.put("home",HOME); + actions.put("select-home",SELECT_HOME); + actions.put("document-home",DOCUMENT_HOME); + actions.put("select-doc-home",SELECT_DOC_HOME); + actions.put("next-char",NEXT_CHAR); + actions.put("next-line",NEXT_LINE); + actions.put("next-page",NEXT_PAGE); + actions.put("next-word",NEXT_WORD); + actions.put("select-next-char",SELECT_NEXT_CHAR); + actions.put("select-next-line",SELECT_NEXT_LINE); + actions.put("select-next-page",SELECT_NEXT_PAGE); + actions.put("select-next-word",SELECT_NEXT_WORD); + actions.put("overwrite",OVERWRITE); + actions.put("prev-char",PREV_CHAR); + actions.put("prev-line",PREV_LINE); + actions.put("prev-page",PREV_PAGE); + actions.put("prev-word",PREV_WORD); + actions.put("select-prev-char",SELECT_PREV_CHAR); + actions.put("select-prev-line",SELECT_PREV_LINE); + actions.put("select-prev-page",SELECT_PREV_PAGE); + actions.put("select-prev-word",SELECT_PREV_WORD); + actions.put("repeat",REPEAT); + actions.put("toggle-rect",TOGGLE_RECT); + actions.put("insert-char",INSERT_CHAR); + actions.put("clipboard-copy",CLIP_COPY); + actions.put("clipboard-paste",CLIP_PASTE); + actions.put("clipboard-cut",CLIP_CUT); + } + + /** + * Returns a named text area action. + * @param name The action name + */ + public static ActionListener getAction(String name) + { + return (ActionListener)actions.get(name); + } + + /** + * Returns the name of the specified text area action. + * @param listener The action + */ + public static String getActionName(ActionListener listener) + { + Enumeration enumeration = getActions(); + while(enumeration.hasMoreElements()) + { + String name = (String)enumeration.nextElement(); + ActionListener _listener = getAction(name); + if(_listener == listener) + return name; + } + return null; + } + + /** + * Returns an enumeration of all available actions. + */ + public static Enumeration getActions() + { + return actions.keys(); + } + + /** + * Adds the default key bindings to this input handler. + * This should not be called in the constructor of this + * input handler, because applications might load the + * key bindings from a file, etc. + */ + public abstract void addDefaultKeyBindings(); + + /** + * Adds a key binding to this input handler. + * @param keyBinding The key binding (the format of this is + * input-handler specific) + * @param action The action + */ + public abstract void addKeyBinding(String keyBinding, ActionListener action); + + /** + * Removes a key binding from this input handler. + * @param keyBinding The key binding + */ + public abstract void removeKeyBinding(String keyBinding); + + /** + * Removes all key bindings from this input handler. + */ + public abstract void removeAllKeyBindings(); + + /** + * Grabs the next key typed event and invokes the specified + * action with the key as a the action command. + * @param action The action + */ + public void grabNextKeyStroke(ActionListener listener) + { + grabAction = listener; + } + + /** + * Returns if repeating is enabled. When repeating is enabled, + * actions will be executed multiple times. This is usually + * invoked with a special key stroke in the input handler. + */ + public boolean isRepeatEnabled() + { + return repeat; + } + + /** + * Enables repeating. When repeating is enabled, actions will be + * executed multiple times. Once repeating is enabled, the input + * handler should read a number from the keyboard. + */ + public void setRepeatEnabled(boolean repeat) + { + this.repeat = repeat; + } + + /** + * Returns the number of times the next action will be repeated. + */ + public int getRepeatCount() + { + return (repeat ? Math.max(1,repeatCount) : 1); + } + + /** + * Sets the number of times the next action will be repeated. + * @param repeatCount The repeat count + */ + public void setRepeatCount(int repeatCount) + { + this.repeatCount = repeatCount; + } + + /** + * Returns the macro recorder. If this is non-null, all executed + * actions should be forwarded to the recorder. + */ + public InputHandler.MacroRecorder getMacroRecorder() + { + return recorder; + } + + /** + * Sets the macro recorder. If this is non-null, all executed + * actions should be forwarded to the recorder. + * @param recorder The macro recorder + */ + public void setMacroRecorder(InputHandler.MacroRecorder recorder) + { + this.recorder = recorder; + } + + /** + * Returns a copy of this input handler that shares the same + * key bindings. Setting key bindings in the copy will also + * set them in the original. + */ + public abstract InputHandler copy(); + + /** + * Executes the specified action, repeating and recording it as + * necessary. + * @param listener The action listener + * @param source The event source + * @param actionCommand The action command + */ + public void executeAction(ActionListener listener, Object source, + String actionCommand) + { + // create event + ActionEvent evt = new ActionEvent(source, + ActionEvent.ACTION_PERFORMED, + actionCommand); + + // don't do anything if the action is a wrapper + // (like EditAction.Wrapper) + if(listener instanceof Wrapper) + { + listener.actionPerformed(evt); + return; + } + + // remember old values, in case action changes them + boolean _repeat = repeat; + int _repeatCount = getRepeatCount(); + + // execute the action + if(listener instanceof InputHandler.NonRepeatable) + listener.actionPerformed(evt); + else + { + for(int i = 0; i < Math.max(1,repeatCount); i++) + listener.actionPerformed(evt); + } + + // do recording. Notice that we do no recording whatsoever + // for actions that grab keys + if(grabAction == null) + { + if(recorder != null) + { + if(!(listener instanceof InputHandler.NonRecordable)) + { + if(_repeatCount != 1) + recorder.actionPerformed(REPEAT,String.valueOf(_repeatCount)); + + recorder.actionPerformed(listener,actionCommand); + } + } + + // If repeat was true originally, clear it + // Otherwise it might have been set by the action, etc + if(_repeat) + { + repeat = false; + repeatCount = 0; + } + } + } + + /** + * Returns the text area that fired the specified event. + * @param evt The event + */ + public static JEditTextArea getTextArea(EventObject evt) + { + if(evt != null) + { + Object o = evt.getSource(); + if(o instanceof Component) + { + // find the parent text area + Component c = (Component)o; + for(;;) + { + if(c instanceof JEditTextArea) + return (JEditTextArea)c; + else if(c == null) + break; + if(c instanceof JPopupMenu) + c = ((JPopupMenu)c) + .getInvoker(); + else + c = c.getParent(); + } + } + } + + // this shouldn't happen + System.err.println("BUG: getTextArea() returning null"); + System.err.println("Report this to Slava Pestov "); + return null; + } + + // protected members + + /** + * If a key is being grabbed, this method should be called with + * the appropriate key event. It executes the grab action with + * the typed character as the parameter. + */ + protected void handleGrabAction(KeyEvent evt) + { + // Clear it *before* it is executed so that executeAction() + // resets the repeat count + ActionListener _grabAction = grabAction; + grabAction = null; + executeAction(_grabAction,evt.getSource(), + String.valueOf(evt.getKeyChar())); + } + + // protected members + protected ActionListener grabAction; + protected boolean repeat; + protected int repeatCount; + protected InputHandler.MacroRecorder recorder; + + /** + * If an action implements this interface, it should not be repeated. + * Instead, it will handle the repetition itself. + */ + public interface NonRepeatable {} + + /** + * If an action implements this interface, it should not be recorded + * by the macro recorder. Instead, it will do its own recording. + */ + public interface NonRecordable {} + + /** + * For use by EditAction.Wrapper only. + * @since jEdit 2.2final + */ + public interface Wrapper {} + + /** + * Macro recorder. + */ + public interface MacroRecorder + { + void actionPerformed(ActionListener listener, + String actionCommand); + } + + public static class Backspace implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + if(!textArea.isEditable()) + { + textArea.getToolkit().beep(); + return; + } + + if(textArea.getSelectionStart() + != textArea.getSelectionEnd()) + { + textArea.setSelectedText(""); + } + else + { + int caret = textArea.getCaretPosition(); + if(caret == 0) + { + textArea.getToolkit().beep(); + return; + } + try + { + textArea.getDocument().remove(caret - 1,1); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + } + } + } + + public static class backspace_word implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int start = textArea.getSelectionStart(); + if(start != textArea.getSelectionEnd()) + { + textArea.setSelectedText(""); + } + + int line = textArea.getCaretLine(); + int lineStart = textArea.getLineStartOffset(line); + int caret = start - lineStart; + + String lineText = textArea.getLineText(textArea + .getCaretLine()); + + if(caret == 0) + { + if(lineStart == 0) + { + textArea.getToolkit().beep(); + return; + } + caret--; + } + else + { + String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); + caret = TextUtilities.findWordStart(lineText,caret,noWordSep); + } + + try + { + textArea.getDocument().remove( + caret + lineStart, + start - (caret + lineStart)); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + } + } + + public static class Delete implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + if(!textArea.isEditable()) + { + textArea.getToolkit().beep(); + return; + } + + if(textArea.getSelectionStart() + != textArea.getSelectionEnd()) + { + textArea.setSelectedText(""); + } + else + { + int caret = textArea.getCaretPosition(); + if(caret == textArea.getDocumentLength()) + { + textArea.getToolkit().beep(); + return; + } + try + { + textArea.getDocument().remove(caret,1); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + } + } + } + + public static class delete_word implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int start = textArea.getSelectionStart(); + if(start != textArea.getSelectionEnd()) + { + textArea.setSelectedText(""); + } + + int line = textArea.getCaretLine(); + int lineStart = textArea.getLineStartOffset(line); + int caret = start - lineStart; + + String lineText = textArea.getLineText(textArea + .getCaretLine()); + + if(caret == lineText.length()) + { + if(lineStart + caret == textArea.getDocumentLength()) + { + textArea.getToolkit().beep(); + return; + } + caret++; + } + else + { + String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); + caret = TextUtilities.findWordEnd(lineText,caret,noWordSep); + } + + try + { + textArea.getDocument().remove(start, + (caret + lineStart) - start); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + } + } + + public static class End implements ActionListener + { + private boolean select; + + public End(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + int caret = textArea.getCaretPosition(); + + int lastOfLine = textArea.getLineEndOffset( + textArea.getCaretLine()) - 1; + int lastVisibleLine = textArea.getFirstLine() + + textArea.getVisibleLines(); + if(lastVisibleLine >= textArea.getLineCount()) + { + lastVisibleLine = Math.min(textArea.getLineCount() - 1, + lastVisibleLine); + } + else + lastVisibleLine -= (textArea.getElectricScroll() + 1); + + int lastVisible = textArea.getLineEndOffset(lastVisibleLine) - 1; + int lastDocument = textArea.getDocumentLength(); + + if(caret == lastDocument) + { + textArea.getToolkit().beep(); + return; + } + else if(!Boolean.TRUE.equals(textArea.getClientProperty( + SMART_HOME_END_PROPERTY))) + caret = lastOfLine; + else if(caret == lastVisible) + caret = lastDocument; + else if(caret == lastOfLine) + caret = lastVisible; + else + caret = lastOfLine; + + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + } + } + + public static class select_all implements ActionListener { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.selectAll(); + } + } + + public static class document_end implements ActionListener + { + private boolean select; + + public document_end(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + if(select) + textArea.select(textArea.getMarkPosition(), + textArea.getDocumentLength()); + else + textArea.setCaretPosition(textArea + .getDocumentLength()); + } + } + + public static class Home implements ActionListener + { + private boolean select; + + public Home(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + int caret = textArea.getCaretPosition(); + + int firstLine = textArea.getFirstLine(); + + int firstOfLine = textArea.getLineStartOffset( + textArea.getCaretLine()); + int firstVisibleLine = (firstLine == 0 ? 0 : + firstLine + textArea.getElectricScroll()); + int firstVisible = textArea.getLineStartOffset( + firstVisibleLine); + + if(caret == 0) + { + textArea.getToolkit().beep(); + return; + } + else if(!Boolean.TRUE.equals(textArea.getClientProperty( + SMART_HOME_END_PROPERTY))) + caret = firstOfLine; + else if(caret == firstVisible) + caret = 0; + else if(caret == firstOfLine) + caret = firstVisible; + else + caret = firstOfLine; + + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + } + } + + public static class document_home implements ActionListener + { + private boolean select; + + public document_home(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + if(select) + textArea.select(textArea.getMarkPosition(),0); + else + textArea.setCaretPosition(0); + } + } + + public static class insert_break implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + if(!textArea.isEditable()) + { + textArea.getToolkit().beep(); + return; + } + + textArea.setSelectedText("\n"); + } + } + + public static class insert_tab implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + + if(!textArea.isEditable()) + { + textArea.getToolkit().beep(); + return; + } + + textArea.overwriteSetSelectedText("\t"); + } + } + + public static class next_char implements ActionListener + { + private boolean select; + + public next_char(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + if(caret == textArea.getDocumentLength()) + { + textArea.getToolkit().beep(); + return; + } + + if(select) + textArea.select(textArea.getMarkPosition(), + caret + 1); + else + textArea.setCaretPosition(caret + 1); + } + } + + public static class next_line implements ActionListener + { + private boolean select; + + public next_line(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + int line = textArea.getCaretLine(); + + if(line == textArea.getLineCount() - 1) + { + textArea.getToolkit().beep(); + return; + } + + int magic = textArea.getMagicCaretPosition(); + if(magic == -1) + { + magic = textArea.offsetToX(line, + caret - textArea.getLineStartOffset(line)); + } + + caret = textArea.getLineStartOffset(line + 1) + + textArea.xToOffset(line + 1,magic); + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + textArea.setMagicCaretPosition(magic); + } + } + + public static class next_page implements ActionListener + { + private boolean select; + + public next_page(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int lineCount = textArea.getLineCount(); + int firstLine = textArea.getFirstLine(); + int visibleLines = textArea.getVisibleLines(); + int line = textArea.getCaretLine(); + + firstLine += visibleLines; + + if(firstLine + visibleLines >= lineCount - 1) + firstLine = lineCount - visibleLines; + + textArea.setFirstLine(firstLine); + + int caret = textArea.getLineStartOffset( + Math.min(textArea.getLineCount() - 1, + line + visibleLines)); + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + } + } + + public static class next_word implements ActionListener + { + private boolean select; + + public next_word(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + int line = textArea.getCaretLine(); + int lineStart = textArea.getLineStartOffset(line); + caret -= lineStart; + + String lineText = textArea.getLineText(textArea + .getCaretLine()); + + if(caret == lineText.length()) + { + if(lineStart + caret == textArea.getDocumentLength()) + { + textArea.getToolkit().beep(); + return; + } + caret++; + } + else + { + String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); + caret = TextUtilities.findWordEnd(lineText,caret,noWordSep); + } + + if(select) + textArea.select(textArea.getMarkPosition(), + lineStart + caret); + else + textArea.setCaretPosition(lineStart + caret); + } + } + + public static class overwrite implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.setOverwriteEnabled( + !textArea.isOverwriteEnabled()); + } + } + + public static class prev_char implements ActionListener + { + private boolean select; + + public prev_char(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + if(caret == 0) + { + textArea.getToolkit().beep(); + return; + } + + if(select) + textArea.select(textArea.getMarkPosition(), + caret - 1); + else + textArea.setCaretPosition(caret - 1); + } + } + + public static class prev_line implements ActionListener + { + private boolean select; + + public prev_line(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + int line = textArea.getCaretLine(); + + if(line == 0) + { + textArea.getToolkit().beep(); + return; + } + + int magic = textArea.getMagicCaretPosition(); + if(magic == -1) + { + magic = textArea.offsetToX(line, + caret - textArea.getLineStartOffset(line)); + } + + caret = textArea.getLineStartOffset(line - 1) + + textArea.xToOffset(line - 1,magic); + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + textArea.setMagicCaretPosition(magic); + } + } + + public static class prev_page implements ActionListener + { + private boolean select; + + public prev_page(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int firstLine = textArea.getFirstLine(); + int visibleLines = textArea.getVisibleLines(); + int line = textArea.getCaretLine(); + + if(firstLine < visibleLines) + firstLine = visibleLines; + + textArea.setFirstLine(firstLine - visibleLines); + + int caret = textArea.getLineStartOffset( + Math.max(0,line - visibleLines)); + if(select) + textArea.select(textArea.getMarkPosition(),caret); + else + textArea.setCaretPosition(caret); + } + } + + public static class prev_word implements ActionListener + { + private boolean select; + + public prev_word(boolean select) + { + this.select = select; + } + + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + int caret = textArea.getCaretPosition(); + int line = textArea.getCaretLine(); + int lineStart = textArea.getLineStartOffset(line); + caret -= lineStart; + + String lineText = textArea.getLineText(textArea + .getCaretLine()); + + if(caret == 0) + { + if(lineStart == 0) + { + textArea.getToolkit().beep(); + return; + } + caret--; + } + else + { + String noWordSep = (String)textArea.getDocument().getProperty("noWordSep"); + caret = TextUtilities.findWordStart(lineText,caret,noWordSep); + } + + if(select) + textArea.select(textArea.getMarkPosition(), + lineStart + caret); + else + textArea.setCaretPosition(lineStart + caret); + } + } + + public static class Repeat implements ActionListener, + InputHandler.NonRecordable + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.getInputHandler().setRepeatEnabled(true); + String actionCommand = evt.getActionCommand(); + if(actionCommand != null) + { + textArea.getInputHandler().setRepeatCount( + Integer.parseInt(actionCommand)); + } + } + } + + public static class toggle_rect implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.setSelectionRectangular( + !textArea.isSelectionRectangular()); + } + } + + public static class insert_char implements ActionListener, + InputHandler.NonRepeatable + { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + String str = evt.getActionCommand(); + int repeatCount = textArea.getInputHandler().getRepeatCount(); + + if(textArea.isEditable()) + { + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < repeatCount; i++) + buf.append(str); + textArea.overwriteSetSelectedText(buf.toString()); + } + else + { + textArea.getToolkit().beep(); + } + } + } + + public static class clip_copy implements ActionListener { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.copy(); + } + } + + public static class clip_paste implements ActionListener { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.paste(); + } + } + + public static class clip_cut implements ActionListener { + public void actionPerformed(ActionEvent evt) + { + JEditTextArea textArea = getTextArea(evt); + textArea.cut(); + } + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.java new file mode 100644 index 0000000..d5c4804 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/JEditTextArea.java @@ -0,0 +1,2144 @@ +/* + * JEditTextArea.java - jEdit's text component + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.event.*; +import javax.swing.text.*; +import javax.swing.undo.*; +import javax.swing.*; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.Token; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.TokenMarker; + +import java.awt.datatransfer.*; +import java.awt.event.*; +import java.awt.*; +import java.util.Enumeration; +import java.util.Vector; + +/** + * jEdit's text area component. It is more suited for editing program + * source code than JEditorPane, because it drops the unnecessary features + * (images, variable-width lines, and so on) and adds a whole bunch of + * useful goodies such as: + *

        + *
      • More flexible key binding scheme + *
      • Supports macro recorders + *
      • Rectangular selection + *
      • Bracket highlighting + *
      • Syntax highlighting + *
      • Command repetition + *
      • Block caret can be enabled + *
      + * It is also faster and doesn't have as many problems. It can be used + * in other applications; the only other part of jEdit it depends on is + * the syntax package.

      + * + * To use it in your app, treat it like any other component, for example: + *

      JEditTextArea ta = new JEditTextArea();
      + * ta.setTokenMarker(new JavaTokenMarker());
      + * ta.setText("public class Test {\n"
      + *     + "    public static void main(String[] args) {\n"
      + *     + "        System.out.println(\"Hello World\");\n"
      + *     + "    }\n"
      + *     + "}");
      + * + * @author Slava Pestov + */ +public class JEditTextArea extends JComponent +{ + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Adding components with this name to the text area will place + * them left of the horizontal scroll bar. In jEdit, the status + * bar is added this way. + */ + public static String LEFT_OF_SCROLLBAR = "los"; + + /** + * Creates a new JEditTextArea with the default settings. + */ + public JEditTextArea() + { + this(TextAreaDefaults.getDefaults()); + } + + /** + * Creates a new JEditTextArea with the specified settings. + * @param defaults The default settings + */ + public JEditTextArea(TextAreaDefaults defaults) + { + // Enable the necessary events + enableEvents(AWTEvent.KEY_EVENT_MASK); + + // Initialize some misc. stuff + painter = new TextAreaPainter(this,defaults); + documentHandler = new DocumentHandler(); + listenerList = new EventListenerList(); + caretEvent = new MutableCaretEvent(); + lineSegment = new Segment(); + bracketLine = bracketPosition = -1; + blink = true; + + // Initialize the GUI + setLayout(new ScrollLayout()); + add(CENTER,painter); + add(RIGHT,vertical = new JScrollBar(JScrollBar.VERTICAL)); + add(BOTTOM,horizontal = new JScrollBar(JScrollBar.HORIZONTAL)); + + // Add some event listeners + vertical.addAdjustmentListener(new AdjustHandler()); + horizontal.addAdjustmentListener(new AdjustHandler()); + painter.addComponentListener(new ComponentHandler()); + painter.addMouseListener(new MouseHandler()); + painter.addMouseMotionListener(new DragHandler()); + + addFocusListener(new FocusHandler()); + + // Load the defaults + setInputHandler(defaults.inputHandler); + setDocument(defaults.document); + editable = defaults.editable; + caretVisible = defaults.caretVisible; + caretBlinks = defaults.caretBlinks; + electricScroll = defaults.electricScroll; + + popup = defaults.popup; + + // We don't seem to get the initial focus event? + focusedComponent = this; + } + + public void setPainter(TextAreaPainter newPainter) { + remove(this.painter); + this.painter = newPainter; + add(CENTER,this.painter); + this.painter.addComponentListener(new ComponentHandler()); + this.painter.addMouseListener(new MouseHandler()); + this.painter.addMouseMotionListener(new DragHandler()); + } + + /** + * Returns if this component can be traversed by pressing + * the Tab key. This returns false. + */ + public final boolean isManagingFocus() + { + return true; + } + + /** + * Returns the object responsible for painting this text area. + */ + public final TextAreaPainter getPainter() + { + return painter; + } + + /** + * Returns the input handler. + */ + public final InputHandler getInputHandler() + { + return inputHandler; + } + + /** + * Sets the input handler. + * @param inputHandler The new input handler + */ + public void setInputHandler(InputHandler inputHandler) + { + this.inputHandler = inputHandler; + } + + /** + * Returns true if the caret is blinking, false otherwise. + */ + public final boolean isCaretBlinkEnabled() + { + return caretBlinks; + } + + /** + * Toggles caret blinking. + * @param caretBlinks True if the caret should blink, false otherwise + */ + public void setCaretBlinkEnabled(boolean caretBlinks) + { + this.caretBlinks = caretBlinks; + if(!caretBlinks) + blink = false; + + painter.invalidateSelectedLines(); + } + + /** + * Returns true if the caret is visible, false otherwise. + */ + public final boolean isCaretVisible() + { + return (!caretBlinks || blink) && caretVisible; + } + + /** + * Sets if the caret should be visible. + * @param caretVisible True if the caret should be visible, false + * otherwise + */ + public void setCaretVisible(boolean caretVisible) + { + this.caretVisible = caretVisible; + blink = true; + + painter.invalidateSelectedLines(); + } + + /** + * Blinks the caret. + */ + public final void blinkCaret() + { + if(caretBlinks) + { + blink = !blink; + painter.invalidateSelectedLines(); + } + else + blink = true; + } + + /** + * Returns the number of lines from the top and button of the + * text area that are always visible. + */ + public final int getElectricScroll() + { + return electricScroll; + } + + /** + * Sets the number of lines from the top and bottom of the text + * area that are always visible + * @param electricScroll The number of lines always visible from + * the top or bottom + */ + public final void setElectricScroll(int electricScroll) + { + this.electricScroll = electricScroll; + } + + /** + * Updates the state of the scroll bars. This should be called + * if the number of lines in the document changes, or when the + * size of the text are changes. + */ + public void updateScrollBars() + { + if(vertical != null && visibleLines != 0) + { + vertical.setValues(firstLine,visibleLines,0,getLineCount()); + vertical.setUnitIncrement(2); + vertical.setBlockIncrement(visibleLines); + } + + int width = painter.getWidth(); + if(horizontal != null && width != 0) + { + horizontal.setValues(-horizontalOffset,width,0,width * 5); + horizontal.setUnitIncrement(painter.getFontMetrics() + .charWidth('w')); + horizontal.setBlockIncrement(width / 2); + } + } + + /** + * Returns the line displayed at the text area's origin. + */ + public final int getFirstLine() + { + return firstLine; + } + + /** + * Sets the line displayed at the text area's origin without + * updating the scroll bars. + */ + public void setFirstLine(int firstLine) + { + if(firstLine == this.firstLine) + return; + int oldFirstLine = this.firstLine; + this.firstLine = firstLine; + if(firstLine != vertical.getValue()) + updateScrollBars(); + painter.repaint(); + } + + /** + * Returns the number of lines visible in this text area. + */ + public final int getVisibleLines() + { + return visibleLines; + } + + /** + * Recalculates the number of visible lines. This should not + * be called directly. + */ + public final void recalculateVisibleLines() + { + if(painter == null) + return; + int height = painter.getHeight(); + int lineHeight = painter.getFontMetrics().getHeight(); + int oldVisibleLines = visibleLines; + visibleLines = height / lineHeight; + updateScrollBars(); + } + + /** + * Returns the horizontal offset of drawn lines. + */ + public final int getHorizontalOffset() + { + return horizontalOffset; + } + + /** + * Sets the horizontal offset of drawn lines. This can be used to + * implement horizontal scrolling. + * @param horizontalOffset offset The new horizontal offset + */ + public void setHorizontalOffset(int horizontalOffset) + { + if(horizontalOffset == this.horizontalOffset) + return; + this.horizontalOffset = horizontalOffset; + if(horizontalOffset != horizontal.getValue()) + updateScrollBars(); + painter.repaint(); + } + + /** + * A fast way of changing both the first line and horizontal + * offset. + * @param firstLine The new first line + * @param horizontalOffset The new horizontal offset + * @return True if any of the values were changed, false otherwise + */ + public boolean setOrigin(int firstLine, int horizontalOffset) + { + boolean changed = false; + int oldFirstLine = this.firstLine; + + if(horizontalOffset != this.horizontalOffset) + { + this.horizontalOffset = horizontalOffset; + changed = true; + } + + if(firstLine != this.firstLine) + { + this.firstLine = firstLine; + changed = true; + } + + if(changed) + { + updateScrollBars(); + painter.repaint(); + } + + return changed; + } + + /** + * Ensures that the caret is visible by scrolling the text area if + * necessary. + * @return True if scrolling was actually performed, false if the + * caret was already visible + */ + public boolean scrollToCaret() + { + int line = getCaretLine(); + int lineStart = getLineStartOffset(line); + int offset = Math.max(0,Math.min(getLineLength(line) - 1, + getCaretPosition() - lineStart)); + + return scrollTo(line,offset); + } + + /** + * Ensures that the specified line and offset is visible by scrolling + * the text area if necessary. + * @param line The line to scroll to + * @param offset The offset in the line to scroll to + * @return True if scrolling was actually performed, false if the + * line and offset was already visible + */ + public boolean scrollTo(int line, int offset) + { + // visibleLines == 0 before the component is realized + // we can't do any proper scrolling then, so we have + // this hack... + if(visibleLines == 0) + { + setFirstLine(Math.max(0,line - electricScroll)); + return true; + } + + int newFirstLine = firstLine; + int newHorizontalOffset = horizontalOffset; + + if(line < firstLine + electricScroll) + { + newFirstLine = Math.max(0,line - electricScroll); + } + else if(line + electricScroll >= firstLine + visibleLines) + { + newFirstLine = (line - visibleLines) + electricScroll + 1; + if(newFirstLine + visibleLines >= getLineCount()) + newFirstLine = getLineCount() - visibleLines; + if(newFirstLine < 0) + newFirstLine = 0; + } + + int x = _offsetToX(line,offset); + int width = painter.getFontMetrics().charWidth('w'); + + if(x < 0) + { + newHorizontalOffset = Math.min(0,horizontalOffset + - x + width + 5); + } + else if(x + width >= painter.getWidth()) + { + newHorizontalOffset = horizontalOffset + + (painter.getWidth() - x) - width - 5; + } + + return setOrigin(newFirstLine,newHorizontalOffset); + } + + /** + * Converts a line index to a y co-ordinate. + * @param line The line + */ + public int lineToY(int line) + { + FontMetrics fm = painter.getFontMetrics(); + return (line - firstLine) * fm.getHeight() + - (fm.getLeading() + fm.getMaxDescent()); + } + + /** + * Converts a y co-ordinate to a line index. + * @param y The y co-ordinate + */ + public int yToLine(int y) + { + FontMetrics fm = painter.getFontMetrics(); + int height = fm.getHeight(); + return Math.max(0,Math.min(getLineCount() - 1, + y / height + firstLine)); + } + + /** + * Converts an offset in a line into an x co-ordinate. This is a + * slow version that can be used any time. + * @param line The line + * @param offset The offset, from the start of the line + */ + public final int offsetToX(int line, int offset) + { + // don't use cached tokens + painter.currentLineTokens = null; + return _offsetToX(line,offset); + } + + /** + * Converts an offset in a line into an x co-ordinate. This is a + * fast version that should only be used if no changes were made + * to the text since the last repaint. + * @param line The line + * @param offset The offset, from the start of the line + */ + public int _offsetToX(int line, int offset) + { + TokenMarker tokenMarker = getTokenMarker(); + + /* Use painter's cached info for speed */ + FontMetrics fm = painter.getFontMetrics(); + + getLineText(line,lineSegment); + + int segmentOffset = lineSegment.offset; + int x = horizontalOffset; + + /* If syntax coloring is disabled, do simple translation */ + if(tokenMarker == null) + { + lineSegment.count = offset; + return x + Utilities.getTabbedTextWidth(lineSegment, + fm,x,painter,0); + } + /* If syntax coloring is enabled, we have to do this because + * tokens can vary in width */ + else + { + Token tokens; + if(painter.currentLineIndex == line + && painter.currentLineTokens != null) + tokens = painter.currentLineTokens; + else + { + painter.currentLineIndex = line; + tokens = painter.currentLineTokens + = tokenMarker.markTokens(lineSegment,line); + } + + Font defaultFont = painter.getFont(); + SyntaxStyle[] styles = painter.getStyles(); + + for(;;) + { + byte id = tokens.id; + if(id == Token.END) + { + return x; + } + + if(id == Token.NULL) + fm = painter.getFontMetrics(); + else + fm = styles[id].getFontMetrics(defaultFont); + + int length = tokens.length; + + if(offset + segmentOffset < lineSegment.offset + length) + { + lineSegment.count = offset - (lineSegment.offset - segmentOffset); + return x + Utilities.getTabbedTextWidth( + lineSegment,fm,x,painter,0); + } + else + { + lineSegment.count = length; + x += Utilities.getTabbedTextWidth( + lineSegment,fm,x,painter,0); + lineSegment.offset += length; + } + tokens = tokens.next; + } + } + } + + /** + * Converts an x co-ordinate to an offset within a line. + * @param line The line + * @param x The x co-ordinate + */ + public int xToOffset(int line, int x) + { + TokenMarker tokenMarker = getTokenMarker(); + + /* Use painter's cached info for speed */ + FontMetrics fm = painter.getFontMetrics(); + + getLineText(line,lineSegment); + + char[] segmentArray = lineSegment.array; + int segmentOffset = lineSegment.offset; + int segmentCount = lineSegment.count; + + int width = horizontalOffset; + + if(tokenMarker == null) + { + for(int i = 0; i < segmentCount; i++) + { + char c = segmentArray[i + segmentOffset]; + int charWidth; + if(c == '\t') + charWidth = (int)painter.nextTabStop(width,i) + - width; + else + charWidth = fm.charWidth(c); + + if(painter.isBlockCaretEnabled()) + { + if(x - charWidth <= width) + return i; + } + else + { + if(x - charWidth / 2 <= width) + return i; + } + + width += charWidth; + } + + return segmentCount; + } + else + { + Token tokens; + if(painter.currentLineIndex == line && painter + .currentLineTokens != null) + tokens = painter.currentLineTokens; + else + { + painter.currentLineIndex = line; + tokens = painter.currentLineTokens + = tokenMarker.markTokens(lineSegment,line); + } + + int offset = 0; + Font defaultFont = painter.getFont(); + SyntaxStyle[] styles = painter.getStyles(); + + for(;;) + { + byte id = tokens.id; + if(id == Token.END) + return offset; + + if(id == Token.NULL) + fm = painter.getFontMetrics(); + else + fm = styles[id].getFontMetrics(defaultFont); + + int length = tokens.length; + + for(int i = 0; i < length; i++) + { + char c = segmentArray[segmentOffset + offset + i]; + int charWidth; + if(c == '\t') + charWidth = (int)painter.nextTabStop(width,offset + i) + - width; + else + charWidth = fm.charWidth(c); + + if(painter.isBlockCaretEnabled()) + { + if(x - charWidth <= width) + return offset + i; + } + else + { + if(x - charWidth / 2 <= width) + return offset + i; + } + + width += charWidth; + } + + offset += length; + tokens = tokens.next; + } + } + } + + /** + * Converts a point to an offset, from the start of the text. + * @param x The x co-ordinate of the point + * @param y The y co-ordinate of the point + */ + public int xyToOffset(int x, int y) + { + int line = yToLine(y); + int start = getLineStartOffset(line); + return start + xToOffset(line,x); + } + + /** + * Returns the document this text area is editing. + */ + public final SyntaxDocument getDocument() + { + return document; + } + + /** + * Sets the document this text area is editing. + * @param document The document + */ + public void setDocument(SyntaxDocument document) + { + if(this.document == document) + return; + if(this.document != null) + this.document.removeDocumentListener(documentHandler); + this.document = document; + + document.addDocumentListener(documentHandler); + + select(0,0); + updateScrollBars(); + painter.repaint(); + } + + /** + * Returns the document's token marker. Equivalent to calling + * getDocument().getTokenMarker(). + */ + public final TokenMarker getTokenMarker() + { + return document.getTokenMarker(); + } + + /** + * Sets the document's token marker. Equivalent to caling + * getDocument().setTokenMarker(). + * @param tokenMarker The token marker + */ + public final void setTokenMarker(TokenMarker tokenMarker) + { + document.setTokenMarker(tokenMarker); + } + + /** + * Returns the length of the document. Equivalent to calling + * getDocument().getLength(). + */ + public final int getDocumentLength() + { + return document.getLength(); + } + + /** + * Returns the number of lines in the document. + */ + public final int getLineCount() + { + return document.getDefaultRootElement().getElementCount(); + } + + /** + * Returns the line containing the specified offset. + * @param offset The offset + */ + public final int getLineOfOffset(int offset) + { + return document.getDefaultRootElement().getElementIndex(offset); + } + + /** + * Returns the start offset of the specified line. + * @param line The line + * @return The start offset of the specified line, or -1 if the line is + * invalid + */ + public int getLineStartOffset(int line) + { + Element lineElement = document.getDefaultRootElement() + .getElement(line); + if(lineElement == null) + return -1; + else + return lineElement.getStartOffset(); + } + + /** + * Returns the end offset of the specified line. + * @param line The line + * @return The end offset of the specified line, or -1 if the line is + * invalid. + */ + public int getLineEndOffset(int line) + { + Element lineElement = document.getDefaultRootElement() + .getElement(line); + if(lineElement == null) + return -1; + else + return lineElement.getEndOffset(); + } + + /** + * Returns the length of the specified line. + * @param line The line + */ + public int getLineLength(int line) + { + Element lineElement = document.getDefaultRootElement() + .getElement(line); + if(lineElement == null) + return -1; + else + return lineElement.getEndOffset() + - lineElement.getStartOffset() - 1; + } + + /** + * Returns the entire text of this text area. + */ + public String getText() + { + try + { + return document.getText(0,document.getLength()); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + return null; + } + } + + /** + * Sets the entire text of this text area. + */ + public void setText(String text) + { + try + { + document.beginCompoundEdit(); + document.remove(0,document.getLength()); + document.insertString(0,text,null); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + finally + { + document.endCompoundEdit(); + } + } + + /** + * Returns the specified substring of the document. + * @param start The start offset + * @param len The length of the substring + * @return The substring, or null if the offsets are invalid + */ + public final String getText(int start, int len) + { + try + { + return document.getText(start,len); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + return null; + } + } + + /** + * Copies the specified substring of the document into a segment. + * If the offsets are invalid, the segment will contain a null string. + * @param start The start offset + * @param len The length of the substring + * @param segment The segment + */ + public final void getText(int start, int len, Segment segment) + { + try + { + document.getText(start,len,segment); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + segment.offset = segment.count = 0; + } + } + + /** + * Returns the text on the specified line. + * @param lineIndex The line + * @return The text, or null if the line is invalid + */ + public final String getLineText(int lineIndex) + { + int start = getLineStartOffset(lineIndex); + return getText(start,getLineEndOffset(lineIndex) - start - 1); + } + + /** + * Copies the text on the specified line into a segment. If the line + * is invalid, the segment will contain a null string. + * @param lineIndex The line + */ + public final void getLineText(int lineIndex, Segment segment) + { + int start = getLineStartOffset(lineIndex); + getText(start,getLineEndOffset(lineIndex) - start - 1,segment); + } + + /** + * Returns the selection start offset. + */ + public final int getSelectionStart() + { + return selectionStart; + } + + /** + * Returns the offset where the selection starts on the specified + * line. + */ + public int getSelectionStart(int line) + { + if(line == selectionStartLine) + return selectionStart; + else if(rectSelect) + { + Element map = document.getDefaultRootElement(); + int start = selectionStart - map.getElement(selectionStartLine) + .getStartOffset(); + + Element lineElement = map.getElement(line); + int lineStart = lineElement.getStartOffset(); + int lineEnd = lineElement.getEndOffset() - 1; + return Math.min(lineEnd,lineStart + start); + } + else + return getLineStartOffset(line); + } + + /** + * Returns the selection start line. + */ + public final int getSelectionStartLine() + { + return selectionStartLine; + } + + /** + * Sets the selection start. The new selection will be the new + * selection start and the old selection end. + * @param selectionStart The selection start + * @see #select(int,int) + */ + public final void setSelectionStart(int selectionStart) + { + select(selectionStart,selectionEnd); + } + + /** + * Returns the selection end offset. + */ + public final int getSelectionEnd() + { + return selectionEnd; + } + + /** + * Returns the offset where the selection ends on the specified + * line. + */ + public int getSelectionEnd(int line) + { + if(line == selectionEndLine) + return selectionEnd; + else if(rectSelect) + { + Element map = document.getDefaultRootElement(); + int end = selectionEnd - map.getElement(selectionEndLine) + .getStartOffset(); + + Element lineElement = map.getElement(line); + int lineStart = lineElement.getStartOffset(); + int lineEnd = lineElement.getEndOffset() - 1; + return Math.min(lineEnd,lineStart + end); + } + else + return getLineEndOffset(line) - 1; + } + + /** + * Returns the selection end line. + */ + public final int getSelectionEndLine() + { + return selectionEndLine; + } + + /** + * Sets the selection end. The new selection will be the old + * selection start and the bew selection end. + * @param selectionEnd The selection end + * @see #select(int,int) + */ + public final void setSelectionEnd(int selectionEnd) + { + select(selectionStart,selectionEnd); + } + + /** + * Returns the caret position. This will either be the selection + * start or the selection end, depending on which direction the + * selection was made in. + */ + public final int getCaretPosition() + { + return (biasLeft ? selectionStart : selectionEnd); + } + + /** + * Returns the caret line. + */ + public final int getCaretLine() + { + return (biasLeft ? selectionStartLine : selectionEndLine); + } + + /** + * Returns the mark position. This will be the opposite selection + * bound to the caret position. + * @see #getCaretPosition() + */ + public final int getMarkPosition() + { + return (biasLeft ? selectionEnd : selectionStart); + } + + /** + * Returns the mark line. + */ + public final int getMarkLine() + { + return (biasLeft ? selectionEndLine : selectionStartLine); + } + + /** + * Sets the caret position. The new selection will consist of the + * caret position only (hence no text will be selected) + * @param caret The caret position + * @see #select(int,int) + */ + public final void setCaretPosition(int caret) + { + select(caret,caret); + } + + /** + * Selects all text in the document. + */ + public final void selectAll() + { + select(0,getDocumentLength()); + } + + /** + * Moves the mark to the caret position. + */ + public final void selectNone() + { + select(getCaretPosition(),getCaretPosition()); + } + + /** + * Selects from the start offset to the end offset. This is the + * general selection method used by all other selecting methods. + * The caret position will be start if start < end, and end + * if end > start. + * @param start The start offset + * @param end The end offset + */ + public void select(int start, int end) + { + int newStart, newEnd; + boolean newBias; + if(start <= end) + { + newStart = start; + newEnd = end; + newBias = false; + } + else + { + newStart = end; + newEnd = start; + newBias = true; + } + + if(newStart < 0 || newEnd > getDocumentLength()) + { + throw new IllegalArgumentException("Bounds out of" + + " range: " + newStart + "," + + newEnd); + } + + // If the new position is the same as the old, we don't + // do all this crap, however we still do the stuff at + // the end (clearing magic position, scrolling) + if(newStart != selectionStart || newEnd != selectionEnd + || newBias != biasLeft) + { + int newStartLine = getLineOfOffset(newStart); + int newEndLine = getLineOfOffset(newEnd); + + if(painter.isBracketHighlightEnabled()) + { + if(bracketLine != -1) + painter.invalidateLine(bracketLine); + updateBracketHighlight(end); + if(bracketLine != -1) + painter.invalidateLine(bracketLine); + } + + painter.invalidateLineRange(selectionStartLine,selectionEndLine); + painter.invalidateLineRange(newStartLine,newEndLine); + + document.addUndoableEdit(new CaretUndo( + selectionStart,selectionEnd)); + + selectionStart = newStart; + selectionEnd = newEnd; + selectionStartLine = newStartLine; + selectionEndLine = newEndLine; + biasLeft = newBias; + + fireCaretEvent(); + } + + // When the user is typing, etc, we don't want the caret + // to blink + blink = true; + caretTimer.restart(); + + // Disable rectangle select if selection start = selection end + if(selectionStart == selectionEnd) + rectSelect = false; + + // Clear the `magic' caret position used by up/down + magicCaret = -1; + + scrollToCaret(); + } + + /** + * Returns the selected text, or null if no selection is active. + */ + public final String getSelectedText() + { + if(selectionStart == selectionEnd) + return null; + + if(rectSelect) + { + // Return each row of the selection on a new line + + Element map = document.getDefaultRootElement(); + + int start = selectionStart - map.getElement(selectionStartLine) + .getStartOffset(); + int end = selectionEnd - map.getElement(selectionEndLine) + .getStartOffset(); + + // Certain rectangles satisfy this condition... + if(end < start) + { + int tmp = end; + end = start; + start = tmp; + } + + StringBuffer buf = new StringBuffer(); + Segment seg = new Segment(); + + for(int i = selectionStartLine; i <= selectionEndLine; i++) + { + Element lineElement = map.getElement(i); + int lineStart = lineElement.getStartOffset(); + int lineEnd = lineElement.getEndOffset() - 1; + int lineLen = lineEnd - lineStart; + + lineStart = Math.min(lineStart + start,lineEnd); + lineLen = Math.min(end - start,lineEnd - lineStart); + + getText(lineStart,lineLen,seg); + buf.append(seg.array,seg.offset,seg.count); + + if(i != selectionEndLine) + buf.append('\n'); + } + + return buf.toString(); + } + else + { + return getText(selectionStart, + selectionEnd - selectionStart); + } + } + + /** + * Replaces the selection with the specified text. + * @param selectedText The replacement text for the selection + */ + public void setSelectedText(String selectedText) + { + if(!editable) + { + throw new InternalError("Text component" + + " read only"); + } + + document.beginCompoundEdit(); + + try + { + if(rectSelect) + { + Element map = document.getDefaultRootElement(); + + int start = selectionStart - map.getElement(selectionStartLine) + .getStartOffset(); + int end = selectionEnd - map.getElement(selectionEndLine) + .getStartOffset(); + + // Certain rectangles satisfy this condition... + if(end < start) + { + int tmp = end; + end = start; + start = tmp; + } + + int lastNewline = 0; + int currNewline = 0; + + for(int i = selectionStartLine; i <= selectionEndLine; i++) + { + Element lineElement = map.getElement(i); + int lineStart = lineElement.getStartOffset(); + int lineEnd = lineElement.getEndOffset() - 1; + int rectStart = Math.min(lineEnd,lineStart + start); + + document.remove(rectStart,Math.min(lineEnd - rectStart, + end - start)); + + if(selectedText == null) + continue; + + currNewline = selectedText.indexOf('\n',lastNewline); + if(currNewline == -1) + currNewline = selectedText.length(); + + document.insertString(rectStart,selectedText + .substring(lastNewline,currNewline),null); + + lastNewline = Math.min(selectedText.length(), + currNewline + 1); + } + + if(selectedText != null && + currNewline != selectedText.length()) + { + int offset = map.getElement(selectionEndLine) + .getEndOffset() - 1; + document.insertString(offset,"\n",null); + document.insertString(offset + 1,selectedText + .substring(currNewline + 1),null); + } + } + else + { + document.remove(selectionStart, + selectionEnd - selectionStart); + if(selectedText != null) + { + document.insertString(selectionStart, + selectedText,null); + } + } + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + throw new InternalError("Cannot replace" + + " selection"); + } + // No matter what happends... stops us from leaving document + // in a bad state + finally + { + document.endCompoundEdit(); + } + + setCaretPosition(selectionEnd); + } + + /** + * Returns true if this text area is editable, false otherwise. + */ + public final boolean isEditable() + { + return editable; + } + + /** + * Sets if this component is editable. + * @param editable True if this text area should be editable, + * false otherwise + */ + public final void setEditable(boolean editable) + { + this.editable = editable; + } + + /** + * Returns the right click popup menu. + */ + public final JPopupMenu getRightClickPopup() + { + return popup; + } + + /** + * Sets the right click popup menu. + * @param popup The popup + */ + public final void setRightClickPopup(JPopupMenu popup) + { + this.popup = popup; + } + + /** + * Returns the `magic' caret position. This can be used to preserve + * the column position when moving up and down lines. + */ + public final int getMagicCaretPosition() + { + return magicCaret; + } + + /** + * Sets the `magic' caret position. This can be used to preserve + * the column position when moving up and down lines. + * @param magicCaret The magic caret position + */ + public final void setMagicCaretPosition(int magicCaret) + { + this.magicCaret = magicCaret; + } + + /** + * Similar to setSelectedText(), but overstrikes the + * appropriate number of characters if overwrite mode is enabled. + * @param str The string + * @see #setSelectedText(String) + * @see #isOverwriteEnabled() + */ + public void overwriteSetSelectedText(String str) + { + // Don't overstrike if there is a selection + if(!overwrite || selectionStart != selectionEnd) + { + setSelectedText(str); + return; + } + + // Don't overstrike if we're on the end of + // the line + int caret = getCaretPosition(); + int caretLineEnd = getLineEndOffset(getCaretLine()); + if(caretLineEnd - caret <= str.length()) + { + setSelectedText(str); + return; + } + + document.beginCompoundEdit(); + + try + { + document.remove(caret,str.length()); + document.insertString(caret,str,null); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + finally + { + document.endCompoundEdit(); + } + } + + /** + * Returns true if overwrite mode is enabled, false otherwise. + */ + public final boolean isOverwriteEnabled() + { + return overwrite; + } + + /** + * Sets if overwrite mode should be enabled. + * @param overwrite True if overwrite mode should be enabled, + * false otherwise. + */ + public final void setOverwriteEnabled(boolean overwrite) + { + this.overwrite = overwrite; + painter.invalidateSelectedLines(); + } + + /** + * Returns true if the selection is rectangular, false otherwise. + */ + public final boolean isSelectionRectangular() + { + return rectSelect; + } + + /** + * Sets if the selection should be rectangular. + * @param overwrite True if the selection should be rectangular, + * false otherwise. + */ + public final void setSelectionRectangular(boolean rectSelect) + { + this.rectSelect = rectSelect; + painter.invalidateSelectedLines(); + } + + /** + * Returns the position of the highlighted bracket (the bracket + * matching the one before the caret) + */ + public final int getBracketPosition() + { + return bracketPosition; + } + + /** + * Returns the line of the highlighted bracket (the bracket + * matching the one before the caret) + */ + public final int getBracketLine() + { + return bracketLine; + } + + /** + * Adds a caret change listener to this text area. + * @param listener The listener + */ + public final void addCaretListener(CaretListener listener) + { + listenerList.add(CaretListener.class,listener); + } + + /** + * Removes a caret change listener from this text area. + * @param listener The listener + */ + public final void removeCaretListener(CaretListener listener) + { + listenerList.remove(CaretListener.class,listener); + } + + /** + * Deletes the selected text from the text area and places it + * into the clipboard. + */ + public void cut() + { + if(editable) + { + copy(); + setSelectedText(""); + } + } + + /** + * Places the selected text into the clipboard. + */ + public void copy() + { + if(selectionStart != selectionEnd) + { + Clipboard clipboard = getToolkit().getSystemClipboard(); + + String selection = getSelectedText(); + + int repeatCount = inputHandler.getRepeatCount(); + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < repeatCount; i++) + buf.append(selection); + + clipboard.setContents(new StringSelection(buf.toString()),null); + } + } + + /** + * Inserts the clipboard contents into the text. + */ + public void paste() + { + if(editable) + { + Clipboard clipboard = getToolkit().getSystemClipboard(); + try + { + // The MacOS MRJ doesn't convert \r to \n, + // so do it here + String selection = ((String)clipboard + .getContents(this).getTransferData( + DataFlavor.stringFlavor)) + .replace('\r','\n'); + + int repeatCount = inputHandler.getRepeatCount(); + StringBuffer buf = new StringBuffer(); + for(int i = 0; i < repeatCount; i++) + buf.append(selection); + selection = buf.toString(); + setSelectedText(selection); + } + catch(Exception e) + { + getToolkit().beep(); + System.err.println("Clipboard does not" + + " contain a string"); + } + } + } + + /** + * Called by the AWT when this component is removed from it's parent. + * This stops clears the currently focused component. + */ + public void removeNotify() + { + super.removeNotify(); + if(focusedComponent == this) + focusedComponent = null; + } + + /** + * Forwards key events directly to the input handler. + * This is slightly faster than using a KeyListener + * because some Swing overhead is avoided. + */ + public void processKeyEvent(KeyEvent evt) + { + if(inputHandler == null) + return; + switch(evt.getID()) + { + case KeyEvent.KEY_TYPED: + inputHandler.keyTyped(evt); + break; + case KeyEvent.KEY_PRESSED: + inputHandler.keyPressed(evt); + break; + case KeyEvent.KEY_RELEASED: + inputHandler.keyReleased(evt); + break; + } + } + + // protected members + protected static String CENTER = "center"; + protected static String RIGHT = "right"; + protected static String BOTTOM = "bottom"; + + protected static JEditTextArea focusedComponent; + protected static Timer caretTimer; + + private TextAreaPainter painter; + + protected JPopupMenu popup; + + protected EventListenerList listenerList; + protected MutableCaretEvent caretEvent; + + protected boolean caretBlinks; + protected boolean caretVisible; + protected boolean blink; + + protected boolean editable; + + protected int firstLine; + protected int visibleLines; + protected int electricScroll; + + protected int horizontalOffset; + + protected JScrollBar vertical; + protected JScrollBar horizontal; + protected boolean scrollBarsInitialized; + + protected InputHandler inputHandler; + protected SyntaxDocument document; + protected DocumentHandler documentHandler; + + protected Segment lineSegment; + + protected int selectionStart; + protected int selectionStartLine; + protected int selectionEnd; + protected int selectionEndLine; + protected boolean biasLeft; + + protected int bracketPosition; + protected int bracketLine; + + protected int magicCaret; + protected boolean overwrite; + protected boolean rectSelect; + + protected void fireCaretEvent() + { + Object[] listeners = listenerList.getListenerList(); + for(int i = listeners.length - 2; i >= 0; i--) + { + if(listeners[i] == CaretListener.class) + { + ((CaretListener)listeners[i+1]).caretUpdate(caretEvent); + } + } + } + + protected void updateBracketHighlight(int newCaretPosition) + { + if(newCaretPosition == 0) + { + bracketPosition = bracketLine = -1; + return; + } + + try + { + int offset = TextUtilities.findMatchingBracket( + document,newCaretPosition - 1); + if(offset != -1) + { + bracketLine = getLineOfOffset(offset); + bracketPosition = offset - getLineStartOffset(bracketLine); + return; + } + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + + bracketLine = bracketPosition = -1; + } + + protected void documentChanged(DocumentEvent evt) + { + DocumentEvent.ElementChange ch = evt.getChange( + document.getDefaultRootElement()); + + int count; + if(ch == null) + count = 0; + else + count = ch.getChildrenAdded().length - + ch.getChildrenRemoved().length; + + int line = getLineOfOffset(evt.getOffset()); + if(count == 0) + { + painter.invalidateLine(line); + } + // do magic stuff + else if(line < firstLine) + { + setFirstLine(firstLine + count); + } + // end of magic stuff + else + { + painter.invalidateLineRange(line,firstLine + visibleLines); + updateScrollBars(); + } + } + + class ScrollLayout implements LayoutManager + { + public void addLayoutComponent(String name, Component comp) + { + if(name.equals(CENTER)) + center = comp; + else if(name.equals(RIGHT)) + right = comp; + else if(name.equals(BOTTOM)) + bottom = comp; + else if(name.equals(LEFT_OF_SCROLLBAR)) + leftOfScrollBar.addElement(comp); + } + + public void removeLayoutComponent(Component comp) + { + if(center == comp) + center = null; + if(right == comp) + right = null; + if(bottom == comp) + bottom = null; + else + leftOfScrollBar.removeElement(comp); + } + + public Dimension preferredLayoutSize(Container parent) + { + Dimension dim = new Dimension(); + Insets insets = getInsets(); + dim.width = insets.left + insets.right; + dim.height = insets.top + insets.bottom; + + Dimension centerPref = center.getPreferredSize(); + dim.width += centerPref.width; + dim.height += centerPref.height; + Dimension rightPref = right.getPreferredSize(); + dim.width += rightPref.width; + Dimension bottomPref = bottom.getPreferredSize(); + dim.height += bottomPref.height; + + return dim; + } + + public Dimension minimumLayoutSize(Container parent) + { + Dimension dim = new Dimension(); + Insets insets = getInsets(); + dim.width = insets.left + insets.right; + dim.height = insets.top + insets.bottom; + + Dimension centerPref = center.getMinimumSize(); + dim.width += centerPref.width; + dim.height += centerPref.height; + Dimension rightPref = right.getMinimumSize(); + dim.width += rightPref.width; + Dimension bottomPref = bottom.getMinimumSize(); + dim.height += bottomPref.height; + + return dim; + } + + public void layoutContainer(Container parent) + { + Dimension size = parent.getSize(); + Insets insets = parent.getInsets(); + int itop = insets.top; + int ileft = insets.left; + int ibottom = insets.bottom; + int iright = insets.right; + + int rightWidth = right.getPreferredSize().width; + int bottomHeight = bottom.getPreferredSize().height; + int centerWidth = size.width - rightWidth - ileft - iright; + int centerHeight = size.height - bottomHeight - itop - ibottom; + + center.setBounds( + ileft, + itop, + centerWidth, + centerHeight); + + right.setBounds( + ileft + centerWidth, + itop, + rightWidth, + centerHeight); + + // Lay out all status components, in order + Enumeration status = leftOfScrollBar.elements(); + while(status.hasMoreElements()) + { + Component comp = (Component)status.nextElement(); + Dimension dim = comp.getPreferredSize(); + comp.setBounds(ileft, + itop + centerHeight, + dim.width, + bottomHeight); + ileft += dim.width; + } + + bottom.setBounds( + ileft, + itop + centerHeight, + size.width - rightWidth - ileft - iright, + bottomHeight); + } + + // private members + private Component center; + private Component right; + private Component bottom; + private Vector leftOfScrollBar = new Vector(); + } + + static class CaretBlinker implements ActionListener + { + public void actionPerformed(ActionEvent evt) + { + if(focusedComponent != null + && focusedComponent.hasFocus()) + focusedComponent.blinkCaret(); + } + } + + class MutableCaretEvent extends CaretEvent + { + MutableCaretEvent() + { + super(JEditTextArea.this); + } + + public int getDot() + { + return getCaretPosition(); + } + + public int getMark() + { + return getMarkPosition(); + } + } + + class AdjustHandler implements AdjustmentListener + { + public void adjustmentValueChanged(final AdjustmentEvent evt) + { + if(!scrollBarsInitialized) + return; + + // If this is not done, mousePressed events accumilate + // and the result is that scrolling doesn't stop after + // the mouse is released + SwingUtilities.invokeLater(new Runnable() { + public void run() + { + if(evt.getAdjustable() == vertical) + setFirstLine(vertical.getValue()); + else + setHorizontalOffset(-horizontal.getValue()); + } + }); + } + } + + class ComponentHandler extends ComponentAdapter + { + public void componentResized(ComponentEvent evt) + { + recalculateVisibleLines(); + scrollBarsInitialized = true; + } + } + + class DocumentHandler implements DocumentListener + { + public void insertUpdate(DocumentEvent evt) + { + documentChanged(evt); + + int offset = evt.getOffset(); + int length = evt.getLength(); + + int newStart; + int newEnd; + + if(selectionStart > offset || (selectionStart + == selectionEnd && selectionStart == offset)) + newStart = selectionStart + length; + else + newStart = selectionStart; + + if(selectionEnd >= offset) + newEnd = selectionEnd + length; + else + newEnd = selectionEnd; + + select(newStart,newEnd); + } + + public void removeUpdate(DocumentEvent evt) + { + documentChanged(evt); + + int offset = evt.getOffset(); + int length = evt.getLength(); + + int newStart; + int newEnd; + + if(selectionStart > offset) + { + if(selectionStart > offset + length) + newStart = selectionStart - length; + else + newStart = offset; + } + else + newStart = selectionStart; + + if(selectionEnd > offset) + { + if(selectionEnd > offset + length) + newEnd = selectionEnd - length; + else + newEnd = offset; + } + else + newEnd = selectionEnd; + + select(newStart,newEnd); + } + + public void changedUpdate(DocumentEvent evt) + { + } + } + + class DragHandler implements MouseMotionListener + { + public void mouseDragged(MouseEvent evt) + { + if(popup != null && popup.isVisible()) + return; + + setSelectionRectangular((evt.getModifiers() + & InputEvent.CTRL_MASK) != 0); + select(getMarkPosition(),xyToOffset(evt.getX(),evt.getY())); + } + + public void mouseMoved(MouseEvent evt) {} + } + + class FocusHandler implements FocusListener + { + public void focusGained(FocusEvent evt) + { + setCaretVisible(true); + focusedComponent = JEditTextArea.this; + } + + public void focusLost(FocusEvent evt) + { + setCaretVisible(false); + focusedComponent = null; + } + } + + class MouseHandler extends MouseAdapter + { + public void mousePressed(MouseEvent evt) + { + requestFocus(); + + // Focus events not fired sometimes? + setCaretVisible(true); + focusedComponent = JEditTextArea.this; + + if((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0 + && popup != null) + { + popup.show(painter,evt.getX(),evt.getY()); + return; + } + + int line = yToLine(evt.getY()); + int offset = xToOffset(line,evt.getX()); + int dot = getLineStartOffset(line) + offset; + + switch(evt.getClickCount()) + { + case 1: + doSingleClick(evt,line,offset,dot); + break; + case 2: + // It uses the bracket matching stuff, so + // it can throw a BLE + try + { + doDoubleClick(evt,line,offset,dot); + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + break; + case 3: + doTripleClick(evt,line,offset,dot); + break; + } + } + + private void doSingleClick(MouseEvent evt, int line, + int offset, int dot) + { + if((evt.getModifiers() & InputEvent.SHIFT_MASK) != 0) + { + rectSelect = (evt.getModifiers() & InputEvent.CTRL_MASK) != 0; + select(getMarkPosition(),dot); + } + else + setCaretPosition(dot); + } + + private void doDoubleClick(MouseEvent evt, int line, + int offset, int dot) throws BadLocationException + { + // Ignore empty lines + if(getLineLength(line) == 0) + return; + + try + { + int bracket = TextUtilities.findMatchingBracket( + document,Math.max(0,dot - 1)); + if(bracket != -1) + { + int mark = getMarkPosition(); + // Hack + if(bracket > mark) + { + bracket++; + mark--; + } + select(mark,bracket); + return; + } + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + + // Ok, it's not a bracket... select the word + String lineText = getLineText(line); + char ch = lineText.charAt(Math.max(0,offset - 1)); + + String noWordSep = (String)document.getProperty("noWordSep"); + if(noWordSep == null) + noWordSep = ""; + + // If the user clicked on a non-letter char, + // we select the surrounding non-letters + boolean selectNoLetter = (!Character + .isLetterOrDigit(ch) + && noWordSep.indexOf(ch) == -1); + + int wordStart = 0; + + for(int i = offset - 1; i >= 0; i--) + { + ch = lineText.charAt(i); + if(selectNoLetter ^ (!Character + .isLetterOrDigit(ch) && + noWordSep.indexOf(ch) == -1)) + { + wordStart = i + 1; + break; + } + } + + int wordEnd = lineText.length(); + for(int i = offset; i < lineText.length(); i++) + { + ch = lineText.charAt(i); + if(selectNoLetter ^ (!Character + .isLetterOrDigit(ch) && + noWordSep.indexOf(ch) == -1)) + { + wordEnd = i; + break; + } + } + + int lineStart = getLineStartOffset(line); + select(lineStart + wordStart,lineStart + wordEnd); + + /* + String lineText = getLineText(line); + String noWordSep = (String)document.getProperty("noWordSep"); + int wordStart = TextUtilities.findWordStart(lineText,offset,noWordSep); + int wordEnd = TextUtilities.findWordEnd(lineText,offset,noWordSep); + + int lineStart = getLineStartOffset(line); + select(lineStart + wordStart,lineStart + wordEnd); + */ + } + + private void doTripleClick(MouseEvent evt, int line, + int offset, int dot) + { + select(getLineStartOffset(line),getLineEndOffset(line)-1); + } + } + + class CaretUndo extends AbstractUndoableEdit + { + private int start; + private int end; + + CaretUndo(int start, int end) + { + this.start = start; + this.end = end; + } + + public boolean isSignificant() + { + return false; + } + + public String getPresentationName() + { + return "caret move"; + } + + public void undo() throws CannotUndoException + { + super.undo(); + + select(start,end); + } + + public void redo() throws CannotRedoException + { + super.redo(); + + select(start,end); + } + + public boolean addEdit(UndoableEdit edit) + { + if(edit instanceof CaretUndo) + { + CaretUndo cedit = (CaretUndo)edit; + start = cedit.start; + end = cedit.end; + cedit.die(); + + return true; + } + else + return false; + } + } + + static + { + caretTimer = new Timer(500,new CaretBlinker()); + caretTimer.setInitialDelay(500); + caretTimer.start(); + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.java new file mode 100644 index 0000000..b0f6832 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/KeywordMap.java @@ -0,0 +1,141 @@ +/* + * KeywordMap.java - Fast keyword->id map + * Copyright (C) 1998, 1999 Slava Pestov + * Copyright (C) 1999 Mike Dillon + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.text.Segment; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.Token; + +/** + * A KeywordMap is similar to a hashtable in that it maps keys + * to values. However, the `keys' are Swing segments. This allows lookups of + * text substrings without the overhead of creating a new string object. + *

      + * This class is used by CTokenMarker to map keywords to ids. + * + * @author Slava Pestov, Mike Dillon + */ +public class KeywordMap +{ + /** + * Creates a new KeywordMap. + * @param ignoreCase True if keys are case insensitive + */ + public KeywordMap(boolean ignoreCase) + { + this(ignoreCase, 52); + this.ignoreCase = ignoreCase; + } + + /** + * Creates a new KeywordMap. + * @param ignoreCase True if the keys are case insensitive + * @param mapLength The number of `buckets' to create. + * A value of 52 will give good performance for most maps. + */ + public KeywordMap(boolean ignoreCase, int mapLength) + { + this.mapLength = mapLength; + this.ignoreCase = ignoreCase; + map = new Keyword[mapLength]; + } + + /** + * Looks up a key. + * @param text The text segment + * @param offset The offset of the substring within the text segment + * @param length The length of the substring + */ + public byte lookup(Segment text, int offset, int length) + { + if(length == 0) + return Token.NULL; + Keyword k = map[getSegmentMapKey(text, offset, length)]; + while(k != null) + { + if(length != k.keyword.length) + { + k = k.next; + continue; + } + if(SyntaxUtilities.regionMatches(ignoreCase,text,offset, + k.keyword)) + return k.id; + k = k.next; + } + return Token.NULL; + } + + /** + * Adds a key-value mapping. + * @param keyword The key + * @Param id The value + */ + public void add(String keyword, byte id) + { + int key = getStringMapKey(keyword); + map[key] = new Keyword(keyword.toCharArray(),id,map[key]); + } + + /** + * Returns true if the keyword map is set to be case insensitive, + * false otherwise. + */ + public boolean getIgnoreCase() + { + return ignoreCase; + } + + /** + * Sets if the keyword map should be case insensitive. + * @param ignoreCase True if the keyword map should be case + * insensitive, false otherwise + */ + public void setIgnoreCase(boolean ignoreCase) + { + this.ignoreCase = ignoreCase; + } + + // protected members + protected int mapLength; + + protected int getStringMapKey(String s) + { + return (Character.toUpperCase(s.charAt(0)) + + Character.toUpperCase(s.charAt(s.length()-1))) + % mapLength; + } + + protected int getSegmentMapKey(Segment s, int off, int len) + { + return (Character.toUpperCase(s.array[off]) + + Character.toUpperCase(s.array[off + len - 1])) + % mapLength; + } + + // private members + static class Keyword + { + public Keyword(char[] keyword, byte id, Keyword next) + { + this.keyword = keyword; + this.id = id; + this.next = next; + } + + public char[] keyword; + public byte id; + public Keyword next; + } + + private Keyword[] map; + private boolean ignoreCase; +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.java new file mode 100644 index 0000000..4dd0961 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxDocument.java @@ -0,0 +1,172 @@ +/* + * SyntaxDocument.java - Document that can be tokenized + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.event.*; +import javax.swing.text.*; +import javax.swing.undo.UndoableEdit; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.TokenMarker; + +/** + * A document implementation that can be tokenized by the syntax highlighting + * system. + * + * @author Slava Pestov + */ +public class SyntaxDocument extends PlainDocument +{ + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Returns the token marker that is to be used to split lines + * of this document up into tokens. May return null if this + * document is not to be colorized. + */ + public TokenMarker getTokenMarker() + { + return tokenMarker; + } + + /** + * Sets the token marker that is to be used to split lines of + * this document up into tokens. May throw an exception if + * this is not supported for this type of document. + * @param tm The new token marker + */ + public void setTokenMarker(TokenMarker tm) + { + tokenMarker = tm; + if(tm == null) + return; + tokenMarker.insertLines(0,getDefaultRootElement() + .getElementCount()); + tokenizeLines(); + } + + /** + * Reparses the document, by passing all lines to the token + * marker. This should be called after the document is first + * loaded. + */ + public void tokenizeLines() + { + tokenizeLines(0,getDefaultRootElement().getElementCount()); + } + + /** + * Reparses the document, by passing the specified lines to the + * token marker. This should be called after a large quantity of + * text is first inserted. + * @param start The first line to parse + * @param len The number of lines, after the first one to parse + */ + public void tokenizeLines(int start, int len) + { + if(tokenMarker == null || !tokenMarker.supportsMultilineTokens()) + return; + + Segment lineSegment = new Segment(); + Element map = getDefaultRootElement(); + + len += start; + + try + { + for(int i = start; i < len; i++) + { + Element lineElement = map.getElement(i); + int lineStart = lineElement.getStartOffset(); + getText(lineStart,lineElement.getEndOffset() + - lineStart - 1,lineSegment); + tokenMarker.markTokens(lineSegment,i); + } + } + catch(BadLocationException bl) + { + bl.printStackTrace(); + } + } + + /** + * Starts a compound edit that can be undone in one operation. + * Subclasses that implement undo should override this method; + * this class has no undo functionality so this method is + * empty. + */ + public void beginCompoundEdit() {} + + /** + * Ends a compound edit that can be undone in one operation. + * Subclasses that implement undo should override this method; + * this class has no undo functionality so this method is + * empty. + */ + public void endCompoundEdit() {} + + /** + * Adds an undoable edit to this document's undo list. The edit + * should be ignored if something is currently being undone. + * @param edit The undoable edit + * + * @since jEdit 2.2pre1 + */ + public void addUndoableEdit(UndoableEdit edit) {} + + // protected members + protected TokenMarker tokenMarker; + + /** + * We overwrite this method to update the token marker + * state immediately so that any event listeners get a + * consistent token marker. + */ + protected void fireInsertUpdate(DocumentEvent evt) + { + if(tokenMarker != null) + { + DocumentEvent.ElementChange ch = evt.getChange( + getDefaultRootElement()); + if(ch != null) + { + tokenMarker.insertLines(ch.getIndex() + 1, + ch.getChildrenAdded().length - + ch.getChildrenRemoved().length); + } + } + + super.fireInsertUpdate(evt); + } + + /** + * We overwrite this method to update the token marker + * state immediately so that any event listeners get a + * consistent token marker. + */ + protected void fireRemoveUpdate(DocumentEvent evt) + { + if(tokenMarker != null) + { + DocumentEvent.ElementChange ch = evt.getChange( + getDefaultRootElement()); + if(ch != null) + { + tokenMarker.deleteLines(ch.getIndex() + 1, + ch.getChildrenRemoved().length - + ch.getChildrenAdded().length); + } + } + + super.fireRemoveUpdate(evt); + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.java new file mode 100644 index 0000000..7061f39 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxStyle.java @@ -0,0 +1,135 @@ +/* + * SyntaxStyle.java - A simple text style class + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import java.awt.*; + +/** + * A simple text style class. It can specify the color, italic flag, + * and bold flag of a run of text. + * @author Slava Pestov + */ +public class SyntaxStyle +{ + /** + * Creates a new SyntaxStyle. + * @param color The text color + * @param italic True if the text should be italics + * @param bold True if the text should be bold + */ + public SyntaxStyle(Color color, boolean italic, boolean bold) + { + this.color = color; + this.italic = italic; + this.bold = bold; + } + + /** + * Returns the color specified in this style. + */ + public Color getColor() + { + return color; + } + + /** + * Returns true if no font styles are enabled. + */ + public boolean isPlain() + { + return !(bold || italic); + } + + /** + * Returns true if italics is enabled for this style. + */ + public boolean isItalic() + { + return italic; + } + + /** + * Returns true if boldface is enabled for this style. + */ + public boolean isBold() + { + return bold; + } + + /** + * Returns the specified font, but with the style's bold and + * italic flags applied. + */ + public Font getStyledFont(Font font) + { + if(font == null) + throw new NullPointerException("font param must not" + + " be null"); + if(font.equals(lastFont)) + return lastStyledFont; + lastFont = font; + lastStyledFont = new Font(font.getFamily(), + (bold ? Font.BOLD : 0) + | (italic ? Font.ITALIC : 0), + font.getSize()); + return lastStyledFont; + } + + /** + * Returns the font metrics for the styled font. + */ + public FontMetrics getFontMetrics(Font font) + { + if(font == null) + throw new NullPointerException("font param must not" + + " be null"); + if(font.equals(lastFont) && fontMetrics != null) + return fontMetrics; + lastFont = font; + lastStyledFont = new Font(font.getFamily(), + (bold ? Font.BOLD : 0) + | (italic ? Font.ITALIC : 0), + font.getSize()); + fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics( + lastStyledFont); + return fontMetrics; + } + + /** + * Sets the foreground color and font of the specified graphics + * context to that specified in this style. + * @param gfx The graphics context + * @param font The font to add the styles to + */ + public void setGraphicsFlags(Graphics gfx, Font font) + { + Font _font = getStyledFont(font); + gfx.setFont(_font); + gfx.setColor(color); + } + + /** + * Returns a string representation of this object. + */ + public String toString() + { + return getClass().getName() + "[color=" + color + + (italic ? ",italic" : "") + + (bold ? ",bold" : "") + "]"; + } + + // private members + private Color color; + private boolean italic; + private boolean bold; + private Font lastFont; + private Font lastStyledFont; + private FontMetrics fontMetrics; +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.java new file mode 100644 index 0000000..97b2ea4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/SyntaxUtilities.java @@ -0,0 +1,160 @@ +/* + * SyntaxUtilities.java - Utility functions used by syntax colorizing + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.text.*; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.Token; + +import java.awt.*; + +/** + * Class with several utility functions used by jEdit's syntax colorizing + * subsystem. + * + * @author Slava Pestov + */ +public class SyntaxUtilities +{ + /** + * Checks if a subregion of a Segment is equal to a + * string. + * @param ignoreCase True if case should be ignored, false otherwise + * @param text The segment + * @param offset The offset into the segment + * @param match The string to match + */ + public static boolean regionMatches(boolean ignoreCase, Segment text, + int offset, String match) + { + int length = offset + match.length(); + char[] textArray = text.array; + if(length > text.offset + text.count) + return false; + for(int i = offset, j = 0; i < length; i++, j++) + { + char c1 = textArray[i]; + char c2 = match.charAt(j); + if(ignoreCase) + { + c1 = Character.toUpperCase(c1); + c2 = Character.toUpperCase(c2); + } + if(c1 != c2) + return false; + } + return true; + } + + /** + * Checks if a subregion of a Segment is equal to a + * character array. + * @param ignoreCase True if case should be ignored, false otherwise + * @param text The segment + * @param offset The offset into the segment + * @param match The character array to match + */ + public static boolean regionMatches(boolean ignoreCase, Segment text, + int offset, char[] match) + { + int length = offset + match.length; + char[] textArray = text.array; + if(length > text.offset + text.count) + return false; + for(int i = offset, j = 0; i < length; i++, j++) + { + char c1 = textArray[i]; + char c2 = match[j]; + if(ignoreCase) + { + c1 = Character.toUpperCase(c1); + c2 = Character.toUpperCase(c2); + } + if(c1 != c2) + return false; + } + return true; + } + + /** + * Returns the default style table. This can be passed to the + * setStyles() method of SyntaxDocument + * to use the default syntax styles. + */ + public static SyntaxStyle[] getDefaultSyntaxStyles() + { + SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT]; + + styles[Token.COMMENT1] = new SyntaxStyle(Color.black,true,false); + styles[Token.COMMENT2] = new SyntaxStyle(new Color(0x990033),true,false); + styles[Token.KEYWORD1] = new SyntaxStyle(Color.black,false,true); + styles[Token.KEYWORD2] = new SyntaxStyle(Color.magenta,false,false); + styles[Token.KEYWORD3] = new SyntaxStyle(new Color(0x009600),false,false); + styles[Token.LITERAL1] = new SyntaxStyle(new Color(0x650099),false,false); + styles[Token.LITERAL2] = new SyntaxStyle(new Color(0x650099),false,true); + styles[Token.LABEL] = new SyntaxStyle(new Color(0x990033),false,true); + styles[Token.OPERATOR] = new SyntaxStyle(Color.black,false,true); + styles[Token.INVALID] = new SyntaxStyle(Color.red,false,true); + + return styles; + } + + /** + * Paints the specified line onto the graphics context. Note that this + * method munges the offset and count values of the segment. + * @param line The line segment + * @param tokens The token list for the line + * @param styles The syntax style list + * @param expander The tab expander used to determine tab stops. May + * be null + * @param gfx The graphics context + * @param x The x co-ordinate + * @param y The y co-ordinate + * @return The x co-ordinate, plus the width of the painted string + */ + public static int paintSyntaxLine(Segment line, Token tokens, + SyntaxStyle[] styles, TabExpander expander, Graphics gfx, + int x, int y) + { + Font defaultFont = gfx.getFont(); + Color defaultColor = gfx.getColor(); + + int offset = 0; + for(;;) + { + byte id = tokens.id; + if(id == Token.END) + break; + + int length = tokens.length; + if(id == Token.NULL) + { + if(!defaultColor.equals(gfx.getColor())) + gfx.setColor(defaultColor); + if(!defaultFont.equals(gfx.getFont())) + gfx.setFont(defaultFont); + } + else + styles[id].setGraphicsFlags(gfx,defaultFont); + + line.count = length; + x = Utilities.drawTabbedText(line,x,y,gfx,expander,0); + line.offset += length; + offset += length; + + tokens = tokens.next; + } + + return x; + } + + // private members + private SyntaxUtilities() {} +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.java new file mode 100644 index 0000000..0dc4a4c --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaDefaults.java @@ -0,0 +1,79 @@ +/* + * TextAreaDefaults.java - Encapsulates default values for various settings + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.JPopupMenu; +import java.awt.Color; + +/** + * Encapsulates default settings for a text area. This can be passed to the + * constructor once the necessary fields have been filled out. The advantage of + * doing this over calling lots of set() methods after creating the text area is + * that this method is faster. + */ +public class TextAreaDefaults { + public InputHandler inputHandler; + public SyntaxDocument document; + public boolean editable; + + public boolean caretVisible; + public boolean caretBlinks; + public boolean blockCaret; + public int electricScroll; + + public int cols; + public int rows; + public SyntaxStyle[] styles; + public Color caretColor; + public Color selectionColor; + public Color lineHighlightColor; + public boolean lineHighlight; + public Color bracketHighlightColor; + public boolean bracketHighlight; + public Color eolMarkerColor; + public boolean eolMarkers; + public boolean paintInvalid; + + public JPopupMenu popup; + + /** + * Returns a new TextAreaDefaults object with the default values filled in. + */ + public static TextAreaDefaults getDefaults() { + TextAreaDefaults DEFAULTS; + + DEFAULTS = new TextAreaDefaults(); + + DEFAULTS.inputHandler = new DefaultInputHandler(); + DEFAULTS.inputHandler.addDefaultKeyBindings(); + DEFAULTS.document = new SyntaxDocument(); + DEFAULTS.editable = true; + + DEFAULTS.blockCaret = false; + DEFAULTS.caretVisible = true; + DEFAULTS.caretBlinks = true; + DEFAULTS.electricScroll = 3; + + DEFAULTS.cols = 80; + DEFAULTS.rows = 25; + DEFAULTS.styles = SyntaxUtilities.getDefaultSyntaxStyles(); + DEFAULTS.caretColor = Color.black; // Color.red; + DEFAULTS.selectionColor = new Color(0xccccff); + DEFAULTS.lineHighlightColor = new Color(0xe0e0e0); + DEFAULTS.lineHighlight = true; + DEFAULTS.bracketHighlightColor = Color.black; + DEFAULTS.bracketHighlight = true; + DEFAULTS.eolMarkerColor = new Color(0x009999); + DEFAULTS.eolMarkers = false; // true; + DEFAULTS.paintInvalid = false; // true; + + return DEFAULTS; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.java new file mode 100644 index 0000000..d634bdc --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextAreaPainter.java @@ -0,0 +1,682 @@ +/* + * TextAreaPainter.java - Paints the text area + * Copyright (C) 1999 Slava Pestov + * + * 08/05/2002 Cursor (caret) rendering fixed for JDK 1.4 (Anonymous) + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.ToolTipManager; +import javax.swing.text.*; +import javax.swing.JComponent; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.Token; +import org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker.TokenMarker; + +import java.awt.event.MouseEvent; +import java.awt.*; + +/** + * The text area repaint manager. It performs double buffering and paints lines + * of text. + * + * @author Slava Pestov + */ +public class TextAreaPainter extends JComponent implements TabExpander { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Creates a new repaint manager. This should be not be called directly. + */ + public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults) { + this.textArea = textArea; + + setAutoscrolls(true); + setDoubleBuffered(true); + setOpaque(true); + + ToolTipManager.sharedInstance().registerComponent(this); + + currentLine = new Segment(); + currentLineIndex = -1; + + setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); + + setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14)); + setForeground(Color.black); + setBackground(Color.white); + + blockCaret = defaults.blockCaret; + styles = defaults.styles; + cols = defaults.cols; + rows = defaults.rows; + caretColor = defaults.caretColor; + selectionColor = defaults.selectionColor; + lineHighlightColor = defaults.lineHighlightColor; + lineHighlight = defaults.lineHighlight; + bracketHighlightColor = defaults.bracketHighlightColor; + bracketHighlight = defaults.bracketHighlight; + paintInvalid = defaults.paintInvalid; + eolMarkerColor = defaults.eolMarkerColor; + eolMarkers = defaults.eolMarkers; + } + + public void setTextArea(JEditTextArea textArea) { + this.textArea = textArea; + } + + /** + * Returns if this component can be traversed by pressing the Tab key. This + * returns false. + */ + public final boolean isManagingFocus() { + return false; + } + + /** + * Returns the syntax styles used to paint colorized text. Entry n + * will be used to paint tokens with id = n. + * + * @see Token + */ + public final SyntaxStyle[] getStyles() { + return styles; + } + + /** + * Sets the syntax styles used to paint colorized text. Entry n will + * be used to paint tokens with id = n. + * + * @param styles + * The syntax styles + * @see Token + */ + public final void setStyles(SyntaxStyle[] styles) { + this.styles = styles; + repaint(); + } + + /** + * Returns the caret color. + */ + public final Color getCaretColor() { + return caretColor; + } + + /** + * Sets the caret color. + * + * @param caretColor + * The caret color + */ + public final void setCaretColor(Color caretColor) { + this.caretColor = caretColor; + invalidateSelectedLines(); + } + + /** + * Returns the selection color. + */ + public final Color getSelectionColor() { + return selectionColor; + } + + /** + * Sets the selection color. + * + * @param selectionColor + * The selection color + */ + public final void setSelectionColor(Color selectionColor) { + this.selectionColor = selectionColor; + invalidateSelectedLines(); + } + + /** + * Returns the line highlight color. + */ + public final Color getLineHighlightColor() { + return lineHighlightColor; + } + + /** + * Sets the line highlight color. + * + * @param lineHighlightColor + * The line highlight color + */ + public final void setLineHighlightColor(Color lineHighlightColor) { + this.lineHighlightColor = lineHighlightColor; + invalidateSelectedLines(); + } + + /** + * Returns true if line highlight is enabled, false otherwise. + */ + public final boolean isLineHighlightEnabled() { + return lineHighlight; + } + + /** + * Enables or disables current line highlighting. + * + * @param lineHighlight + * True if current line highlight should be enabled, false + * otherwise + */ + public final void setLineHighlightEnabled(boolean lineHighlight) { + this.lineHighlight = lineHighlight; + invalidateSelectedLines(); + } + + /** + * Returns the bracket highlight color. + */ + public final Color getBracketHighlightColor() { + return bracketHighlightColor; + } + + /** + * Sets the bracket highlight color. + * + * @param bracketHighlightColor + * The bracket highlight color + */ + public final void setBracketHighlightColor(Color bracketHighlightColor) { + this.bracketHighlightColor = bracketHighlightColor; + invalidateLine(textArea.getBracketLine()); + } + + /** + * Returns true if bracket highlighting is enabled, false otherwise. When + * bracket highlighting is enabled, the bracket matching the one before the + * caret (if any) is highlighted. + */ + public final boolean isBracketHighlightEnabled() { + return bracketHighlight; + } + + /** + * Enables or disables bracket highlighting. When bracket highlighting is + * enabled, the bracket matching the one before the caret (if any) is + * highlighted. + * + * @param bracketHighlight + * True if bracket highlighting should be enabled, false + * otherwise + */ + public final void setBracketHighlightEnabled(boolean bracketHighlight) { + this.bracketHighlight = bracketHighlight; + invalidateLine(textArea.getBracketLine()); + } + + /** + * Returns true if the caret should be drawn as a block, false otherwise. + */ + public final boolean isBlockCaretEnabled() { + return blockCaret; + } + + /** + * Sets if the caret should be drawn as a block, false otherwise. + * + * @param blockCaret + * True if the caret should be drawn as a block, false otherwise. + */ + public final void setBlockCaretEnabled(boolean blockCaret) { + this.blockCaret = blockCaret; + invalidateSelectedLines(); + } + + /** + * Returns the EOL marker color. + */ + public final Color getEOLMarkerColor() { + return eolMarkerColor; + } + + /** + * Sets the EOL marker color. + * + * @param eolMarkerColor + * The EOL marker color + */ + public final void setEOLMarkerColor(Color eolMarkerColor) { + this.eolMarkerColor = eolMarkerColor; + repaint(); + } + + /** + * Returns true if EOL markers are drawn, false otherwise. + */ + public final boolean getEOLMarkersPainted() { + return eolMarkers; + } + + /** + * Sets if EOL markers are to be drawn. + * + * @param eolMarkers + * True if EOL markers should be drawn, false otherwise + */ + public final void setEOLMarkersPainted(boolean eolMarkers) { + this.eolMarkers = eolMarkers; + repaint(); + } + + /** + * Returns true if invalid lines are painted as red tildes (~), false + * otherwise. + */ + public boolean getInvalidLinesPainted() { + return paintInvalid; + } + + /** + * Sets if invalid lines are to be painted as red tildes. + * + * @param paintInvalid + * True if invalid lines should be drawn, false otherwise + */ + public void setInvalidLinesPainted(boolean paintInvalid) { + this.paintInvalid = paintInvalid; + } + + /** + * Adds a custom highlight painter. + * + * @param highlight + * The highlight + */ + public void addCustomHighlight(Highlight highlight) { + highlight.init(textArea, highlights); + highlights = highlight; + } + + /** + * Highlight interface. + */ + public interface Highlight { + /** + * Called after the highlight painter has been added. + * + * @param textArea + * The text area + * @param next + * The painter this one should delegate to + */ + void init(JEditTextArea textArea, Highlight next); + + /** + * This should paint the highlight and delgate to the next highlight + * painter. + * + * @param gfx + * The graphics context + * @param line + * The line number + * @param y + * The y co-ordinate of the line + */ + void paintHighlight(Graphics gfx, int line, int y); + + /** + * Returns the tool tip to display at the specified location. If this + * highlighter doesn't know what to display, it should delegate to the + * next highlight painter. + * + * @param evt + * The mouse event + */ + String getToolTipText(MouseEvent evt); + } + + /** + * Returns the tool tip to display at the specified location. + * + * @param evt + * The mouse event + */ + public String getToolTipText(MouseEvent evt) { + if (highlights != null) + return highlights.getToolTipText(evt); + else + return null; + } + + /** + * Returns the font metrics used by this component. + */ + public FontMetrics getFontMetrics() { + return getFm(); + } + + /** + * Sets the font for this component. This is overridden to update the cached + * font metrics and to recalculate which lines are visible. + * + * @param font + * The font + */ + public void setFont(Font font) { + super.setFont(font); + setFm(Toolkit.getDefaultToolkit().getFontMetrics(font)); + textArea.recalculateVisibleLines(); + } + + /** + * Repaints the text. + * + * @param gfx + * The graphics context + */ + public void paint(Graphics gfx) { + tabSize = getFm().charWidth(' ') + * ((Integer) textArea.getDocument().getProperty( + PlainDocument.tabSizeAttribute)).intValue(); + + Rectangle clipRect = gfx.getClipBounds(); + + gfx.setColor(getBackground()); + gfx.fillRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height); + + // We don't use yToLine() here because that method doesn't + // return lines past the end of the document + int height = getFm().getHeight(); + int firstLine = textArea.getFirstLine(); + int firstInvalid = firstLine + clipRect.y / height; + // Because the clipRect's height is usually an even multiple + // of the font height, we subtract 1 from it, otherwise one + // too many lines will always be painted. + int lastInvalid = firstLine + (clipRect.y + clipRect.height - 1) + / height; + + try { + TokenMarker tokenMarker = textArea.getDocument().getTokenMarker(); + int x = textArea.getHorizontalOffset(); + + for (int line = firstInvalid; line <= lastInvalid; line++) { + paintLine(gfx, tokenMarker, line, x); + } + + if (tokenMarker != null && tokenMarker.isNextLineRequested()) { + int h = clipRect.y + clipRect.height; + repaint(0, h, getWidth(), getHeight() - h); + } + } catch (Exception e) { + System.err.println("Error repainting line" + " range {" + + firstInvalid + "," + lastInvalid + "}:"); + e.printStackTrace(); + } + } + + /** + * Marks a line as needing a repaint. + * + * @param line + * The line to invalidate + */ + public final void invalidateLine(int line) { + repaint(0, textArea.lineToY(line) + getFm().getMaxDescent() + + getFm().getLeading(), getWidth(), getFm().getHeight()); + } + + /** + * Marks a range of lines as needing a repaint. + * + * @param firstLine + * The first line to invalidate + * @param lastLine + * The last line to invalidate + */ + public final void invalidateLineRange(int firstLine, int lastLine) { + repaint(0, textArea.lineToY(firstLine) + getFm().getMaxDescent() + + getFm().getLeading(), getWidth(), (lastLine - firstLine + 1) + * getFm().getHeight()); + } + + /** + * Repaints the lines containing the selection. + */ + public final void invalidateSelectedLines() { + invalidateLineRange(textArea.getSelectionStartLine(), textArea + .getSelectionEndLine()); + } + + /** + * Implementation of TabExpander interface. Returns next tab stop after a + * specified point. + * + * @param x + * The x co-ordinate + * @param tabOffset + * Ignored + * @return The next tab stop after x + */ + public float nextTabStop(float x, int tabOffset) { + int offset = textArea.getHorizontalOffset(); + int ntabs = ((int) x - offset) / tabSize; + return (ntabs + 1) * tabSize + offset; + } + + /** + * Returns the painter's preferred size. + */ + public Dimension getPreferredSize() { + Dimension dim = new Dimension(); + dim.width = getFm().charWidth('w') * cols; + dim.height = getFm().getHeight() * rows; + return dim; + } + + /** + * Returns the painter's minimum size. + */ + public Dimension getMinimumSize() { + return getPreferredSize(); + } + + // package-private members + protected int currentLineIndex; + protected Token currentLineTokens; + Segment currentLine; + + // protected members + protected JEditTextArea textArea; + + protected SyntaxStyle[] styles; + protected Color caretColor; + protected Color selectionColor; + protected Color lineHighlightColor; + protected Color bracketHighlightColor; + protected Color eolMarkerColor; + + protected boolean blockCaret; + protected boolean lineHighlight; + protected boolean bracketHighlight; + protected boolean paintInvalid; + protected boolean eolMarkers; + protected int cols; + protected int rows; + + protected int tabSize; + private FontMetrics fm; + + protected Highlight highlights; + + protected void paintLine(Graphics gfx, TokenMarker tokenMarker, int line, + int x) { + Font defaultFont = getFont(); + Color defaultColor = getForeground(); + + currentLineIndex = line; + int y = textArea.lineToY(line); + + if (line < 0 || line >= textArea.getLineCount()) { + if (paintInvalid) { + paintHighlight(gfx, line, y); + styles[Token.INVALID].setGraphicsFlags(gfx, defaultFont); + gfx.drawString("~", 0, y + getFm().getHeight()); + } + } else if (tokenMarker == null) { + paintPlainLine(gfx, line, defaultFont, defaultColor, x, y); + } else { + paintSyntaxLine(gfx, tokenMarker, line, defaultFont, defaultColor, + x, y); + } + } + + protected void paintPlainLine(Graphics gfx, int line, Font defaultFont, + Color defaultColor, int x, int y) { + paintHighlight(gfx, line, y); + textArea.getLineText(line, currentLine); + + gfx.setFont(defaultFont); + gfx.setColor(defaultColor); + + y += getFm().getHeight(); + x = Utilities.drawTabbedText(currentLine, x, y, gfx, this, 0); + + if (eolMarkers) { + gfx.setColor(eolMarkerColor); + gfx.drawString(".", x, y); + } + } + + protected void paintSyntaxLine(Graphics gfx, TokenMarker tokenMarker, + int line, Font defaultFont, Color defaultColor, int x, int y) { + textArea.getLineText(currentLineIndex, currentLine); + currentLineTokens = tokenMarker.markTokens(currentLine, + currentLineIndex); + + paintHighlight(gfx, line, y); + + gfx.setFont(defaultFont); + gfx.setColor(defaultColor); + y += getFm().getHeight(); + x = SyntaxUtilities.paintSyntaxLine(currentLine, currentLineTokens, + styles, this, gfx, x, y); + + if (eolMarkers) { + gfx.setColor(eolMarkerColor); + gfx.drawString(".", x, y); + } + } + + protected void paintHighlight(Graphics gfx, int line, int y) + { + if(line >= textArea.getSelectionStartLine() + && line <= textArea.getSelectionEndLine()) + { + paintLineHighlight(gfx,line,y); + } + + if(highlights != null) + highlights.paintHighlight(gfx,line,y); + + if(bracketHighlight && line == textArea.getBracketLine()) + paintBracketHighlight(gfx,line,y); + + if(line == textArea.getCaretLine()) + paintCaret(gfx,line,y); + } + + protected void paintLineHighlight(Graphics gfx, int line, int y) { + int height = getFm().getHeight(); + y += getFm().getLeading() + getFm().getMaxDescent(); + + int selectionStart = textArea.getSelectionStart(); + int selectionEnd = textArea.getSelectionEnd(); + + if (selectionStart == selectionEnd) { + if (lineHighlight) { + gfx.setColor(lineHighlightColor); + gfx.fillRect(0, y, getWidth(), height); + } + } else { + gfx.setColor(selectionColor); + + int selectionStartLine = textArea.getSelectionStartLine(); + int selectionEndLine = textArea.getSelectionEndLine(); + int lineStart = textArea.getLineStartOffset(line); + + int x1, x2; + if (textArea.isSelectionRectangular()) { + int lineLen = textArea.getLineLength(line); + x1 = textArea._offsetToX(line, Math.min(lineLen, selectionStart + - textArea.getLineStartOffset(selectionStartLine))); + x2 = textArea._offsetToX(line, Math.min(lineLen, selectionEnd + - textArea.getLineStartOffset(selectionEndLine))); + if (x1 == x2) + x2++; + } else if (selectionStartLine == selectionEndLine) { + x1 = textArea._offsetToX(line, selectionStart - lineStart); + x2 = textArea._offsetToX(line, selectionEnd - lineStart); + } else if (line == selectionStartLine) { + x1 = textArea._offsetToX(line, selectionStart - lineStart); + x2 = getWidth(); + } else if (line == selectionEndLine) { + x1 = 0; + x2 = textArea._offsetToX(line, selectionEnd - lineStart); + } else { + x1 = 0; + x2 = getWidth(); + } + + // "inlined" min/max() + gfx.fillRect(x1 > x2 ? x2 : x1, y, x1 > x2 ? (x1 - x2) : (x2 - x1), + height); + } + + } + + protected void paintBracketHighlight(Graphics gfx, int line, int y) { + int position = textArea.getBracketPosition(); + if (position == -1) + return; + y += getFm().getLeading() + getFm().getMaxDescent(); + int x = textArea._offsetToX(line, position); + gfx.setColor(bracketHighlightColor); + // Hack!!! Since there is no fast way to get the character + // from the bracket matching routine, we use ( since all + // brackets probably have the same width anyway + gfx.drawRect(x, y, getFm().charWidth('(') - 1, getFm().getHeight() - 1); + } + + protected void paintCaret(Graphics gfx, int line, int y) { + if (textArea.isCaretVisible()) { + int offset = textArea.getCaretPosition() + - textArea.getLineStartOffset(line); + int caretX = textArea._offsetToX(line, offset); + int caretWidth = ((blockCaret || textArea.isOverwriteEnabled()) ? getFm() + .charWidth('w') + : 1); + y += getFm().getLeading() + getFm().getMaxDescent(); + int height = getFm().getHeight(); + + gfx.setColor(caretColor); + + if (textArea.isOverwriteEnabled()) { + gfx.fillRect(caretX, y + height - 1, caretWidth, 1); + } else { + gfx.drawRect(caretX, y, caretWidth, height - 1); + } + } + } + + public void setFm(FontMetrics fm) { + this.fm = fm; + } + + public FontMetrics getFm() { + return fm; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.java new file mode 100644 index 0000000..9a465cb --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/TextUtilities.java @@ -0,0 +1,183 @@ +/* + * TextUtilities.java - Utility functions used by the text area classes + * Copyright (C) 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit; + +import javax.swing.text.*; + +/** + * Class with several utility functions used by the text area component. + * @author Slava Pestov + */ +public class TextUtilities +{ + /** + * Returns the offset of the bracket matching the one at the + * specified offset of the document, or -1 if the bracket is + * unmatched (or if the character is not a bracket). + * @param doc The document + * @param offset The offset + * @exception BadLocationException If an out-of-bounds access + * was attempted on the document text + */ + public static int findMatchingBracket(Document doc, int offset) + throws BadLocationException + { + if(doc.getLength() == 0) + return -1; + char c = doc.getText(offset,1).charAt(0); + char cprime; // c` - corresponding character + boolean direction; // true = back, false = forward + + switch(c) + { + case '(': cprime = ')'; direction = false; break; + case ')': cprime = '('; direction = true; break; + case '[': cprime = ']'; direction = false; break; + case ']': cprime = '['; direction = true; break; + case '{': cprime = '}'; direction = false; break; + case '}': cprime = '{'; direction = true; break; + default: return -1; + } + + int count; + + // How to merge these two cases is left as an exercise + // for the reader. + + // Go back or forward + if(direction) + { + // Count is 1 initially because we have already + // `found' one closing bracket + count = 1; + + // Get text[0,offset-1]; + String text = doc.getText(0,offset); + + // Scan backwards + for(int i = offset - 1; i >= 0; i--) + { + // If text[i] == c, we have found another + // closing bracket, therefore we will need + // two opening brackets to complete the + // match. + char x = text.charAt(i); + if(x == c) + count++; + + // If text[i] == cprime, we have found a + // opening bracket, so we return i if + // --count == 0 + else if(x == cprime) + { + if(--count == 0) + return i; + } + } + } + else + { + // Count is 1 initially because we have already + // `found' one opening bracket + count = 1; + + // So we don't have to + 1 in every loop + offset++; + + // Number of characters to check + int len = doc.getLength() - offset; + + // Get text[offset+1,len]; + String text = doc.getText(offset,len); + + // Scan forwards + for(int i = 0; i < len; i++) + { + // If text[i] == c, we have found another + // opening bracket, therefore we will need + // two closing brackets to complete the + // match. + char x = text.charAt(i); + + if(x == c) + count++; + + // If text[i] == cprime, we have found an + // closing bracket, so we return i if + // --count == 0 + else if(x == cprime) + { + if(--count == 0) + return i + offset; + } + } + } + + // Nothing found + return -1; + } + + /** + * Locates the start of the word at the specified position. + * @param line The text + * @param pos The position + */ + public static int findWordStart(String line, int pos, String noWordSep) + { + char ch = line.charAt(pos - 1); + + if(noWordSep == null) + noWordSep = ""; + boolean selectNoLetter = (!Character.isLetterOrDigit(ch) + && noWordSep.indexOf(ch) == -1); + + int wordStart = 0; + for(int i = pos - 1; i >= 0; i--) + { + ch = line.charAt(i); + if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) && + noWordSep.indexOf(ch) == -1)) + { + wordStart = i + 1; + break; + } + } + + return wordStart; + } + + /** + * Locates the end of the word at the specified position. + * @param line The text + * @param pos The position + */ + public static int findWordEnd(String line, int pos, String noWordSep) + { + char ch = line.charAt(pos); + + if(noWordSep == null) + noWordSep = ""; + boolean selectNoLetter = (!Character.isLetterOrDigit(ch) + && noWordSep.indexOf(ch) == -1); + + int wordEnd = line.length(); + for(int i = pos; i < line.length(); i++) + { + ch = line.charAt(i); + if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) && + noWordSep.indexOf(ch) == -1)) + { + wordEnd = i; + break; + } + } + return wordEnd; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.java new file mode 100644 index 0000000..5c385c5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/package-info.java @@ -0,0 +1,4 @@ +/** + * Customized version of the JEdit text editor. + */ +package org.jalgo.module.am0c0.gui.jeditor.jedit; diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.java new file mode 100644 index 0000000..1dcd609 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/AM0TokenMarker.java @@ -0,0 +1,112 @@ +/* + * CTokenMarker.java - C token marker + * Copyright (C) 1998, 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; + +import javax.swing.text.Segment; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.KeywordMap; + +/** + * AM0 token marker. + * + * @author Felix Schmitt + */ +public class AM0TokenMarker extends TokenMarker { + public AM0TokenMarker() { + this(getKeywords()); + } + + public AM0TokenMarker(KeywordMap keywords) { + this.keywords = keywords; + } + + public byte markTokensImpl(byte token, Segment line, int lineIndex) { + char[] array = line.array; + int offset = line.offset; + lastOffset = offset; + lastKeyword = offset; + int length = line.count + offset; + + for (int i = offset; i < length; i++) { + char c = array[i]; + + switch (token) { + case Token.NULL: + switch (c) { + default: + if (!Character.isLetterOrDigit(c) && c != '_') + doKeyword(line, i, c); + break; + } + break; + default: + throw new InternalError("Invalid state: " + token); + } + } + + if (token == Token.NULL) + doKeyword(line, length, '\0'); + + switch (token) { + default: + addToken(length - lastOffset, token); + break; + } + + return token; + } + + public static KeywordMap getKeywords() { + if (cKeywords == null) { + cKeywords = new KeywordMap(false); + cKeywords.add("ADD", Token.KEYWORD1); + cKeywords.add("MUL", Token.KEYWORD1); + cKeywords.add("SUB", Token.KEYWORD1); + cKeywords.add("DIV", Token.KEYWORD1); + cKeywords.add("MOD", Token.KEYWORD1); + cKeywords.add("LT", Token.KEYWORD1); + cKeywords.add("EQ", Token.KEYWORD1); + cKeywords.add("NE", Token.KEYWORD1); + cKeywords.add("GT", Token.KEYWORD1); + cKeywords.add("LE", Token.KEYWORD1); + cKeywords.add("GE", Token.KEYWORD1); + cKeywords.add("LOAD", Token.KEYWORD1); + cKeywords.add("LIT", Token.KEYWORD1); + cKeywords.add("STORE", Token.KEYWORD1); + cKeywords.add("JMP", Token.KEYWORD1); + cKeywords.add("JMC", Token.KEYWORD1); + cKeywords.add("READ", Token.KEYWORD1); + cKeywords.add("WRITE", Token.KEYWORD1); + } + return cKeywords; + } + + // private members + private static KeywordMap cKeywords; + + private KeywordMap keywords; + private int lastOffset; + private int lastKeyword; + + private boolean doKeyword(Segment line, int i, char c) { + int i1 = i + 1; + + int len = i - lastKeyword; + byte id = keywords.lookup(line, lastKeyword, len); + if (id != Token.NULL) { + if (lastKeyword != lastOffset) + addToken(lastKeyword - lastOffset, Token.NULL); + addToken(len, id); + lastOffset = i; + } + lastKeyword = i1; + return false; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.java new file mode 100644 index 0000000..d3c2c9f --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTokenMarker.java @@ -0,0 +1,212 @@ +/* + * CTokenMarker.java - C token marker + * Copyright (C) 1998, 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; + +import javax.swing.text.Segment; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.KeywordMap; + +/** + * C token marker. + * + * @author Slava Pestov + */ +public class CTokenMarker extends TokenMarker { + public CTokenMarker() { + this(true, getKeywords()); + } + + public CTokenMarker(boolean cpp, KeywordMap keywords) { + this.cpp = cpp; + this.keywords = keywords; + } + + public byte markTokensImpl(byte token, Segment line, int lineIndex) { + char[] array = line.array; + int offset = line.offset; + lastOffset = offset; + lastKeyword = offset; + int length = line.count + offset; + boolean backslash = false; + + loop: for (int i = offset; i < length; i++) { + int i1 = (i + 1); + + char c = array[i]; + if (c == '\\') { + backslash = !backslash; + continue; + } + + switch (token) { + case Token.NULL: + switch (c) { + case '#': + if (backslash) + backslash = false; + else if (cpp) { + if (doKeyword(line, i, c)) + break; + addToken(i - lastOffset, token); + addToken(length - i, Token.KEYWORD2); + lastOffset = lastKeyword = length; + break loop; + } + break; + case '"': + doKeyword(line, i, c); + if (backslash) + backslash = false; + else { + addToken(i - lastOffset, token); + token = Token.LITERAL1; + lastOffset = lastKeyword = i; + } + break; + case '\'': + doKeyword(line, i, c); + if (backslash) + backslash = false; + else { + addToken(i - lastOffset, token); + token = Token.LITERAL2; + lastOffset = lastKeyword = i; + } + break; + case ':': + if (lastKeyword == offset) { + if (doKeyword(line, i, c)) + break; + backslash = false; + addToken(i1 - lastOffset, Token.LABEL); + lastOffset = lastKeyword = i1; + } else if (doKeyword(line, i, c)) + break; + break; + case '/': + backslash = false; + doKeyword(line, i, c); + if (length - i > 1) { + switch (array[i1]) { + case '*': + addToken(i - lastOffset, token); + lastOffset = lastKeyword = i; + if (length - i > 2 && array[i + 2] == '*') + token = Token.COMMENT2; + else + token = Token.COMMENT1; + break; + case '/': + addToken(i - lastOffset, token); + addToken(length - i, Token.COMMENT1); + lastOffset = lastKeyword = length; + break loop; + } + } + break; + default: + backslash = false; + if (!Character.isLetterOrDigit(c) && c != '_') + doKeyword(line, i, c); + break; + } + break; + case Token.COMMENT1: + case Token.COMMENT2: + backslash = false; + if (c == '*' && length - i > 1) { + if (array[i1] == '/') { + i++; + addToken((i + 1) - lastOffset, token); + token = Token.NULL; + lastOffset = lastKeyword = i + 1; + } + } + break; + case Token.LITERAL1: + if (backslash) + backslash = false; + else if (c == '"') { + addToken(i1 - lastOffset, token); + token = Token.NULL; + lastOffset = lastKeyword = i1; + } + break; + case Token.LITERAL2: + if (backslash) + backslash = false; + else if (c == '\'') { + addToken(i1 - lastOffset, Token.LITERAL1); + token = Token.NULL; + lastOffset = lastKeyword = i1; + } + break; + default: + throw new InternalError("Invalid state: " + token); + } + } + + if (token == Token.NULL) + doKeyword(line, length, '\0'); + + switch (token) { + case Token.LITERAL1: + case Token.LITERAL2: + addToken(length - lastOffset, Token.INVALID); + token = Token.NULL; + break; + case Token.KEYWORD2: + addToken(length - lastOffset, token); + if (!backslash) + token = Token.NULL; + default: + addToken(length - lastOffset, token); + break; + } + + return token; + } + + public static KeywordMap getKeywords() { + if (cKeywords == null) { + cKeywords = new KeywordMap(false); + cKeywords.add("int", Token.KEYWORD1); + cKeywords.add("const", Token.KEYWORD1); + cKeywords.add("else", Token.KEYWORD1); + cKeywords.add("if", Token.KEYWORD1); + cKeywords.add("return", Token.KEYWORD1); + cKeywords.add("while", Token.KEYWORD1); + } + return cKeywords; + } + + // private members + private static KeywordMap cKeywords; + + private boolean cpp; + private KeywordMap keywords; + private int lastOffset; + private int lastKeyword; + + private boolean doKeyword(Segment line, int i, char c) { + int i1 = i + 1; + + int len = i - lastKeyword; + byte id = keywords.lookup(line, lastKeyword, len); + if (id != Token.NULL) { + if (lastKeyword != lastOffset) + addToken(lastKeyword - lastOffset, Token.NULL); + addToken(len, id); + lastOffset = i; + } + lastKeyword = i1; + return false; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.java new file mode 100644 index 0000000..b7faf0f --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CTransTokenMarker.java @@ -0,0 +1,238 @@ +/* + * CTokenMarker.java - C token marker + * Copyright (C) 1998, 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; + +import javax.swing.text.Segment; + +import org.jalgo.module.am0c0.gui.jeditor.jedit.KeywordMap; + +/** + * C token marker. + * + * @author Slava Pestov + */ +public class CTransTokenMarker extends TokenMarker { + public CTransTokenMarker() { + this(true, getKeywords()); + } + + public CTransTokenMarker(boolean cpp, KeywordMap keywords) { + this.cpp = cpp; + this.keywords = keywords; + } + + public byte markTokensImpl(byte token, Segment line, int lineIndex) { + char[] array = line.array; + int offset = line.offset; + lastOffset = offset; + lastKeyword = offset; + int length = line.count + offset; + boolean backslash = false; + + loop: for (int i = offset; i < length; i++) { + int i1 = (i + 1); + + char c = array[i]; + if (c == '\\') { + backslash = !backslash; + continue; + } + + switch (token) { + case Token.NULL: + switch (c) { + case '#': + if (backslash) + backslash = false; + else if (cpp) { + if (doKeyword(line, i, c)) + break; + addToken(i - lastOffset, token); + addToken(length - i, Token.KEYWORD2); + lastOffset = lastKeyword = length; + break loop; + } + break; + case '"': + doKeyword(line, i, c); + if (backslash) + backslash = false; + else { + addToken(i - lastOffset, token); + token = Token.LITERAL1; + lastOffset = lastKeyword = i; + } + break; + case '\'': + doKeyword(line, i, c); + if (backslash) + backslash = false; + else { + addToken(i - lastOffset, token); + token = Token.LITERAL2; + lastOffset = lastKeyword = i; + } + break; + case ':': + if (lastKeyword == offset) { + if (doKeyword(line, i, c)) + break; + backslash = false; + addToken(i1 - lastOffset, Token.LABEL); + lastOffset = lastKeyword = i1; + } else if (doKeyword(line, i, c)) + break; + break; + case '/': + backslash = false; + doKeyword(line, i, c); + if (length - i > 1) { + switch (array[i1]) { + case '*': + addToken(i - lastOffset, token); + lastOffset = lastKeyword = i; + if (length - i > 2 && array[i + 2] == '*') + token = Token.COMMENT2; + else + token = Token.COMMENT1; + break; + case '/': + addToken(i - lastOffset, token); + addToken(length - i, Token.COMMENT1); + lastOffset = lastKeyword = length; + break loop; + } + } + break; + default: + backslash = false; + if (!Character.isLetterOrDigit(c) && c != '_') + doKeyword(line, i, c); + break; + } + break; + case Token.COMMENT1: + case Token.COMMENT2: + backslash = false; + if (c == '*' && length - i > 1) { + if (array[i1] == '/') { + i++; + addToken((i + 1) - lastOffset, token); + token = Token.NULL; + lastOffset = lastKeyword = i + 1; + } + } + break; + case Token.LITERAL1: + if (backslash) + backslash = false; + else if (c == '"') { + addToken(i1 - lastOffset, token); + token = Token.NULL; + lastOffset = lastKeyword = i1; + } + break; + case Token.LITERAL2: + if (backslash) + backslash = false; + else if (c == '\'') { + addToken(i1 - lastOffset, Token.LITERAL1); + token = Token.NULL; + lastOffset = lastKeyword = i1; + } + break; + default: + throw new InternalError("Invalid state: " + token); + } + } + + if (token == Token.NULL) + doKeyword(line, length, '\0'); + + switch (token) { + case Token.LITERAL1: + case Token.LITERAL2: + addToken(length - lastOffset, Token.INVALID); + token = Token.NULL; + break; + case Token.KEYWORD2: + addToken(length - lastOffset, token); + if (!backslash) + token = Token.NULL; + default: + addToken(length - lastOffset, token); + break; + } + + return token; + } + + public static KeywordMap getKeywords() { + if (cKeywords == null) { + cKeywords = new KeywordMap(false); + cKeywords.add("int", Token.KEYWORD3); + cKeywords.add("const", Token.KEYWORD3); + cKeywords.add("else", Token.KEYWORD3); + cKeywords.add("if", Token.KEYWORD3); + cKeywords.add("return", Token.KEYWORD3); + cKeywords.add("while", Token.KEYWORD3); + + cKeywords.add("trans", Token.KEYWORD1); + cKeywords.add("blocktrans", Token.KEYWORD1); + cKeywords.add("stseqtrans", Token.KEYWORD1); + cKeywords.add("sttrans", Token.KEYWORD1); + cKeywords.add("simpleexptrans", Token.KEYWORD1); + cKeywords.add("boolexptrans", Token.KEYWORD1); + + cKeywords.add("ADD", Token.KEYWORD1); + cKeywords.add("MUL", Token.KEYWORD1); + cKeywords.add("SUB", Token.KEYWORD1); + cKeywords.add("DIV", Token.KEYWORD1); + cKeywords.add("MOD", Token.KEYWORD1); + cKeywords.add("LT", Token.KEYWORD1); + cKeywords.add("EQ", Token.KEYWORD1); + cKeywords.add("NE", Token.KEYWORD1); + cKeywords.add("GT", Token.KEYWORD1); + cKeywords.add("LE", Token.KEYWORD1); + cKeywords.add("GE", Token.KEYWORD1); + cKeywords.add("LOAD", Token.KEYWORD1); + cKeywords.add("LIT", Token.KEYWORD1); + cKeywords.add("STORE", Token.KEYWORD1); + cKeywords.add("JMP", Token.KEYWORD1); + cKeywords.add("JMC", Token.KEYWORD1); + cKeywords.add("READ", Token.KEYWORD1); + cKeywords.add("WRITE", Token.KEYWORD1); + } + return cKeywords; + } + + // private members + private static KeywordMap cKeywords; + + private boolean cpp; + private KeywordMap keywords; + private int lastOffset; + private int lastKeyword; + + private boolean doKeyword(Segment line, int i, char c) { + int i1 = i + 1; + + int len = i - lastKeyword; + byte id = keywords.lookup(line, lastKeyword, len); + if (id != Token.NULL) { + if (lastKeyword != lastOffset) + addToken(lastKeyword - lastOffset, Token.NULL); + addToken(len, id); + lastOffset = i; + } + lastKeyword = i1; + return false; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Entries b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Entries new file mode 100644 index 0000000..5064b97 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Entries @@ -0,0 +1,6 @@ +/AM0TokenMarker.java/1.1/Mon Aug 16 12:05:48 2010// +/CTokenMarker.java/1.2/Wed Dec 8 13:01:52 2010// +/CTransTokenMarker.java/1.2/Wed Dec 8 13:01:52 2010// +/Token.java/1.2/Wed Dec 8 13:01:52 2010// +/TokenMarker.java/1.2/Wed Dec 8 13:01:52 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Repository b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Repository new file mode 100644 index 0000000..3ac35ac --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Root b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.java new file mode 100644 index 0000000..69e2a6e --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/Token.java @@ -0,0 +1,149 @@ +/* + * Token.java - Generic token + * Copyright (C) 1998, 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; + +/** + * A linked list of tokens. Each token has three fields - a token + * identifier, which is a byte value that can be looked up in the + * array returned by SyntaxDocument.getColors() + * to get a color value, a length value which is the length of the + * token in the text, and a pointer to the next token in the list. + * + * @author Slava Pestov + */ + +public class Token +{ + /** + * Normal text token id. This should be used to mark + * normal text. + */ + public static final byte NULL = 0; + + /** + * Comment 1 token id. This can be used to mark a comment. + */ + public static final byte COMMENT1 = 1; + + /** + * Comment 2 token id. This can be used to mark a comment. + */ + public static final byte COMMENT2 = 2; + + + /** + * Literal 1 token id. This can be used to mark a string + * literal (eg, C mode uses this to mark "..." literals) + */ + public static final byte LITERAL1 = 3; + + /** + * Literal 2 token id. This can be used to mark an object + * literal (eg, Java mode uses this to mark true, false, etc) + */ + public static final byte LITERAL2 = 4; + + /** + * Label token id. This can be used to mark labels + * (eg, C mode uses this to mark ...: sequences) + */ + public static final byte LABEL = 5; + + /** + * Keyword 1 token id. This can be used to mark a + * keyword. This should be used for general language + * constructs. + */ + public static final byte KEYWORD1 = 6; + + /** + * Keyword 2 token id. This can be used to mark a + * keyword. This should be used for preprocessor + * commands, or variables. + */ + public static final byte KEYWORD2 = 7; + + /** + * Keyword 3 token id. This can be used to mark a + * keyword. This should be used for data types. + */ + public static final byte KEYWORD3 = 8; + + /** + * Operator token id. This can be used to mark an + * operator. (eg, SQL mode marks +, -, etc with this + * token type) + */ + public static final byte OPERATOR = 9; + + /** + * Invalid token id. This can be used to mark invalid + * or incomplete tokens, so the user can easily spot + * syntax errors. + */ + public static final byte INVALID = 10; + + /** + * The total number of defined token ids. + */ + public static final byte ID_COUNT = 11; + + /** + * The first id that can be used for internal state + * in a token marker. + */ + public static final byte INTERNAL_FIRST = 100; + + /** + * The last id that can be used for internal state + * in a token marker. + */ + public static final byte INTERNAL_LAST = 126; + + /** + * The token type, that along with a length of 0 + * marks the end of the token list. + */ + public static final byte END = 127; + + /** + * The length of this token. + */ + public int length; + + /** + * The id of this token. + */ + public byte id; + + /** + * The next token in the linked list. + */ + public Token next; + + /** + * Creates a new token. + * @param length The length of the token + * @param id The id of the token + */ + public Token(int length, byte id) + { + this.length = length; + this.id = id; + } + + /** + * Returns a string representation of this token. + */ + public String toString() + { + return "[id=" + id + ",length=" + length + "]"; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.java new file mode 100644 index 0000000..16d35db --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/TokenMarker.java @@ -0,0 +1,343 @@ +/* + * TokenMarker.java - Generic token marker + * Copyright (C) 1998, 1999 Slava Pestov + * + * You may use and modify this package for any purpose. Redistribution is + * permitted, in both source and binary form, provided that this notice + * remains intact in all source distributions of this package. + */ + +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; + +import javax.swing.text.Segment; + +/** + * A token marker that splits lines of text into tokens. Each token carries + * a length field and an indentification tag that can be mapped to a color + * for painting that token.

      + * + * For performance reasons, the linked list of tokens is reused after each + * line is tokenized. Therefore, the return value of markTokens + * should only be used for immediate painting. Notably, it cannot be + * cached. + * + * @author Slava Pestov + * + * @see jedit.tokenmarker.syntax.jedit.Token + */ +public abstract class TokenMarker +{ + /** + * A wrapper for the lower-level markTokensImpl method + * that is called to split a line up into tokens. + * @param line The line + * @param lineIndex The line number + */ + public Token markTokens(Segment line, int lineIndex) + { + if(lineIndex >= length) + { + throw new IllegalArgumentException("Tokenizing invalid line: " + + lineIndex); + } + + lastToken = null; + + LineInfo info = lineInfo[lineIndex]; + LineInfo prev; + if(lineIndex == 0) + prev = null; + else + prev = lineInfo[lineIndex - 1]; + + byte oldToken = info.token; + byte token = markTokensImpl(prev == null ? + Token.NULL : prev.token,line,lineIndex); + + info.token = token; + + /* + * This is a foul hack. It stops nextLineRequested + * from being cleared if the same line is marked twice. + * + * Why is this necessary? It's all JEditTextArea's fault. + * When something is inserted into the text, firing a + * document event, the insertUpdate() method shifts the + * caret (if necessary) by the amount inserted. + * + * All caret movement is handled by the select() method, + * which eventually pipes the new position to scrollTo() + * and calls repaint(). + * + * Note that at this point in time, the new line hasn't + * yet been painted; the caret is moved first. + * + * scrollTo() calls offsetToX(), which tokenizes the line + * unless it is being called on the last line painted + * (in which case it uses the text area's painter cached + * token list). What scrollTo() does next is irrelevant. + * + * After scrollTo() has done it's job, repaint() is + * called, and eventually we end up in paintLine(), whose + * job is to paint the changed line. It, too, calls + * markTokens(). + * + * The problem was that if the line started a multiline + * token, the first markTokens() (done in offsetToX()) + * would set nextLineRequested (because the line end + * token had changed) but the second would clear it + * (because the line was the same that time) and therefore + * paintLine() would never know that it needed to repaint + * subsequent lines. + * + * This bug took me ages to track down, that's why I wrote + * all the relevant info down so that others wouldn't + * duplicate it. + */ + if(!(lastLine == lineIndex && nextLineRequested)) + nextLineRequested = (oldToken != token); + + lastLine = lineIndex; + + addToken(0,Token.END); + + return firstToken; + } + + /** + * An abstract method that splits a line up into tokens. It + * should parse the line, and call addToken() to + * add syntax tokens to the token list. Then, it should return + * the initial token type for the next line.

      + * + * For example if the current line contains the start of a + * multiline comment that doesn't end on that line, this method + * should return the comment token type so that it continues on + * the next line. + * + * @param token The initial token type for this line + * @param line The line to be tokenized + * @param lineIndex The index of the line in the document, + * starting at 0 + * @return The initial token type for the next line + */ + protected abstract byte markTokensImpl(byte token, Segment line, + int lineIndex); + + /** + * Returns if the token marker supports tokens that span multiple + * lines. If this is true, the object using this token marker is + * required to pass all lines in the document to the + * markTokens() method (in turn).

      + * + * The default implementation returns true; it should be overridden + * to return false on simpler token markers for increased speed. + */ + public boolean supportsMultilineTokens() + { + return true; + } + + /** + * Informs the token marker that lines have been inserted into + * the document. This inserts a gap in the lineInfo + * array. + * @param index The first line number + * @param lines The number of lines + */ + public void insertLines(int index, int lines) + { + if(lines <= 0) + return; + length += lines; + ensureCapacity(length); + int len = index + lines; + System.arraycopy(lineInfo,index,lineInfo,len, + lineInfo.length - len); + + for(int i = index + lines - 1; i >= index; i--) + { + lineInfo[i] = new LineInfo(); + } + } + + /** + * Informs the token marker that line have been deleted from + * the document. This removes the lines in question from the + * lineInfo array. + * @param index The first line number + * @param lines The number of lines + */ + public void deleteLines(int index, int lines) + { + if (lines <= 0) + return; + int len = index + lines; + length -= lines; + System.arraycopy(lineInfo,len,lineInfo, + index,lineInfo.length - len); + } + + /** + * Returns the number of lines in this token marker. + */ + public int getLineCount() + { + return length; + } + + /** + * Returns true if the next line should be repainted. This + * will return true after a line has been tokenized that starts + * a multiline token that continues onto the next line. + */ + public boolean isNextLineRequested() + { + return nextLineRequested; + } + + // protected members + + /** + * The first token in the list. This should be used as the return + * value from markTokens(). + */ + protected Token firstToken; + + /** + * The last token in the list. New tokens are added here. + * This should be set to null before a new line is to be tokenized. + */ + protected Token lastToken; + + /** + * An array for storing information about lines. It is enlarged and + * shrunk automatically by the insertLines() and + * deleteLines() methods. + */ + protected LineInfo[] lineInfo; + + /** + * The number of lines in the model being tokenized. This can be + * less than the length of the lineInfo array. + */ + protected int length; + + /** + * The last tokenized line. + */ + protected int lastLine; + + /** + * True if the next line should be painted. + */ + protected boolean nextLineRequested; + + /** + * Creates a new TokenMarker. This DOES NOT create + * a lineInfo array; an initial call to insertLines() + * does that. + */ + protected TokenMarker() + { + lastLine = -1; + } + + /** + * Ensures that the lineInfo array can contain the + * specified index. This enlarges it if necessary. No action is + * taken if the array is large enough already.

      + * + * It should be unnecessary to call this under normal + * circumstances; insertLine() should take care of + * enlarging the line info array automatically. + * + * @param index The array index + */ + protected void ensureCapacity(int index) + { + if(lineInfo == null) + lineInfo = new LineInfo[index + 1]; + else if(lineInfo.length <= index) + { + LineInfo[] lineInfoN = new LineInfo[(index + 1) * 2]; + System.arraycopy(lineInfo,0,lineInfoN,0, + lineInfo.length); + lineInfo = lineInfoN; + } + } + + /** + * Adds a token to the token list. + * @param length The length of the token + * @param id The id of the token + */ + protected void addToken(int length, byte id) + { + if(id >= Token.INTERNAL_FIRST && id <= Token.INTERNAL_LAST) + throw new InternalError("Invalid id: " + id); + + if(length == 0 && id != Token.END) + return; + + if(firstToken == null) + { + firstToken = new Token(length,id); + lastToken = firstToken; + } + else if(lastToken == null) + { + lastToken = firstToken; + firstToken.length = length; + firstToken.id = id; + } + else if(lastToken.next == null) + { + lastToken.next = new Token(length,id); + lastToken = lastToken.next; + } + else + { + lastToken = lastToken.next; + lastToken.length = length; + lastToken.id = id; + } + } + + /** + * Inner class for storing information about tokenized lines. + */ + public static class LineInfo + { + /** + * Creates a new LineInfo object with token = Token.NULL + * and obj = null. + */ + public LineInfo() + { + } + + /** + * Creates a new LineInfo object with the specified + * parameters. + */ + public LineInfo(byte token, Object obj) + { + this.token = token; + this.obj = obj; + } + + /** + * The id of the last token of the line. + */ + public byte token; + + /** + * This is for use by the token marker implementations + * themselves. It can be used to store anything that + * is an object and that needs to exist on a per-line + * basis. + */ + public Object obj; + } +} diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.java b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.java new file mode 100644 index 0000000..00310b6 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/jedit/tokenmarker/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes controlling the syntax highlighting in the editor. + */ +package org.jalgo.module.am0c0.gui.jeditor.jedit.tokenmarker; diff --git a/src/org/jalgo/module/am0c0/gui/jeditor/package-info.java b/src/org/jalgo/module/am0c0/gui/jeditor/package-info.java new file mode 100644 index 0000000..015f9bc --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/jeditor/package-info.java @@ -0,0 +1,5 @@ +/** + * Editor which is used to show and handle am0 and c0 code. + */ +package org.jalgo.module.am0c0.gui.jeditor; + diff --git a/src/org/jalgo/module/am0c0/gui/package-info.java b/src/org/jalgo/module/am0c0/gui/package-info.java new file mode 100644 index 0000000..d59e596 --- /dev/null +++ b/src/org/jalgo/module/am0c0/gui/package-info.java @@ -0,0 +1,5 @@ +/** + * All elements to build and show the GUI and handle user input. + */ +package org.jalgo.module.am0c0.gui; + diff --git a/src/org/jalgo/module/am0c0/model/AM0History.java b/src/org/jalgo/module/am0c0/model/AM0History.java new file mode 100644 index 0000000..0611696 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/AM0History.java @@ -0,0 +1,164 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.jalgo.module.am0c0.model.am0.MachineConfiguration; +import org.jalgo.module.am0c0.model.c0.ast.C0AST; + +/** + * History to store already calculated elements like + * {@link MachineConfiguration} or {@link C0AST}. + * + * @author Max Leuthäuser + */ +public class AM0History implements Iterator { + private List history; + private int currentIndex; + + public AM0History() { + history = new ArrayList(); + currentIndex = 0; + } + + /** + * @return true if there is one more element in the history, false + * otherwise. + * + * @see java.util.Iterator#hasNext() + */ + @Override + public boolean hasNext() { + return currentIndex < history.size(); + } + + /** + * @return true if there is one more previous element in the history, false + * otherwise. + * + */ + public boolean hasPrevious() { + return currentIndex > 0; + } + + /** + * @return the next element in the history if this exists, null + * otherwise. + * + * @see java.util.Iterator#next() + */ + @Override + public T next() { + if (hasNext()) { + currentIndex++; + return history.get(currentIndex); + } + return null; + } + + /** + * @return the previous element in the history if this exists, null + * otherwise. + * + */ + public T previous() { + if (hasPrevious()) { + currentIndex--; + return history.get(currentIndex); + } + return null; + } + + @Override + public void remove() { + throw new AbstractMethodError( + "Calling this method is not allowed for this class."); + } + + /** + * @return the current size of the history. + */ + public int getCount() { + return history.size(); + } + + /** + * @return the current index. + */ + public int getCurrentIndex() { + return currentIndex; + } + + /** + * Add an object of type T to the history. + * + * @param m + * Element of type T which should be added. + * @throws IllegalArgumentException + */ + public void add(T m) throws IllegalArgumentException { + if (m != null) { + currentIndex++; + for (int killIndex = currentIndex; killIndex < history.size(); killIndex++) { + history.remove(killIndex); + } + history.add(m); + } else + throw new IllegalArgumentException( + "Null arguments are not allowed here!"); + } + + /** + * Deletes all entries in the history. + */ + public void clear() { + history.clear(); + } + + /** + * @return The object which is the last one in this history. + */ + public T getLastElement() { + return history.get(history.size() - 1); + } + + /** + * @param s + * Step to check. + * @return true if this step exists already in the history. + */ + public boolean stepExists(int s) { + return history.size() > s; + } + + /** + * @param step + * @return the object at this step in the history. + */ + public T getAtStep(int step) { + return history.get(step); + } +} diff --git a/src/org/jalgo/module/am0c0/model/AM0PagingTableModel.java b/src/org/jalgo/module/am0c0/model/AM0PagingTableModel.java new file mode 100644 index 0000000..9df4fa1 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/AM0PagingTableModel.java @@ -0,0 +1,384 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +import java.util.ArrayList; +import java.util.List; +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Polygon; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ScrollPaneConstants; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.gui.SimulationView; +import org.jalgo.module.am0c0.model.am0.MachineConfiguration; + +/** + * Simple paging table model which shows only a given number of lines at one + * time. + * + * @author Max Leuthäuser + */ +public class AM0PagingTableModel extends AbstractTableModel { + private static final long serialVersionUID = 1L; + protected int pageSize; + protected int pageOffset; + protected List data; + private final String[] header = { Messages.getString("am0c0", "AM0PagingTableModel.0"), Messages.getString("am0c0", "AM0PagingTableModel.1"), Messages.getString("am0c0", "AM0PagingTableModel.2"), Messages.getString("am0c0", "AM0PagingTableModel.3"), Messages.getString("am0c0", "AM0PagingTableModel.4") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ + private int rowCount = 0; + private static final int STANDARD_PAGE_SIZE = 50; + private SimulationView simView; + + public AM0PagingTableModel(SimulationView v) { + data = new ArrayList(); + pageSize = STANDARD_PAGE_SIZE; + simView = v; + } + + /** + * Update the row count to fit to the currently shows values. + */ + private void updateRowCount() { + if (data.isEmpty()) { + rowCount = 0; + return; + } + if (data.size() % pageSize == 0) { + rowCount = pageSize; + return; + } + rowCount = data.size() % pageSize; + } + + /** + * Return values appropriate for the visible table part. + * + * @see javax.swing.table.TableModel#getRowCount() + */ + public int getRowCount() { + return rowCount; + } + + /* + * (non-Javadoc) + * + * @see javax.swing.table.TableModel#getColumnCount() + */ + public int getColumnCount() { + return header.length; + } + + /** + * Work only on the visible part of the table. + * + * @see javax.swing.table.TableModel#getValueAt(int, int) + */ + public Object getValueAt(int row, int col) { + int realRow = row + (pageOffset * pageSize); + + switch (col) { + case 0: + return data.get(realRow).getProgramCounter(); + case 1: + return data.get(realRow).getStack(); + case 2: + return data.get(realRow).getRam(); + case 3: + return data.get(realRow).getInputStream(); + case 4: + return data.get(realRow).getOutputStream(); + default: + throw new IllegalArgumentException("Col has to be between 0 and 4!"); //$NON-NLS-1$ + } + } + + /* + * (non-Javadoc) + * + * @see javax.swing.table.AbstractTableModel#getColumnName(int) + */ + @Override + public String getColumnName(int col) { + return header[col]; + } + + /** + * Use this method to figure out which page you are on. + * + * @return the number of the page which is currently shown. + */ + public int getPageOffset() { + return pageOffset; + } + + /** + * Add a new row containing the values of a {@link MachineConfiguration}. + * + * @param m + */ + public void addRow(MachineConfiguration m) { + data.add(m); + fireTableDataChanged(); + updateRowCount(); + pageDown(); + } + + /** + * Show only the last page. + */ + public void showLastPage() { + if (pageOffset < getPageCount()) { + while (pageDown()) { + } + ; + } + } + + /** + * Show only the fist page. + */ + public void showFirstPage() { + while (pageUp()) { + } + ; + } + + /** + * Remove the last page and call {@link AM0PagingTableModel#pageUp()} if + * necessary. + */ + public void removeLastRow() { + data.remove(data.size() - 1); + updateRowCount(); + fireTableDataChanged(); + if (data.size() % pageSize == 0) + pageUp(); + } + + /** + * Delete all entries. + */ + public void clear() { + data.clear(); + pageOffset = 0; + rowCount = 0; + fireTableDataChanged(); + simView.getRangeLabel().setText(""); //$NON-NLS-1$ + } + + /** + * @return the number of pages needed. + */ + public int getPageCount() { + return (int) Math.ceil((double) data.size() / (double) pageSize); + } + + /** + * Use this method if you want to know how big the real table is. + * + * @return the size of the underlying model. + */ + public int getRealRowCount() { + return data.size(); + } + + /** + * @return the standard page size. + */ + public int getPageSize() { + return pageSize; + } + + /** + * Set a new page size. Not needed here. + * + * @param s + * @deprecated + */ + @Deprecated + public void setPageSize(int s) { + if (s == pageSize) { + return; + } + int oldPageSize = pageSize; + pageSize = s; + pageOffset = (oldPageSize * pageOffset) / pageSize; + fireTableDataChanged(); + } + + /** + * Update the page offset and fire a data changed (all rows). + * + * @return true if a page down was successful, false otherwise + */ + public boolean pageDown() { + if (pageOffset < getPageCount() - 1) { + pageOffset++; + rowCount = pageSize; + if ((pageOffset == getPageCount() - 1)) { + updateRowCount(); + } + fireTableDataChanged(); + simView.getRangeLabel().setText( + Messages.getString("am0c0", "AM0PagingTableModel.7") //$NON-NLS-1$ + + (getPageOffset() == 0 ? 1 + : (getPageSize() * getPageOffset())) + + Messages.getString("am0c0", "AM0PagingTableModel.8") //$NON-NLS-1$ + + (getPageSize() * (getPageOffset() + 1)) + + Messages.getString("am0c0", "AM0PagingTableModel.9")); //$NON-NLS-1$ + return true; + } + return false; + } + + /** + * Update the page offset and fire a data changed (all rows). + * + * @return true if a page up was successful, false otherwise + */ + public boolean pageUp() { + if (pageOffset > 0) { + pageOffset--; + rowCount = pageSize; + fireTableDataChanged(); + simView.getRangeLabel().setText( + Messages.getString("am0c0", "AM0PagingTableModel.10") //$NON-NLS-1$ + + (getPageOffset() == 0 ? 1 + : (getPageSize() * getPageOffset())) + + Messages.getString("am0c0", "AM0PagingTableModel.11") //$NON-NLS-1$ + + (getPageSize() * (getPageOffset() + 1)) + + Messages.getString("am0c0", "AM0PagingTableModel.12")); //$NON-NLS-1$ + return true; + } + return false; + } + + /** + * We provide our own version of a {@link JScrollPane} that includes the + * page up and page down buttons by default. + * + * @param jt + * {@link JTable} + * @return a {@link JScrollPane} with our page up/down buttons and the table + */ + public static JScrollPane createPagingScrollPaneForTable(JTable jt) { + JScrollPane jsp = new JScrollPane(jt); + TableModel tmodel = jt.getModel(); + + if (!(tmodel instanceof AM0PagingTableModel)) { + return jsp; + } + + final AM0PagingTableModel model = (AM0PagingTableModel) tmodel; + final JButton upButton = new JButton(new ArrowIcon(ArrowIcon.UP)); + final JButton downButton = new JButton(new ArrowIcon(ArrowIcon.DOWN)); + + upButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + model.pageUp(); + } + }); + + downButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + model.pageDown(); + } + }); + + // Turn on the scrollbars - otherwise we won't get our corners. + jsp + .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + jsp + .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + + // Add in the corners (page up/down). + jsp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, upButton); + jsp.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, downButton); + + return jsp; + } +} + +/** + * Class which represents the corner up/down buttons used in + * {@link AM0PagingTableModel}. + * + * @author Max Leuthäuser + */ +class ArrowIcon implements Icon { + + public static final int UP = 0; + + public static final int DOWN = 1; + + private int direction; + + private Polygon pagePolygon = new Polygon(new int[] { 2, 4, 4, 10, 10, 2 }, + new int[] { 4, 4, 2, 2, 12, 12 }, 6); + + private int[] arrowX = { 4, 9, 6 }; + + private Polygon arrowUpPolygon = new Polygon(arrowX, + new int[] { 10, 10, 4 }, 3); + + private Polygon arrowDownPolygon = new Polygon(arrowX, + new int[] { 6, 6, 11 }, 3); + + public ArrowIcon(int which) { + direction = which; + } + + public int getIconWidth() { + return 14; + } + + public int getIconHeight() { + return 14; + } + + public void paintIcon(Component c, Graphics g, int x, int y) { + g.setColor(Color.black); + pagePolygon.translate(x, y); + g.drawPolygon(pagePolygon); + pagePolygon.translate(-x, -y); + if (direction == UP) { + arrowUpPolygon.translate(x, y); + g.fillPolygon(arrowUpPolygon); + arrowUpPolygon.translate(-x, -y); + } else { + arrowDownPolygon.translate(x, y); + g.fillPolygon(arrowDownPolygon); + arrowDownPolygon.translate(-x, -y); + } + } +} diff --git a/src/org/jalgo/module/am0c0/model/Address.java b/src/org/jalgo/module/am0c0/model/Address.java new file mode 100644 index 0000000..77fa01c --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/Address.java @@ -0,0 +1,62 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +/** + * Abstract base class for machine address information + * + * @author Felix Schmitt + * + */ + +public abstract class Address { + protected boolean visible; + + /** + * sets visibility + * + * @param visible + * new visibility + */ + public void setVisible(boolean visible) { + this.visible = visible; + } + + /** + * returns visibility + * + * @return the visibility + */ + public boolean isVisible() { + return visible; + } + + @Override + public abstract String toString(); + + @Override + public abstract boolean equals(Object o); + + @Override + public abstract int hashCode(); +} diff --git a/src/org/jalgo/module/am0c0/model/AddressException.java b/src/org/jalgo/module/am0c0/model/AddressException.java new file mode 100644 index 0000000..7e5a541 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/AddressException.java @@ -0,0 +1,42 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +/** + * Exception indicating an error in handling {@link Address} and derived classes + * + * @author Felix Schmitt + * + */ +public class AddressException extends Exception { + + private static final long serialVersionUID = 1L; + + public AddressException() { + super(); + } + + public AddressException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/am0c0/model/C0History.java b/src/org/jalgo/module/am0c0/model/C0History.java new file mode 100644 index 0000000..a1406aa --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/C0History.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + + +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + +public class C0History { + private ListIterator iterator; + private List list; + + public C0History(){ + list = new ArrayList(); + iterator = list.listIterator(); + } + + public boolean hasNext() { + return iterator.hasNext(); + } + + public T next() { + return (T) iterator.next(); + } + + public boolean hasPrevious() { + return iterator.hasPrevious(); + } + + public T previous() { + return (T) iterator.previous(); + } + + public int getCount() { + return list.size(); + } + + public int getCurrentIndex() { + return iterator.nextIndex() - 1; + } + + public void add(T entity) { + // add the entity between the last returned element and the next element + iterator.add(entity); + + // remove all following elements + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + } + + public void remove(int index) { + + } +} diff --git a/src/org/jalgo/module/am0c0/model/CVS/Entries b/src/org/jalgo/module/am0c0/model/CVS/Entries new file mode 100644 index 0000000..aa849f3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/CVS/Entries @@ -0,0 +1,13 @@ +/AM0History.java/1.2/Wed Dec 8 13:01:53 2010// +/AM0PagingTableModel.java/1.1/Mon Aug 16 12:05:49 2010// +/Address.java/1.1/Mon Aug 16 12:05:49 2010// +/AddressException.java/1.1/Mon Aug 16 12:05:49 2010// +/C0History.java/1.1/Mon Aug 16 12:05:49 2010// +/CodeObject.java/1.1/Mon Aug 16 12:05:49 2010// +/GenericProgram.java/1.1/Mon Aug 16 12:05:49 2010// +/LineAddress.java/1.1/Mon Aug 16 12:05:49 2010// +/SimulationSet.java/1.1/Mon Aug 16 12:05:49 2010// +/TreeAddress.java/1.1/Mon Aug 16 12:05:49 2010// +D/am0//// +D/c0//// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/am0c0/model/CVS/Repository b/src/org/jalgo/module/am0c0/model/CVS/Repository new file mode 100644 index 0000000..134675c --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/model diff --git a/src/org/jalgo/module/am0c0/model/CVS/Root b/src/org/jalgo/module/am0c0/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/model/CodeObject.java b/src/org/jalgo/module/am0c0/model/CodeObject.java new file mode 100644 index 0000000..c1f7348 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/CodeObject.java @@ -0,0 +1,87 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +/** + * Abstract basic code model which has an {@link Address} and code text + * + * @author Felix Schmitt + * + */ +public abstract class CodeObject { + + protected Address address; + + /** + * constructor + * + * @param address + * the {@link Address} of this CodeObject + */ + public CodeObject(Address address) { + setAddress(address); + } + + /** + * returns the string representation (address + code text) + * + * @return string representation + */ + @Override + public String toString() { + return getAddress().toString() + ": " + getCodeText(); + } + + /** + * returns the {@link Address} associated with this code + * + * @return the {@link Address} + */ + public Address getAddress() { + return address; + } + + /** + * sets the {@link Address} associated with this code + * + * @param address + * new {@link Address} + */ + public void setAddress(Address address) { + this.address = address; + } + + /** + * returns the code text as a string + * + * @return code text String + */ + public abstract String getCodeText(); + + /** + * returns the number of lines this code spans over + * + * @return number of lines + */ + public abstract int getLinesCount(); +} diff --git a/src/org/jalgo/module/am0c0/model/GenericProgram.java b/src/org/jalgo/module/am0c0/model/GenericProgram.java new file mode 100644 index 0000000..cec7104 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/GenericProgram.java @@ -0,0 +1,38 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +import java.util.ArrayList; + +/** + * Generic list of {@link CodeObject} which form a program + * @author Felix Schmitt + * + */ +public class GenericProgram extends ArrayList{ + + /** + * + */ + private static final long serialVersionUID = 1L; +} diff --git a/src/org/jalgo/module/am0c0/model/LineAddress.java b/src/org/jalgo/module/am0c0/model/LineAddress.java new file mode 100644 index 0000000..55bf135 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/LineAddress.java @@ -0,0 +1,96 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +/** + * provides line-based addresses + * + * @author Felix Schmitt + * + */ +public class LineAddress extends Address { + private int address; + + /** + * constructor + * + * @param address + * line number to initialize with + * @throws AddressException + */ + public LineAddress(int address) throws AddressException { + setLine(address); + setVisible(true); + } + + /** + * set the line number + * + * @param address + * new line number. must be >= 0 + */ + public void setLine(int address) throws AddressException { + if (address >= 0) + this.address = address; + else + throw new AddressException("A line address must not be < 0"); + } + + /** + * returns string representation + * + * @return string representation + */ + @Override + public String toString() { + return String.valueOf(address); + } + + /** + * returns the line number + * + * @return line number + */ + public int getLine() { + return address; + } + + @Override + /** + * compares two LineAddresses using their line numbers + */ + public boolean equals(Object o) { + return (o instanceof LineAddress) + && ((LineAddress) o).getLine() == getLine(); + } + + /** + * It is asserted that this method is never called. The implementation of + * {@link TreeAddress#equals(Object)}, however requests that one must + * override {@link Object#hashCode()}. + */ + @Override + public int hashCode() { + throw new AssertionError(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/SimulationSet.java b/src/org/jalgo/module/am0c0/model/SimulationSet.java new file mode 100644 index 0000000..a6ad6be --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/SimulationSet.java @@ -0,0 +1,56 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +import org.jalgo.module.am0c0.model.am0.MachineConfiguration; + +/** + * Represents an data set for a new simulation. This set is created by + * {@link AM0InputDialog}. + * + * @author Max Leuthäuser + */ +public class SimulationSet { + private int steps; + private MachineConfiguration m; + + public SimulationSet(MachineConfiguration m, int steps) { + this.m = m; + this.steps = steps; + } + + /** + * @return the {@link MachineConfiguration} which is stored here. + */ + public MachineConfiguration getMachineConfiguration() { + return m; + } + + /** + * @return the maximum number of steps the user wants to simulate at once. + */ + public int getSteps() { + return steps; + } + +} diff --git a/src/org/jalgo/module/am0c0/model/TreeAddress.java b/src/org/jalgo/module/am0c0/model/TreeAddress.java new file mode 100644 index 0000000..7bafa62 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/TreeAddress.java @@ -0,0 +1,121 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * provides tree structured addresses like 1.2.1.3 + * @author Felix Schmitt + * + */ +public class TreeAddress extends Address { + private List address; + + /** + * constructor + */ + public TreeAddress() { + this(null, false); + } + + /** + * constructor + * default visibility is false + * @param base base TreeAddress to copy from. null is allowed + */ + public TreeAddress(TreeAddress base) { + this(base, false); + } + + /** + * constructor + * @param base base TreeAddress to copy from. null is allowed + * @param visible the visibility of this TreeAddress + */ + public TreeAddress(TreeAddress base, boolean visible) { + setVisible(visible); + + if (base == null) { + address = new ArrayList(); + address.add(Integer.valueOf(1)); + } else { + address = new ArrayList(base.address); + } + } + + /** + * return string representation, e.g. 1.2.3 + * @return string representation + */ + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < address.size() - 1; i++) { + result.append(address.get(i).toString()); + result.append("."); + } + + result.append(address.get(address.size() - 1).toString()); + + return result.toString(); + } + + /** + * adds new level in address tree + * (e.g. extends 1.2 to 1.2.1) + */ + public void extend() { + address.add(Integer.valueOf(1)); + } + + /** + * increases the last (most bottom) level in address tree + * (e.g. increases 1.2 to 1.3) + */ + public void increase() { + int i = address.remove(address.size() - 1); + address.add(Integer.valueOf(i + 1)); + } + + @Override + /** + * compares two TreeAddresses using their String representations + */ + public boolean equals(Object o) { + return (o instanceof TreeAddress) + && ((TreeAddress) o).toString().equals(toString()); + } + + /** + * It is asserted that this method is never called. The implementation + * of {@link TreeAddress#equals(Object)}, however requests that one must + * override {@link Object#hashCode()}. + */ + @Override + public int hashCode() { + throw new AssertionError(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/AM0Program.java b/src/org/jalgo/module/am0c0/model/am0/AM0Program.java new file mode 100644 index 0000000..b025dbd --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/AM0Program.java @@ -0,0 +1,35 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.GenericProgram; + +/** + * Class which represents an AM0 program which contains + * {@link SimulationStatement}s. + * + * @author Max Leuthäuser + */ +public class AM0Program extends GenericProgram { + private static final long serialVersionUID = 1L; +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Add.java b/src/org/jalgo/module/am0c0/model/am0/Add.java new file mode 100644 index 0000000..6aca01b --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Add.java @@ -0,0 +1,65 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Add extends ArithmeticStatement { + public Add(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + Messages.getString("am0c0", "Add.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + configuration.getStack().push(arg1 + arg0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Add.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "ADD;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.java b/src/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.java new file mode 100644 index 0000000..5815247 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/ArithmeticStatement.java @@ -0,0 +1,40 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; + + +/** + * This class is a simple blueprint for all arithmetic or logic commands + * + * @author Max Leuthäuser + * @author David Voigt + */ +abstract class ArithmeticStatement extends SimulationStatement { + + public ArithmeticStatement(LineAddress address) { + super(address); + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/CVS/Entries b/src/org/jalgo/module/am0c0/model/am0/CVS/Entries new file mode 100644 index 0000000..24a97dd --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/CVS/Entries @@ -0,0 +1,35 @@ +/AM0Program.java/1.1/Mon Aug 16 12:05:48 2010// +/Add.java/1.1/Mon Aug 16 12:05:48 2010// +/ArithmeticStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/CompareStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/Div.java/1.1/Mon Aug 16 12:05:48 2010// +/Equal.java/1.1/Mon Aug 16 12:05:48 2010// +/GreaterEqual.java/1.1/Mon Aug 16 12:05:48 2010// +/GreaterThen.java/1.1/Mon Aug 16 12:05:48 2010// +/IOStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/IndexedMemoryCell.java/1.2/Wed Dec 8 13:01:53 2010// +/InputStream.java/1.1/Mon Aug 16 12:05:48 2010// +/Jmc.java/1.1/Mon Aug 16 12:05:48 2010// +/Jmp.java/1.1/Mon Aug 16 12:05:48 2010// +/JumpStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/LesserEqual.java/1.1/Mon Aug 16 12:05:48 2010// +/LesserThen.java/1.1/Mon Aug 16 12:05:48 2010// +/Lit.java/1.1/Mon Aug 16 12:05:48 2010// +/Load.java/1.1/Mon Aug 16 12:05:48 2010// +/MachineConfiguration.java/1.1/Mon Aug 16 12:05:48 2010// +/MemoryCell.java/1.1/Mon Aug 16 12:05:48 2010// +/MemoryStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/Mod.java/1.1/Mon Aug 16 12:05:48 2010// +/Mul.java/1.1/Mon Aug 16 12:05:48 2010// +/NotEqual.java/1.1/Mon Aug 16 12:05:48 2010// +/OutputStream.java/1.1/Mon Aug 16 12:05:48 2010// +/ProgramCounter.java/1.1/Mon Aug 16 12:05:48 2010// +/Ram.java/1.1/Mon Aug 16 12:05:48 2010// +/Read.java/1.1/Mon Aug 16 12:05:48 2010// +/SimulationStatement.java/1.1/Mon Aug 16 12:05:48 2010// +/Stack.java/1.1/Mon Aug 16 12:05:48 2010// +/Store.java/1.1/Mon Aug 16 12:05:48 2010// +/Stream.java/1.1/Mon Aug 16 12:05:48 2010// +/Sub.java/1.1/Mon Aug 16 12:05:48 2010// +/Write.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/model/am0/CVS/Repository b/src/org/jalgo/module/am0c0/model/am0/CVS/Repository new file mode 100644 index 0000000..b7c138b --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/model/am0 diff --git a/src/org/jalgo/module/am0c0/model/am0/CVS/Root b/src/org/jalgo/module/am0c0/model/am0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/model/am0/CompareStatement.java b/src/org/jalgo/module/am0c0/model/am0/CompareStatement.java new file mode 100644 index 0000000..00a333a --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/CompareStatement.java @@ -0,0 +1,37 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * This class is a simple blueprint for all compare commands + * + * @author David Voigt + */ +public abstract class CompareStatement extends SimulationStatement { + + public CompareStatement(LineAddress address) { + super(address); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Div.java b/src/org/jalgo/module/am0c0/model/am0/Div.java new file mode 100644 index 0000000..6d3758d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Div.java @@ -0,0 +1,70 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Div extends ArithmeticStatement { + + public Div(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException, ArithmeticException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Div.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + if (arg0 == 0) { + throw new ArithmeticException(Messages.getString("am0c0", "Div.1")); //$NON-NLS-1$ + } + + configuration.getStack().push(arg1 / arg0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Div.2"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "DIV;"; //$NON-NLS-1$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Equal.java b/src/org/jalgo/module/am0c0/model/am0/Equal.java new file mode 100644 index 0000000..69d6fc5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Equal.java @@ -0,0 +1,66 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Equal extends CompareStatement { + + public Equal(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Equal.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 == arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Equal.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "EQ;"; //$NON-NLS-1$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/GreaterEqual.java b/src/org/jalgo/module/am0c0/model/am0/GreaterEqual.java new file mode 100644 index 0000000..3a96957 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/GreaterEqual.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class GreaterEqual extends CompareStatement { + + public GreaterEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + Messages.getString("am0c0", "GreaterEqual.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 >= arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "GreaterEqual.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "GE;"; //$NON-NLS-1$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/GreaterThen.java b/src/org/jalgo/module/am0c0/model/am0/GreaterThen.java new file mode 100644 index 0000000..52b7c9f --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/GreaterThen.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class GreaterThen extends CompareStatement { + + public GreaterThen(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + Messages.getString("am0c0", "GreaterThen.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 > arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "GreaterThen.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "GT;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/IOStatement.java b/src/org/jalgo/module/am0c0/model/am0/IOStatement.java new file mode 100644 index 0000000..9f872d3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/IOStatement.java @@ -0,0 +1,38 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * This class is a simple blueprint for all read or write commands + * + * @author Max Leuthäuser + * @author David Voigt + */ +public abstract class IOStatement extends SimulationStatement { + + public IOStatement(LineAddress address) { + super(address); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.java b/src/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.java new file mode 100644 index 0000000..7bcd1bd --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/IndexedMemoryCell.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +/** + * This class represents a indexed memory cell which is used in the following + * abstract machine element:

    • {@link Ram}
    • + * + * @author Max Leuthäuser + */ +public class IndexedMemoryCell extends MemoryCell implements + Comparable { + private int index; + + public IndexedMemoryCell(int index, int value) { + super(value); + this.index = index; + } + + /** + * @return the index for this cell + */ + public int getIndex() { + return index; + } + + /** + * Set a new index for this cell + * + * @param index + */ + public void setIndex(final int index) { + this.index = index; + } + + @Override + public int hashCode() { + throw new AssertionError(); + } + + @Override + public boolean equals(Object o) { + return o instanceof IndexedMemoryCell + && ((IndexedMemoryCell) o).getIndex() == getIndex() + && ((IndexedMemoryCell) o).get() == get(); + } + + @Override + public int compareTo(IndexedMemoryCell o) { + return this.getIndex() - o.getIndex(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/InputStream.java b/src/org/jalgo/module/am0c0/model/am0/InputStream.java new file mode 100644 index 0000000..195b8db --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/InputStream.java @@ -0,0 +1,75 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents an input stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public class InputStream extends Stream { + + /** + * Create a new empty input stream + */ + public InputStream() { + super(); + } + + /** + * Copyconstructor + * + * @param i + * {@link InputStream} which should be copied. + */ + public InputStream(InputStream i) { + super(); + for (MemoryCell m : i.stream) { + this.stream.add(new MemoryCell(m.get())); + } + } + + /** + * Create a new input stream based on an already existing and filled list of + * values. + * + * @param initList + */ + public InputStream(final List initList) { + super(); + for (int i : initList) { + stream.add(new MemoryCell(i)); + } + } + + /** + * @return the first element of the input stream and remove it. + */ + public int read() { + return ((LinkedList) stream).remove().get(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Jmc.java b/src/org/jalgo/module/am0c0/model/am0/Jmc.java new file mode 100644 index 0000000..80cd15f --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Jmc.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Jmc extends JumpStatement { + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Jmc(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 1) { + throw new IllegalArgumentException( + Messages.getString("am0c0", "Jmc.0")); //$NON-NLS-1$ + } + if (configuration.getStack().pop() == 0) { + configuration.getProgramCounter().set(target); + } else { + configuration.getProgramCounter().inc(); + } + + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Jmc.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "JMC " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Jmp.java b/src/org/jalgo/module/am0c0/model/am0/Jmp.java new file mode 100644 index 0000000..f22a9d4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Jmp.java @@ -0,0 +1,68 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Jmp extends JumpStatement { + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Jmp(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) { + configuration.getProgramCounter().set(target); + return configuration; + + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Jmp.0"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "JMP " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/JumpStatement.java b/src/org/jalgo/module/am0c0/model/am0/JumpStatement.java new file mode 100644 index 0000000..74c4a2d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/JumpStatement.java @@ -0,0 +1,38 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * This class is a simple blueprint for all jump commands + * + * @author Max Leuthäuser + * @author David Voigt + */ +public abstract class JumpStatement extends SimulationStatement { + + public JumpStatement(LineAddress address) { + super(address); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/LesserEqual.java b/src/org/jalgo/module/am0c0/model/am0/LesserEqual.java new file mode 100644 index 0000000..1ed91e4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/LesserEqual.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class LesserEqual extends CompareStatement { + + public LesserEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "LesserEqual.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 <= arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "LesserEqual.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "LE;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/LesserThen.java b/src/org/jalgo/module/am0c0/model/am0/LesserThen.java new file mode 100644 index 0000000..e7af959 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/LesserThen.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class LesserThen extends CompareStatement { + + public LesserThen(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "LesserThen.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 < arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "LesserThen.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "LT;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Lit.java b/src/org/jalgo/module/am0c0/model/am0/Lit.java new file mode 100644 index 0000000..8773e81 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Lit.java @@ -0,0 +1,60 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Lit extends SimulationStatement { + + private int target; + + public Lit(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) { + configuration.getProgramCounter().inc(); + configuration.getStack().push(target); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Lit.0"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "LIT " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Load.java b/src/org/jalgo/module/am0c0/model/am0/Load.java new file mode 100644 index 0000000..9d78978 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Load.java @@ -0,0 +1,74 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Load extends MemoryStatement { + + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Load(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getRam().cellIsDefined(target)) { + configuration.getProgramCounter().inc(); + configuration.getStack().push(configuration.getRam().load(target)); + return configuration; + } else + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Load.0")); //$NON-NLS-1$ + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Load.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "LOAD " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/MachineConfiguration.java b/src/org/jalgo/module/am0c0/model/am0/MachineConfiguration.java new file mode 100644 index 0000000..459b386 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/MachineConfiguration.java @@ -0,0 +1,152 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +import java.util.LinkedList; +import java.util.TreeMap; + +/** + * Configuration for an abstract machine as introduced in the lectures. Holds + * the following elements: + * + *

      + *

    • {@link ProgramCounter}
    • + *
    • {@link Stack}
    • + *
    • {@link Ram}
    • + *
    • {@link InputStream}
    • + *
    • {@link OutputStream}
    • + *

      + *
      + * + *

      + * It is possible to do a deep copy. Use the copyconstructor: + * {@link MachineConfiguration#MachineConfiguration(MachineConfiguration)} + *

      + *
      + * + * @author Max Leuthäuser + */ +public class MachineConfiguration { + private ProgramCounter programCounter; + private Stack stack; + private Ram ram; + private InputStream inputStream; + private OutputStream outputStream; + + /** + * Creates an empty new machine configuration. + */ + public MachineConfiguration() { + programCounter = new ProgramCounter(); + stack = new Stack(); + ram = new Ram(); + inputStream = new InputStream(); + outputStream = new OutputStream(); + } + + /** + * Copyconstructor + * + * @param m + * {@link MachineConfiguration} which should be copied. + */ + public MachineConfiguration(MachineConfiguration m) { + if (m != null) { + programCounter = new ProgramCounter(m.getProgramCounter()); + stack = new Stack(m.getStack()); + ram = new Ram(m.getRam()); + inputStream = new InputStream(m.getInputStream()); + outputStream = new OutputStream(m.getOutputStream()); + } else { + throw new IllegalArgumentException( + "Null argument is not allowed here!"); + } + } + + /** + * Create a new machine configuration with filled values. Use a parameter + * with null will create a new and empty element in the abstract + * machine. + * + * @param programCounter + * Use 0 here to set it to initial value. + * @param stack + * @param ram + * @param inputStream + * @param outputStream + */ + public MachineConfiguration(int programCounter, LinkedList stack, + TreeMap ram, LinkedList inputStream, + LinkedList outputStream) { + if (programCounter != 0) { + this.programCounter = new ProgramCounter(programCounter); + } else { + this.programCounter = new ProgramCounter(); + } + + if (stack != null) { + this.stack = new Stack(stack); + } else { + this.stack = new Stack(); + } + + if (ram != null) { + this.ram = new Ram(ram); + } else { + this.ram = new Ram(); + } + + if (inputStream != null) { + this.inputStream = new InputStream(inputStream); + } else { + this.inputStream = new InputStream(); + } + + if (outputStream != null) { + this.outputStream = new OutputStream(outputStream); + } else { + this.outputStream = new OutputStream(); + } + } + + public ProgramCounter getProgramCounter() { + return programCounter; + } + + public Stack getStack() { + return stack; + } + + public Ram getRam() { + return ram; + } + + public InputStream getInputStream() { + return inputStream; + } + + public OutputStream getOutputStream() { + return outputStream; + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/MemoryCell.java b/src/org/jalgo/module/am0c0/model/am0/MemoryCell.java new file mode 100644 index 0000000..3316036 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/MemoryCell.java @@ -0,0 +1,55 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +/** + * This class represents a memory cell which is used in the following abstract + * machine elements:
    • {@link Stack}
    • {@link Stream}
    • + * {@link InputStream}
    • {@link OutputStream}
    • + * + * @author Max Leuthäuser + */ +public class MemoryCell { + private int value; + + public MemoryCell(final int value) { + set(value); + } + + /** + * @return the value saved in this cell + */ + public int get() { + return value; + } + + /** + * Set a new value for this cell + * + * @param value + */ + public void set(final int value) { + this.value = value; + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/MemoryStatement.java b/src/org/jalgo/module/am0c0/model/am0/MemoryStatement.java new file mode 100644 index 0000000..0592f85 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/MemoryStatement.java @@ -0,0 +1,40 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * This class is a simple blueprint for all commands. Just a method to return + * the type of the command is stipulated + * + * @author Max Leuthäuser + * @author David Voigt + */ +abstract class MemoryStatement extends SimulationStatement { + + public MemoryStatement(LineAddress address) { + super(address); + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Mod.java b/src/org/jalgo/module/am0c0/model/am0/Mod.java new file mode 100644 index 0000000..5815596 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Mod.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Mod extends ArithmeticStatement { + + public Mod(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Mod.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + configuration.getStack().push(arg1 % arg0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Mod.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "MOD;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Mul.java b/src/org/jalgo/module/am0c0/model/am0/Mul.java new file mode 100644 index 0000000..04f331e --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Mul.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Mul extends ArithmeticStatement { + + public Mul(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Mul.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + configuration.getStack().push(arg1 * arg0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Mul.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "MUL;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/NotEqual.java b/src/org/jalgo/module/am0c0/model/am0/NotEqual.java new file mode 100644 index 0000000..89920b3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/NotEqual.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class NotEqual extends CompareStatement { + + public NotEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "NotEqual.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 != arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "NotEqual.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "NE;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/OutputStream.java b/src/org/jalgo/module/am0c0/model/am0/OutputStream.java new file mode 100644 index 0000000..6bc605b --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/OutputStream.java @@ -0,0 +1,75 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +import java.util.List; + +/** + * This class represents an input stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public class OutputStream extends Stream { + + /** + * Create a new empty output stream + */ + public OutputStream() { + super(); + } + + /** + * Copyconstructor + * + * @param i + * {@link OutputStream} which should be copied. + */ + public OutputStream(OutputStream i) { + super(); + for (MemoryCell m : i.stream) { + this.stream.add(new MemoryCell(m.get())); + } + } + + /** + * Create a new output stream based on an already existing and filled list + * of values. + * + * @param initList + */ + public OutputStream(final List initList) { + for (int i : initList) { + stream.add(new MemoryCell(i)); + } + } + + /** + * Write a new value on the output stream. + * + * @param value + */ + public void write(final int value) { + stream.add(new MemoryCell(value)); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/ProgramCounter.java b/src/org/jalgo/module/am0c0/model/am0/ProgramCounter.java new file mode 100644 index 0000000..0f4bfe7 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/ProgramCounter.java @@ -0,0 +1,90 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +/** + * Class which represents the program counter in an abstract machine. + * + * @author Max Leuthäuser + */ +public class ProgramCounter { + private int pc; + + /** + * Create a new program counter which is set to 1. + */ + public ProgramCounter() { + pc = 1; + } + + /** + * Copyconstructor + * + * @param i + * {@link ProgramCounter} which should be copied. + */ + public ProgramCounter(ProgramCounter i) { + pc = i.get(); + } + + /** + * Create a new program counter which is set to the given value. + * + * @param value + */ + public ProgramCounter(final int value) { + pc = value; + } + + /** + * @return the current program counter + */ + public int get() { + return pc; + } + + /** + * Set a new program counter. + * + * @param value + */ + public void set(final int value) { + pc = value; + } + + /** + * Increase the program counter. + */ + public void inc() { + pc++; + } + + /** + * @return the program counter as String + */ + @Override + public String toString() { + return "" + pc; + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Ram.java b/src/org/jalgo/module/am0c0/model/am0/Ram.java new file mode 100644 index 0000000..2c59938 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Ram.java @@ -0,0 +1,138 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import java.util.Collections; +import java.util.List; +import java.util.LinkedList; +import java.util.Map; + +/** + * Class which represents the RAM in an abstract machine. + * + * @author Max Leuthäuser + */ +public class Ram { + private List values; + + /** + * Create a new empty ram. + */ + public Ram() { + values = new LinkedList(); + } + + /** + * Copyconstructor + * + * @param i + * {@link Ram} which should be copied. + */ + public Ram(Ram i) { + values = new LinkedList(); + + for (IndexedMemoryCell c : i.getRamAsList()) { + store(c.getIndex(), c.get()); + } + } + + /** + * Create a new ram based on an already existing and filled map of values. + * + * @param values + * {@link Map} which already holds some values. + */ + public Ram(final Map values) { + this.values = new LinkedList(); + for (int i : values.keySet()) { + store(i, values.get(i)); + } + } + + /** + * Store a new entry in the ram. + * + * @param index + * @param value + */ + public void store(final int index, final int value) { + for (IndexedMemoryCell i : values) { + if (i.getIndex() == index) { + i.set(value); + return; + } + } + values.add(new IndexedMemoryCell(index, value)); + } + + /** + * Returns the value at this index in the ram. + * + * @param index + * @return the value for the given index, -1 if there is no entry at + * this index. + */ + public int load(final int index) { + for (IndexedMemoryCell i : values) { + if (i.getIndex() == index) { + return i.get(); + } + } + return -1; + } + + /** + * @return the ram as list. + */ + public List getRamAsList() { + return this.values; + } + + public boolean cellIsDefined(int address) { + for (IndexedMemoryCell i : values) { + if (i.getIndex() == address) { + return true; + } + } + return false; + } + + /** + * @return the ram as String + */ + @Override + public String toString() { + if (values.isEmpty()) { + char o = '\u00D8'; + return "h" + o + "= [ ]"; + } + Collections.sort(values); + StringBuilder result = new StringBuilder(); + result.append("["); + for (IndexedMemoryCell i : values) { + result.append("," + i.getIndex() + "/" + i.get()); + } + return result.toString().replaceFirst(",", "") + "]"; + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Read.java b/src/org/jalgo/module/am0c0/model/am0/Read.java new file mode 100644 index 0000000..73bbf53 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Read.java @@ -0,0 +1,74 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Read extends IOStatement { + + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Read(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (!configuration.getInputStream().stream.isEmpty()) { + configuration.getProgramCounter().inc(); + configuration.getRam().store(target, + configuration.getInputStream().read()); + return configuration; + } else + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Read.1")); //$NON-NLS-1$ + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Read.2"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "READ " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/SimulationStatement.java b/src/org/jalgo/module/am0c0/model/am0/SimulationStatement.java new file mode 100644 index 0000000..44993cb --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/SimulationStatement.java @@ -0,0 +1,64 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.CodeObject; +import org.jalgo.module.am0c0.model.LineAddress; + + +/** + * abstract base class for all AM0 simulation statements + * + * @author Felix Schmitt + * @author David Voigt + * + */ +public abstract class SimulationStatement extends CodeObject { + + public SimulationStatement(LineAddress address) { + super(address); + } + + @Override + public int getLinesCount() { + return 1; + } + + @Override + public LineAddress getAddress() { + return ((LineAddress)super.getAddress()); + } + + /** + * @param configuration + * the {@link MachineConfiguration} + * @return the updated {@link MachineConfiguration} after applying this + * statement + */ + public abstract MachineConfiguration apply(MachineConfiguration configuration); + + /** + * @return the description for this statement in html format + */ + public abstract String getDescription(); +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Stack.java b/src/org/jalgo/module/am0c0/model/am0/Stack.java new file mode 100644 index 0000000..ce348f4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Stack.java @@ -0,0 +1,118 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents a stack which is used in a {@link MachineConfiguration} + * . + * + * @author Max Leuthäuser + */ +public class Stack { + private List values; + + /** + * Create a new empty stack. + */ + public Stack() { + values = new LinkedList(); + } + + /** + * Copyconstructor + * + * @param i + * {@link Stack} which should be copied. + */ + public Stack(Stack i) { + values = new LinkedList(); + + for (MemoryCell c : i.getStackAsList()) { + push(c.get()); + } + } + + /** + * Create a new stack based on an already existing and filled list of + * values. + * + * @param values + * {@link LinkedList} which already holds some values. + */ + public Stack(final List values) { + this.values = new LinkedList(); + for (int i : values) { + push(i); + } + } + + /** + * Adds a single element at the top of the stack. + * + * @param value + */ + public void push(final int value) { + values.add(new MemoryCell(value)); + } + + /** + * @return the current element from the top of the stack + */ + public int pop() { + return values.remove(values.size() - 1).get(); + } + + /** + * @return the stack as list. + */ + public List getStackAsList() { + return this.values; + } + + /** + * @return the stack as String + */ + @Override + public String toString() { + if (values.isEmpty()) { + return "Æ"; + } + StringBuilder result = new StringBuilder(); + ArrayList l = new ArrayList(); + for (MemoryCell i : values) { + l.add(i.get()); + } + Collections.reverse(l); + for (int s : l) { + result.append(s); + result.append(":"); + } + return result.toString().substring(0, result.length() - 1); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Store.java b/src/org/jalgo/module/am0c0/model/am0/Store.java new file mode 100644 index 0000000..b0e957e --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Store.java @@ -0,0 +1,74 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Store extends MemoryStatement { + + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Store(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 1) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Store.0")); //$NON-NLS-1$ + } + + configuration.getProgramCounter().inc(); + configuration.getRam().store(target, configuration.getStack().pop()); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Store.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "STORE " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Stream.java b/src/org/jalgo/module/am0c0/model/am0/Stream.java new file mode 100644 index 0000000..66b9660 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Stream.java @@ -0,0 +1,57 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents a non specific stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public abstract class Stream { + protected List stream; + + /** + * Creates a new empty stream. + */ + public Stream() { + stream = new LinkedList(); + } + + /** + * @return the stream as String + */ + @Override + public String toString() { + if (stream.isEmpty()) { + return "Æ"; + } + StringBuilder result = new StringBuilder(); + for (MemoryCell i : stream) { + result.append("," + i.get()); + } + return result.toString().replaceFirst(",", ""); + } +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Sub.java b/src/org/jalgo/module/am0c0/model/am0/Sub.java new file mode 100644 index 0000000..8e99524 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Sub.java @@ -0,0 +1,66 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.main.util.Messages; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Sub extends ArithmeticStatement { + + public Sub(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Sub.0")); //$NON-NLS-1$ + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + configuration.getStack().push(arg1 - arg0); + return configuration; + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Sub.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "SUB;"; //$NON-NLS-1$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/Write.java b/src/org/jalgo/module/am0c0/model/am0/Write.java new file mode 100644 index 0000000..65d50b6 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/Write.java @@ -0,0 +1,76 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.am0; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.LineAddress; + +/** + * Updates the AM after the specific command. + * + * @author Max Leuthäuser + * @author David Voigt + */ +public class Write extends IOStatement { + + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Write(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException("Jump target must not be < 0."); //$NON-NLS-1$ + } + + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + + if (configuration.getRam().cellIsDefined(target)) { + configuration.getProgramCounter().inc(); + configuration.getOutputStream().write( + configuration.getRam().load(target)); + return configuration; + } else + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Write.0")); //$NON-NLS-1$ + } + + @Override + public String getDescription() { + return Messages.getString("am0c0", "Write.1"); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "WRITE " + target + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/am0/package-info.java b/src/org/jalgo/module/am0c0/model/am0/package-info.java new file mode 100644 index 0000000..40848a5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/am0/package-info.java @@ -0,0 +1,5 @@ +/** + * Classes that represent an abstract machine as introduced in the lectures and classes that handle an AM0 simulation. + */ +package org.jalgo.module.am0c0.model.am0; + diff --git a/src/org/jalgo/module/am0c0/model/c0/C0Program.java b/src/org/jalgo/module/am0c0/model/c0/C0Program.java new file mode 100644 index 0000000..fb77ea6 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/C0Program.java @@ -0,0 +1,41 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0; + +import org.jalgo.module.am0c0.model.GenericProgram; +import org.jalgo.module.am0c0.model.c0.ast.C0AST; + +/** + * Specialized GenericProgram + * Represents a C0 program which consists of {@link C0AST} classes + * @author Felix Schmitt + * + */ +public class C0Program extends GenericProgram { + + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/CVS/Entries b/src/org/jalgo/module/am0c0/model/c0/CVS/Entries new file mode 100644 index 0000000..2a0787a --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/CVS/Entries @@ -0,0 +1,4 @@ +/C0Program.java/1.1/Mon Aug 16 12:05:48 2010// +D/ast//// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// +D/trans//// diff --git a/src/org/jalgo/module/am0c0/model/c0/CVS/Repository b/src/org/jalgo/module/am0c0/model/c0/CVS/Repository new file mode 100644 index 0000000..e9e011c --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/model/c0 diff --git a/src/org/jalgo/module/am0c0/model/c0/CVS/Root b/src/org/jalgo/module/am0c0/model/c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Block.java b/src/org/jalgo/module/am0c0/model/c0/ast/Block.java new file mode 100644 index 0000000..86f1f5c --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Block.java @@ -0,0 +1,93 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * AST part that represents the syntactic variable {@code Block}. A block + * contains a {@code Declaration} and, optionally, a {@code StatementSequence}. + * + * @author Martin Morgenstern + */ +public class Block extends C0AST { + private final Declaration declaration; + private final StatementSequence statementSequence; + private final String codeText; + + /** + * Construct a new {@code Block} with given a given {@code Declaration} and + * an optional {@code StatementSequence}. + * + * @param declaration + * the declaration + * @param statementSequence + * the statement sequence or {@code null} + * @throws NullPointerException + * if declaration is {@code null} + */ + public Block(final Declaration declaration, final StatementSequence statementSequence) { + if (null == declaration) { + throw new NullPointerException(); + } + + this.declaration = declaration; + this.statementSequence = statementSequence; + codeText = initCodeText(); + } + + /** + * @return the declaration part of the block + */ + public Declaration getDeclaration() { + return declaration; + } + + /** + * @return the statement sequence or {@code null} if the block does not + * contain a statement sequence + */ + public StatementSequence getStatementSequence() { + return statementSequence; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + + private String initCodeText() { + assert declaration != null; + + final StringBuilder result = new StringBuilder(); + + result.append("{\n"); + result.append(declaration.getCodeText()); + + if (null != statementSequence) { + result.append(statementSequence.getCodeText()); + } + + result.append("return 0;\n}"); + + return result.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.java b/src/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.java new file mode 100644 index 0000000..4a3cd7d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/BoolExpression.java @@ -0,0 +1,125 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType; + +/** + * AST part that represents the syntactic variable {@code BoolExpression}. + * + * @author Martin Morgenstern + */ +public class BoolExpression extends C0AST { + private final SimpleExpr left; + private final AtomicType rel; + private final SimpleExpr right; + private final String codeText; + + /** + * @param left + * the simple expression on the left hand side of the relation + * @param rel + * the relation + * @param right + * the simple expression on the right hand side of the relation + */ + public BoolExpression(final SimpleExpr left, final AtomicType rel, + final SimpleExpr right) { + this.left = left; + this.rel = rel; + this.right = right; + codeText = initCodeText(); + } + + /** + * @return the relation type of the boolean expression. + */ + public AtomicType getRelation() { + return rel; + } + + /** + * @return the {@code SimpleExpr} on the left hand side of the relation. + */ + public SimpleExpr getSimpleExp1() { + return left; + } + + /** + * @return the {@code SimpleExpr} on the right hand side of the relation. + */ + public SimpleExpr getSimpleExp2() { + return right; + } + + /** + * Gets the cached C0 code representation of this object, e.g. + * {@code a >= b} . + * + * @return C0 code representation of this object + */ + @Override + protected String getCodeTextInternal() { + return codeText; + } + + /** + * Construct the C0 code representation for this object. This method should + * only be invoked when all private fields of this object are initialized + * (this is checked using assertions). + * + * @return C0 code representation of this object + */ + private String initCodeText() { + assert rel != null; + assert left != null; + assert right != null; + + String relation; + + switch (rel) { + case EQ: + relation = "=="; + break; + case NE: + relation = "!="; + break; + case LT: + relation = "<"; + break; + case GT: + relation = ">"; + break; + case LE: + relation = "<="; + break; + case GE: + relation = ">="; + break; + default: + throw new AssertionError(rel); // should not happen + } + + return left.getCodeText() + " " + relation + " " + right.getCodeText(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/C0AST.java b/src/org/jalgo/module/am0c0/model/c0/ast/C0AST.java new file mode 100644 index 0000000..8319b42 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/C0AST.java @@ -0,0 +1,159 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +import org.apache.commons.lang.StringUtils; +import org.jalgo.module.am0c0.model.Address; +import org.jalgo.module.am0c0.model.CodeObject; + +/** + * Represents the base of the abstract syntax tree for a parsed C0 program. + * + *

      + * All parts of the abstract syntax tree extend this class. + *

      + * + *

      + * Additionally, this class contains AST types that are used frequently by the + * other AST types ({@link Ident} and {@link ConstIdent}). + *

      + * + * @author Martin Morgenstern + */ +public abstract class C0AST extends CodeObject { + public C0AST(Address address) { + super(address); + } + + public C0AST() { + this(null); + } + + /** + * + */ + protected String compressText(final String codeText) { + if (codeText == null) { + throw new NullPointerException(); + } + + String[] parts = codeText.split("\n"); + + if (parts.length <= 5) { + return codeText; + } + + final StringBuilder result = new StringBuilder(); + + for (int i = 0; i < 3; i++) { + result.append(parts[i]); + result.append("\n"); + } + + result.append("...\n"); + + for (int i = parts.length - 2; i < parts.length; i++) { + result.append(parts[i]); + result.append("\n"); + } + + return result.toString(); + } + + @Override + public int getLinesCount() { + String codeText = compressText(getCodeTextInternal()); + return StringUtils.countMatches(codeText, "\n") + 1; //$NON-NLS-1$ + } + + protected abstract String getCodeTextInternal(); + + @Override + public String getCodeText() { + return compressText(getCodeTextInternal()); + } + + /** + * Represents identifiers for variables. + * + * @author Martin Morgenstern + */ + static public class Ident { + private final String name; + + /** + * Construct a new identifier named {@code name}. + * + * @param name + * the name of the new identifier + */ + public Ident(final String name) { + this.name = name; + } + + /** + * @return the name of the identifier + */ + public String getName() { + return name; + } + } + + /** + * Represents identifiers for constants. + * + * @author Martin Morgenstern + */ + static public class ConstIdent { + private final String name; + private final int value; + + /** + * Construct a new constant identifier {@code name} with the value + * {@code value} . + * + * @param name + * the name of the constant + * @param value + * the value of the constant + */ + public ConstIdent(final String name, final int value) { + this.name = name; + this.value = value; + } + + /** + * @return the name of the constant + */ + public String getName() { + return name; + } + + /** + * @return the value of the constant + */ + public int getValue() { + return value; + } + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Entries b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Entries new file mode 100644 index 0000000..90c089d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Entries @@ -0,0 +1,13 @@ +/Block.java/1.1/Mon Aug 16 12:05:48 2010// +/BoolExpression.java/1.1/Mon Aug 16 12:05:48 2010// +/C0AST.java/1.1/Mon Aug 16 12:05:48 2010// +/ConstDeclaration.java/1.1/Mon Aug 16 12:05:48 2010// +/Declaration.java/1.1/Mon Aug 16 12:05:48 2010// +/Factor.java/1.1/Mon Aug 16 12:05:48 2010// +/Program.java/1.1/Mon Aug 16 12:05:48 2010// +/SimpleExpr.java/1.1/Mon Aug 16 12:05:48 2010// +/Statement.java/1.1/Mon Aug 16 12:05:48 2010// +/StatementSequence.java/1.1/Mon Aug 16 12:05:48 2010// +/Term.java/1.1/Mon Aug 16 12:05:48 2010// +/VarDeclaration.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Repository b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Repository new file mode 100644 index 0000000..6f02d62 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/model/c0/ast diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Root b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.java b/src/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.java new file mode 100644 index 0000000..318e5e4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/ConstDeclaration.java @@ -0,0 +1,87 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +import java.util.ArrayList; +import java.util.List; + +/** + * AST representation for the syntactic variable {@code ConstDeclaration}. Note + * that at this stage no semantic check is done, i.e. this + * representation explicitly allows multiple constants with the same name. + * + * @author Martin Morgenstern + */ +public class ConstDeclaration extends C0AST { + private final List constants = new ArrayList(); + + /** + * Initialize a constant declaration with the initial element {@code ident}. + * + * @param ident + * the constant identifier that is to be added to the declaration + */ + public ConstDeclaration(ConstIdent ident) { + constants.add(ident); + } + + /** + * Add constants to the declaration. Note: multiple identifiers + * with the same name are allowed. + * + * @param ident + * the constant identifier that is to be added to the declaration + */ + public void addConstant(ConstIdent ident) { + constants.add(ident); + } + + /** + * Get a list containing values of the type {@link ConstIdent}. A defensive + * copy is returned to ensure that the internal list can only be changed by + * the method {@code addConstant}. + * + * @return a list containing all constant identifiers of this declaration + */ + public List getConstants() { + return new ArrayList(constants); + } + + @Override + protected String getCodeTextInternal() { + StringBuilder codeText = new StringBuilder("const "); + + for (int i = 0; i < constants.size(); i++) { + codeText.append(constants.get(i).getName()); + codeText.append(" = "); + codeText.append(constants.get(i).getValue()); + + if (i < constants.size() - 1) { + codeText.append(", "); + } + } + + codeText.append(";\n"); + return codeText.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Declaration.java b/src/org/jalgo/module/am0c0/model/c0/ast/Declaration.java new file mode 100644 index 0000000..4e29ab0 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Declaration.java @@ -0,0 +1,80 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * AST representation of the syntactic variable {@code Declaration}. It contains + * a {@code ConstDeclaration} and a {@code VarDeclaration} (both optional). + * + * @author Martin Morgenstern + */ +public class Declaration extends C0AST { + private final ConstDeclaration constDecl; + private final VarDeclaration varDecl; + private final String codeText; + + /** + * @param constDecl + * the optional {@code ConstDeclaration} + * @param varDecl + * the optional {@code VarDeclaration} + */ + public Declaration(ConstDeclaration constDecl, VarDeclaration varDecl) { + this.constDecl = constDecl; + this.varDecl = varDecl; + codeText = initCodeText(); + } + + /** + * @return the {@code ConstDeclaration} or {@code null} + */ + public ConstDeclaration getConstDecl() { + return constDecl; + } + + /** + * @return the {@code VarDeclaration} or {@code null} + */ + public VarDeclaration getVarDecl() { + return varDecl; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + + private String initCodeText() { + StringBuilder result = new StringBuilder(); + + if (null != constDecl) { + result.append(constDecl.getCodeText()); + } + + if (null != varDecl) { + result.append(varDecl.getCodeText()); + } + + return result.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Factor.java b/src/org/jalgo/module/am0c0/model/c0/ast/Factor.java new file mode 100644 index 0000000..9a056c5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Factor.java @@ -0,0 +1,111 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * Abstract AST representation type for the syntactic variable {@code Factor}. + * It is used as a supertype for its inner classes that represent the actual + * syntactic variants of a {@code Factor}. + * + * @author Martin Morgenstern + */ +public abstract class Factor extends C0AST { + /** + * A {@code Factor} that contains a {@code SimpleExpr} in parentheses. + * + * @author Martin Morgenstern + */ + public static class CompExprFactor extends Factor { + private final SimpleExpr expr; + private final String codeText; + + /** + * @param expr + * the contained {@code SimpleExpr} + */ + public CompExprFactor(final SimpleExpr expr) { + this.expr = expr; + codeText = "(" + expr.getCodeText() + ")"; + } + + /** + * @return the contained {@code SimpleExpr} + */ + public SimpleExpr getSimpleExpr() { + return expr; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * A {@code Factor} that is an identifier. + * + * @author Martin Morgenstern + */ + public static class IdentFactor extends Factor { + private final String ident; + + public IdentFactor(final String ident) { + if (null == ident) { + this.ident = ""; + } else { + this.ident = ident; + } + } + + public String getIdentName() { + return ident; + } + + @Override + protected String getCodeTextInternal() { + return ident; + } + } + + /** + * A {@code Factor} that is a number. + * + * @author Martin Morgenstern + */ + public static class NumberFactor extends Factor { + public NumberFactor(final int num) { + this.num = num; + } + + public int getNumber() { + return num; + } + + private final int num; + + @Override + protected String getCodeTextInternal() { + return Integer.toString(num); + } + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Program.java b/src/org/jalgo/module/am0c0/model/c0/ast/Program.java new file mode 100644 index 0000000..482ffad --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Program.java @@ -0,0 +1,48 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * AST representation of the syntactic variable {@code Program}. A program + * contains a {@code Block}. + * + * @author Martin Morgenstern + */ +public class Program extends C0AST { + private final Block block; + private final String codeText; + + public Program(final Block block) { + this.block = block; + codeText = "\n#include \n\nint main()\n" + block.getCodeText(); + } + + public Block getBlock() { + return block; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.java b/src/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.java new file mode 100644 index 0000000..b3229f6 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/SimpleExpr.java @@ -0,0 +1,167 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * Abstract AST representation of the syntactic variable {@code + * SimpleExpression}. Simple expressions can be devided into unary and binary + * expressions. This abstract class contains AST types for the actual syntactic + * variants of a {@code SimpleExpression}. + * + * @author Martin Morgenstern + */ +public abstract class SimpleExpr extends C0AST { + /** + * Abstract class for all binary simple expressions, i.e. simple expressions + * that have two arguments (a simple expression and a term). + * + * @author Martin Morgenstern + */ + public static abstract class BinSimpleExpr extends SimpleExpr { + private final SimpleExpr left; + private final Term right; + + public BinSimpleExpr(SimpleExpr left, Term right) { + this.left = left; + this.right = right; + } + + /** + * Get the left operand, which is a simple expression. + * + * @return + */ + public SimpleExpr getLeft() { + return left; + } + + /** + * Get the right operand, which is a term. + * + * @return + */ + public Term getRight() { + return right; + } + + @Override + protected String getCodeTextInternal() { + return left.getCodeText() + + " " + + getOperatorSign() + + " " + + right.getCodeText(); + } + + public abstract String getOperatorSign(); + } + + /** + * Represents binary plus expressions. + * + * @author Martin Morgenstern + */ + public static class PlusExpr extends BinSimpleExpr { + public PlusExpr(SimpleExpr left, Term right) { + super(left, right); + } + + @Override + public String getOperatorSign() { + return "+"; + } + } + + /** + * Represents binary minus expressions. + * + * @author Martin Morgenstern + */ + public static class MinusExpr extends BinSimpleExpr { + public MinusExpr(SimpleExpr left, Term right) { + super(left, right); + } + + @Override + public String getOperatorSign() { + return "-"; + } + } + + /** + * Abstract class for all unary simple expressions, i.e. simple expressions + * that only have one operand (a term). + * + * @author Martin Morgenstern + */ + public static abstract class UnarySimpleExpr extends SimpleExpr { + private final Term term; + + public UnarySimpleExpr(Term t) { + term = t; + } + + public Term getTerm() { + return term; + } + + @Override + protected String getCodeTextInternal() { + return getOperatorSign() + term.getCodeText(); + } + + public abstract String getOperatorSign(); + } + + /** + * Represents unary plus expressions. + * + * @author Martin Morgenstern + */ + public static class UnaryPlusExpr extends UnarySimpleExpr { + public UnaryPlusExpr(Term t) { + super(t); + } + + @Override + public String getOperatorSign() { + return ""; + } + } + + /** + * Represents unary minus expressions. + * + * @author Martin Morgenstern + */ + public static class UnaryMinusExpr extends UnarySimpleExpr { + public UnaryMinusExpr(Term t) { + super(t); + } + + @Override + public String getOperatorSign() { + return "-"; + } + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Statement.java b/src/org/jalgo/module/am0c0/model/c0/ast/Statement.java new file mode 100644 index 0000000..6092f39 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Statement.java @@ -0,0 +1,286 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * AST representation of the syntactic variable {@code Statement}. There are six + * actual variants of statements which are implemented as static inner classes. + * Additionally, similar statements are grouped using static abstract inner + * classes. + * + * @author Martin Morgenstern + */ +public abstract class Statement extends C0AST { + /** + * Abstract super class for {@code PrintfStatement} and + * {@code ScanfStatement}, as they share the same type of content (an + * identifier). + * + * @author Martin Morgenstern + */ + public static abstract class IOStatement extends Statement { + protected final String ident; + + /** + * @param ident + * the identifier that is the source/destination of the I/O + * operation + */ + public IOStatement(final String ident) { + this.ident = ident; + } + + /** + * @return the identifier that is the source/destination of the I/O + * operation + */ + public String getIdent() { + return ident; + } + } + + /** + * Represents the output operation "printf". + * + * @author Martin Morgenstern + */ + public static class PrintfStatement extends IOStatement { + private final String codeText; + + public PrintfStatement(final String ident) { + super(ident); + codeText = "printf(\"%i\", " + ident + ");"; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Represents the input operation "scanf". + * + * @author Martin Morgenstern + */ + public static class ScanfStatement extends IOStatement { + private final String codeText; + + public ScanfStatement(final String ident) { + super(ident); + codeText = "scanf(\"%i\", &" + ident + ");"; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Represents an if statement that has a {@code BoolExpression} and a + * {@code Statement}. + * + * @author Martin Morgenstern + */ + public static class IfStatement extends Statement { + private final BoolExpression expr; + private final Statement statement; + private final String codeText; + + public IfStatement(final BoolExpression expr, final Statement statement) { + this.expr = expr; + this.statement = statement; + codeText = "if (" + expr.getCodeText() + ")\n" + + statement.getCodeText(); + } + + public BoolExpression getBoolExpr() { + return expr; + } + + /** + * Alias for the method {@code getFirstStatement}. + * + * @return + */ + public Statement getStatement() { + return statement; + } + + /** + * Gets the first statement (for if and while statements, this is the + * only statement). + * + * @return the statement that immediately follows the head of the + * conditional or loop statement + */ + public Statement getFirstStatement() { + return statement; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Represents if-else statements. They differ from {@code IfStatement} only + * in one point: they contain an additional statement for the else-branch. + * + * @author Martin Morgenstern + */ + public static class IfElseStatement extends Statement { + private final BoolExpression expr; + private final Statement statement; + private final Statement secondStatement; + private final String codeText; + + public IfElseStatement(final BoolExpression expr, + final Statement firstStatement, final Statement secondStatement) { + this.expr = expr; + this.statement = firstStatement; + this.secondStatement = secondStatement; + codeText = "if (" + expr.getCodeText() + ")\n" + + statement.getCodeText() + "\nelse\n" + + secondStatement.getCodeText(); + } + + public BoolExpression getBoolExpr() { + return expr; + } + + public Statement getFirstStatement() { + return statement; + } + + /** + * @return the statement that belongs to the else-branch + */ + public Statement getSecondStatement() { + return secondStatement; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Representation of while statements. + * + * @author Martin Morgenstern + */ + public static class WhileStatement extends Statement { + private final BoolExpression expr; + private final Statement statement; + private final String codeText; + + public WhileStatement(BoolExpression expr, Statement statement) { + this.expr = expr; + this.statement = statement; + codeText = "while (" + expr.getCodeText() + ")\n" + + statement.getCodeText(); + } + + public BoolExpression getBoolExpr() { + return expr; + } + + public Statement getFirstStatement() { + return statement; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Represents assignments of simple expressions to variables. + * + * @author Martin Morgenstern + */ + public static class AssignmentStatement extends Statement { + private final String ident; + private final SimpleExpr expr; + private final String codeText; + + public AssignmentStatement(final String ident, final SimpleExpr expr) { + this.ident = ident; + this.expr = expr; + codeText = ident + " = " + expr.getCodeText() + ";"; + } + + /** + * @return the name to which the result of the evaluation of the + * expression is assigned + */ + public String getIdent() { + return ident; + } + + /** + * @return the expression on the right hand side of the assignment + */ + public SimpleExpr getExpr() { + return expr; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } + + /** + * Represents compound statements, i.e. statements that contain a statement + * sequence in parentheses. + * + * @author Martin Morgenstern + */ + public static class CompStatement extends Statement { + private final StatementSequence seq; + private final String codeText; + + public CompStatement(final StatementSequence seq) { + this.seq = seq; + codeText = "{\n" + seq.getCodeText() + "}"; + } + + /** + * @return the inner statement sequence + */ + public StatementSequence getStatementSequence() { + return seq; + } + + @Override + protected String getCodeTextInternal() { + return codeText; + } + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.java b/src/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.java new file mode 100644 index 0000000..2a0ce0d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/StatementSequence.java @@ -0,0 +1,93 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +import java.util.ArrayList; +import java.util.List; + +/** + * AST representation for the syntactic variable {@code StatementSequence}. A + * statement sequence is a non-empty list of statements. + * + * @author Martin Morgenstern + */ +public class StatementSequence extends C0AST { + private final List statementList = new ArrayList(); + + /** + * Construct a new statement sequence with the first element {@code stat}. + * + * @param stat + * the first statement to add + */ + public StatementSequence(Statement stat) { + statementList.add(stat); + } + + /** + * Get a copy of the list of statements. The copy is made to ensure that the + * internal list representation is only changed by the {@code addStatement} + * method. + * + * @return list of statements + */ + public List getStatements() { + return new ArrayList(statementList); + } + + /** + * Add statements to the list. + * + * @param stat the statement to add + */ + public void addStatement(Statement stat) { + statementList.add(stat); + } + + /*@Override + protected String compressText(String codeText) { + if (statementList.size() <= 4) + return codeText; + else { + String result = ""; + for (int i = 0; i < 2; i++) + result += statementList.get(i).getCodeText() + "\n"; + result += "...\n"; + for (int i = statementList.size() - 2; i < statementList.size(); i++) + result += statementList.get(i).getCodeText() + "\n"; + return result; + } + }*/ + + @Override + protected String getCodeTextInternal() { + StringBuilder codeText = new StringBuilder(); + + for (Statement stat : statementList) { + codeText.append(stat.getCodeText()); + codeText.append("\n"); + } + + return codeText.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/Term.java b/src/org/jalgo/module/am0c0/model/c0/ast/Term.java new file mode 100644 index 0000000..fd7593d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/Term.java @@ -0,0 +1,142 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +/** + * Abstract AST representation for the syntactic variable {@code Term}. Terms + * have different actual syntactic variants (e.g. {@code MultTerm}) and can also + * be grouped into binary and unary terms. + * + * @author Martin Morgenstern + */ +public abstract class Term extends C0AST { + /** + * Terms that take two arguments, a term and a factor. + * + * @author Martin Morgenstern + */ + public static abstract class BinTerm extends Term { + protected final Term left; + protected final Factor right; + + protected BinTerm(Term left, Factor right) { + this.left = left; + this.right = right; + } + + /** + * @return the term from the left hand side of the term + */ + public Term getLeft() { + return left; + } + + /** + * @return the factor from the right hand side of the term + */ + public Factor getRight() { + return right; + } + + @Override + protected String getCodeTextInternal() { + return left.getCodeText() + + " " + + getOperatorSign() + + " " + + right.getCodeText(); + } + + public abstract String getOperatorSign(); + } + + /** + * Unary term that contains a factor. + * + * @author Martin Morgenstern + */ + public static class FactorTerm extends Term { + public FactorTerm(Factor f) { + factor = f; + } + + public Factor getFactor() { + return factor; + } + + private final Factor factor; + + @Override + protected String getCodeTextInternal() { + return factor.getCodeText(); + } + } + + /** + * Multiplication term. + * + * @author Martin Morgenstern + */ + public static class MultTerm extends BinTerm { + public MultTerm(Term left, Factor right) { + super(left, right); + } + + @Override + public String getOperatorSign() { + return "*"; + } + } + + /** + * Division term. + * + * @author Martin Morgenstern + */ + public static class DivTerm extends BinTerm { + public DivTerm(Term left, Factor right) { + super(left, right); + } + + @Override + public String getOperatorSign() { + return "/"; + } + } + + /** + * Modulo term. + * + * @author Martin Morgenstern + */ + public static class ModTerm extends BinTerm { + public ModTerm(Term left, Factor right) { + super(left, right); + } + + @Override + public String getOperatorSign() { + return "%"; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.java b/src/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.java new file mode 100644 index 0000000..ba8510b --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/VarDeclaration.java @@ -0,0 +1,80 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.ast; + +import java.util.ArrayList; +import java.util.List; + +/** + * AST representation for the syntactic variable {@code VarDeclaration}. + * Note: no semantic checks are made, i.e. multiple variables with the + * same names can be added to the declaration. + * + * @author Martin Morgenstern + */ +public class VarDeclaration extends C0AST { + private final List vars = new ArrayList(); + + /** + * @param firstIdent + * the first identifier to be added to the declaration list + */ + public VarDeclaration(Ident firstIdent) { + vars.add(firstIdent); + } + + /** + * @param ident + * the identifier to be added to the declaration list + */ + public void addVariable(Ident ident) { + vars.add(ident); + } + + /** + * Get a copy of the list of identifiers. A defensive copy is returned to + * ensure that the internal list can only be changed by the method {@code + * addVariable}. + * + * @return list of identifiers + */ + public List getDeclaredVars() { + return new ArrayList(vars); + } + + @Override + protected String getCodeTextInternal() { + StringBuilder codeText = new StringBuilder("int "); + + for (int i = 0; i < vars.size(); i++) { + codeText.append(vars.get(i).getName()); + + if (i < vars.size() - 1) { + codeText.append(", "); + } + } + + codeText.append("\n"); + return codeText.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/ast/package-info.java b/src/org/jalgo/module/am0c0/model/c0/ast/package-info.java new file mode 100644 index 0000000..f9e7414 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/ast/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes implementing an abstract syntax tree for C0. + */ +package org.jalgo.module.am0c0.model.c0.ast; diff --git a/src/org/jalgo/module/am0c0/model/c0/package-info.java b/src/org/jalgo/module/am0c0/model/c0/package-info.java new file mode 100644 index 0000000..eba6e2e --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/package-info.java @@ -0,0 +1,5 @@ +/** + * Classes that provide an internal data representation for C0 programs. + */ +package org.jalgo.module.am0c0.model.c0; + diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.java b/src/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.java new file mode 100644 index 0000000..8a6ad70 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/AddressSolver.java @@ -0,0 +1,80 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.AddressException; +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.model.TreeAddress; + +/** + * Address solver which creates the TreeAddress-to-LineAddress map + * + * @author Felix Schmitt + * + */ +public class AddressSolver { + + /** + * maps {@link TreeAddress}es to {@link LineAddress}es + * + * @param transFunctions + * a List of {@link TransformFunction} with {@link TreeAddress}es + * @return a Map of {@link TreeAddress}-Strings to {@link LineAddress}es + * @throws NullPointerException + */ + public static Map solve(List transFunctions) + throws NullPointerException { + Map solved = new HashMap(); + + int line = 1; + int index = 0; + + while (index < transFunctions.size()) { + TransformFunction func = transFunctions.get(index); + + if (func.getAddress() != null) + try { + solved.put(func.getAddress().toString(), new LineAddress(line)); + } catch (AddressException e) { + // there can't be an AddressException here (as long as line + // does not overflow + } + + if (func instanceof StubTrans) { + if (func.getAddress() == null) + throw new NullPointerException(Messages.getString("am0c0", "AddressSolver.0")); //$NON-NLS-1$ + } else { + line++; + } + + index++; + } + + return solved; + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.java new file mode 100644 index 0000000..1fbf87e --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/AtomicTrans.java @@ -0,0 +1,216 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.List; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.AddressException; +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.am0.*; +import org.jalgo.module.am0c0.model.c0.ast.C0AST; + +/** + * An atomic c0 statement (which can be used to generate an AM0 + * SimulationStatement) + * + * @author Felix Schmitt + * + */ +public class AtomicTrans extends TransformFunction { + + public static enum AtomicType { + ADD, DIV, EQ, GE, GT, JMC, JMP, LE, LT, LIT, LOAD, MOD, MUL, NE, READ, STORE, SUB, WRITE + } + + protected AtomicType atomicType; + protected int value; + protected TreeAddress jumpAddress; + protected String codePreview; + + /** + * creates a {@link SimulationStatement} from this {@link AtomicTrans} + * + * @param addressTable + * the table created by {@link AddressSolver} used for + * translation + */ + protected SimulationStatement createSimulationStatement(LineAddress lineAddress, + Map addressTable) throws IllegalArgumentException { + + switch (atomicType) { + case ADD: + return new Add(lineAddress); + case DIV: + return new Div(lineAddress); + case EQ: + return new Equal(lineAddress); + case GE: + return new GreaterEqual(lineAddress); + case GT: + return new GreaterThen(lineAddress); + case JMC: + return new Jmc(lineAddress, addressTable.get(jumpAddress.toString()).getLine()); + case JMP: + return new Jmp(lineAddress, addressTable.get(jumpAddress.toString()).getLine()); + case LE: + return new LesserEqual(lineAddress); + case LT: + return new LesserThen(lineAddress); + case LIT: + return new Lit(lineAddress, value); + case LOAD: + return new Load(lineAddress, value); + case MOD: + return new Mod(lineAddress); + case MUL: + return new Mul(lineAddress); + case NE: + return new NotEqual(lineAddress); + case READ: + return new Read(lineAddress, value); + case STORE: + return new Store(lineAddress, value); + case SUB: + return new Sub(lineAddress); + case WRITE: + return new Write(lineAddress, value); + default: + throw new IllegalArgumentException(Messages.getString("am0c0", "AtomicTrans.0")); //$NON-NLS-1$ + } + } + + /** + * returns the preview String for this AtomicTrans + * + * @return the preview String + * @throws TransException + */ + protected String getPreview() throws TransException { + switch (atomicType) { + case JMC: + return "JMC " + jumpAddress.toString() + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + case JMP: + return "JMP " + jumpAddress.toString() + ";"; //$NON-NLS-1$ //$NON-NLS-2$ + default: + try { + return createSimulationStatement(new LineAddress(0), null).getCodeText(); + } catch (IllegalArgumentException e) { + throw new TransException(e.getMessage()); + } catch (AddressException e) { + // there should be no AddressException here at all + e.printStackTrace(); + } + return ""; + } + } + + /** + * constructor jumpAddress is set to null + * + * @param token + * must be null + * @param address + * the TreeAddress for this TransformFunction + * @param atomicType + * the AM0 type it represents + * @param value + * for AM0 commands with fixed values (like LOAD,STORE or LIT), + * set their value here for other statements, it will be ignored + */ + public AtomicTrans(C0AST token, TreeAddress address, AtomicType atomicType, int value) { + this(token, address, atomicType, value, null); + } + + /** + * constructor + * + * @param token + * must be null + * @param address + * the TreeAddress for this TransformFunction + * @param atomicType + * the AM0 type it represents + * @param value + * for AM0 commands with fixed values (like LOAD,STORE or LIT), + * set their value here. for other statements it will be ignored + * @param jumpAddress + * target address for jump statements. null for other statements + */ + public AtomicTrans(C0AST token, TreeAddress address, AtomicType atomicType, int value, + TreeAddress jumpAddress) throws IllegalArgumentException { + super(token, address); + this.atomicType = atomicType; + this.value = value; + this.jumpAddress = jumpAddress; + + if (token != null) + throw new IllegalArgumentException(Messages.getString("am0c0", "AtomicTrans.5")); //$NON-NLS-1$ + + if ((atomicType == AtomicType.JMC || atomicType == AtomicType.JMP) && (jumpAddress == null)) + throw new IllegalArgumentException(Messages.getString("am0c0", "AtomicTrans.6")); //$NON-NLS-1$ + + try { + codePreview = getPreview(); + } catch (TransException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + @Override + /** + * see {@link TransformFunction#apply} + * this must not be called + */ + public List apply(SymbolTable symbolTable) { + throw new IllegalAccessError(Messages.getString("am0c0", "AtomicTrans.7")); //$NON-NLS-1$ + } + + @Override + /** + * see {@link TransformFunction#getCodeText} + */ + public String getCodeText() { + return codePreview; + } + + /** + * returns the {@link SimulationStatement} generated by this + * {@link AtomicTrans} function + * + * @param lineAddress + * the target {@link LineAddress} for the generated + * {@link SimulationStatement} + * @param addressTable + * the solved address table created by {@link AddressSolver} + * + * @return the generated {@link SimulationStatement} + */ + public SimulationStatement getStatement(LineAddress lineAddress, + Map addressTable) throws IllegalArgumentException { + return createSimulationStatement(lineAddress, addressTable); + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.java new file mode 100644 index 0000000..43be109 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/BlockTrans.java @@ -0,0 +1,100 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.Block; + +/** + * Implements C0 blocktrans function + * + * @author Felix Schmitt + * + */ +public class BlockTrans extends TransformFunction { + + private Block block; + + public BlockTrans(Block token, TreeAddress address) { + super(token, address); + this.block = token; + + description = Messages.getString("am0c0", "BlockTrans.0") //$NON-NLS-1$ + + Messages.getString("am0c0", "BlockTrans.1") //$NON-NLS-1$ + + Messages.getString("am0c0", "BlockTrans.2") //$NON-NLS-1$ + + Messages.getString("am0c0", "BlockTrans.3"); //$NON-NLS-1$ + } + + @Override + /** + * see {@link TransformFunction#apply} + * updates the symbol table + */ + public List apply(SymbolTable symbolTable) throws TransException { + List result = new ArrayList(); + + UpdateTrans updateTrans = new UpdateTrans(block.getDeclaration(), null); + updateTrans.updateTable(symbolTable); + // we should have our symbol table ready now + + if (block.getStatementSequence() == null) { + StubTrans stub = new StubTrans(null, new TreeAddress()); + result.add(stub); + return result; + } + + STSeqTrans stSeqTrans = new STSeqTrans(block.getStatementSequence(), new TreeAddress()); + + result.add(stSeqTrans); + return result; + } + + /** + * special version of apply() for BlockTrans which does not alter the symbol + * table + * + * @return see {@link BlockTrans#apply()} + */ + public List applyPreview() { + List result = new ArrayList(); + + STSeqTrans stSeqTrans = new STSeqTrans(block.getStatementSequence(), + new TreeAddress()); + + result.add(stSeqTrans); + return result; + } + + @Override + /*** see {@link TransformFunction#getCodeText} + * + */ + public String getCodeText() { + return "blocktrans(" + block.getCodeText() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.java new file mode 100644 index 0000000..83792d9 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/BoolExpTrans.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.BoolExpression; + +/** + * Implements C0 boolexptrans function + * @author Felix Schmitt + * + */ +public class BoolExpTrans extends TransformFunction { + + private BoolExpression boolExpression; + + public BoolExpTrans(BoolExpression token, + TreeAddress address) { + super(token, address); + this.boolExpression = token; + + description = Messages.getString("am0c0", "BoolExpTrans.0") + //$NON-NLS-1$ + Messages.getString("am0c0", "BoolExpTrans.1") + //$NON-NLS-1$ + Messages.getString("am0c0", "BoolExpTrans.2") + //$NON-NLS-1$ + Messages.getString("am0c0", "BoolExpTrans.3") + //$NON-NLS-1$ + Messages.getString("am0c0", "BoolExpTrans.4") + //$NON-NLS-1$ + Messages.getString("am0c0", "BoolExpTrans.5"); //$NON-NLS-1$ + } + + @Override + public List apply(SymbolTable symbolTable) { + List result = new ArrayList(); + + SimpleExpTrans simpleExpTrans1 = new SimpleExpTrans(boolExpression + .getSimpleExp1(), null); + SimpleExpTrans simpleExpTrans2 = new SimpleExpTrans(boolExpression + .getSimpleExp2(), null); + + AtomicTrans atomicTrans = new AtomicTrans(null, + null, boolExpression.getRelation(), -1); + + result.add(simpleExpTrans1); + result.add(simpleExpTrans2); + result.add(atomicTrans); + + return result; + } + + @Override + public String getCodeText() { + return "boolexptrans(" + boolExpression.getCodeText() + ", tab)"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.java b/src/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.java new file mode 100644 index 0000000..100cb27 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/C0TransProgram.java @@ -0,0 +1,45 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import org.jalgo.module.am0c0.model.GenericProgram; + +public class C0TransProgram extends GenericProgram { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + public C0TransProgram clone() { + C0TransProgram transProgram = (C0TransProgram) super.clone(); + transProgram.clear(); + + for (TransformFunction transFunction : this) { + transProgram.add(transFunction.clone()); + } + + return transProgram; + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Entries b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Entries new file mode 100644 index 0000000..242d2c9 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Entries @@ -0,0 +1,17 @@ +/AddressSolver.java/1.1/Mon Aug 16 12:05:48 2010// +/AtomicTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/BlockTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/BoolExpTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/C0TransProgram.java/1.1/Mon Aug 16 12:05:48 2010// +/STSeqTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/STTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/SimpleExpTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/StubTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/Symbol.java/1.1/Mon Aug 16 12:05:48 2010// +/SymbolException.java/1.1/Mon Aug 16 12:05:48 2010// +/SymbolTable.java/1.1/Mon Aug 16 12:05:48 2010// +/Trans.java/1.1/Mon Aug 16 12:05:48 2010// +/TransException.java/1.1/Mon Aug 16 12:05:48 2010// +/TransformFunction.java/1.1/Mon Aug 16 12:05:48 2010// +/UpdateTrans.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Repository b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Repository new file mode 100644 index 0000000..e25b020 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/model/c0/trans diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Root b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.java new file mode 100644 index 0000000..3a0cd05 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/STSeqTrans.java @@ -0,0 +1,95 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.Statement; +import org.jalgo.module.am0c0.model.c0.ast.StatementSequence; + +/** + * Implements C0 stseqtrans function + * + * @author Felix Schmitt + */ +public class STSeqTrans extends TransformFunction { + /** + * The statement sequence, which may be {@code null}. + */ + private StatementSequence statementSequence; + + public STSeqTrans(StatementSequence token, + TreeAddress address) { + super(token, address); + this.statementSequence = token; + + description = Messages.getString("am0c0", "STSeqTrans.0") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.1") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.2") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.3") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.4") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.5") //$NON-NLS-1$ + + Messages.getString("am0c0", "STSeqTrans.6"); //$NON-NLS-1$ + } + + @Override + public List apply(SymbolTable symbolTable) throws TransException { + List result = new ArrayList(); + + if (null == statementSequence || statementSequence.getStatements().size() == 0) { + throw new TransException(Messages.getString("am0c0", "STSeqTrans.7")); //$NON-NLS-1$ + } + + TreeAddress baseAddr = new TreeAddress(getAddress()); + baseAddr.extend(); + + for (int i = 0; i < statementSequence.getStatements().size(); i++) { + Statement statement = statementSequence.getStatements().get(i); + + STTrans stTrans = new STTrans(statement, + new TreeAddress(baseAddr)); + result.add(stTrans); + + baseAddr.increase(); + } + + return result; + } + + @Override + public String getCodeText() { + StringBuilder result = new StringBuilder(); + result.append("stseqtrans("); + + if (null != statementSequence) { + result.append(statementSequence.getCodeText()); + } + + result.append(", tab, " + address + ")"); + + return result.toString(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/STTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/STTrans.java new file mode 100644 index 0000000..f90258a --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/STTrans.java @@ -0,0 +1,274 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.*; +import org.jalgo.module.am0c0.model.c0.ast.Statement.*; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType; +import org.jalgo.module.am0c0.model.c0.trans.Symbol.SymbolType; + +/** + * Implements C0 sttrans function + * + * @author Felix Schmitt + * + */ +public class STTrans extends TransformFunction { + + private Statement statement; + + public STTrans(Statement token, TreeAddress address) { + super(token, address); + this.statement = token; + + description = Messages.getString("am0c0", "STTrans.0"); //$NON-NLS-1$ + + if (statement instanceof CompStatement) + description += Messages.getString("am0c0", "STTrans.1") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.2") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.3"); //$NON-NLS-1$ + + if (statement instanceof AssignmentStatement) + description += Messages.getString("am0c0", "STTrans.4") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.5") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.6"); //$NON-NLS-1$ + + if (statement instanceof ScanfStatement) + description += Messages.getString("am0c0", "STTrans.7") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.8") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.9"); //$NON-NLS-1$ + + if (statement instanceof PrintfStatement) + description += Messages.getString("am0c0", "STTrans.10") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.11") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.12"); //$NON-NLS-1$ + + if (statement instanceof IfStatement) + description += Messages.getString("am0c0", "STTrans.13") + Messages.getString("am0c0", "STTrans.14") //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("am0c0", "STTrans.15") + Messages.getString("am0c0", "STTrans.16") + Messages.getString("am0c0", "STTrans.17") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + Messages.getString("am0c0", "STTrans.18") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.19"); //$NON-NLS-1$ + + if (statement instanceof IfElseStatement) + description += Messages.getString("am0c0", "STTrans.20") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.21") + Messages.getString("am0c0", "STTrans.22") //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("am0c0", "STTrans.23") + Messages.getString("am0c0", "STTrans.24") //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("am0c0", "STTrans.25") + Messages.getString("am0c0", "STTrans.26") //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("am0c0", "STTrans.27") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.28"); //$NON-NLS-1$ + + if (statement instanceof WhileStatement) + description += Messages.getString("am0c0", "STTrans.29") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.30") + Messages.getString("am0c0", "STTrans.31") //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("am0c0", "STTrans.32") + Messages.getString("am0c0", "STTrans.33") + Messages.getString("am0c0", "STTrans.34") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + Messages.getString("am0c0", "STTrans.35") //$NON-NLS-1$ + + Messages.getString("am0c0", "STTrans.36"); //$NON-NLS-1$ + } + + @Override + public List apply(SymbolTable symbolTable) throws TransException { + List result = new ArrayList(); + + if (statement instanceof CompStatement) { + StatementSequence statementSequence = ((CompStatement) statement) + .getStatementSequence(); + + STSeqTrans stSeqTrans = new STSeqTrans(statementSequence, getAddress()); + result.add(stSeqTrans); + return result; + } + + if (statement instanceof AssignmentStatement) { + String id = ((AssignmentStatement) statement).getIdent(); + try { + if (symbolTable.exists(id) && symbolTable.getType(id) == SymbolType.ST_VAR) { + SimpleExpTrans simpleExpTrans = new SimpleExpTrans( + ((AssignmentStatement) statement).getExpr(), null); + AtomicTrans atomicTrans = new AtomicTrans(null, null, AtomicType.STORE, + symbolTable.getAddress(id)); + + result.add(simpleExpTrans); + result.add(atomicTrans); + return result; + + } else { + throw new TransException(Messages.getString("am0c0", "STTrans.AssignError")); //$NON-NLS-1$ + } + } catch (SymbolException e) { + throw new TransException(e.getMessage()); + } + } + + if (statement instanceof ScanfStatement) { + String id = ((ScanfStatement) statement).getIdent(); + + try { + if (symbolTable.exists(id) && symbolTable.getType(id) == SymbolType.ST_VAR) { + + AtomicTrans atomicTrans = new AtomicTrans(null, null, AtomicType.READ, + symbolTable.getAddress(id)); + + result.add(atomicTrans); + return result; + } else { + throw new TransException(Messages.getString("am0c0", "STTrans.ScanfError")); //$NON-NLS-1$ + } + } catch (SymbolException e) { + throw new TransException(e.getMessage()); + } + } + + if (statement instanceof PrintfStatement) { + String id = ((PrintfStatement) statement).getIdent(); + + try { + if (symbolTable.exists(id) && symbolTable.getType(id) == SymbolType.ST_VAR) { + + AtomicTrans atomicTrans = new AtomicTrans(null, null, AtomicType.WRITE, + symbolTable.getAddress(id)); + + result.add(atomicTrans); + return result; + } else { + throw new TransException(Messages.getString("am0c0", "STTrans.PrintfError")); //$NON-NLS-1$ + } + } catch (SymbolException e) { + throw new TransException(e.getMessage()); + } + } + + if (statement instanceof IfStatement) { + BoolExpTrans boolExpTrans = new BoolExpTrans(((IfStatement) statement).getBoolExpr(), + null); + + TreeAddress jmcTargetAddress = new TreeAddress(getAddress()); + jmcTargetAddress.extend(); + AtomicTrans atomicTrans = new AtomicTrans(null, null, AtomicType.JMC, 0, + jmcTargetAddress); + + TreeAddress sttransAddress = new TreeAddress(jmcTargetAddress); + sttransAddress.increase(); + STTrans stTrans = new STTrans(((IfStatement) statement).getFirstStatement(), + sttransAddress); + + TreeAddress stubAddress = new TreeAddress(jmcTargetAddress, true); + StubTrans stubTrans = new StubTrans(null, stubAddress); + + result.add(boolExpTrans); + result.add(atomicTrans); + result.add(stTrans); + result.add(stubTrans); + return result; + } + + if (statement instanceof IfElseStatement) { + BoolExpTrans boolExpTrans = new BoolExpTrans(((IfElseStatement) statement) + .getBoolExpr(), null); + + TreeAddress jmcTargetAddress = new TreeAddress(getAddress()); + jmcTargetAddress.extend(); + AtomicTrans atomicTrans1 = new AtomicTrans(null, null, AtomicType.JMC, 0, + jmcTargetAddress); + + TreeAddress sttransAddress1 = new TreeAddress(jmcTargetAddress); + sttransAddress1.increase(); + STTrans stTrans1 = new STTrans(((IfElseStatement) statement).getFirstStatement(), + sttransAddress1); + + TreeAddress jmpTargetAddress = new TreeAddress(sttransAddress1); + jmpTargetAddress.increase(); + AtomicTrans atomicTrans2 = new AtomicTrans(null, null, AtomicType.JMP, 0, + jmpTargetAddress); + + TreeAddress stubAddress1 = new TreeAddress(jmcTargetAddress, true); + StubTrans stubTrans1 = new StubTrans(null, stubAddress1); + + TreeAddress sttransAddress2 = new TreeAddress(jmpTargetAddress); + sttransAddress2.increase(); + STTrans stTrans2 = new STTrans(((IfElseStatement) statement).getSecondStatement(), + sttransAddress2); + + TreeAddress stubAddress2 = new TreeAddress(jmpTargetAddress, true); + StubTrans stubTrans2 = new StubTrans(null, stubAddress2); + + result.add(boolExpTrans); + result.add(atomicTrans1); + result.add(stTrans1); + result.add(atomicTrans2); + result.add(stubTrans1); + result.add(stTrans2); + result.add(stubTrans2); + return result; + } + + if (statement instanceof WhileStatement) { + + TreeAddress boolStubAddress = new TreeAddress(getAddress(), true); + boolStubAddress.extend(); + + StubTrans boolStub = new StubTrans(null, boolStubAddress); + + BoolExpTrans boolExpTrans = new BoolExpTrans( + ((WhileStatement) statement).getBoolExpr(), null); + + TreeAddress jmcTargetAddress = new TreeAddress(boolStubAddress); + jmcTargetAddress.increase(); + AtomicTrans atomicTrans1 = new AtomicTrans(null, null, AtomicType.JMC, 0, + jmcTargetAddress); + + TreeAddress sttransAddress = new TreeAddress(jmcTargetAddress); + sttransAddress.increase(); + STTrans stTrans = new STTrans(((WhileStatement) statement).getFirstStatement(), + sttransAddress); + + TreeAddress jmpTargetAddress = new TreeAddress(boolStubAddress); + AtomicTrans atomicTrans2 = new AtomicTrans(null, null, AtomicType.JMP, 0, + jmpTargetAddress); + + TreeAddress stubAddress = new TreeAddress(jmcTargetAddress, true); + StubTrans stubTrans = new StubTrans(null, stubAddress); + + result.add(boolStub); + result.add(boolExpTrans); + result.add(atomicTrans1); + result.add(stTrans); + result.add(atomicTrans2); + result.add(stubTrans); + return result; + } + + throw new IllegalStateException( + "The correct instance of this Statement could not be determined."); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "sttrans(" + statement.getCodeText() + ", tab, " + address + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.java new file mode 100644 index 0000000..4135fc3 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/SimpleExpTrans.java @@ -0,0 +1,200 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.*; +import org.jalgo.module.am0c0.model.c0.ast.Factor.*; +import org.jalgo.module.am0c0.model.c0.ast.SimpleExpr.*; +import org.jalgo.module.am0c0.model.c0.ast.Term.*; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType; +import org.jalgo.module.am0c0.model.c0.trans.Symbol.SymbolType; + +/** + * Implementation of the C0 {@code simpleexptrans} function. + * + * @author Felix Schmitt + * @author Martin Morgenstern + */ +public class SimpleExpTrans extends TransformFunction { + + private SimpleExpr simpleExpression; + + public SimpleExpTrans(SimpleExpr token, TreeAddress address) { + super(token, address); + this.simpleExpression = token; + + description = Messages.getString("am0c0", "SimpleExpTrans.0"); //$NON-NLS-1$ + } + + /** + * Transform the SimpleExpression into a (semantic) equivalent list of + * TransformFunctions, in this case actually a list of AtomicTrans. + * + *

      + * As the lecture notes have no formal rules for transformation of + * SimpleExpressions, this transformation is done in one step (using private + * helper methods for transformation of Factors and Terms). + *

      + * + * @return a list of equivalent AtomicTrans objects + * @throws TransException + */ + @Override + public List apply(SymbolTable symbolTable) throws TransException { + List result = new ArrayList(); + try { + if (simpleExpression instanceof UnaryPlusExpr) { + result.addAll(termTrans(((UnaryPlusExpr) simpleExpression).getTerm(), symbolTable)); + } else if (simpleExpression instanceof UnaryMinusExpr) { + result.addAll(termTrans(((UnaryMinusExpr) simpleExpression).getTerm(), symbolTable)); + result.add(new AtomicTrans(null, null, AtomicType.LIT, -1)); + result.add(new AtomicTrans(null, null, AtomicType.MUL, 0)); + } else if (simpleExpression instanceof PlusExpr) { + PlusExpr plusExpr = (PlusExpr) simpleExpression; + SimpleExpTrans simpleExpTrans = new SimpleExpTrans(plusExpr.getLeft(), + null); + + result.addAll(simpleExpTrans.apply(symbolTable)); + result.addAll(termTrans(plusExpr.getRight(), symbolTable)); + result.add(new AtomicTrans(null, null, AtomicType.ADD, 0)); + } else if (simpleExpression instanceof MinusExpr) { + MinusExpr minusExpr = (MinusExpr) simpleExpression; + SimpleExpTrans simpleExpTrans = new SimpleExpTrans(minusExpr.getLeft(), + null); + + result.addAll(simpleExpTrans.apply(symbolTable)); + result.addAll(termTrans(minusExpr.getRight(), symbolTable)); + result.add(new AtomicTrans(null, null, AtomicType.SUB, 0)); + } else { + throw new IllegalStateException("Illegal form of SimpleExpression."); //$NON-NLS-1$ + } + + } catch (SymbolException e) { + throw new TransException(e.getMessage()); + } + return result; + } + + /** + * Transform Factors into a (semantic) equivalent list of AtomicTrans. + * + *
        + *
      • IdentFactors are translated into a {@code LOAD addr} AtomicTrans + * object, where {@code addr} is the corresponding address of the identifier + * (determined by looking up the symbol table).
      • + * + *
      • NumberFactors are translated into a {@code LIT z} AtomicTrans object, + * where {@code z} is the constant number (determined by the value of the + * token).
      • + * + *
      • Factors that contain SimpleExpressions in parentheses just transform + * the contained SimpleExpression.
      • + *
      + * + * @param factor + * the factor that is to be transformed + * @return a list of equivalent AtomicTrans objects + * @throws SymbolException + * @throws TransException + */ + private List factorTrans(Factor factor, SymbolTable symbolTable) throws SymbolException, + TransException { + List result = new ArrayList(); + + if (factor instanceof IdentFactor) { + String ident = ((IdentFactor) factor).getIdentName(); + + if (symbolTable.getType(ident) == SymbolType.ST_CONST) { + int value = 0; + value = symbolTable.getValue(ident); + + result.add(new AtomicTrans(null, null, AtomicType.LIT, value)); + } else { + int address = symbolTable.getAddress(ident); + result.add(new AtomicTrans(null, null, AtomicType.LOAD, address)); + } + } else if (factor instanceof NumberFactor) { + int value = ((NumberFactor) factor).getNumber(); + result.add(new AtomicTrans(null, null, AtomicType.LIT, value)); + } else if (factor instanceof CompExprFactor) { + SimpleExpr simpleExpr = ((CompExprFactor) factor).getSimpleExpr(); + SimpleExpTrans simpleExpTrans = new SimpleExpTrans(simpleExpr, null); + result.addAll(simpleExpTrans.apply(symbolTable)); + } else { + throw new TransException("Illegal form of Factor."); //$NON-NLS-1$ + } + + return result; + } + + /** + * Transform Terms into a (semantic) equivalent list of AtomicTrans objects. + * + *
        + *
      • FactorTerms are transformed by transforming the contained Factor.
      • + *
      • All other terms, which have two operands (a Term on the left side, a + * Factor on the right side) are transformed by transforming the Term, then + * the Factor and finally adding the corresponding AM0 operation (i.e. an + * AtomicTrans object for {@code MUL}, {@code DIV} or {@code MOD}).
      • + *
      + * + * @param term + * the Term to be transformed + * @return an equivalent list of AtomicTrans objects + * @throws SymbolException + * @throws TransException + */ + private List termTrans(Term term, SymbolTable symbolTable) throws SymbolException, TransException { + List result = new ArrayList(); + + if (term instanceof FactorTerm) { + result.addAll(factorTrans(((FactorTerm) term).getFactor(), symbolTable)); + } else if (term instanceof BinTerm) { + BinTerm multTerm = (BinTerm) term; + result.addAll(termTrans(multTerm.getLeft(), symbolTable)); + result.addAll(factorTrans(multTerm.getRight(), symbolTable)); + + if (term instanceof MultTerm) { + result.add(new AtomicTrans(null, null, AtomicType.MUL, 0)); + } else if (term instanceof DivTerm) { + result.add(new AtomicTrans(null, null, AtomicType.DIV, 0)); + } else if (term instanceof ModTerm) { + result.add(new AtomicTrans(null, null, AtomicType.MOD, 0)); + } + } else { + throw new TransException("Illegal form of Term."); //$NON-NLS-1$ + } + + return result; + } + + @Override + public String getCodeText() { + return "simpleexptrans(" + simpleExpression.getCodeText() + ", tab)"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/StubTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/StubTrans.java new file mode 100644 index 0000000..6ed424e --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/StubTrans.java @@ -0,0 +1,51 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.List; + +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.C0AST; + +/** + * Stub TransformFunction used for address merging + * @author Felix Schmitt + * + */ +public class StubTrans extends TransformFunction { + + public StubTrans(C0AST token, TreeAddress address) { + super(token, address); + } + + @Override + public List apply(SymbolTable symbolTable) { + throw new IllegalAccessError("Applying StubTrans is not allowed."); + } + + @Override + public String getCodeText() { + return ""; + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/Symbol.java b/src/org/jalgo/module/am0c0/model/c0/trans/Symbol.java new file mode 100644 index 0000000..9d20f19 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/Symbol.java @@ -0,0 +1,188 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import org.jalgo.main.util.Messages; + +/** + * Immutable representation of a C0 symbol, which may be a variable or constant. + * Both types have an identifier and additionally, + *
        + *
      • a variable symbol has a memory address and
      • + *
      • a constant symbol has a value.
      • + *
      + * Use the static factory methods {@link #varSymbol(String, int)} or + * {@link #constSymbol(String, int)} to get a new instance of a variable or + * constant symbol, respectively. They were chosen in favor of the standard + * constructor because of their clearer names and easier usage. + * + * @author Felix Schmitt + * @author Martin Morgenstern + */ +public class Symbol { + /** + * Enumeration that defines the type of a {@link Symbol}. + */ + public static enum SymbolType { + /** Constant symbols */ + ST_CONST, + /** Variable symbols */ + ST_VAR + } + + private final String id; + private final int value; + private final SymbolType type; + private final int address; + + /** The minimum value for an address. */ + private final static int ADDRESS_MIN = 1; + + /** + * Constant that is used to make clear that a value is actually not needed, + * but has to be initialized. + */ + private final static int UNUSED = -1; + + /** + * Static factory method which returns a new constant symbol. + * + * @param id + * the id (name) of the constant symbol + * @param value + * the value of the constant symbol + * @return a new constant symbol + */ + public static Symbol constSymbol(String id, int value) { + return new Symbol(id, UNUSED, SymbolType.ST_CONST, value); + } + + /** + * Static factory method which returns a new variable symbol. + * + * @param id + * the id (name) of the variable symbol + * @param address + * the memory address of the variable symbol + * @return a new variable symbol + * @throws IllegalArgumentException + * if address < {@value #ADDRESS_MIN} + */ + public static Symbol varSymbol(String id, int address) { + if (address < ADDRESS_MIN) { + throw new IllegalArgumentException(Messages.getString( + "am0c0", "Symbol.0") + ADDRESS_MIN); //$NON-NLS-1$ + } + + return new Symbol(id, address, SymbolType.ST_VAR, UNUSED); + } + + /** + * Constructs a new symbol. This is internal, please use the easier to use + * and read static factories {@link #constSymbol(String, int)} and + * {@link #varSymbol(String, int)} to get instances of this class. + * + * @param id + * the name of the symbol + * @param address + * the address of the symbol (use {@link #UNUSED} for constant + * symbols) + * @param type + * the type (const or var) of the symbol + * @param value + * the value of the symbol (use {@link #UNUSED} for variable + * symbols) + * @throws NullPointerException + * if {@code id} is {@code null} + */ + private Symbol(String id, int address, SymbolType type, int value) { + if (null == id) { + throw new NullPointerException("id must not be null"); + } + + this.id = id; + this.address = address; + this.value = value; + this.type = type; + } + + /** + * returns the name of the symbol + * + * @return the symbol's name/id + */ + public String getID() { + return id; + } + + /** + * returns the integer value of the symbol retrieving the value of an + * uninitialized symbol raises an exception + * + * @return the symbol's value + * @throws SymbolException + */ + public int getValue() { + return value; + } + + /** + * Get the address of this symbol. + * + * @return address of the symbol + * @throws SymbolException + * if the symbol is a constant symbol + */ + public int getAddress() throws SymbolException { + if (type == SymbolType.ST_CONST) + throw new SymbolException(Messages.getString("am0c0", "Symbol.1")); //$NON-NLS-1$ + + return address; + } + + /** + * returns the type of the symbol (const or var) + * + * @return the symbol's type + */ + public SymbolType getType() { + return type; + } + + /** + * returns the string representation of the symbol consisting of its id and + * value + * + * @return a string representation + */ + @Override + public String toString() { + String result = id; + + if (type == SymbolType.ST_CONST) { + result += " = " + value; //$NON-NLS-1$ + } + + return result; + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/SymbolException.java b/src/org/jalgo/module/am0c0/model/c0/trans/SymbolException.java new file mode 100644 index 0000000..69536a7 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/SymbolException.java @@ -0,0 +1,45 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +/** + * Indicates an error in handling of Symbol or SymbolTable + * + * @author Felix Schmitt + * + */ +public class SymbolException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public SymbolException() { + super(); + } + + public SymbolException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.java b/src/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.java new file mode 100644 index 0000000..0e0b569 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/SymbolTable.java @@ -0,0 +1,203 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.am0.Ram; +import org.jalgo.module.am0c0.model.c0.trans.Symbol.SymbolType; + +/** + * Represents a C0 symbol table + * + * @author Felix Schmitt + * + */ +public class SymbolTable implements Cloneable { + private Map symbols; + + /** + * constructor + */ + public SymbolTable() { + symbols = new HashMap(); + } + + @Override + public SymbolTable clone() { + try { + SymbolTable result = (SymbolTable) super.clone(); + result.symbols = new HashMap(symbols); + return result; + } catch (CloneNotSupportedException e) { + throw new AssertionError(e); + } + } + + /** + * removes all {@link Symbol}s from the table + */ + public void clear() { + symbols.clear(); + } + + /** + * adds a new symbol to the table + * + * @param symbol + * the new symbol + * @throws SymbolException + */ + public void add(Symbol symbol) throws SymbolException { + if (exists(symbol.getID())) + throw new SymbolException(Messages.getString("am0c0", "SymbolTable.0") + symbol.getID() + Messages.getString("am0c0", "SymbolTable.1")); //$NON-NLS-1$ //$NON-NLS-2$ + + if (symbol.getType() == SymbolType.ST_VAR) + for (Symbol s : symbols.values()) + if (s.getType() == SymbolType.ST_VAR && s.getAddress() == symbol.getAddress()) + throw new SymbolException(Messages.getString("am0c0", "SymbolTable.2") + s.getAddress() //$NON-NLS-1$ + + Messages.getString("am0c0", "SymbolTable.3")); //$NON-NLS-1$ + + symbols.put(symbol.getID(), symbol); + } + + /** + * checks if an symbol id already exists in the table + * + * @param id + * the id to check + * @return if the id exists in the table + */ + public boolean exists(String id) { + return symbols.containsKey(id); + } + + /** + * returns the number of entries in the table + * + * @return number of table entries + */ + public int size() { + return symbols.size(); + } + + /** + * transforms this SymbolTable into type String[][] for use with JTable + * + * @return a String[][] representation of this SymbolTable + * @throws SymbolException + */ + public String[][] toStringTable() throws SymbolException { + String[][] result = new String[size()][4]; + + Iterator iter = symbols.keySet().iterator(); + int i = 0; + while (iter.hasNext()) { + String key = iter.next(); + Symbol symbol = symbols.get(key); + + String tabOfId = ""; + + if (symbol.getType() == SymbolType.ST_CONST) { + tabOfId = "(const, " + symbol.getValue() + ")"; + } else { + tabOfId = "(var, " + symbol.getAddress() + ")"; + } + + String[] row = { symbol.getID(), tabOfId }; + result[i] = row; + i++; + } + + return result; + } + + /** + * returns a String representation of this SymbolTable. one {@link Symbol} + * per line + * + * @return a String representation + */ + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + + for (Symbol s : symbols.values()) { + result.append(s.toString()); + result.append("\n"); //$NON-NLS-1$ + } + + return result.toString(); + } + + /** + * returns the SymbolType of an id in the table. retrieving the type of an + * id not in the table raises an exception + * + * @param id + * the id to check + * @return the type of the symbol with this id + */ + public SymbolType getType(String id) throws SymbolException { + if (!exists(id)) + throw new SymbolException( + Messages.getString("am0c0", "SymbolTable.9")); //$NON-NLS-1$ + + return symbols.get(id).getType(); + } + + /** + * returns the value of an id in the table. retrieving the value of an id + * not in the table raises an exception + * + * @param id + * the id to check + * @return the value of the symbol with this id + */ + public int getValue(String id) throws SymbolException { + if (!exists(id)) + throw new SymbolException( + Messages.getString("am0c0", "SymbolTable.10")); //$NON-NLS-1$ + + return symbols.get(id).getValue(); + } + + /** + * returns the {@link Ram} address of the {@link Symbol} id in the table + * + * @param id + * identifier of the {@link Symbol} + * @return the {@link Ram} address of the {@link Symbol} + * @throws SymbolException + */ + public int getAddress(String id) throws SymbolException { + if (!exists(id)) + throw new SymbolException( + Messages.getString("am0c0", "SymbolTable.11")); //$NON-NLS-1$ + + return symbols.get(id).getAddress(); + } +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/Trans.java b/src/org/jalgo/module/am0c0/model/c0/trans/Trans.java new file mode 100644 index 0000000..a82ff8d --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/Trans.java @@ -0,0 +1,61 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.Program; + +/** + * Implements C0 trans function + * @author Felix Schmitt + * + */ +public class Trans extends TransformFunction { + + private Program program; + + public Trans(Program token, TreeAddress address) { + super(token, address); + this.program = token; + + description = Messages.getString("am0c0", "Trans.0") + //$NON-NLS-1$ + Messages.getString("am0c0", "Trans.1"); //$NON-NLS-1$ + } + + @Override + public List apply(SymbolTable symbolTable) { + List result = new ArrayList(); + result.add(new BlockTrans(program.getBlock(), null)); + return result; + } + + @Override + public String getCodeText() { + return "trans(" + program.getCodeText() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/TransException.java b/src/org/jalgo/module/am0c0/model/c0/trans/TransException.java new file mode 100644 index 0000000..aa212eb --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/TransException.java @@ -0,0 +1,45 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +/** + * Indicates an error in handling a TransformFunction + * + * @author Felix Schmitt + * + */ +public class TransException extends Exception { + + public TransException() { + super(); + } + + public TransException(String message) { + super(message); + } + + /** + * + */ + private static final long serialVersionUID = 1L; +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.java b/src/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.java new file mode 100644 index 0000000..e562f38 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/TransformFunction.java @@ -0,0 +1,81 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.model.CodeObject; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.C0AST; + +public abstract class TransformFunction extends CodeObject implements Cloneable { + protected String description; + + /** + * a C0-to-AM0 transformation function + * @param token the C0 token for this function + * @param address the basic address of this function, which is shown in the JEditor + */ + public TransformFunction(C0AST token, TreeAddress address) { + super(address); + description = Messages.getString("am0c0", "TransformFunction.0"); //$NON-NLS-1$ + } + + @Override + public TransformFunction clone() { + try { + TransformFunction clone = (TransformFunction) super.clone(); + return clone; + } catch (CloneNotSupportedException e) { + throw new AssertionError(e); // never happens + } + } + + /** + * returns the description of this TransformFunction + * @return a String representing which describes this TransformFunction + */ + public String getDescription() { + return description; + } + + @Override + public int getLinesCount() { + return StringUtils.countMatches(getCodeText(), "\n") + 1; //$NON-NLS-1$ + } + + @Override + public TreeAddress getAddress() { + return (TreeAddress)(super.getAddress()); + } + + /** + * Applies this TransformFunction and returns a List of resulting TransformFunctions + * @param symbolTable the current SymbolTable + * @return a List of generated TransformFunctions + * @throws TransException + */ + public abstract List apply(SymbolTable symbolTable) throws TransException; +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.java b/src/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.java new file mode 100644 index 0000000..33d7392 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/UpdateTrans.java @@ -0,0 +1,113 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.model.c0.trans; + +import java.util.List; + +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.ast.Declaration; +import org.jalgo.module.am0c0.model.c0.ast.C0AST.*; + +/** + * Implementation of the C0 {@code updatetrans} function. + * + * @author Felix Schmitt + * @author Martin Morgenstern + */ +public class UpdateTrans extends TransformFunction { + /** + * Contains the declaration part of the abstract syntax tree. + */ + private final Declaration declaration; + + public UpdateTrans(Declaration token, TreeAddress address) throws TransException { + super(token, address); + this.declaration = token; + } + + /** + * Runs the actual update function on symbolTable + * + * @param symbolTable + * the {@link SymbolTable} which has be to updated + * @throws TransException + */ + public void updateTable(SymbolTable symbolTable) throws TransException { + try { + updateConst(symbolTable); + updateVar(symbolTable); + } catch (SymbolException e) { + symbolTable.clear(); + throw new TransException(e.getMessage()); + } + } + + /** + * Fills the symbol table with the declared constants. + * + * @param symbolTable + * the {@link SymbolTable} which has be to updated + * @throws SymbolException + */ + private void updateConst(SymbolTable symbolTable) throws SymbolException { + if (declaration.getConstDecl() != null) { + List constants = declaration.getConstDecl().getConstants(); + + for (ConstIdent ident : constants) { + symbolTable.add(Symbol.constSymbol(ident.getName(), ident.getValue())); + } + } + } + + /** + * Fills the symbol table with the declared variables. + * + * @param symbolTable + * the {@link SymbolTable} which has be to updated + * @throws SymbolException + */ + private void updateVar(SymbolTable symbolTable) throws SymbolException { + if (declaration.getVarDecl() != null) { + List vars = declaration.getVarDecl().getDeclaredVars(); + + int addressCounter = 1; + + for (Ident ident : vars) { + symbolTable.add(Symbol.varSymbol(ident.getName(), addressCounter)); + ++addressCounter; + } + } + } + + @Override + public List apply(SymbolTable symbolTable) { + throw new IllegalAccessError("Applying UpdateTrans is not allowed." //$NON-NLS-1$ + + " Its constructor implicitly applies."); //$NON-NLS-1$ + } + + @Override + public String getCodeText() { + return "update(" + declaration.getCodeText() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/org/jalgo/module/am0c0/model/c0/trans/package-info.java b/src/org/jalgo/module/am0c0/model/c0/trans/package-info.java new file mode 100644 index 0000000..070a8fc --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/c0/trans/package-info.java @@ -0,0 +1,5 @@ +/** + * Classes that represent all transform functions from C0 to AM0. + */ +package org.jalgo.module.am0c0.model.c0.trans; + diff --git a/src/org/jalgo/module/am0c0/model/package-info.java b/src/org/jalgo/module/am0c0/model/package-info.java new file mode 100644 index 0000000..48d7731 --- /dev/null +++ b/src/org/jalgo/module/am0c0/model/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes to store and handle data of different types. + */ +package org.jalgo.module.am0c0.model; diff --git a/src/org/jalgo/module/am0c0/package-info.java b/src/org/jalgo/module/am0c0/package-info.java new file mode 100644 index 0000000..2eb9850 --- /dev/null +++ b/src/org/jalgo/module/am0c0/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes providing j-Algo module integration. + */ +package org.jalgo.module.am0c0; diff --git a/src/org/jalgo/module/am0c0/parser/CVS/Entries b/src/org/jalgo/module/am0c0/parser/CVS/Entries new file mode 100644 index 0000000..6b1f61c --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/CVS/Entries @@ -0,0 +1,7 @@ +/ErrorEvents.java/1.1/Mon Aug 16 12:05:49 2010// +/Parser.java/1.1/Mon Aug 16 12:05:49 2010// +/ParserConstants.java/1.1/Mon Aug 16 12:05:49 2010// +/ParserUtils.java/1.1/Mon Aug 16 12:05:49 2010// +D/am0//// +D/c0//// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/am0c0/parser/CVS/Repository b/src/org/jalgo/module/am0c0/parser/CVS/Repository new file mode 100644 index 0000000..dac0f65 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/parser diff --git a/src/org/jalgo/module/am0c0/parser/CVS/Root b/src/org/jalgo/module/am0c0/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/parser/ErrorEvents.java b/src/org/jalgo/module/am0c0/parser/ErrorEvents.java new file mode 100644 index 0000000..16d4723 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/ErrorEvents.java @@ -0,0 +1,361 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am0c0.parser.am0.GeneratedAM0Parser; +import org.jalgo.module.am0c0.parser.c0.GeneratedC0Parser; + +import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; + +import beaver.Scanner; +import beaver.Symbol; +import beaver.Parser.Events; + +/** + * Provides a replacement for the standard error reporting gateway of the Beaver + * parser generator. This class is not intended to be instantiated directly + * (since it is abstract), use {@link #forAm0()} or {@link #forC0()} to get + * instances of this class that are specialized for AM0 and C0 error reporting, + * respectively. + * + * @author Martin Morgenstern + */ +public abstract class ErrorEvents extends Events { + /** + * CSS style for highlighted user input (tokens) in error messages. + */ + private final static String STYLE_TOKEN = "background-color:#fff3af;font-size:100%;font-weight:bold;"; //$NON-NLS-1$ + + /** + * CSS style for words indicating an error. + */ + private final static String STYLE_ERROR = "color: #ff0000;"; //$NON-NLS-1$ + + /** + * Collects all syntax errors. + */ + private List syntaxErrors = new ArrayList(); + + /** + * Collects all lexer errors. + */ + private List lexicalErrors = new ArrayList(); + + /** + * Caches forbidden input sequences. + */ + private StringBuilder forbiddenInput = new StringBuilder(); + + /** + * Marker for the last line where an unmatched character was found (i.e. the + * "catch-all" rule of the lexer matched) and a lexer error occured. + */ + private int lastScannerErrorLine = 1; + + /** + * Handles scanner errors. Unmatched characters are collected per line and + * printed together. + */ + @Override + public void scannerError(Scanner.Exception e) { + if (e.line != lastScannerErrorLine) { + finishScannerErrorLine(); + } + + forbiddenInput.append(e.getMessage()); + lastScannerErrorLine = e.line; + } + + /** + * Add an error message with the cached characters in {@code forbiddenInput} + * to the lexer error list and clear the cache. If the cache is empty, do + * nothing. + */ + private void finishScannerErrorLine() { + if (forbiddenInput.length() > 0) { + final String error = String.format( + translate("DontKnowWhatToDo"), //$NON-NLS-1$ + STYLE_TOKEN, escapeHtml(forbiddenInput.toString()), + lastScannerErrorLine); + lexicalErrors.add(error); + forbiddenInput = new StringBuilder(); + } + } + + /** + * Handle syntax errors. + */ + @Override + public void syntaxError(Symbol token) { + final String tokenValue = (token.value != null) ? token.value + .toString() : "#" + token.getId(); //$NON-NLS-1$ + + int line = Symbol.getLine(token.getStart()); + int col = Symbol.getColumn(token.getStart()); + + String error; + + if (ParserConstants.EOF.equals(tokenValue)) { + error = String.format(translate("UnexpectedEOF"), line, col); //$NON-NLS-1$ + } else if (ParserConstants.EOL.equals(tokenValue)) { + error = String.format(translate("UnexpectedEOL"), line, col); //$NON-NLS-1$ + } else { + error = String.format(translate("UnexpectedTokenAt"), STYLE_TOKEN, //$NON-NLS-1$ + escapeHtml(tokenValue), line, col); + } + + syntaxErrors.add(error); + } + + /** + * Handle the deletion of unexpected tokens. Here an error message is + * appended to the last error message to give the user a hint. + */ + @Override + public void unexpectedTokenRemoved(Symbol token) { + extendLastErrorMessage(translate("RemoveThisToken")); //$NON-NLS-1$ + } + + /** + * Helper method that appends a string to the last element of the syntax + * error list. + * + * @param extension + * the string to append + */ + protected void extendLastErrorMessage(String extension) { + int replacePosition = syntaxErrors.size() - 1; + + if (replacePosition >= 0) { + String error = syntaxErrors.get(replacePosition) + " " + extension; //$NON-NLS-1$ + syntaxErrors.set(replacePosition, error); + } + } + + /** + * Specific implementation of C0 error events to give the user better hints + * how to recover from a syntax error. + */ + private static class C0ErrorEvents extends ErrorEvents { + /** + * Contains a mapping of hints for terminal symbols that should be + * inserted by the user. + */ + private static final Map hints; + + static { + final Map m = new HashMap(); + + final String insertRelation = translate("InsertRelation"); //$NON-NLS-1$ + m.put(GeneratedC0Parser.Terminals.EQ, insertRelation); + m.put(GeneratedC0Parser.Terminals.NE, insertRelation); + m.put(GeneratedC0Parser.Terminals.LE, insertRelation); + m.put(GeneratedC0Parser.Terminals.GE, insertRelation); + m.put(GeneratedC0Parser.Terminals.LT, insertRelation); + m.put(GeneratedC0Parser.Terminals.GT, insertRelation); + + m.put(GeneratedC0Parser.Terminals.AMP, translate("InsertAmp")); //$NON-NLS-1$ + m.put(GeneratedC0Parser.Terminals.COMMA, translate("InsertComma")); //$NON-NLS-1$ + m.put(GeneratedC0Parser.Terminals.ASSIGN, translate("InsertAssign")); //$NON-NLS-1$ + m.put(GeneratedC0Parser.Terminals.SEMICOLON, + translate("InsertSemicolon")); //$NON-NLS-1$ + + m.put(GeneratedC0Parser.Terminals.IDENT, translate("InsertIdent")); //$NON-NLS-1$ + m.put(GeneratedC0Parser.Terminals.NUMBER, translate("InsertNumber")); //$NON-NLS-1$ + + hints = Collections.unmodifiableMap(m); + } + + @Override + public void missingTokenInserted(Symbol token) { + final Short id = token.getId(); + if (hints.containsKey(id)) { + extendLastErrorMessage(hints.get(id)); + } + } + } + + /** + * Specific implementation of AM0 error events. + */ + private static class AM0ErrorEvents extends ErrorEvents { + /** + * Contains a mapping of hints for terminal symbols that should be + * inserted by the user. + */ + private static final Map hints; + + static { + final Map m = new HashMap(); + + m.put(GeneratedAM0Parser.Terminals.NUMBER, + translate("InsertNumber_AM0")); //$NON-NLS-1$ + m.put(GeneratedAM0Parser.Terminals.SEMICOLON, + translate("InsertSemicolon_AM0")); //$NON-NLS-1$ + + hints = Collections.unmodifiableMap(m); + } + + @Override + public void missingTokenInserted(Symbol token) { + final Short id = token.getId(); + if (hints.containsKey(id)) { + extendLastErrorMessage(hints.get(id)); + } + } + } + + /** + * Indicates that an error can be recovered if {@code token} is inserted at + * the position of the syntax error. + */ + @Override + public abstract void missingTokenInserted(Symbol token); + + /** + * Indicates that an error can be recovered if the error token is replaced + * by {@code token}. + */ + @Override + public void misspelledTokenReplaced(Symbol token) { + } + + @Override + public void errorPhraseRemoved(Symbol error) { + } + + /** + * Used to collect string to int conversion errors because of too large + * integers. + * + * @param number + * the string containing the number that was too large to convert + * @param line + * the line on which the error occured + * @param col + * the column in which the error occured + */ + public void conversionError(final String number, final int line, + final int col) { + lexicalErrors.add(String.format(translate("NumberTooLarge"), + STYLE_TOKEN, escapeHtml(number), line, col, Integer.MAX_VALUE)); + } + + /** + * Get the total amount of errors collected. + * + * @return total amount of errors + */ + private int getErrorCount() { + return lexicalErrors.size() + syntaxErrors.size(); + } + + /** + * Check wether an error occured during parsing. + * + * @return {@code true}, if there was at least one error, otherwise + * {@code false} + */ + public boolean hasErrors() { + // update internal state + finishScannerErrorLine(); + return getErrorCount() > 0; + } + + /** + * Get a summarizing error text (HTML formatted) for all the errors that + * occured during parsing or {@code null}, if no error occured. Use + * {@link #hasErrors()} to check if errors occured. + * + * @return summarizing error text or {@code null}, if no error occured + */ + public String getErrorText() { + if (!hasErrors()) { + return null; + } + + StringBuilder result = new StringBuilder("

      "); // $NON-NLS-1$ + + if (getErrorCount() > 1) { + result.append(String.format(translate("FollowingErrors"), + STYLE_ERROR)); // $NON-NLS-1$ + } else { + result.append(String.format(translate("FollowingError"), + STYLE_ERROR)); // $NON-NLS-1$ + } + + result.append("
      "); // $NON-NLS-1$ + final String itemFormat = " - %s: %s
      "; //$NON-NLS-1$ + + for (String error : lexicalErrors) { + result.append(String.format(itemFormat, + translate("LexicalAnalysis"), error)); //$NON-NLS-1$ + } + + for (String error : syntaxErrors) { + result.append(String.format(itemFormat, + translate("SyntacticAnalysis"), error)); //$NON-NLS-1$ + } + + result.append("

      "); //$NON-NLS-1$ + + return result.toString(); + } + + /** + * Get a fresh {@link ErrorEvents} instance specialized for AM0 parsers. + * + * @return a new {@link ErrorEvents} instance + */ + public static ErrorEvents forAm0() { + return new AM0ErrorEvents(); + } + + /** + * Get a fresh {@link ErrorEvents} instance specialized for C0 parsers. + * + * @return a new {@link ErrorEvents} instance + */ + public static ErrorEvents forC0() { + return new C0ErrorEvents(); + } + + /** + * Convenience method to get translated strings for this class. + * + * @see Messages + * @param index + * the index name of the externalized string + * @return the translation + */ + protected static String translate(String index) { + return Messages.getString("am0c0", "ErrorEvents." + index); //$NON-NLS-1$ $NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/am0c0/parser/Parser.java b/src/org/jalgo/module/am0c0/parser/Parser.java new file mode 100644 index 0000000..15fcee1 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/Parser.java @@ -0,0 +1,55 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser; + +/** + * The {@code Parser} interface provides common methods for dealing + * with the AM0 and C0 parsers. + * + * @author Martin Morgenstern + * @see org.jalgo.module.am0c0.parser.c0.C0Parser + * @see org.jalgo.module.am0c0.parser.am0.AM0Parser + */ +public interface Parser { + /** + * Parse the source code contained in {@code text} and check the source code + * for syntax errors. If there was no syntax error, {@code true} is + * returned, else {@code false} is returned and a detailed error message + * will be available by invoking the method {@link #getErrorText()}. + * + * @param text + * the program source code + * @return {@code true}, if the program source code contains no syntax + * errors, {@code false} otherwise + */ + public boolean parse(String text); + + /** + * If a previous call to {@link #parse(String)} returned {@code false}, this + * method returns a detailed message describing the error that occured while + * parsing. Otherwise it will return {@code null}. + * + * @return a detailed error message from the parser + */ + public String getErrorText(); +} diff --git a/src/org/jalgo/module/am0c0/parser/ParserConstants.java b/src/org/jalgo/module/am0c0/parser/ParserConstants.java new file mode 100644 index 0000000..6634598 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/ParserConstants.java @@ -0,0 +1,48 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser; + +/** + * Set of constants that are used by the parser package. + * + * @author Martin Morgenstern + */ +public final class ParserConstants { + /** + * This class is not designed to be instantiated, therefore it's constructor + * is private. + */ + private ParserConstants() { + throw new AssertionError(); + } + + /** + * Constant used as the value for end-of-file symbols (i.e. tokens). + */ + public static final String EOF = "end-of-file"; + + /** + * Constant used as the value for end-of-line symbols (i.e. tokens). + */ + public static final String EOL = "end-of-line"; +} diff --git a/src/org/jalgo/module/am0c0/parser/ParserUtils.java b/src/org/jalgo/module/am0c0/parser/ParserUtils.java new file mode 100644 index 0000000..78a7599 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/ParserUtils.java @@ -0,0 +1,66 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser; + +import beaver.Symbol; + +/** + * Utility class for parser-related work. + * + * @author Martin Morgenstern + */ +public class ParserUtils { + /** + * Utility method that safely converts symbols into numbers. If the + * conversion is not successful, the error is reported through the error + * reporting gateway. + * + * @param symbol + * the symbol that should be converted + * @param report + * the error reporting gateway to use + * @return the corresponding integer value, or {@code 0} if conversion + * failed + * @see ErrorEvents + */ + public static int safeSymbolToInt(final Symbol symbol, + final ErrorEvents report) { + int result = 0; + + if ((null == symbol) || (null == symbol.value)) { + return result; + } + + final String number = symbol.value.toString(); + final int line = Symbol.getLine(symbol.getStart()); + final int col = Symbol.getColumn(symbol.getStart()); + + try { + result = Integer.parseInt(number); + } catch (NumberFormatException e) { + report.conversionError(number, line, col); + } + + return result; + } +} diff --git a/src/org/jalgo/module/am0c0/parser/am0/AM0Parser.java b/src/org/jalgo/module/am0c0/parser/am0/AM0Parser.java new file mode 100644 index 0000000..cbc037e --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/AM0Parser.java @@ -0,0 +1,109 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser.am0; + +import java.io.IOException; +import java.io.StringReader; + +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.parser.ErrorEvents; +import org.jalgo.module.am0c0.parser.Parser; + +/** + * Provides an abstraction to the generated AM0 lexer and parser as well as an + * implementation of the {@code Parser} interface. + * + * @author Martin Morgenstern + * @see Parser + */ +public class AM0Parser implements Parser { + /** + * The resulting AM0 program. + */ + private AM0Program program; + + /** + * Contains the parser error message in case of an error, otherwise + * {@code null}. + */ + private String errorText; + + /** + * Get the abstract representation of the parsed program, or {@code null} if + * there was an error while parsing. + * + *

      + * Note: You must invoke {@link #parse(String)} first and + * do error handling as needed, otherwise you will get unexpected results. + * + * @return an AM0Program containing the abstract representation of the + * parsed program + */ + public AM0Program getProgram() { + return program; + } + + /** + * {@inheritDoc} + */ + @Override + public String getErrorText() { + return errorText; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean parse(final String text) { + boolean errorFlag = false; + + GeneratedAM0Parser parser = new GeneratedAM0Parser(); + AM0Scanner scanner = new AM0Scanner(new StringReader(text.trim())); + + errorText = ""; + program = null; + + try { + program = (AM0Program) parser.parse(scanner); + } catch (beaver.Parser.Exception e) { + errorFlag = true; + } catch (IOException e) { + errorFlag = true; + } + + ErrorEvents errors = parser.getErrorEvents(); + + if (errors.hasErrors()) { + errorFlag = true; + errorText += errors.getErrorText(); + } + + if (!errorFlag) { + errorText = null; + return true; + } + + return false; + } +} diff --git a/src/org/jalgo/module/am0c0/parser/am0/AM0Scanner.java b/src/org/jalgo/module/am0c0/parser/am0/AM0Scanner.java new file mode 100644 index 0000000..17f569a --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/AM0Scanner.java @@ -0,0 +1,735 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/* The following code was generated by JFlex 1.4.3 on 30.06.10 19:58 */ + +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +package org.jalgo.module.am0c0.parser.am0; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.am0c0.parser.ParserConstants; +import org.jalgo.module.am0c0.parser.am0.GeneratedAM0Parser.Terminals; + + +/** + * This class is a scanner generated by + * JFlex 1.4.3 + * on 30.06.10 19:58 from the specification file + * /home/mm/Projekte/SWP/module/am0-lexer.l + */ +class AM0Scanner extends Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\5\1\1\1\0\1\5\1\2\22\0\1\5\14\0\1\7"+ + "\2\0\1\3\11\4\1\0\1\6\5\0\1\10\1\16\1\32\1\11"+ + "\1\22\1\0\1\26\1\0\1\17\1\30\1\0\1\14\1\12\1\24"+ + "\1\21\1\31\1\23\1\27\1\15\1\25\1\13\1\20\1\33\uffa8\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\2\2\2\3\1\4\1\5\1\6\13\1"+ + "\6\0\1\7\1\10\2\0\1\11\1\12\1\13\1\14"+ + "\3\0\1\15\1\16\1\17\1\20\1\21\1\0\1\22"+ + "\2\0\1\23\1\24\1\0\1\25\1\0\1\26\1\0"+ + "\1\27\1\30"; + + private static int [] zzUnpackAction() { + int [] result = new int[55]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\34\0\34\0\70\0\34\0\124\0\160\0\34"+ + "\0\34\0\214\0\250\0\304\0\340\0\374\0\u0118\0\u0134"+ + "\0\u0150\0\u016c\0\u0188\0\u01a4\0\u01c0\0\u01dc\0\u01f8\0\u0214"+ + "\0\u0230\0\u024c\0\34\0\34\0\u0268\0\u0284\0\34\0\34"+ + "\0\34\0\34\0\u02a0\0\u02bc\0\u02d8\0\34\0\34\0\34"+ + "\0\34\0\34\0\u02f4\0\34\0\u0310\0\u032c\0\34\0\34"+ + "\0\u0348\0\34\0\u0364\0\34\0\u0380\0\34\0\34"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[55]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11"+ + "\1\12\1\13\1\14\1\2\1\15\1\16\4\2\1\17"+ + "\1\2\1\20\1\2\1\21\1\22\1\23\2\2\1\24"+ + "\35\0\1\3\35\0\2\6\34\0\1\7\37\0\1\25"+ + "\41\0\1\26\27\0\1\27\5\0\1\30\31\0\1\31"+ + "\1\0\1\32\1\33\2\0\1\34\21\0\1\35\11\0"+ + "\1\36\31\0\1\37\32\0\1\40\33\0\1\41\2\0"+ + "\1\42\30\0\1\43\23\0\1\44\50\0\1\45\15\0"+ + "\1\46\42\0\1\47\27\0\1\50\30\0\1\51\47\0"+ + "\1\52\16\0\1\53\41\0\1\54\36\0\1\55\22\0"+ + "\1\56\54\0\1\57\1\60\20\0\1\61\25\0\1\62"+ + "\51\0\1\63\15\0\1\64\47\0\1\65\30\0\1\66"+ + "\33\0\1\67\11\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[924]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\2\11\1\1\1\11\2\1\2\11\13\1\6\0"+ + "\2\11\2\0\4\11\3\0\5\11\1\0\1\11\2\0"+ + "\2\11\1\0\1\11\1\0\1\11\1\0\2\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[55]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + AM0Scanner(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + AM0Scanner(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 80) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Symbol nextToken() throws java.io.IOException, Scanner.Exception { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 24: + { return symbol(Terminals.WRITE, "WRITE"); + } + case 25: break; + case 14: + { return symbol(Terminals.DIV, "DIV"); + } + case 26: break; + case 6: + { return symbol(Terminals.MINUS, "-"); + } + case 27: break; + case 21: + { return symbol(Terminals.LOAD, "LOAD"); + } + case 28: break; + case 1: + { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); + } + case 29: break; + case 3: + { return symbol(Terminals.NUMBER, yytext()); + } + case 30: break; + case 2: + { return symbol(Terminals.EOL, ParserConstants.EOL); + } + case 31: break; + case 12: + { return symbol(Terminals.GT, "GT"); + } + case 32: break; + case 18: + { return symbol(Terminals.SUB, "SUB"); + } + case 33: break; + case 9: + { return symbol(Terminals.EQ, "EQ"); + } + case 34: break; + case 8: + { return symbol(Terminals.LT, "LT"); + } + case 35: break; + case 7: + { return symbol(Terminals.LE, "LE"); + } + case 36: break; + case 10: + { return symbol(Terminals.NE, "NE"); + } + case 37: break; + case 13: + { return symbol(Terminals.ADD, "ADD"); + } + case 38: break; + case 19: + { return symbol(Terminals.JMP, "JMP"); + } + case 39: break; + case 15: + { return symbol(Terminals.MUL, "MUL"); + } + case 40: break; + case 5: + { return symbol(Terminals.SEMICOLON, ";"); + } + case 41: break; + case 17: + { return symbol(Terminals.LIT, "LIT"); + } + case 42: break; + case 22: + { return symbol(Terminals.READ, "READ"); + } + case 43: break; + case 11: + { return symbol(Terminals.GE, "GE"); + } + case 44: break; + case 20: + { return symbol(Terminals.JMC, "JMC"); + } + case 45: break; + case 16: + { return symbol(Terminals.MOD, "MOD"); + } + case 46: break; + case 4: + { /* ignore */ + } + case 47: break; + case 23: + { return symbol(Terminals.STORE, "STORE"); + } + case 48: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + { return symbol(Terminals.EOF, ParserConstants.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/src/org/jalgo/module/am0c0/parser/am0/CVS/Entries b/src/org/jalgo/module/am0c0/parser/am0/CVS/Entries new file mode 100644 index 0000000..9d81184 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/CVS/Entries @@ -0,0 +1,4 @@ +/AM0Parser.java/1.2/Wed Dec 8 13:01:53 2010// +/AM0Scanner.java/1.1/Mon Aug 16 12:05:48 2010// +/GeneratedAM0Parser.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/parser/am0/CVS/Repository b/src/org/jalgo/module/am0c0/parser/am0/CVS/Repository new file mode 100644 index 0000000..42fc4b4 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/parser/am0 diff --git a/src/org/jalgo/module/am0c0/parser/am0/CVS/Root b/src/org/jalgo/module/am0c0/parser/am0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.java b/src/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.java new file mode 100644 index 0000000..05e359d --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/GeneratedAM0Parser.java @@ -0,0 +1,260 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ + +package org.jalgo.module.am0c0.parser.am0; + +import java.util.ArrayList; +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.parser.ParserUtils; +import beaver.*; +import org.jalgo.module.am0c0.model.am0.*; +import org.jalgo.module.am0c0.parser.ErrorEvents; +import org.jalgo.module.am0c0.model.AddressException; + +/** + * This class is a LALR parser generated by + * Beaver v0.9.6.1 + * from the grammar specification "am0-parser.g". + */ +public class GeneratedAM0Parser extends Parser { + static public class Terminals { + static public final short EOF = 0; + static public final short SEMICOLON = 1; + static public final short NUMBER = 2; + static public final short EOL = 3; + static public final short ADD = 4; + static public final short MUL = 5; + static public final short SUB = 6; + static public final short DIV = 7; + static public final short MOD = 8; + static public final short EQ = 9; + static public final short NE = 10; + static public final short LT = 11; + static public final short GT = 12; + static public final short LE = 13; + static public final short GE = 14; + static public final short JMP = 15; + static public final short JMC = 16; + static public final short LOAD = 17; + static public final short STORE = 18; + static public final short LIT = 19; + static public final short WRITE = 20; + static public final short READ = 21; + static public final short MINUS = 22; + } + + static final ParsingTables PARSING_TABLES = new ParsingTables( + "U9oLqGbB0b4KXk5lHjjjDHjJsnUYeB35iYIAecYXA8h#Jl#sVT$BFBqZ8qWas0pFEOSxXxl" + + "CbNIYMjMfNWrgL9CYQbQBMjMcTdMgIt4brAU1gdg6v9hPcNqhf1GnggGL55QD5InlN$Pf7$" + + "PkR$PgB$PiJ$Qe3aNjGJrsgHZLlJpYdRg9jtPZ5#gbEbS$yLg3n2iD#$DLt0tpiQDOLJrnr" + + "f6I2B5kI2wd4ACEjVFdwz7ZSDvILHwT2gFIo2c1$v8dZQ85KnX36jEOmIpcaC4y5f358fQG" + + "mp9Mi8erh6C3czZ2EBQnWrtiOHy7ECGHZZ7fxuad4cJFp$$bdwUidWXoQUvqaADbFPaWPuE" + + "S#pMV$yIv4uUxSH4ktaVrt8eylYUANAL#0E9wMni="); + + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + + private final Action[] actions; + + public GeneratedAM0Parser() { + super(PARSING_TABLES); + actions = new Action[] { + Action.RETURN, // [0] Program = CommandList + new Action() { // [1] CommandList = Command.a SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final SimulationStatement a = (SimulationStatement) _symbol_a.value; + AM0Program program = new AM0Program(); program.add(a); return new Symbol(program); + } + }, + new Action() { // [2] CommandList = CommandList.a EOL Command.b SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final AM0Program a = (AM0Program) _symbol_a.value; + final Symbol _symbol_b = _symbols[offset + 3]; + final SimulationStatement b = (SimulationStatement) _symbol_b.value; + a.add(b); return new Symbol(a); + } + }, + new Action() { // [3] Command = ADD.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Add(address(a))); + } + }, + new Action() { // [4] Command = MUL.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Mul(address(a))); + } + }, + new Action() { // [5] Command = SUB.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Sub(address(a))); + } + }, + new Action() { // [6] Command = DIV.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Div(address(a))); + } + }, + new Action() { // [7] Command = MOD.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Mod(address(a))); + } + }, + new Action() { // [8] Command = EQ.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new Equal(address(a))); + } + }, + new Action() { // [9] Command = NE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new NotEqual(address(a))); + } + }, + new Action() { // [10] Command = LT.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new LesserThen(address(a))); + } + }, + new Action() { // [11] Command = GT.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new GreaterThen(address(a))); + } + }, + new Action() { // [12] Command = LE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new LesserEqual(address(a))); + } + }, + new Action() { // [13] Command = GE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(new GreaterEqual(address(a))); + } + }, + new Action() { // [14] Command = JMP.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Jmp(address(a), b)); + } + }, + new Action() { // [15] Command = JMC.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Jmc(address(a), b)); + } + }, + new Action() { // [16] Command = LOAD.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Load(address(a), b)); + } + }, + new Action() { // [17] Command = STORE.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Store(address(a), b)); + } + }, + new Action() { // [18] Command = LIT.a Number.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Lit(address(a), b)); + } + }, + new Action() { // [19] Command = WRITE.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Write(address(a), b)); + } + }, + new Action() { // [20] Command = READ.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(new Read(address(a), b)); + } + }, + new Action() { // [21] UnsignedNumber = NUMBER.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(ParserUtils.safeSymbolToInt(a, (ErrorEvents) report)); + } + }, + new Action() { // [22] Number = UnsignedNumber.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final Integer a = (Integer) _symbol_a.value; + return new Symbol(a); + } + }, + new Action() { // [23] Number = MINUS UnsignedNumber.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 2]; + final Integer a = (Integer) _symbol_a.value; + return new Symbol(-a); + } + } + }; + + + this.report = ErrorEvents.forAm0(); + } + + protected Symbol invokeReduceAction(int rule_num, int offset) { + return actions[rule_num].reduce(_symbols, offset); + } +} diff --git a/src/org/jalgo/module/am0c0/parser/am0/package-info.java b/src/org/jalgo/module/am0c0/parser/am0/package-info.java new file mode 100644 index 0000000..dcea7a1 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/am0/package-info.java @@ -0,0 +1,4 @@ +/** + * Lexer, parser and related classes for analysing AM0 source code. + */ +package org.jalgo.module.am0c0.parser.am0; diff --git a/src/org/jalgo/module/am0c0/parser/c0/C0Parser.java b/src/org/jalgo/module/am0c0/parser/c0/C0Parser.java new file mode 100644 index 0000000..42f879d --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/C0Parser.java @@ -0,0 +1,117 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.parser.c0; + +import java.io.IOException; +import java.io.StringReader; + +import org.jalgo.module.am0c0.model.c0.C0Program; +import org.jalgo.module.am0c0.model.c0.ast.Program; +import org.jalgo.module.am0c0.parser.ErrorEvents; +import org.jalgo.module.am0c0.parser.Parser; + +/** + * Provides an abstraction to the generated C0 parser/lexer as well as an + * implementation of the {@code Parser} interface. + * + * @author Martin Morgenstern + * @see Parser + */ +public class C0Parser implements Parser { + /** + * The resulting C0 program. + */ + private C0Program program; + + /** + * Contains the error message in case of an parser error. + */ + private String errorText; + + /** + * Gets the resulting generic program containing the abstract syntax tree + * part {@code Program}. Returns {@code null} if the parser encountered an + * error. + * + *

      + * Note: You must first parse the source code via + * {@link #parse(String)} and handle any errors that may occur while + * parsing. + * + * @return a C0Program containing the abstract representation of the parsed + * program + */ + public C0Program getProgram() { + return program; + } + + /** + * {@inheritDoc} + */ + @Override + public String getErrorText() { + return errorText; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean parse(final String text) { + if (null == text) { + throw new NullPointerException("text must not be null"); + } + + boolean errorFlag = false; + + GeneratedC0Parser parser = new GeneratedC0Parser(); + C0Scanner scanner = new C0Scanner(new StringReader(text)); + + errorText = ""; + program = null; + + try { + Program prog = (Program) parser.parse(scanner); + program = new C0Program(); + program.add(prog); + } catch (beaver.Parser.Exception e) { + errorFlag = true; + } catch (IOException e) { + errorFlag = true; + } + + ErrorEvents errors = parser.getErrorEvents(); + + if (errors.hasErrors()) { + errorFlag = true; + errorText += errors.getErrorText(); + } + + if (!errorFlag) { + errorText = null; + return true; + } + + return false; + } +} diff --git a/src/org/jalgo/module/am0c0/parser/c0/C0Scanner.java b/src/org/jalgo/module/am0c0/parser/c0/C0Scanner.java new file mode 100644 index 0000000..1acf459 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/C0Scanner.java @@ -0,0 +1,934 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/* The following code was generated by JFlex 1.4.3 on 30.06.10 19:59 */ + +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +package org.jalgo.module.am0c0.parser.c0; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.am0c0.parser.ParserConstants; +import org.jalgo.module.am0c0.parser.c0.GeneratedC0Parser.Terminals; + + +/** + * This class is a scanner generated by + * JFlex 1.4.3 + * on 30.06.10 19:59 from the specification file + * /home/mm/Projekte/SWP/module/c0-lexer.l + */ +class C0Scanner extends Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\3\1\1\1\1\1\0\1\1\1\1\16\3\4\0\1\1\1\51"+ + "\1\45\1\10\1\2\1\46\1\40\1\0\1\31\1\32\1\7\1\47"+ + "\1\36\1\50\1\24\1\6\1\4\11\5\1\0\1\37\1\20\1\35"+ + "\1\26\2\0\32\2\4\0\1\2\1\0\1\30\1\2\1\13\1\16"+ + "\1\17\1\41\1\2\1\25\1\11\2\2\1\14\1\27\1\12\1\23"+ + "\1\43\1\2\1\44\1\21\1\22\1\15\1\2\1\42\3\2\1\33"+ + "\1\0\1\34\1\0\41\3\2\0\4\2\4\0\1\2\2\0\1\3"+ + "\7\0\1\2\4\0\1\2\5\0\27\2\1\0\37\2\1\0\u013f\2"+ + "\31\0\162\2\4\0\14\2\16\0\5\2\11\0\1\2\21\0\130\3"+ + "\5\0\23\3\12\0\1\2\13\0\1\2\1\0\3\2\1\0\1\2"+ + "\1\0\24\2\1\0\54\2\1\0\46\2\1\0\5\2\4\0\202\2"+ + "\1\0\4\3\3\0\105\2\1\0\46\2\2\0\2\2\6\0\20\2"+ + "\41\0\46\2\2\0\1\2\7\0\47\2\11\0\21\3\1\0\27\3"+ + "\1\0\3\3\1\0\1\3\1\0\2\3\1\0\1\3\13\0\33\2"+ + "\5\0\3\2\15\0\4\3\14\0\6\3\13\0\32\2\5\0\13\2"+ + "\16\3\7\0\12\3\4\0\2\2\1\3\143\2\1\0\1\2\10\3"+ + "\1\0\6\3\2\2\2\3\1\0\4\3\2\2\12\3\3\2\2\0"+ + "\1\2\17\0\1\3\1\2\1\3\36\2\33\3\2\0\3\2\60\0"+ + "\46\2\13\3\1\2\u014f\0\3\3\66\2\2\0\1\3\1\2\20\3"+ + "\2\0\1\2\4\3\3\0\12\2\2\3\2\0\12\3\21\0\3\3"+ + "\1\0\10\2\2\0\2\2\2\0\26\2\1\0\7\2\1\0\1\2"+ + "\3\0\4\2\2\0\1\3\1\2\7\3\2\0\2\3\2\0\3\3"+ + "\11\0\1\3\4\0\2\2\1\0\3\2\2\3\2\0\12\3\4\2"+ + "\15\0\3\3\1\0\6\2\4\0\2\2\2\0\26\2\1\0\7\2"+ + "\1\0\2\2\1\0\2\2\1\0\2\2\2\0\1\3\1\0\5\3"+ + "\4\0\2\3\2\0\3\3\13\0\4\2\1\0\1\2\7\0\14\3"+ + "\3\2\14\0\3\3\1\0\11\2\1\0\3\2\1\0\26\2\1\0"+ + "\7\2\1\0\2\2\1\0\5\2\2\0\1\3\1\2\10\3\1\0"+ + "\3\3\1\0\3\3\2\0\1\2\17\0\2\2\2\3\2\0\12\3"+ + "\1\0\1\2\17\0\3\3\1\0\10\2\2\0\2\2\2\0\26\2"+ + "\1\0\7\2\1\0\2\2\1\0\5\2\2\0\1\3\1\2\6\3"+ + "\3\0\2\3\2\0\3\3\10\0\2\3\4\0\2\2\1\0\3\2"+ + "\4\0\12\3\1\0\1\2\20\0\1\3\1\2\1\0\6\2\3\0"+ + "\3\2\1\0\4\2\3\0\2\2\1\0\1\2\1\0\2\2\3\0"+ + "\2\2\3\0\3\2\3\0\10\2\1\0\3\2\4\0\5\3\3\0"+ + "\3\3\1\0\4\3\11\0\1\3\17\0\11\3\11\0\1\2\7\0"+ + "\3\3\1\0\10\2\1\0\3\2\1\0\27\2\1\0\12\2\1\0"+ + "\5\2\4\0\7\3\1\0\3\3\1\0\4\3\7\0\2\3\11\0"+ + "\2\2\4\0\12\3\22\0\2\3\1\0\10\2\1\0\3\2\1\0"+ + "\27\2\1\0\12\2\1\0\5\2\2\0\1\3\1\2\7\3\1\0"+ + "\3\3\1\0\4\3\7\0\2\3\7\0\1\2\1\0\2\2\4\0"+ + "\12\3\22\0\2\3\1\0\10\2\1\0\3\2\1\0\27\2\1\0"+ + "\20\2\4\0\6\3\2\0\3\3\1\0\4\3\11\0\1\3\10\0"+ + "\2\2\4\0\12\3\22\0\2\3\1\0\22\2\3\0\30\2\1\0"+ + "\11\2\1\0\1\2\2\0\7\2\3\0\1\3\4\0\6\3\1\0"+ + "\1\3\1\0\10\3\22\0\2\3\15\0\60\2\1\3\2\2\7\3"+ + "\4\0\10\2\10\3\1\0\12\3\47\0\2\2\1\0\1\2\2\0"+ + "\2\2\1\0\1\2\2\0\1\2\6\0\4\2\1\0\7\2\1\0"+ + "\3\2\1\0\1\2\1\0\1\2\2\0\2\2\1\0\4\2\1\3"+ + "\2\2\6\3\1\0\2\3\1\2\2\0\5\2\1\0\1\2\1\0"+ + "\6\3\2\0\12\3\2\0\2\2\42\0\1\2\27\0\2\3\6\0"+ + "\12\3\13\0\1\3\1\0\1\3\1\0\1\3\4\0\2\3\10\2"+ + "\1\0\42\2\6\0\24\3\1\0\2\3\4\2\4\0\10\3\1\0"+ + "\44\3\11\0\1\3\71\0\42\2\1\0\5\2\1\0\2\2\1\0"+ + "\7\3\3\0\4\3\6\0\12\3\6\0\6\2\4\3\106\0\46\2"+ + "\12\0\51\2\7\0\132\2\5\0\104\2\5\0\122\2\6\0\7\2"+ + "\1\0\77\2\1\0\1\2\1\0\4\2\2\0\7\2\1\0\1\2"+ + "\1\0\4\2\2\0\47\2\1\0\1\2\1\0\4\2\2\0\37\2"+ + "\1\0\1\2\1\0\4\2\2\0\7\2\1\0\1\2\1\0\4\2"+ + "\2\0\7\2\1\0\7\2\1\0\27\2\1\0\37\2\1\0\1\2"+ + "\1\0\4\2\2\0\7\2\1\0\47\2\1\0\23\2\16\0\11\3"+ + "\56\0\125\2\14\0\u026c\2\2\0\10\2\12\0\32\2\5\0\113\2"+ + "\3\0\3\2\17\0\15\2\1\0\4\2\3\3\13\0\22\2\3\3"+ + "\13\0\22\2\2\3\14\0\15\2\1\0\3\2\1\0\2\3\14\0"+ + "\64\2\40\3\3\0\1\2\3\0\2\2\1\3\2\0\12\3\41\0"+ + "\3\3\2\0\12\3\6\0\130\2\10\0\51\2\1\3\126\0\35\2"+ + "\3\0\14\3\4\0\14\3\12\0\12\3\36\2\2\0\5\2\u038b\0"+ + "\154\2\224\0\234\2\4\0\132\2\6\0\26\2\2\0\6\2\2\0"+ + "\46\2\2\0\6\2\2\0\10\2\1\0\1\2\1\0\1\2\1\0"+ + "\1\2\1\0\37\2\2\0\65\2\1\0\7\2\1\0\1\2\3\0"+ + "\3\2\1\0\7\2\3\0\4\2\2\0\6\2\4\0\15\2\5\0"+ + "\3\2\1\0\7\2\17\0\4\3\32\0\5\3\20\0\2\2\23\0"+ + "\1\2\13\0\4\3\6\0\6\3\1\0\1\2\15\0\1\2\40\0"+ + "\22\2\36\0\15\3\4\0\1\3\3\0\6\3\27\0\1\2\4\0"+ + "\1\2\2\0\12\2\1\0\1\2\3\0\5\2\6\0\1\2\1\0"+ + "\1\2\1\0\1\2\1\0\4\2\1\0\3\2\1\0\7\2\3\0"+ + "\3\2\5\0\5\2\26\0\44\2\u0e81\0\3\2\31\0\11\2\6\3"+ + "\1\0\5\2\2\0\5\2\4\0\126\2\2\0\2\3\2\0\3\2"+ + "\1\0\137\2\5\0\50\2\4\0\136\2\21\0\30\2\70\0\20\2"+ + "\u0200\0\u19b6\2\112\0\u51a6\2\132\0\u048d\2\u0773\0\u2ba4\2\u215c\0\u012e\2"+ + "\2\0\73\2\225\0\7\2\14\0\5\2\5\0\1\2\1\3\12\2"+ + "\1\0\15\2\1\0\5\2\1\0\1\2\1\0\2\2\1\0\2\2"+ + "\1\0\154\2\41\0\u016b\2\22\0\100\2\2\0\66\2\50\0\15\2"+ + "\3\0\20\3\20\0\4\3\17\0\2\2\30\0\3\2\31\0\1\2"+ + "\6\0\5\2\1\0\207\2\2\0\1\3\4\0\1\2\13\0\12\3"+ + "\7\0\32\2\4\0\1\2\1\0\32\2\12\0\132\2\3\0\6\2"+ + "\2\0\6\2\2\0\6\2\2\0\3\2\3\0\2\2\3\0\2\2"+ + "\22\0\3\3\4\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\1\5\1\6\1\1"+ + "\3\3\1\7\1\3\1\10\1\3\1\11\1\12\1\13"+ + "\1\14\1\15\1\16\1\17\1\20\3\3\1\1\1\21"+ + "\1\22\1\23\1\1\2\0\1\3\1\24\2\3\1\0"+ + "\1\25\1\3\1\26\1\3\1\27\3\3\1\0\1\30"+ + "\3\0\1\31\2\3\1\0\5\3\3\0\1\2\1\0"+ + "\1\3\1\32\1\0\1\3\1\33\3\3\1\34\1\35"+ + "\1\0\1\36\1\0\1\37\1\40\2\3\2\0\1\41"+ + "\1\3\3\0\1\42\1\0\1\43\1\44"; + + private static int [] zzUnpackAction() { + int [] result = new int[94]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\52\0\124\0\176\0\52\0\250\0\322\0\52"+ + "\0\374\0\u0126\0\u0150\0\u017a\0\u01a4\0\u01ce\0\u01f8\0\u0222"+ + "\0\52\0\52\0\52\0\52\0\u024c\0\52\0\52\0\52"+ + "\0\u0276\0\u02a0\0\u02ca\0\u02f4\0\52\0\52\0\52\0\u031e"+ + "\0\u0348\0\u0372\0\u039c\0\176\0\u03c6\0\u03f0\0\u041a\0\52"+ + "\0\u0444\0\52\0\u046e\0\52\0\u0498\0\u04c2\0\u04ec\0\u0516"+ + "\0\52\0\u0540\0\u056a\0\u0594\0\176\0\u05be\0\u05e8\0\u0612"+ + "\0\u063c\0\u0666\0\u0690\0\u06ba\0\u06e4\0\u070e\0\u0738\0\u0762"+ + "\0\52\0\u078c\0\u07b6\0\176\0\u07e0\0\u080a\0\176\0\u0834"+ + "\0\u085e\0\u0888\0\52\0\52\0\u08b2\0\176\0\u08dc\0\176"+ + "\0\176\0\u0906\0\u0930\0\u095a\0\u0984\0\176\0\u09ae\0\u09d8"+ + "\0\u0a02\0\u0a2c\0\52\0\u0a56\0\52\0\52"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[94]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\7\1\10"+ + "\1\11\1\12\1\4\1\13\3\4\1\14\1\15\1\16"+ + "\2\4\1\2\1\4\1\17\1\20\1\4\1\21\1\22"+ + "\1\23\1\24\1\25\1\26\1\27\1\30\1\4\1\31"+ + "\1\32\1\33\1\34\1\35\1\36\1\37\1\40\53\0"+ + "\1\3\52\0\4\4\3\0\7\4\1\0\3\4\1\0"+ + "\1\4\1\0\2\4\10\0\4\4\11\0\2\6\53\0"+ + "\1\41\53\0\1\42\42\0\4\4\3\0\1\4\1\43"+ + "\5\4\1\0\3\4\1\0\1\4\1\0\2\4\10\0"+ + "\1\44\3\4\7\0\4\4\3\0\7\4\1\0\2\4"+ + "\1\45\1\0\1\4\1\0\2\4\10\0\4\4\7\0"+ + "\4\4\3\0\3\4\1\46\3\4\1\0\3\4\1\0"+ + "\1\4\1\0\2\4\10\0\4\4\26\0\1\47\13\0"+ + "\1\50\16\0\4\4\3\0\2\4\1\51\4\4\1\0"+ + "\3\4\1\0\1\4\1\0\2\4\10\0\4\4\42\0"+ + "\1\52\16\0\4\4\3\0\7\4\1\0\3\4\1\0"+ + "\1\4\1\0\1\4\1\53\10\0\4\4\42\0\1\54"+ + "\16\0\4\4\3\0\7\4\1\0\3\4\1\0\1\55"+ + "\1\0\2\4\10\0\4\4\7\0\4\4\3\0\7\4"+ + "\1\0\3\4\1\0\1\4\1\0\2\4\10\0\3\4"+ + "\1\56\7\0\4\4\3\0\6\4\1\57\1\0\3\4"+ + "\1\0\1\4\1\0\2\4\10\0\4\4\53\0\1\60"+ + "\40\0\1\61\14\0\7\62\1\63\42\62\12\0\1\64"+ + "\41\0\4\4\3\0\7\4\1\0\1\4\1\65\1\4"+ + "\1\0\1\4\1\0\2\4\10\0\4\4\7\0\4\4"+ + "\3\0\1\4\1\66\5\4\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\4\4\7\0\4\4\3\0\7\4"+ + "\1\0\1\67\2\4\1\0\1\4\1\0\2\4\10\0"+ + "\4\4\27\0\1\70\31\0\4\4\3\0\7\4\1\0"+ + "\3\4\1\0\1\4\1\0\1\4\1\71\10\0\4\4"+ + "\7\0\4\4\3\0\1\72\6\4\1\0\3\4\1\0"+ + "\1\4\1\0\2\4\10\0\4\4\7\0\4\4\3\0"+ + "\1\73\6\4\1\0\3\4\1\0\1\4\1\0\2\4"+ + "\10\0\4\4\7\0\4\4\3\0\1\74\6\4\1\0"+ + "\3\4\1\0\1\4\1\0\2\4\10\0\4\4\7\0"+ + "\4\4\3\0\7\4\1\0\1\4\1\75\1\4\1\0"+ + "\1\4\1\0\2\4\10\0\4\4\16\0\1\76\4\0"+ + "\1\77\33\0\7\62\1\100\42\62\6\0\1\101\1\63"+ + "\55\0\1\102\40\0\4\4\3\0\7\4\1\0\1\103"+ + "\2\4\1\0\1\4\1\0\2\4\10\0\4\4\7\0"+ + "\4\4\3\0\6\4\1\104\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\4\4\23\0\1\105\35\0\4\4"+ + "\3\0\1\4\1\106\5\4\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\4\4\7\0\4\4\3\0\1\4"+ + "\1\107\5\4\1\0\3\4\1\0\1\4\1\0\2\4"+ + "\10\0\4\4\7\0\4\4\3\0\3\4\1\110\3\4"+ + "\1\0\3\4\1\0\1\4\1\0\2\4\10\0\4\4"+ + "\7\0\4\4\3\0\1\4\1\111\5\4\1\0\3\4"+ + "\1\0\1\4\1\0\2\4\10\0\4\4\7\0\4\4"+ + "\3\0\4\4\1\112\2\4\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\4\4\52\0\1\113\51\0\1\114"+ + "\4\0\6\62\1\101\1\100\42\62\14\0\1\115\37\0"+ + "\4\4\3\0\7\4\1\0\1\4\1\116\1\4\1\0"+ + "\1\4\1\0\2\4\10\0\4\4\16\0\1\117\42\0"+ + "\4\4\3\0\7\4\1\0\3\4\1\0\1\4\1\0"+ + "\2\4\10\0\1\120\3\4\7\0\4\4\3\0\6\4"+ + "\1\121\1\0\3\4\1\0\1\4\1\0\2\4\10\0"+ + "\4\4\7\0\4\4\3\0\7\4\1\0\1\4\1\122"+ + "\1\4\1\0\1\4\1\0\2\4\10\0\4\4\7\0"+ + "\4\4\3\0\7\4\1\0\3\4\1\0\1\4\1\0"+ + "\2\4\10\0\3\4\1\123\22\0\1\124\57\0\1\125"+ + "\30\0\4\4\3\0\7\4\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\1\126\3\4\7\0\4\4\3\0"+ + "\1\4\1\127\5\4\1\0\3\4\1\0\1\4\1\0"+ + "\2\4\10\0\4\4\23\0\1\130\57\0\1\131\26\0"+ + "\1\132\4\4\3\0\7\4\1\0\3\4\1\0\1\4"+ + "\1\0\2\4\10\0\4\4\24\0\1\133\57\0\1\134"+ + "\25\0\1\132\2\0\1\135\73\0\1\136\23\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[2688]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\2\1\1\11\10\1\4\11"+ + "\1\1\3\11\4\1\3\11\1\1\2\0\4\1\1\0"+ + "\1\11\1\1\1\11\1\1\1\11\3\1\1\0\1\11"+ + "\3\0\3\1\1\0\5\1\3\0\1\11\1\0\2\1"+ + "\1\0\5\1\2\11\1\0\1\1\1\0\4\1\2\0"+ + "\2\1\3\0\1\11\1\0\2\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[94]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + C0Scanner(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + C0Scanner(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 1746) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Symbol nextToken() throws java.io.IOException, Scanner.Exception { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 2: + { /* ignore */ + } + case 37: break; + case 36: + { return symbol(Terminals.STDIO, ""); + } + case 38: break; + case 16: + { return symbol(Terminals.AMP, "&"); + } + case 39: break; + case 34: + { return symbol(Terminals.INCLUDE, "#include"); + } + case 40: break; + case 26: + { return symbol(Terminals.ELSE, "else"); + } + case 41: break; + case 18: + { return symbol(Terminals.PLUS, "+"); + } + case 42: break; + case 4: + { return symbol(Terminals.NUMBER, yytext()); + } + case 43: break; + case 12: + { return symbol(Terminals.RBRACKET, "}"); + } + case 44: break; + case 5: + { return symbol(Terminals.DIV, "/"); + } + case 45: break; + case 35: + { return symbol(Terminals.RETURN, "return 0"); + } + case 46: break; + case 28: + { return symbol(Terminals.IFORMAT, "\"%i\""); + } + case 47: break; + case 8: + { return symbol(Terminals.GT, ">"); + } + case 48: break; + case 10: + { return symbol(Terminals.RPAREN, ")"); + } + case 49: break; + case 24: + { return symbol(Terminals.NE, "!="); + } + case 50: break; + case 30: + { return symbol(Terminals.CONST, "const"); + } + case 51: break; + case 32: + { return symbol(Terminals.WHILE, "while"); + } + case 52: break; + case 21: + { return symbol(Terminals.LE, "<="); + } + case 53: break; + case 6: + { return symbol(Terminals.MULT, "*"); + } + case 54: break; + case 7: + { return symbol(Terminals.LT, "<"); + } + case 55: break; + case 27: + { return symbol(Terminals.MAIN, "main"); + } + case 56: break; + case 9: + { return symbol(Terminals.LPAREN, "("); + } + case 57: break; + case 14: + { return symbol(Terminals.COMMA, ","); + } + case 58: break; + case 25: + { return symbol(Terminals.INT, "int"); + } + case 59: break; + case 11: + { return symbol(Terminals.LBRACKET, "{"); + } + case 60: break; + case 33: + { return symbol(Terminals.PRINTF, "printf"); + } + case 61: break; + case 29: + { return symbol(Terminals.DFORMAT, "\"%d\""); + } + case 62: break; + case 3: + { return symbol(Terminals.IDENT, yytext()); + } + case 63: break; + case 20: + { return symbol(Terminals.IF, "if"); + } + case 64: break; + case 19: + { return symbol(Terminals.MINUS, "-"); + } + case 65: break; + case 23: + { return symbol(Terminals.EQ, "=="); + } + case 66: break; + case 22: + { return symbol(Terminals.GE, ">="); + } + case 67: break; + case 31: + { return symbol(Terminals.SCANF, "scanf"); + } + case 68: break; + case 15: + { return symbol(Terminals.SEMICOLON, ";"); + } + case 69: break; + case 13: + { return symbol(Terminals.ASSIGN, "="); + } + case 70: break; + case 1: + { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); + } + case 71: break; + case 17: + { return symbol(Terminals.MOD, "%"); + } + case 72: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + { return symbol(Terminals.EOF, ParserConstants.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/src/org/jalgo/module/am0c0/parser/c0/CVS/Entries b/src/org/jalgo/module/am0c0/parser/c0/CVS/Entries new file mode 100644 index 0000000..808697e --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/CVS/Entries @@ -0,0 +1,4 @@ +/C0Parser.java/1.2/Wed Dec 8 13:01:53 2010// +/C0Scanner.java/1.1/Mon Aug 16 12:05:49 2010// +/GeneratedC0Parser.java/1.1/Mon Aug 16 12:05:49 2010// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/am0c0/parser/c0/CVS/Repository b/src/org/jalgo/module/am0c0/parser/c0/CVS/Repository new file mode 100644 index 0000000..3c87bfc --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/parser/c0 diff --git a/src/org/jalgo/module/am0c0/parser/c0/CVS/Root b/src/org/jalgo/module/am0c0/parser/c0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.java b/src/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.java new file mode 100644 index 0000000..fb847b1 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.java @@ -0,0 +1,436 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ + +package org.jalgo.module.am0c0.parser.c0; + +import java.util.ArrayList; +import org.jalgo.module.am0c0.model.c0.ast.*; +import org.jalgo.module.am0c0.parser.ParserUtils; +import beaver.*; +import org.jalgo.module.am0c0.parser.ErrorEvents; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType; + +/** + * This class is a LALR parser generated by + * Beaver v0.9.6.1 + * from the grammar specification "c0-parser.g". + */ +public class GeneratedC0Parser extends Parser { + static public class Terminals { + static public final short EOF = 0; + static public final short IDENT = 1; + static public final short MINUS = 2; + static public final short PLUS = 3; + static public final short SEMICOLON = 4; + static public final short LPAREN = 5; + static public final short NUMBER = 6; + static public final short LBRACKET = 7; + static public final short SCANF = 8; + static public final short PRINTF = 9; + static public final short IF = 10; + static public final short WHILE = 11; + static public final short RPAREN = 12; + static public final short RETURN = 13; + static public final short EQ = 14; + static public final short NE = 15; + static public final short LE = 16; + static public final short GE = 17; + static public final short LT = 18; + static public final short GT = 19; + static public final short RBRACKET = 20; + static public final short MULT = 21; + static public final short DIV = 22; + static public final short MOD = 23; + static public final short COMMA = 24; + static public final short ELSE = 25; + static public final short INT = 26; + static public final short ASSIGN = 27; + static public final short IFORMAT = 28; + static public final short AMP = 29; + static public final short DFORMAT = 30; + static public final short INCLUDE = 31; + static public final short STDIO = 32; + static public final short MAIN = 33; + static public final short CONST = 34; + } + + static final ParsingTables PARSING_TABLES = new ParsingTables( + "U9obbbjiL4K0Xl#pjrBPbW8LjYsrq7OBhQMW8Du0kNW1lA9o4PHI5E#9ngWFFXYZYI$6nCk" + + "3HatGX0TzyS6O#6vCr0TVC055MwsY8hG52wK5AkCtS#PiTxUx98tdpzz$vf$$pENCdZcLOg" + + "tc5mjbj51PtQ9wrMawzLZeUnpK75sc#UPdYuBiJTItXBvlZVlIZnO#ctJP#wbl2ttVcl2b7" + + "onyDkMost7#2NtVMk5BVHO#MscpvFhCSEZxrcb#lZyv77KmxkymzTFUTz0CNphiy9U5gfsU" + + "fdxA#mwgygLUXpyTBhY$fqol7lI#WsRwqY67Fomqr$tTJlsCzntKv4k$EHonq0AdPwYFUDz" + + "17Nvj$Gw$MwZJwOZfrsBlEsY9p$vgeMQrwWfjqEMsH7rMw7kS2xEQfrfpBeUJ#7lKeajqBs" + + "KFBOVBjCDcDLlNu9tG2Zsag$6lDISYQ3UqetOpwfNAu0rfbTlVBbrdXYBG0hNQjTWT7JA3k" + + "jxDSaWDPZ02EQWrkToW6T1QbnlK9ZCGWHpKkbnkm1mdTIbxFQ0RpF48MW$j6fhL2DlmZg6B" + + "pD$u6ysn27eKtgExzOZvLrjr7zvvxTG3seM$rvoFe1xui1dNOt8NtdW4QkDkB7zP9tVTgjj" + + "qk#xGdRhBd9smpTa8gidpRzHANQLsBLMDDbFVCSbD#$j79rmpciCOldIpIun5O8GnttzDNb" + + "$vlUgYxJ75bL3WrBxnAIrY7asgrWpkcAbP$5Aws8CvcbiccoZ8pY#HNU2ocKdP#XBPP9bik" + + "aIseansSOciocIp9RArPRA9AVJRK2BRKYRRCeLiiaGsdSjcBxAs5jxefDeuWMqfJIa$6#Hb" + + "ApY9ApaxfkDMyIj9S$PqvhbPt3Ix5$QRuNa5zDpCELH7QI8N8sV7IhbH0v#pSwtZ$i9H0ju" + + "oss9fS#5ywxYpEDTOa0lAvj85EPlAailavHBamcVTwXZbqkGwYjPHIph5RhVxTLWq5AqtHQ" + + "u19sNSHIxNHisDPKpKPd9NuJxa#GKhAkUglbosO6x5TzLEzQxS#ANRfSTViYUJuQmMhdYEO" + + "atIUhW1ReFFIW7lJ700zb9$2puFFwJ#7lecZ56U1wlXSlgxWAx5jsTm1rm3CtZiHc3xtefk" + + "GPz4xHWlmtVXf$0hF7kg7qQVG4$2xs4NFCXGTYxDAFCDLk0DknDP0QTcR3Qw2JP1sru95yA" + + "baFK4k#0os0vtmvMm6$R05#0pz67dUHI#2Z#6duVdVl0Y#ZJ4rmVmC$WDxAEDPn3mA8Dtg3" + + "UYNwDsd45erxKHVH#rOt5ly0hifFuSodFKQ$0ZodmNWdtmTVW6tXVeVlGxlqz7h1QJQvLN#" + + "xzNFxgpJExGH3dOxBst2pD1XzTktxxFwoUJ#mjwlExD6#E0ro#zVfkNh$BUIAdvJOMiSpHQ" + + "W#zx3rmzbJx8F$L$vp6vJtUryskju9kMWac#k06CSI8BnZmJdC#MISyKTyMW$KudtBSwIny" + + "JEWt6EPFZl551IROvnZpZZgruhKv3jhZpqZAk9Vy1gTSq70=="); + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + + private int convert(final Symbol symbol) { + return ParserUtils.safeSymbolToInt(symbol, (ErrorEvents) report); + } + + private final Action[] actions; + + public GeneratedC0Parser() { + super(PARSING_TABLES); + actions = new Action[] { + new Action() { // [0] Program = INCLUDE STDIO INT MAIN LPAREN RPAREN Block.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_b = _symbols[offset + 7]; + final Block b = (Block) _symbol_b.value; + return new Symbol(new Program(b)); + } + }, + new Action() { // [1] Block = LBRACKET Declaration.d StatementSequence.s RETURN SEMICOLON RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 2]; + final Declaration d = (Declaration) _symbol_d.value; + final Symbol _symbol_s = _symbols[offset + 3]; + final StatementSequence s = (StatementSequence) _symbol_s.value; + return new Symbol(new Block(d, s)); + } + }, + new Action() { // [2] Block = LBRACKET Declaration.d RETURN SEMICOLON RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 2]; + final Declaration d = (Declaration) _symbol_d.value; + return new Symbol(new Block(d, null)); + } + }, + new Action() { // [3] StatementSequence = Statement.stat + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_stat = _symbols[offset + 1]; + final Statement stat = (Statement) _symbol_stat.value; + return new Symbol(new StatementSequence(stat)); + } + }, + new Action() { // [4] StatementSequence = StatementSequence.seq Statement.stat + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_seq = _symbols[offset + 1]; + final StatementSequence seq = (StatementSequence) _symbol_seq.value; + final Symbol _symbol_stat = _symbols[offset + 2]; + final Statement stat = (Statement) _symbol_stat.value; + seq.addStatement(stat); return new Symbol(seq); + } + }, + new Action() { // [5] Declaration = + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(new Declaration(null, null)); + } + }, + new Action() { // [6] Declaration = ConstDeclaration.constdecl SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_constdecl = _symbols[offset + 1]; + final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value; + return new Symbol(new Declaration(constdecl, null)); + } + }, + new Action() { // [7] Declaration = VarDeclaration.vardecl SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_vardecl = _symbols[offset + 1]; + final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value; + return new Symbol(new Declaration(null, vardecl)); + } + }, + new Action() { // [8] Declaration = ConstDeclaration.constdecl SEMICOLON VarDeclaration.vardecl SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_constdecl = _symbols[offset + 1]; + final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value; + final Symbol _symbol_vardecl = _symbols[offset + 3]; + final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value; + return new Symbol(new Declaration(constdecl, vardecl)); + } + }, + new Action() { // [9] ConstDeclaration = CONST IDENT.i ASSIGN NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + final Symbol n = _symbols[offset + 4]; + return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, convert(n)))); + } + }, + new Action() { // [10] ConstDeclaration = CONST IDENT.i ASSIGN MINUS NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + final Symbol n = _symbols[offset + 5]; + return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, -convert(n)))); + } + }, + new Action() { // [11] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 1]; + final ConstDeclaration d = (ConstDeclaration) _symbol_d.value; + final Symbol _symbol_i = _symbols[offset + 3]; + final String i = (String) _symbol_i.value; + final Symbol n = _symbols[offset + 5]; + d.addConstant(new C0AST.ConstIdent(i, convert(n))); return new Symbol(d); + } + }, + new Action() { // [12] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN MINUS NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 1]; + final ConstDeclaration d = (ConstDeclaration) _symbol_d.value; + final Symbol _symbol_i = _symbols[offset + 3]; + final String i = (String) _symbol_i.value; + final Symbol n = _symbols[offset + 6]; + d.addConstant(new C0AST.ConstIdent(i, -convert(n))); return new Symbol(d); + } + }, + new Action() { // [13] VarDeclaration = INT IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + return new Symbol(new VarDeclaration(new C0AST.Ident(i))); + } + }, + new Action() { // [14] VarDeclaration = VarDeclaration.d COMMA IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 1]; + final VarDeclaration d = (VarDeclaration) _symbol_d.value; + final Symbol _symbol_i = _symbols[offset + 3]; + final String i = (String) _symbol_i.value; + d.addVariable(new C0AST.Ident(i)); return new Symbol(d); + } + }, + new Action() { // [15] Statement = IDENT.i ASSIGN SimpleExpr.e SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 1]; + final String i = (String) _symbol_i.value; + final Symbol _symbol_e = _symbols[offset + 3]; + final SimpleExpr e = (SimpleExpr) _symbol_e.value; + return new Symbol(new Statement.AssignmentStatement(i, e)); + } + }, + new Action() { // [16] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_e = _symbols[offset + 3]; + final BoolExpression e = (BoolExpression) _symbol_e.value; + final Symbol _symbol_s = _symbols[offset + 5]; + final Statement s = (Statement) _symbol_s.value; + return new Symbol(new Statement.IfStatement(e, s)); + } + }, + new Action() { // [17] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s1 ELSE Statement.s2 + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_e = _symbols[offset + 3]; + final BoolExpression e = (BoolExpression) _symbol_e.value; + final Symbol _symbol_s1 = _symbols[offset + 5]; + final Statement s1 = (Statement) _symbol_s1.value; + final Symbol _symbol_s2 = _symbols[offset + 7]; + final Statement s2 = (Statement) _symbol_s2.value; + return new Symbol(new Statement.IfElseStatement(e, s1, s2)); + } + }, + new Action() { // [18] Statement = WHILE LPAREN BoolExpr.e RPAREN Statement.s + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_e = _symbols[offset + 3]; + final BoolExpression e = (BoolExpression) _symbol_e.value; + final Symbol _symbol_s = _symbols[offset + 5]; + final Statement s = (Statement) _symbol_s.value; + return new Symbol(new Statement.WhileStatement(e, s)); + } + }, + new Action() { // [19] Statement = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 5]; + final String i = (String) _symbol_i.value; + return new Symbol(new Statement.PrintfStatement(i)); + } + }, + new Action() { // [20] Statement = SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 6]; + final String i = (String) _symbol_i.value; + return new Symbol(new Statement.ScanfStatement(i)); + } + }, + new Action() { // [21] Statement = LBRACKET StatementSequence.s RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_s = _symbols[offset + 2]; + final StatementSequence s = (StatementSequence) _symbol_s.value; + return new Symbol(new Statement.CompStatement(s)); + } + }, + new Action() { // [22] BoolExpr = SimpleExpr.l Relation.rel SimpleExpr.r + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_l = _symbols[offset + 1]; + final SimpleExpr l = (SimpleExpr) _symbol_l.value; + final Symbol _symbol_rel = _symbols[offset + 2]; + final AtomicType rel = (AtomicType) _symbol_rel.value; + final Symbol _symbol_r = _symbols[offset + 3]; + final SimpleExpr r = (SimpleExpr) _symbol_r.value; + return new Symbol(new BoolExpression(l, rel, r)); + } + }, + new Action() { // [23] Relation = EQ + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.EQ); + } + }, + new Action() { // [24] Relation = NE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.NE); + } + }, + new Action() { // [25] Relation = LE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.LE); + } + }, + new Action() { // [26] Relation = GE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.GE); + } + }, + new Action() { // [27] Relation = LT + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.LT); + } + }, + new Action() { // [28] Relation = GT + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(AtomicType.GT); + } + }, + new Action() { // [29] SimpleExpr = Term.t + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 1]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new SimpleExpr.UnaryPlusExpr(t)); + } + }, + new Action() { // [30] SimpleExpr = PLUS Term.t + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 2]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new SimpleExpr.UnaryPlusExpr(t)); + } + }, + new Action() { // [31] SimpleExpr = MINUS Term.t + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 2]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new SimpleExpr.UnaryMinusExpr(t)); + } + }, + new Action() { // [32] SimpleExpr = SimpleExpr.s PLUS Term.t + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_s = _symbols[offset + 1]; + final SimpleExpr s = (SimpleExpr) _symbol_s.value; + final Symbol _symbol_t = _symbols[offset + 3]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new SimpleExpr.PlusExpr(s, t)); + } + }, + new Action() { // [33] SimpleExpr = SimpleExpr.s MINUS Term.t + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_s = _symbols[offset + 1]; + final SimpleExpr s = (SimpleExpr) _symbol_s.value; + final Symbol _symbol_t = _symbols[offset + 3]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new SimpleExpr.MinusExpr(s, t)); + } + }, + new Action() { // [34] Term = Factor.f + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_f = _symbols[offset + 1]; + final Factor f = (Factor) _symbol_f.value; + return new Symbol(new Term.FactorTerm(f)); + } + }, + new Action() { // [35] Term = Term.t MULT Factor.f + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 1]; + final Term t = (Term) _symbol_t.value; + final Symbol _symbol_f = _symbols[offset + 3]; + final Factor f = (Factor) _symbol_f.value; + return new Symbol(new Term.MultTerm(t, f)); + } + }, + new Action() { // [36] Term = Term.t DIV Factor.f + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 1]; + final Term t = (Term) _symbol_t.value; + final Symbol _symbol_f = _symbols[offset + 3]; + final Factor f = (Factor) _symbol_f.value; + return new Symbol(new Term.DivTerm(t, f)); + } + }, + new Action() { // [37] Term = Term.t MOD Factor.f + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 1]; + final Term t = (Term) _symbol_t.value; + final Symbol _symbol_f = _symbols[offset + 3]; + final Factor f = (Factor) _symbol_f.value; + return new Symbol(new Term.ModTerm(t, f)); + } + }, + new Action() { // [38] Factor = IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 1]; + final String i = (String) _symbol_i.value; + return new Symbol(new Factor.IdentFactor(i)); + } + }, + new Action() { // [39] Factor = NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol n = _symbols[offset + 1]; + return new Symbol(new Factor.NumberFactor(convert(n))); + } + }, + new Action() { // [40] Factor = LPAREN SimpleExpr.s RPAREN + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_s = _symbols[offset + 2]; + final SimpleExpr s = (SimpleExpr) _symbol_s.value; + return new Symbol(new Factor.CompExprFactor(s)); + } + } + }; + + + this.report = ErrorEvents.forC0(); + } + + protected Symbol invokeReduceAction(int rule_num, int offset) { + return actions[rule_num].reduce(_symbols, offset); + } +} diff --git a/src/org/jalgo/module/am0c0/parser/c0/package-info.java b/src/org/jalgo/module/am0c0/parser/c0/package-info.java new file mode 100644 index 0000000..54dc05e --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/c0/package-info.java @@ -0,0 +1,4 @@ +/** + * Lexer, parser and related classes for analysing C0 source code. + */ +package org.jalgo.module.am0c0.parser.c0; diff --git a/src/org/jalgo/module/am0c0/parser/package-info.java b/src/org/jalgo/module/am0c0/parser/package-info.java new file mode 100644 index 0000000..bb82ef9 --- /dev/null +++ b/src/org/jalgo/module/am0c0/parser/package-info.java @@ -0,0 +1,4 @@ +/** + * Classes shared by both AM0 and C0 parsers and lexers. + */ +package org.jalgo.module.am0c0.parser; diff --git a/src/org/jalgo/module/am0c0/res.properties b/src/org/jalgo/module/am0c0/res.properties new file mode 100644 index 0000000..ec73c2e --- /dev/null +++ b/src/org/jalgo/module/am0c0/res.properties @@ -0,0 +1,26 @@ +HelpSet_Name=/help/jhelp/am0c0_help.hs +Main_Icon=/am0c0_pix/logo.gif +back_to_editor_Icon=/am0c0_pix/back_to_editor.png +clear_Icon=/am0c0_pix/clear.png +initial_config_Icon=/am0c0_pix/initial_configuration.png +last_Icon=/am0c0_pix/last.png +next_Icon=/am0c0_pix/next.png +open_Icon=/am0c0_pix/open.png +previous_Icon=/am0c0_pix/previous.png +run_Icon=/am0c0_pix/run.png +save_Icon=/am0c0_pix/save.png +ghost=/am0c0_pix/ilovecandy/ghost.gif +pacman=/am0c0_pix/ilovecandy/pacman.gif +up1=/am0c0_pix/ilovecandy/up1.gif +up2=/am0c0_pix/ilovecandy/up2.gif +up3=/am0c0_pix/ilovecandy/up3.gif +up1=/am0c0_pix/ilovecandy/up1.gif +down1=/am0c0_pix/ilovecandy/down1.gif +down2=/am0c0_pix/ilovecandy/down2.gif +down3=/am0c0_pix/ilovecandy/down3.gif +left1=/am0c0_pix/ilovecandy/left1.gif +left2=/am0c0_pix/ilovecandy/left2.gif +left3=/am0c0_pix/ilovecandy/left3.gif +right1=/am0c0_pix/ilovecandy/right1.gif +right2=/am0c0_pix/ilovecandy/right2.gif +right3=/am0c0_pix/ilovecandy/right3.gif \ No newline at end of file diff --git a/src/org/jalgo/module/am0c0/tests/AddressSolverTest.java b/src/org/jalgo/module/am0c0/tests/AddressSolverTest.java new file mode 100644 index 0000000..aab0938 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/AddressSolverTest.java @@ -0,0 +1,73 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.model.TreeAddress; +import org.jalgo.module.am0c0.model.c0.trans.AddressSolver; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans; +import org.jalgo.module.am0c0.model.c0.trans.StubTrans; +import org.jalgo.module.am0c0.model.c0.trans.TransformFunction; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType; +import org.junit.Test; + +public class AddressSolverTest { + + @Test + public void testSolve() { + List functions = new ArrayList(); + + functions.add(new AtomicTrans(null, null, AtomicType.LIT, 1)); + functions.add(new AtomicTrans(null, null, AtomicType.GT, -1)); + + TreeAddress stubAddress = new TreeAddress(); + stubAddress.extend(); + functions.add(new StubTrans(null, stubAddress)); + + TreeAddress jmpAddress = new TreeAddress(stubAddress); + jmpAddress.increase(); + functions.add(new AtomicTrans(null, jmpAddress, AtomicType.JMP, -1, stubAddress)); + + TreeAddress stubAddress2 = new TreeAddress(jmpAddress); + stubAddress2.increase(); + functions.add(new StubTrans(null, stubAddress2)); + + TreeAddress addAddress = new TreeAddress(); + addAddress.increase(); + functions.add(new AtomicTrans(null, addAddress, AtomicType.GT, -1)); + + Map solved = AddressSolver.solve(functions); + + assertTrue(solved.get(stubAddress.toString()).getLine() == 3); + assertTrue(solved.get(jmpAddress.toString()).getLine() == 3); + assertTrue(solved.get(stubAddress2.toString()).getLine() == 4); + assertTrue(solved.get(addAddress.toString()).getLine() == 4); + } + +} diff --git a/src/org/jalgo/module/am0c0/tests/CParserTest.java b/src/org/jalgo/module/am0c0/tests/CParserTest.java new file mode 100644 index 0000000..454fc21 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/CParserTest.java @@ -0,0 +1,112 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +import static org.junit.Assert.*; + +import org.jalgo.module.am0c0.parser.c0.C0Parser; +import org.junit.Test; + +/** + * Unit tests for the C0 parser. + * + * @author Martin Morgenstern + */ +public class CParserTest { + /** + * A pair of C0 source code and a corresponding flag whether this code is + * expected to be valid C0 or not. Used together with + * {@link CParserTest#testFixture(CTestFixture)}. + */ + private interface CTestFixture { + /** + * Get the C0 code to be tested. + */ + public String getSource(); + + /** + * Returns {@code true}, if the code returned by {@link #getSource()} is + * expected to be valid C0, otherwise {@code false}. + */ + public boolean isValid(); + } + + /** + * Utility method that tests a {@link CTestFixture}. For an example of + * usage, see {@link #testSummation()} or {@link #testNullArgument()}. + * + * @param fixture + * the fixture to test + */ + private void testFixture(final CTestFixture fixture) { + final C0Parser parser = new C0Parser(); + final boolean result = parser.parse(fixture.getSource()); + + assertEquals(fixture.isValid(), result); + } + + @Test + public void testNullArgument() { + final C0Parser parser = new C0Parser(); + + try { + parser.parse(null); + fail("Should have raised a " + NullPointerException.class); + } catch (NullPointerException e) { + } + } + + @Test + public void testEmptyArgument() { + testFixture(new CTestFixture() { + @Override + public boolean isValid() { + return false; + } + + @Override + public String getSource() { + return ""; + } + }); + } + + @Test + public void testSummation() { + testFixture(new CTestFixture() { + @Override + public String getSource() { + return "/* Summation */" + "#include " + "int main()" + + "{" + "int i, n, s;" + "scanf(\"%i\", &n);" + + "i = 1;" + "s = 0;" + "while (i <= n)" + "{" + + "s = s + i * i;" + "i = i + 1;" + "}" + + "printf(\"%d\", s);" + "return 0;" + "}" + ""; + } + + @Override + public boolean isValid() { + return true; + } + }); + } +} diff --git a/src/org/jalgo/module/am0c0/tests/CVS/Entries b/src/org/jalgo/module/am0c0/tests/CVS/Entries new file mode 100644 index 0000000..265f9e7 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/CVS/Entries @@ -0,0 +1,6 @@ +/AddressSolverTest.java/1.1/Mon Aug 16 12:05:48 2010// +/CParserTest.java/1.2/Wed Dec 8 13:01:53 2010// +/SymbolTableTest.java/1.1/Mon Aug 16 12:05:48 2010// +/SymbolTest.java/1.1/Mon Aug 16 12:05:48 2010// +/TestUtils.java/1.1/Mon Aug 16 12:05:48 2010// +/TransformationTest.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/am0c0/tests/CVS/Repository b/src/org/jalgo/module/am0c0/tests/CVS/Repository new file mode 100644 index 0000000..09d3df5 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am0c0/tests diff --git a/src/org/jalgo/module/am0c0/tests/CVS/Root b/src/org/jalgo/module/am0c0/tests/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am0c0/tests/SymbolTableTest.java b/src/org/jalgo/module/am0c0/tests/SymbolTableTest.java new file mode 100644 index 0000000..17e7902 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/SymbolTableTest.java @@ -0,0 +1,154 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +import static org.junit.Assert.*; + +import org.jalgo.module.am0c0.model.c0.trans.Symbol; +import org.jalgo.module.am0c0.model.c0.trans.Symbol.SymbolType; +import org.jalgo.module.am0c0.model.c0.trans.SymbolException; +import org.jalgo.module.am0c0.model.c0.trans.SymbolTable; +import org.junit.Test; + +/** + * Unit tests for {@link SymbolTable}. + * + * @author Felix Schmitt + * @author Martin Morgenstern + */ +public class SymbolTableTest { + + @Test + public void testAdd1() { + try { + SymbolTable table = new SymbolTable(); + Symbol symbol1 = Symbol.varSymbol("x", 1); + table.add(symbol1); + Symbol symbol2 = Symbol.varSymbol("x", 2); + + table.add(symbol2); + fail("Should have raised an exception"); + } catch (SymbolException e) { + + } + } + + @Test + public void testAdd2() { + try { + SymbolTable table = new SymbolTable(); + Symbol symbol1 = Symbol.varSymbol("x", 1); + table.add(symbol1); + Symbol symbol2 = Symbol.varSymbol("y", 1); + + table.add(symbol2); + fail("Should have raised an exception"); + } catch (SymbolException e) { + + } + } + + @Test + public void testAdd3() { + try { + SymbolTable table = new SymbolTable(); + Symbol symbol1 = Symbol.constSymbol("x", 1); + table.add(symbol1); + Symbol symbol2 = Symbol.constSymbol("y", 1); + + table.add(symbol2); + } catch (SymbolException e) { + fail("Should not have raised an exception"); + } + } + + @Test + public void testGetType() { + SymbolTable table = new SymbolTable(); + try { + table.getType("x"); + fail("Should have raised an exception"); + } catch (SymbolException e) { + + } + } + + @Test + public void testGetAddress() { + SymbolTable table = new SymbolTable(); + try { + table.getAddress("x"); + fail("Should have raised an exception"); + } catch (SymbolException e) { + + } + } + + @Test + public void testInsertedConstSymbol() throws SymbolException { + final String id = "id"; + final int value = 42; + final Symbol sym = Symbol.constSymbol(id, value); + final SymbolTable tab = new SymbolTable(); + + tab.add(sym); + + assertTrue(tab.exists(id)); + assertTrue(tab.exists(new String(id))); + assertEquals(value, tab.getValue(id)); + assertEquals(SymbolType.ST_CONST, tab.getType(id)); + } + + @Test + public void testInsertedVarSymbol() throws SymbolException { + final String id = "id"; + final int address = 24; + final Symbol sym = Symbol.varSymbol(id, address); + final SymbolTable tab = new SymbolTable(); + + tab.add(sym); + + assertTrue(tab.exists(id)); + assertTrue(tab.exists(new String(id))); + assertEquals(address, tab.getAddress(id)); + assertEquals(SymbolType.ST_VAR, tab.getType(id)); + } + + @Test + public void testClear() throws SymbolException { + final String id1 = "a", id2 = "b"; + + final Symbol sym1 = Symbol.varSymbol(id1, 2); + final Symbol sym2 = Symbol.constSymbol(id2, 0); + + final SymbolTable tab = new SymbolTable(); + + tab.add(sym1); + tab.add(sym2); + + tab.clear(); + + assertFalse(tab.exists(id1)); + assertFalse(tab.exists(id2)); + } +} diff --git a/src/org/jalgo/module/am0c0/tests/SymbolTest.java b/src/org/jalgo/module/am0c0/tests/SymbolTest.java new file mode 100644 index 0000000..187b240 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/SymbolTest.java @@ -0,0 +1,95 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +import static org.junit.Assert.*; + +import org.jalgo.module.am0c0.model.c0.trans.Symbol; +import org.jalgo.module.am0c0.model.c0.trans.Symbol.SymbolType; +import org.jalgo.module.am0c0.model.c0.trans.SymbolException; +import org.junit.Test; + +/** + * Unit tests for {@link Symbol}. + * + * @author Felix Schmitt + * @author Martin Morgenstern + */ +public class SymbolTest { + @Test + public void testSymbolIdNotNull() { + try { + Symbol.varSymbol(null, 1); + fail("Should have raised an exception"); + } catch (NullPointerException e) { + } + + try { + Symbol.constSymbol(null, 0); + fail("Should have raised an exception"); + } catch (NullPointerException e) { + } + } + + @Test + public void testVarSymbolRaisesException() { + try { + Symbol.varSymbol("x", 0); + fail("Should have raised an exception"); + } catch (IllegalArgumentException e) { + } + } + + @Test + public void testConstSymbolRaisesException() { + Symbol sym = Symbol.constSymbol("a", 0); + + try { + sym.getAddress(); + fail("Should have raised an exception"); + } catch (SymbolException e) { + } + } + + @Test + public void testVarSymbol() throws SymbolException { + final String id = "a"; + final int address = 10; + Symbol sym = Symbol.varSymbol(id, address); + + assertEquals(SymbolType.ST_VAR, sym.getType()); + assertEquals(address, sym.getAddress()); + assertEquals(id, sym.getID()); + } + + @Test + public void testConstSymbol() { + final String id = "a"; + final int value = -20; + Symbol sym = Symbol.constSymbol(id, value); + + assertEquals(SymbolType.ST_CONST, sym.getType()); + assertEquals(value, sym.getValue()); + assertEquals(id, sym.getID()); + } +} diff --git a/src/org/jalgo/module/am0c0/tests/TestUtils.java b/src/org/jalgo/module/am0c0/tests/TestUtils.java new file mode 100644 index 0000000..14db51e --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/TestUtils.java @@ -0,0 +1,39 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +public class TestUtils { + public static final String C0_VALID = "#include int main(){return 0;}"; + public static final String C0_VALID_FULL = "#include int main() " + + "{ int i, n, s; scanf(\"%i\", &n); " + "i = 1; s = 0; " + + "while (i <= n){s = s+i*i; i = i+1;} " + + "printf(\"%d\", s); return 0;}"; + public static final String C0_INVALID = "invalid"; + + public static final String AM0_VALID = "READ 1\nLOAD 1\nLIT 2\nADD\nSTORE 2\nWRITE 2"; + public static final String AM0_VALID_FULL = "READ 2;\nLIT 1;\nSTORE 1;\n" + + "LIT 0;\nSTORE 3;\nLOAD 1;\n" + "LOAD 2;\nLE;\nJMC 21;\n" + + "LOAD 3;\nLOAD 1;\nLOAD 1;\n" + "MUL;\nADD;\nSTORE 3;\n" + + "LOAD 1;\nLIT 1;\nADD;\n" + "STORE 1;\nJMP 6;\nWRITE 3;\n"; + public static final String AM0_INVALID = "invalid"; +} diff --git a/src/org/jalgo/module/am0c0/tests/TransformationTest.java b/src/org/jalgo/module/am0c0/tests/TransformationTest.java new file mode 100644 index 0000000..1be7294 --- /dev/null +++ b/src/org/jalgo/module/am0c0/tests/TransformationTest.java @@ -0,0 +1,154 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am0c0.tests; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.jalgo.module.am0c0.model.AddressException; +import org.jalgo.module.am0c0.model.LineAddress; +import org.jalgo.module.am0c0.model.am0.AM0Program; +import org.jalgo.module.am0c0.model.am0.SimulationStatement; +import org.jalgo.module.am0c0.model.c0.C0Program; +import org.jalgo.module.am0c0.model.c0.ast.Program; +import org.jalgo.module.am0c0.model.c0.trans.AddressSolver; +import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans; +import org.jalgo.module.am0c0.model.c0.trans.StubTrans; +import org.jalgo.module.am0c0.model.c0.trans.SymbolTable; +import org.jalgo.module.am0c0.model.c0.trans.Trans; +import org.jalgo.module.am0c0.model.c0.trans.TransException; +import org.jalgo.module.am0c0.model.c0.trans.TransformFunction; +import org.jalgo.module.am0c0.parser.c0.C0Parser; + +/** + * This is the complete transformation test + * @author Felix Schmitt + * + */ +public class TransformationTest extends TestCase { + private List functions; + private SymbolTable symbolTable; + + protected List getApplyFunc(int index) throws TransException { + TransformFunction func = functions.get(index); + + if (func instanceof AtomicTrans || func instanceof StubTrans) + throw new IllegalArgumentException( + "This index points to a TransformFunctions which cannot be applied"); + + return func.apply(symbolTable); + } + + private void applyFunc(int index) throws IllegalStateException, TransException { + List resultFunctions; + + try { + resultFunctions = getApplyFunc(index); + /** + * TODO: make history copy here + */ + functions.remove(index); + functions.addAll(index, resultFunctions); + /** + * TODO: update model here + */ + } catch (IllegalArgumentException e) { + throw new IllegalStateException(e.getMessage()); + } + } + + private boolean internalTranslateStatement() throws TransException { + int nextIndex = -1; + + for (int i = 0; i < functions.size(); i++) { + TransformFunction func = functions.get(i); + if (!(func instanceof AtomicTrans) && !(func instanceof StubTrans)) { + nextIndex = i; + break; + } + } + + if (nextIndex == -1) { + return false; + } else { + try { + applyFunc(nextIndex); + return true; + } catch (IllegalStateException e) { + System.out.println("An error occured during transformation: " + e.getMessage()); + return false; + } + } + } + + public void testTransformation() throws TransException { + C0Parser parser = new C0Parser(); + assertTrue(parser.parse(TestUtils.C0_VALID_FULL)); + + C0Program c0program = parser.getProgram(); + assertNotNull(c0program); + + functions = new ArrayList(); + assertTrue(c0program.size() == 1); + assertTrue(c0program.get(0) instanceof Program); + symbolTable = new SymbolTable(); + functions.add(new Trans((Program)c0program.get(0), null)); + + while(internalTranslateStatement()) {}; + assertTrue(functions.size() > 0); + + Map addresses = AddressSolver.solve(functions); + + AM0Program am0program = new AM0Program(); + + int line = 1; + for (TransformFunction func : functions) { + if (!(func instanceof StubTrans)) { + assertTrue(func instanceof AtomicTrans); + AtomicTrans atomFunc = (AtomicTrans)func; + try { + am0program.add(atomFunc.getStatement(new LineAddress(line), addresses)); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (AddressException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + line++; + } + } + + assertTrue(am0program.size() > 0); + + String am0ProgramCode = ""; + for (SimulationStatement statement : am0program) + am0ProgramCode += statement.getCodeText() + "\n"; + + assertEquals(TestUtils.AM0_VALID_FULL, am0ProgramCode); + } +} + diff --git a/src/org/jalgo/module/am1simulator/AM1Simulator.java b/src/org/jalgo/module/am1simulator/AM1Simulator.java new file mode 100644 index 0000000..7150d7b --- /dev/null +++ b/src/org/jalgo/module/am1simulator/AM1Simulator.java @@ -0,0 +1,43 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.jalgo.module.am1simulator; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +import org.jalgo.module.am1simulator.presenter.Simulator; + +/** + * Main class and application entry point. + * + * @author Max Leuthäuser + */ +public class AM1Simulator { + public AM1Simulator(final JComponent contentPane, final JMenu menu, final JToolBar toolbar) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + new Simulator().init(contentPane, menu, toolbar); + } + }); + } +} diff --git a/src/org/jalgo/module/am1simulator/CVS/Entries b/src/org/jalgo/module/am1simulator/CVS/Entries new file mode 100644 index 0000000..03dc2c4 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/CVS/Entries @@ -0,0 +1,9 @@ +/AM1Simulator.java/1.1/Mon Mar 7 19:57:18 2011// +/ModuleConnector.java/1.1/Mon Mar 7 19:57:18 2011// +/ModuleInfo.java/1.1/Mon Mar 7 19:57:18 2011// +D/model//// +/package-info.java/1.1/Mon Mar 7 19:57:18 2011// +D/parser//// +D/presenter//// +/res.properties/1.1/Mon Mar 7 19:57:18 2011// +D/view//// diff --git a/src/org/jalgo/module/am1simulator/CVS/Repository b/src/org/jalgo/module/am1simulator/CVS/Repository new file mode 100644 index 0000000..e183ef1 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator diff --git a/src/org/jalgo/module/am1simulator/CVS/Root b/src/org/jalgo/module/am1simulator/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/ModuleConnector.java b/src/org/jalgo/module/am1simulator/ModuleConnector.java new file mode 100644 index 0000000..d4bac60 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/ModuleConnector.java @@ -0,0 +1,70 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am1simulator; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; + +public class ModuleConnector extends AbstractModuleConnector { + + @Override + public void init() { + JComponent contentPane = JAlgoGUIConnector.getInstance() + .getModuleComponent(this); + + JMenu menu = JAlgoGUIConnector.getInstance().getModuleMenu(this); + + JToolBar toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar( + this); + + new AM1Simulator(contentPane, menu, toolbar); + } + + @Override + public void run() { + // TODO Auto-generated method stub + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + // TODO Auto-generated method stub + } + + @Override + public ByteArrayOutputStream getDataForFile() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void print() { + // TODO Auto-generated method stub + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/am1simulator/ModuleInfo.java b/src/org/jalgo/module/am1simulator/ModuleInfo.java new file mode 100644 index 0000000..944cf78 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/ModuleInfo.java @@ -0,0 +1,82 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am1simulator; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) + instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "AM1-Simulator"; + } + + public String getVersion() { + return "0.8"; + } + + public String getAuthor() { + return "Max Leuth\u00E4user"; + } + + public String getDescription() { + return "With this module you are able to simulate" + + "AM1 code on an abstract machine."; + } + + public URL getLogoURL() { + return Messages.getResourceURL("am1simulator", "Main_Icon"); + } + + public String getLicense() { + return "GNU General Public License. Using icons from the Tango Desktop Project."; + } + + public URL getHelpSetURL() { + return Messages.getResourceURL("am1simulator", "HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/am1simulator/model/AM1History.java b/src/org/jalgo/module/am1simulator/model/AM1History.java new file mode 100644 index 0000000..f93017c --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/AM1History.java @@ -0,0 +1,158 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * History to store already calculated elements like + * {@link MachineConfiguration} + * + * @author Max Leuthäuser + */ +public class AM1History implements Iterator { + private List history; + private int currentIndex; + + public AM1History() { + history = new ArrayList(); + currentIndex = 0; + } + + /** + * @return true if there is one more element in the history, false + * otherwise. + * + * @see java.util.Iterator#hasNext() + */ + @Override + public boolean hasNext() { + return currentIndex < history.size(); + } + + /** + * @return true if there is one more previous element in the history, false + * otherwise. + * + */ + public boolean hasPrevious() { + return currentIndex > 0; + } + + /** + * @return the next element in the history if this exists, null + * otherwise. + * + * @see java.util.Iterator#next() + */ + @Override + public T next() { + if (hasNext()) { + currentIndex++; + return history.get(currentIndex); + } + return null; + } + + /** + * @return the previous element in the history if this exists, null + * otherwise. + * + */ + public T previous() { + if (hasPrevious()) { + currentIndex--; + return history.get(currentIndex); + } + return null; + } + + @Override + public void remove() { + throw new AbstractMethodError( + "Calling this method is not allowed for this class."); + } + + /** + * @return the current size of the history. + */ + public int getCount() { + return history.size(); + } + + /** + * @return the current index. + */ + public int getCurrentIndex() { + return currentIndex; + } + + /** + * Add an object of type T to the history. + * + * @param m + * Element of type T which should be added. + * @throws IllegalArgumentException + */ + public void add(T m) throws IllegalArgumentException { + if (m != null) { + currentIndex++; + history.add(m); + } else + throw new IllegalArgumentException( + "Null arguments are not allowed here!"); + } + + /** + * Deletes all entries in the history. + */ + public void clear() { + history.clear(); + } + + /** + * @return The object which is the last one in this history. + */ + public T getLastElement() { + return history.get(history.size() - 1); + } + + /** + * @param s + * Step to check. + * @return true if this step exists already in the history. + */ + public boolean stepExists(int s) { + return history.size() > s; + } + + /** + * @param step + * @return the object at this step in the history. + */ + public T getAtStep(int step) { + return history.get(step); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/AM1PagingTableModel.java b/src/org/jalgo/module/am1simulator/model/AM1PagingTableModel.java new file mode 100644 index 0000000..8b43fef --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/AM1PagingTableModel.java @@ -0,0 +1,361 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model; + + +import java.util.ArrayList; +import java.util.List; +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Polygon; +import java.awt.event.ActionListener; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ScrollPaneConstants; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableModel; + +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Simple paging table model which shows only a given number of lines at one + * time. + * + * @author Max Leuthäuser + */ +public class AM1PagingTableModel extends AbstractTableModel { + private static final long serialVersionUID = 1L; + protected int pageSize; + protected int pageOffset; + protected List data; + private final String[] header = { "PC", "Stack", "Runtime stack", "REF", + "Input", "Output" }; + private int rowCount = 0; + private static final int STANDARD_PAGE_SIZE = 50; + + JButton upButton; + JButton downButton; + + public AM1PagingTableModel() { + data = new ArrayList(); + pageSize = STANDARD_PAGE_SIZE; + } + + /** + * Update the row count to fit to the currently shows values. + */ + private void updateRowCount() { + if (data.isEmpty()) { + rowCount = 0; + return; + } + if (data.size() % pageSize == 0) { + rowCount = pageSize; + return; + } + rowCount = data.size() % pageSize; + } + + /** + * Return values appropriate for the visible table part. + * + * @see javax.swing.table.TableModel#getRowCount() + */ + public int getRowCount() { + return rowCount; + } + + /* + * (non-Javadoc) + * + * @see javax.swing.table.TableModel#getColumnCount() + */ + public int getColumnCount() { + return header.length; + } + + /** + * Work only on the visible part of the table. + * + * @see javax.swing.table.TableModel#getValueAt(int, int) + */ + public Object getValueAt(int row, int col) { + int realRow = row + (pageOffset * pageSize); + + switch (col) { + case 0: + return data.get(realRow).getProgramCounter(); + case 1: + return data.get(realRow).getStack(); + case 2: + return data.get(realRow).getRuntimeStack(); + case 3: + return data.get(realRow).getRef(); + case 4: + return data.get(realRow).getInputStream(); + case 5: + return data.get(realRow).getOutputStream(); + default: + throw new IllegalArgumentException("Col has to be between 0 and 5!"); + } + } + + /* + * (non-Javadoc) + * + * @see javax.swing.table.AbstractTableModel#getColumnName(int) + */ + @Override + public String getColumnName(int col) { + return header[col]; + } + + /** + * Use this method to figure out which page you are on. + * + * @return the number of the page which is currently shown. + */ + public int getPageOffset() { + return pageOffset; + } + + /** + * Add a new row containing the values of a {@link MachineConfiguration}. + * + * @param m + */ + public void addRow(MachineConfiguration m) { + data.add(m); + fireTableDataChanged(); + updateRowCount(); + fireTableRowsInserted(getRowCount() - 1, getRowCount()); + pageDown(); + } + + /** + * Show only the last page. + */ + public void showLastPage() { + if (pageOffset < getPageCount()) { + while (pageDown()) { + } + ; + } + } + + /** + * Show only the fist page. + */ + public void showFirstPage() { + while (pageUp()) { + } + ; + } + + /** + * Remove the last page and call {@link AM1PagingTableModel#pageUp()} if + * necessary. + */ + public void removeLastRow() { + data.remove(data.size() - 1); + updateRowCount(); + fireTableRowsDeleted(getRowCount(), getRowCount() + 1); + if (data.size() % pageSize == 0) + pageUp(); + } + + /** + * Delete all entries. + */ + public void clear() { + data.clear(); + pageOffset = 0; + rowCount = 0; + fireTableDataChanged(); + } + + /** + * @return the number of pages needed. + */ + public int getPageCount() { + return (int) Math.ceil((double) data.size() / (double) pageSize); + } + + /** + * Use this method if you want to know how big the real table is. + * + * @return the size of the underlying model. + */ + public int getRealRowCount() { + return data.size(); + } + + /** + * @return the standard page size. + */ + public int getPageSize() { + return pageSize; + } + + /** + * Set a new page size. Not needed here. + * + * @param s + * @deprecated + */ + @Deprecated + public void setPageSize(int s) { + if (s == pageSize) { + return; + } + int oldPageSize = pageSize; + pageSize = s; + pageOffset = (oldPageSize * pageOffset) / pageSize; + fireTableDataChanged(); + } + + /** + * Update the page offset and fire a data changed (all rows). + * + * @return true if a page down was successful, false otherwise + */ + public boolean pageDown() { + if (pageOffset < getPageCount() - 1) { + pageOffset++; + rowCount = pageSize; + if ((pageOffset == getPageCount() - 1)) { + updateRowCount(); + } + fireTableDataChanged(); + return true; + } + return false; + } + + /** + * Update the page offset and fire a data changed (all rows). + * + * @return true if a page up was successful, false otherwise + */ + public boolean pageUp() { + if (pageOffset > 0) { + pageOffset--; + rowCount = pageSize; + fireTableDataChanged(); + return true; + } + return false; + } + + /** + * We provide our own version of a {@link JScrollPane} that includes the + * page up and page down buttons by default. + * + * @param jt + * {@link JTable} + * @return a {@link JScrollPane} with our page up/down buttons and the table + */ + public JScrollPane createPagingScrollPaneForTable(JTable jt) { + JScrollPane jsp = new JScrollPane(jt); + TableModel tmodel = jt.getModel(); + + if (!(tmodel instanceof AM1PagingTableModel)) { + return jsp; + } + upButton = new JButton(new ArrowIcon(ArrowIcon.UP)); + downButton = new JButton(new ArrowIcon(ArrowIcon.DOWN)); + + upButton.setToolTipText("Click here to move one page up."); + downButton.setToolTipText("Click here to move one page down."); + + // Turn on the scrollbars - otherwise we won't get our corners. + jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + + // Add in the corners (page up/down). + jsp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, upButton); + jsp.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, downButton); + + return jsp; + } + + public void addUserInputListener(ActionListener a1, ActionListener a2) { + upButton.addActionListener(a1); + downButton.addActionListener(a2); + } +} + +/** + * Class which represents the corner up/down buttons used in + * {@link AM1PagingTableModel}. + * + * @author Max Leuthäuser + */ +class ArrowIcon implements Icon { + + public static final int UP = 0; + + public static final int DOWN = 1; + + private int direction; + + private Polygon pagePolygon = new Polygon(new int[] { 2, 4, 4, 10, 10, 2 }, + new int[] { 4, 4, 2, 2, 12, 12 }, 6); + + private int[] arrowX = { 4, 9, 6 }; + + private Polygon arrowUpPolygon = new Polygon(arrowX, + new int[] { 10, 10, 4 }, 3); + + private Polygon arrowDownPolygon = new Polygon(arrowX, + new int[] { 6, 6, 11 }, 3); + + public ArrowIcon(int which) { + direction = which; + } + + public int getIconWidth() { + return 14; + } + + public int getIconHeight() { + return 14; + } + + public void paintIcon(Component c, Graphics g, int x, int y) { + g.setColor(Color.black); + pagePolygon.translate(x, y); + g.drawPolygon(pagePolygon); + pagePolygon.translate(-x, -y); + if (direction == UP) { + arrowUpPolygon.translate(x, y); + g.fillPolygon(arrowUpPolygon); + arrowUpPolygon.translate(-x, -y); + } else { + arrowDownPolygon.translate(x, y); + g.fillPolygon(arrowDownPolygon); + arrowDownPolygon.translate(-x, -y); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/AddressException.java b/src/org/jalgo/module/am1simulator/model/AddressException.java new file mode 100644 index 0000000..5f638a6 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/AddressException.java @@ -0,0 +1,40 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model; + +/** + * Exception indicating an error in handling {@link LineAddress}. + * + * @author Felix Schmitt + * + */ +public class AddressException extends Exception { + + private static final long serialVersionUID = 1L; + + public AddressException() { + super(); + } + + public AddressException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/CVS/Entries b/src/org/jalgo/module/am1simulator/model/CVS/Entries new file mode 100644 index 0000000..0aa2a73 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/CVS/Entries @@ -0,0 +1,7 @@ +/AM1History.java/1.1/Mon Mar 7 19:57:18 2011// +/AM1PagingTableModel.java/1.1/Mon Mar 7 19:57:18 2011// +/AddressException.java/1.1/Mon Mar 7 19:57:18 2011// +/LineAddress.java/1.1/Mon Mar 7 19:57:18 2011// +/SimulationSet.java/1.1/Mon Mar 7 19:57:18 2011// +D/am1//// +/package-info.java/1.1/Mon Mar 7 19:57:18 2011// diff --git a/src/org/jalgo/module/am1simulator/model/CVS/Repository b/src/org/jalgo/module/am1simulator/model/CVS/Repository new file mode 100644 index 0000000..7b58bee --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/model diff --git a/src/org/jalgo/module/am1simulator/model/CVS/Root b/src/org/jalgo/module/am1simulator/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/model/LineAddress.java b/src/org/jalgo/module/am1simulator/model/LineAddress.java new file mode 100644 index 0000000..5bb55a9 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/LineAddress.java @@ -0,0 +1,91 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model; + +/** + * Provides line-based addresses + * + * @author Felix Schmitt + * @author Max Leuthäuser + */ +public class LineAddress { + private int address; + + /** + * Constructor + * + * @param address + * line number to initialize with + * @throws AddressException + */ + public LineAddress(int address) throws AddressException { + setLine(address); + } + + /** + * set the line number + * + * @param address + * new line number. must be >= 0 + */ + public void setLine(int address) throws AddressException { + if (address >= 0) + this.address = address; + else + throw new AddressException("A line address must not be < 0"); + } + + /** + * returns string representation + * + * @return string representation + */ + @Override + public String toString() { + return String.valueOf(address); + } + + /** + * Returns the line number + * + * @return line number + */ + public int getLine() { + return address; + } + + /** + * Compares two LineAddresses using their line numbers + */ + @Override + public boolean equals(Object o) { + return (o instanceof LineAddress) + && ((LineAddress) o).getLine() == getLine(); + } + + /** + * It is asserted that this method is never called. + */ + @Override + public int hashCode() { + throw new AssertionError(); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/SimulationSet.java b/src/org/jalgo/module/am1simulator/model/SimulationSet.java new file mode 100644 index 0000000..c5fd3be --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/SimulationSet.java @@ -0,0 +1,55 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model; + +import org.jalgo.module.am1simulator.view.components.AM1InputDialog; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Represents an data set for a new simulation. This set is created by + * {@link AM1InputDialog}. + * + * @author Max Leuthäuser + */ +public class SimulationSet { + private int steps; + private MachineConfiguration m; + + public SimulationSet(MachineConfiguration m, int steps) { + this.m = m; + this.steps = steps; + } + + /** + * @return the {@link MachineConfiguration} which is stored here. + */ + public MachineConfiguration getMachineConfiguration() { + return m; + } + + /** + * @return the maximum number of steps the user wants to simulate at once. + */ + public int getSteps() { + return steps; + } + +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/AM1Program.java b/src/org/jalgo/module/am1simulator/model/am1/AM1Program.java new file mode 100644 index 0000000..0deb936 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/AM1Program.java @@ -0,0 +1,42 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import java.util.ArrayList; + +/** + * Class which represents an AM1 program which contains + * {@link SimulationStatement}s. + * + * @author Max Leuthäuser + */ +public class AM1Program extends ArrayList { + private static final long serialVersionUID = 1L; + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (SimulationStatement s : this) { + result.append(s.toString()); + } + return result.toString(); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.java new file mode 100644 index 0000000..a9505b7 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/AbstractStatementFactory.java @@ -0,0 +1,49 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +/** + * Base class for all statement factories. Provides all available + * statements as enumeration. + * + * @author Max Leuthäuser + */ +public interface AbstractStatementFactory { + /** + * Enumeration that holds all available statement types. + * + * @author Max Leuthäuser + */ + public static enum Statement { + ADD, CALL, DIV, EQUAL, GREATEREQUAL, GREATERTHEN, INIT, JMC, JMP, LESSEREQUAL, LESSERTHEN, LIT, LOAD, LOADA, LOADI, MOD, MUL, NOTEQUAL, PUSH, READ, READI, REF, RET, STORE, STOREI, SUB, WRITE, WRITEI + } + + /** + * Build a new {@link SimulationStatement} based on the value + * {@link Statement} and the {@link StatementResource} resource. + * + * @param statement + * @param resource + * @return a new {@link SimulationStatement} + */ + SimulationStatement newStatement(Statement statement, + StatementResource resource); +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.java new file mode 100644 index 0000000..fa1f871 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/ArithmeticStatementFactory.java @@ -0,0 +1,244 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.StatementResource; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Statement factory for all arithmetic statements. + * + * @author Max Leuthäuser + */ +public class ArithmeticStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling ADD. + * + * @author Max Leuthäuser + */ + private class Add extends SimulationStatement { + public Add(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + configuration.getStack().push(arg1 + arg0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2+d.1):d.3: ... :d.n,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "ADD;"; + } + } + + /** + * Updates the AM after calling DIV. + * + * @author Max Leuthäuser + */ + private class Div extends SimulationStatement { + public Div(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException, ArithmeticException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + if (arg0 == 0) { + throw new ArithmeticException("Division by zero."); + } + + configuration.getStack().push(arg1 / arg0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2/d.1):d.3: ... :d.n,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "DIV;"; + } + } + + /** + * Updates the AM after calling MOD. + * + * @author Max Leuthäuser + */ + private class Mod extends SimulationStatement { + public Mod(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + configuration.getStack().push(arg1 % arg0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2%.1):d.3: ... :d.n,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "MOD;"; + } + } + + /** + * Updates the AM after calling MUL. + * + * @author Max Leuthäuser + */ + private class Mul extends SimulationStatement { + public Mul(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + + configuration.getStack().push(arg1 * arg0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2*d.1):d.3: ... :d.n,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "MUL;"; + } + } + + /** + * Updates the AM after calling SUB. + * + * @author Max Leuthäuser + */ + private class Sub extends SimulationStatement { + public Sub(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + // this way round because this is the way its + // written in the script + configuration.getStack().push(arg1 - arg0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,(d.2-d.1):d.3: ... :d.n,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "SUB;"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + switch (statement) { + case ADD: + return new Add(address); + case DIV: + return new Div(address); + case MOD: + return new Mod(address); + case MUL: + return new Mul(address); + case SUB: + return new Sub(address); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/CVS/Entries b/src/org/jalgo/module/am1simulator/model/am1/CVS/Entries new file mode 100644 index 0000000..a4cab96 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/CVS/Entries @@ -0,0 +1,12 @@ +/AM1Program.java/1.1/Mon Mar 7 19:57:17 2011// +/AbstractStatementFactory.java/1.1/Mon Mar 7 19:57:18 2011// +/ArithmeticStatementFactory.java/1.1/Mon Mar 7 19:57:17 2011// +/CompareStatementFactory.java/1.1/Mon Mar 7 19:57:17 2011// +/IOStatementFactory.java/1.1/Mon Mar 7 19:57:18 2011// +/JumpStatementFactory.java/1.1/Mon Mar 7 19:57:17 2011// +/MemoryStatementFactory.java/1.1/Mon Mar 7 19:57:17 2011// +/ProceduralStatementFactory.java/1.1/Mon Mar 7 19:57:18 2011// +/SimulationStatement.java/1.1/Mon Mar 7 19:57:17 2011// +/StatementResource.java/1.1/Mon Mar 7 19:57:17 2011// +D/machine//// +/package-info.java/1.1/Mon Mar 7 19:57:17 2011// diff --git a/src/org/jalgo/module/am1simulator/model/am1/CVS/Repository b/src/org/jalgo/module/am1simulator/model/am1/CVS/Repository new file mode 100644 index 0000000..909b26b --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/model/am1 diff --git a/src/org/jalgo/module/am1simulator/model/am1/CVS/Root b/src/org/jalgo/module/am1simulator/model/am1/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.java new file mode 100644 index 0000000..2086372 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/CompareStatementFactory.java @@ -0,0 +1,281 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Statement factory for all compare statements. + * + * @author Max Leuthäuser + */ +public class CompareStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling EQ. + * + * @author Max Leuthäuser + */ + private class Equal extends SimulationStatement { + public Equal(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 == arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2=d.1, and b=0, if d.2\\!=d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "EQ;"; + } + } + + /** + * Updates the AM after calling GE. + * + * @author Max Leuthäuser + */ + private class GreaterEqual extends SimulationStatement { + public GreaterEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 >= arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\u2265d.1, and b=0, if d.2<d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "GE;"; + } + } + + /** + * Updates the AM after calling GT. + * + * @author Max Leuthäuser + */ + private class GreaterThen extends SimulationStatement { + public GreaterThen(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 > arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2>d.1, and b=0, if d.2\u2264d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "GT;"; + } + } + + /** + * Updates the AM after the calling LE. + * + * @author Max Leuthäuser + */ + private class LesserEqual extends SimulationStatement { + public LesserEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 <= arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\u2264d.1, and b=0, if d.2>d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "LE;"; + } + } + + /** + * Updates the AM after calling LT. + * + * @author Max Leuthäuser + */ + public class LesserThen extends SimulationStatement { + public LesserThen(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 < arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2<d.1, and b=0, if d.2\u2265d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "LT;"; + } + } + + /** + * Updates the AM after calling NE. + * + * @author Max Leuthäuser + */ + public class NotEqual extends SimulationStatement { + public NotEqual(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 2) { + throw new IllegalArgumentException( + "Stack does not contain 2 or more values."); + } + configuration.getProgramCounter().inc(); + int arg0 = configuration.getStack().pop(); + int arg1 = configuration.getStack().pop(); + if (arg1 != arg0) { + configuration.getStack().push(1); + } else + configuration.getStack().push(0); + return configuration; + } + + @Override + public String getDescription() { + return "if d=d.1:d.2:d.3: ... :d.n with n \u2265 2 then (m+1,b:d.3: ... :d.n,h, inp, out)
      and b=1, if d.2\\!=d.1, and b=0, if d.2=d.1,
      that means for the value true (or false respectively) is 1 (or 0 respectively) pushed to the stack."; + } + + @Override + public String getCodeText() { + return "NE;"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + switch (statement) { + case EQUAL: + return new Equal(address); + case GREATERTHEN: + return new GreaterThen(address); + case GREATEREQUAL: + return new GreaterEqual(address); + case LESSEREQUAL: + return new LesserEqual(address); + case LESSERTHEN: + return new LesserThen(address); + case NOTEQUAL: + return new NotEqual(address); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.java new file mode 100644 index 0000000..09e59f7 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/IOStatementFactory.java @@ -0,0 +1,237 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import java.util.NoSuchElementException; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Statement factory for all I/O statements. + * + * @author Max Leuthäuser + */ +public class IOStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling READ. + * + * @author Max Leuthäuser + */ + private class Read extends SimulationStatement { + private int target; + private String location; + + public Read(LineAddress address, String location, int target) { + super(address); + this.target = target; + this.location = location; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getInputStream().read(); + } catch (NoSuchElementException e) { + throw new IllegalArgumentException("The input stream is empty!"); + } + if (configuration.getRuntimeStack().store(location, target, + configuration.getRef().get(), z) == -1) { + throw new IllegalArgumentException( + "This value in the runtime stack does not exist!"); + } + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "if inp = z : inp', z \u220A \u2124 then (m + 1, d, h', r, inp', out)" + + "
      " + + "with h' = h[adr(r,b,o)/z]" + + " and

      " + + "
      adr(r,b,o) = {r + o
      o
      if b=lokal;
      if b=global
      "; + } + + @Override + public String getCodeText() { + return "READ(" + location + "," + target + ");"; + } + } + + /** + * Updates the AM after calling READI. + * + * @author Max Leuthäuser + */ + private class Readi extends SimulationStatement { + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Readi(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getInputStream().read(); + } catch (NoSuchElementException e) { + throw new IllegalArgumentException("The input stream is empty!"); + } + if (configuration.getRuntimeStack().storei(target, + configuration.getRef().get(), z) == -1) { + throw new IllegalArgumentException( + "The value in the runtime stack does not exist!"); + } + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "if inp = z : inp', z \u220A \u2124 then (m + 1, d, h', r, inp', out)" + + "
      " + + "with h' = h[h.(r + o)/z]"; + } + + @Override + public String getCodeText() { + return "READI(" + target + ");"; + } + } + + /** + * Updates the AM after calling WRITE. + * + * @author Max Leuthäuser + */ + private class Write extends SimulationStatement { + private int target; + private String location; + + public Write(LineAddress address, String location, int target) { + super(address); + this.target = target; + this.location = location; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + + int z = configuration.getRuntimeStack().load(location, target, + configuration.getRef().get()); + + if (z == -1) { + throw new IllegalArgumentException("The target (" + location + + ", " + target + ") does not exist"); + } else { + configuration.getProgramCounter().inc(); + configuration.getOutputStream().write(z); + } + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, d, h, r, inp, out : z)" + + "
      " + + "with z = h.(adr(r,b,o))" + + " and

      " + + "
      adr(r,b,o) = {r + o
      o
      if b=lokal;
      if b=global
      "; + } + + @Override + public String getCodeText() { + return "WRITE(" + location + "," + target + ");"; + } + } + + /** + * Updates the AM after calling WRITEI. + * + * @author Max Leuthäuser + */ + private class Writei extends SimulationStatement { + private int target; + + public Writei(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z = configuration.getRuntimeStack().loadi(target, + configuration.getRef().get()); + if (z == -1) { + throw new IllegalArgumentException("The target (" + target + + ") does not exist"); + } else { + configuration.getProgramCounter().inc(); + configuration.getOutputStream().write(z); + } + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, d, h, r, inp, out : z)" + + "
      " + + "with z = h.(h.(r + o))"; + } + + @Override + public String getCodeText() { + return "WRITEI(" + target + ");"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + String location = resource.getLocation(); + int value = resource.getValue(); + switch (statement) { + case READ: + return new Read(address, location, value); + case READI: + return new Readi(address, value); + case WRITE: + return new Write(address, location, value); + case WRITEI: + return new Writei(address, value); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.java new file mode 100644 index 0000000..9448ba9 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/JumpStatementFactory.java @@ -0,0 +1,133 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Statement factory for all jump statements. + * + * @author Max Leuthäuser + */ +public class JumpStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling JMC. + * + * @author Max Leuthäuser + */ + private class Jmc extends SimulationStatement { + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Jmc(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException( + "Jump target must not be < 0."); + } + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + if (configuration.getStack().getStackAsList().size() < 1) { + throw new IllegalArgumentException( + "Stack does not contain 1 or more values."); + } + if (configuration.getStack().pop() == 0) { + configuration.getProgramCounter().set(target); + } else { + configuration.getProgramCounter().inc(); + } + return configuration; + } + + @Override + public String getDescription() { + return "if d=0:d.2: ... :d.n with n \u2265 1 then (e,d.2: ... :d.n,h, inp, out)
      else (m+1,d.2: ... :d.n,h, inp, out)
      If the first stack element is 0 (logic false), then the program counter will be set to e.
      Otherwise the first stack element has an other value (logic true), then the program counter will be incremented."; + } + + @Override + public String getCodeText() { + return "JMC " + target + ";"; + } + } + + /** + * Updates the AM after calling JMP. + * + * @author Max Leuthäuser + */ + private class Jmp extends SimulationStatement { + private int target; + + /** + * @throws IllegalArgumentException + * if target < 0 + */ + public Jmp(LineAddress address, int target) { + super(address); + + if (target < 0) { + throw new IllegalArgumentException( + "Jump target must not be < 0."); + } + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) { + configuration.getProgramCounter().set(target); + return configuration; + } + + @Override + public String getDescription() { + return "(e,d,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "JMP " + target + ";"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + int value = resource.getValue(); + switch (statement) { + case JMC: + return new Jmc(address, value); + case JMP: + return new Jmp(address, value); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.java new file mode 100644 index 0000000..36d2df7 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/MemoryStatementFactory.java @@ -0,0 +1,273 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; +import org.jalgo.module.am1simulator.model.am1.machine.RuntimeStack; + +/** + * This class is a simple blueprint for all commands. Just a method to return + * the type of the command is stipulated + * + * @author Max Leuthäuser + */ +public class MemoryStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling LOAD. + * + * @author Max Leuthäuser + */ + private class Load extends SimulationStatement { + private int target; + private String location; + + public Load(LineAddress address, String location, int target) { + super(address); + this.target = target; + this.location = location; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getRuntimeStack().load(location, target, + configuration.getRef().get()); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException("The target (" + location + + ", " + target + ") does not exist"); + } + configuration.getProgramCounter().inc(); + configuration.getStack().push(z); + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, z : d, h, r, inp, out)" + + "
      " + + "with z = h.(adr(r,b,o))" + + " and

      " + + "
      adr(r,b,o) = {r + o
      o
      if b=lokal;
      if b=global
      "; + } + + @Override + public String getCodeText() { + return "LOAD(" + location.toLowerCase() + "," + target + ");"; + } + } + + /** + * Updates the AM after calling LOADA. + * + * @author Max Leuthäuser + */ + private class Loada extends SimulationStatement { + private int target; + private String location; + + public Loada(LineAddress address, String location, int target) { + super(address); + this.target = target; + this.location = location; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z = RuntimeStack.adr(configuration.getRef().get(), location, + target); + configuration.getProgramCounter().inc(); + configuration.getStack().push(z); + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, adr(r,b,o) : d, h, r, inp, out)"; + } + + @Override + public String getCodeText() { + return "LOADA(" + location.toLowerCase() + "," + target + ");"; + } + } + + /** + * Updates the AM after calling LOADI. + * + * @author Max Leuthäuser + */ + private class Loadi extends SimulationStatement { + private int target; + + public Loadi(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getRuntimeStack().loadi(target, + configuration.getRef().get()); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException("The target (" + target + + ") does not exist"); + } + configuration.getProgramCounter().inc(); + configuration.getStack().push(z); + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, z : d, h, r, inp, out)" + + "
      " + + "with z = h.(h.(r + o))"; + } + + @Override + public String getCodeText() { + return "LOADI(" + target + ");"; + } + } + + /** + * Updates the AM after calling STORE. + * + * @author Max Leuthäuser + */ + private class Store extends SimulationStatement { + private int target; + private String location; + + public Store(LineAddress address, String location, int target) { + super(address); + this.target = target; + this.location = location; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getStack().pop(); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException("The stack is empty!"); + } + + if (configuration.getRuntimeStack().store(location, target, + configuration.getRef().get(), z) == -1) { + throw new IllegalArgumentException( + "The value at this address does not exist!"); + } + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "if d = z : d' then (m + 1, d', h', r, inp, out)" + + "
      " + + "with h' = h[adr(r,b,o)/z]" + + " and

      " + + "
      adr(r,b,o) = {r + o
      o
      if b=lokal;
      if b=global
      "; + } + + @Override + public String getCodeText() { + return "STORE(" + location + "," + target + ");"; + } + } + + /** + * Updates the AM after calling STOREI. + * + * @author Max Leuthäuser + */ + private class Storei extends SimulationStatement { + private int target; + + public Storei(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getStack().pop(); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException("The stack is empty!"); + } + + if (configuration.getRuntimeStack().storei(target, + configuration.getRef().get(), z) == -1) { + throw new IllegalArgumentException( + "The value at this address does not exist!"); + } + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "if d = z : d' then (m + 1, d', h', r, inp, out)" + + "
      " + + "with h' = h[h.(r + o)/z]"; + } + + @Override + public String getCodeText() { + return "STOREI(" + target + ");"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + String location = resource.getLocation(); + int value = resource.getValue(); + switch (statement) { + case LOAD: + return new Load(address, location, value); + case LOADA: + return new Loada(address, location, value); + case LOADI: + return new Loadi(address, value); + case STORE: + return new Store(address, location, value); + case STOREI: + return new Storei(address, value); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.java b/src/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.java new file mode 100644 index 0000000..dbcf4ef --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/ProceduralStatementFactory.java @@ -0,0 +1,237 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import java.util.NoSuchElementException; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Statement factory for all procedural statements. + * + * @author Max Leuthäuser + */ +public class ProceduralStatementFactory implements AbstractStatementFactory { + /** + * Updates the AM after calling CALL. + * + * @author Max Leuthäuser + */ + private class Call extends SimulationStatement { + private int target; + + public Call(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + + int pc = configuration.getProgramCounter().get(); + int ref = configuration.getRef().get(); + + configuration.getProgramCounter().set(target); + configuration.getRef().set( + configuration.getRuntimeStack().getLength() + 2); + + configuration.getRuntimeStack().call(pc + 1, ref); + return configuration; + } + + @Override + public String getDescription() { + return "(adr, d, h : (m + 1) : r, length(h) + 2, inp, out)"; + } + + @Override + public String getCodeText() { + return "CALL " + target + ";"; + } + } + + /** + * Updates the AM after calling INIT. + * + * @author Max Leuthäuser + */ + private class Init extends SimulationStatement { + private int amount; + + public Init(LineAddress address, int amount) { + super(address); + this.amount = amount; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + + configuration.getRuntimeStack().init(amount); + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "(m + 1, d, h : 0{n}, r, inp, out)"; + } + + @Override + public String getCodeText() { + return "INIT " + amount + ";"; + } + } + + /** + * Updates the AM after calling PUSH. + * + * @author Max Leuthäuser + */ + private class Push extends SimulationStatement { + public Push(LineAddress address) { + super(address); + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + int z; + try { + z = configuration.getStack().pop(); + } catch (NoSuchElementException e) { + throw new IllegalArgumentException("The stack is empty!"); + } + configuration.getRuntimeStack().push(z); + configuration.getProgramCounter().inc(); + return configuration; + } + + @Override + public String getDescription() { + return "if d = z : d' then (m + 1, d', h : z, r, inp, out)"; + } + + @Override + public String getCodeText() { + return "PUSH;"; + } + } + + /** + * Updates the AM after calling RET. + * + * @author Max Leuthäuser + */ + private class Ret extends SimulationStatement { + private int target; + + public Ret(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) + throws IllegalArgumentException { + final int oldref = configuration.getRef().get(); + final int oldPc = configuration.getProgramCounter().get(); + configuration.getRef().set( + configuration.getRuntimeStack().getAtCount(oldref)); + configuration.getProgramCounter().set( + configuration.getRuntimeStack().getAtCount(oldref - 1)); + + try { + configuration.getRuntimeStack().ret(); + } catch (IndexOutOfBoundsException e) { + configuration.getRef().set(oldref); + configuration.getProgramCounter().set(oldPc); + throw new IllegalArgumentException( + "The runtime stack is empty!"); + } + return configuration; + } + + @Override + public String getDescription() { + return "(h.(r - 1),d,h.1 : ... : h.(r - 2 - n),h.r,inp,out)"; + } + + @Override + public String getCodeText() { + return "RET " + target + ";"; + } + } + + /** + * Updates the AM after calling LIT. + * + * @author Max Leuthäuser + */ + private class Lit extends SimulationStatement { + private int target; + + public Lit(LineAddress address, int target) { + super(address); + this.target = target; + } + + @Override + public MachineConfiguration apply(MachineConfiguration configuration) { + configuration.getProgramCounter().inc(); + configuration.getStack().push(target); + return configuration; + } + + @Override + public String getDescription() { + return "(m+1,z:d,h, inp, out)"; + } + + @Override + public String getCodeText() { + return "LIT " + target + ";"; + } + } + + @Override + public SimulationStatement newStatement(Statement statement, + StatementResource resource) { + LineAddress address = resource.getAddress(); + int value = resource.getValue(); + switch (statement) { + case CALL: + return new Call(address, value); + case INIT: + return new Init(address, value); + case PUSH: + return new Push(address); + case RET: + return new Ret(address, value); + case LIT: + return new Lit(address, value); + default: + throw new AssertionError("Unknown statement type:" + statement); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/SimulationStatement.java b/src/org/jalgo/module/am1simulator/model/am1/SimulationStatement.java new file mode 100644 index 0000000..d0fd86a --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/SimulationStatement.java @@ -0,0 +1,94 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Abstract base class for all AM1 simulation statements. + * + * @author Max Leuthäuser + */ +public abstract class SimulationStatement { + private LineAddress address; + + public SimulationStatement(LineAddress address) { + setAddress(address); + } + + /** + * @return the number of lines this statement spans over. + */ + public int getLinesCount() { + return 1; + } + + /** + * Returns the {@link LineAddress} associated with this statement. + * + * @return the {@link LineAddress} + */ + public LineAddress getAddress() { + return address; + } + + /** + * Sets the {@link LineAddress} associated with this statement. + * + * @param address + * new {@link LineAddress} + */ + public void setAddress(LineAddress address) { + this.address = address; + } + + /** + * @param configuration + * the {@link MachineConfiguration} + * @return the updated {@link MachineConfiguration} after applying this + * statement + */ + public abstract MachineConfiguration apply( + MachineConfiguration configuration); + + /** + * @return the description for this statement in HTML format + */ + public abstract String getDescription(); + + /** + * Returns the statement code text as a string + * + * @return statement code text as String + */ + public abstract String getCodeText(); + + /** + * Returns the string representation (code text) and a newline added. + * + * @return string representation + */ + @Override + public String toString() { + return getCodeText() + "\n"; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/StatementResource.java b/src/org/jalgo/module/am1simulator/model/am1/StatementResource.java new file mode 100644 index 0000000..df78e70 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/StatementResource.java @@ -0,0 +1,89 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1; + +import org.jalgo.module.am1simulator.model.LineAddress; + +/** + * Class which holds the necessary and optional values for all kinds of + * {@link SimulationStatement}. Implementation is characterized through the + * builder pattern. Null arguments are not allowed and causes an + * {@link IllegalArgumentException}. + * + * @author Max Leuthäuser + */ +public class StatementResource { + private final LineAddress address; + private final String location; + private final int value; + + public static class Builder { + // always required: + private LineAddress address; + // optional - initialized to default values: + private String location = ""; + private int value = 0; + + public Builder(LineAddress address) { + if (address == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + this.address = address; + } + + public Builder location(String loc) { + if (loc == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + location = loc; + return this; + } + + public Builder value(int val) { + value = val; + return this; + } + + public StatementResource build() { + return new StatementResource(this); + } + } + + private StatementResource(Builder builder) { + address = builder.address; + location = builder.location; + value = builder.value; + } + + public LineAddress getAddress() { + return address; + } + + public String getLocation() { + return location; + } + + public int getValue() { + return value; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Entries b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Entries new file mode 100644 index 0000000..34319e5 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Entries @@ -0,0 +1,11 @@ +/InputStream.java/1.1/Mon Mar 7 19:57:17 2011// +/MachineConfiguration.java/1.1/Mon Mar 7 19:57:17 2011// +/MemoryCell.java/1.1/Mon Mar 7 19:57:17 2011// +/OutputStream.java/1.1/Mon Mar 7 19:57:17 2011// +/ProgramCounter.java/1.1/Mon Mar 7 19:57:17 2011// +/Ref.java/1.1/Mon Mar 7 19:57:17 2011// +/RuntimeStack.java/1.1/Mon Mar 7 19:57:17 2011// +/RuntimeStackEntry.java/1.1/Mon Mar 7 19:57:17 2011// +/Stack.java/1.1/Mon Mar 7 19:57:17 2011// +/Stream.java/1.1/Mon Mar 7 19:57:17 2011// +/package-info.java/1.1/Mon Mar 7 19:57:17 2011// diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Repository b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Repository new file mode 100644 index 0000000..e714ffb --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/model/am1/machine diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Root b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/InputStream.java b/src/org/jalgo/module/am1simulator/model/am1/machine/InputStream.java new file mode 100644 index 0000000..3264dba --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/InputStream.java @@ -0,0 +1,72 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents an input stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public class InputStream extends Stream { + + /** + * Create a new empty input stream + */ + public InputStream() { + super(); + } + + /** + * Copyconstructor + * + * @param i + * {@link InputStream} which should be copied. + */ + public InputStream(InputStream i) { + super(); + for (MemoryCell m : i.stream) { + this.stream.add(new MemoryCell(m.get())); + } + } + + /** + * Create a new input stream based on an already existing and filled list of + * values. + * + * @param initList + */ + public InputStream(final List initList) { + super(); + for (int i : initList) { + stream.add(new MemoryCell(i)); + } + } + + /** + * @return the first element of the input stream and remove it. + */ + public int read() { + return ((LinkedList) stream).remove().get(); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.java b/src/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.java new file mode 100644 index 0000000..2a736ac --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/MachineConfiguration.java @@ -0,0 +1,183 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.LinkedList; + + +/** + * Configuration for an abstract machine (AM1) as introduced in the lectures. + * Holds the following elements: + * + *

      + *

    • {@link ProgramCounter}
    • + *
    • {@link Stack}
    • + *
    • {@link RuntimeStack}
    • + *
    • {@link Ref}
    • + *
    • {@link InputStream}
    • + *
    • {@link OutputStream}
    • + *

      + *
      + * + *

      + * It is possible to do a deep copy. Use the copyconstructor: + * {@link MachineConfiguration#MachineConfiguration(MachineConfiguration)} + *

      + *
      + * + * @author Max Leuthäuser + */ +public class MachineConfiguration { + private ProgramCounter programCounter; + private Stack stack; + private RuntimeStack runtimeStack; + private Ref ref; + private InputStream inputStream; + private OutputStream outputStream; + + /** + * Creates an empty new machine configuration. + */ + public MachineConfiguration() { + programCounter = new ProgramCounter(); + stack = new Stack(); + runtimeStack = new RuntimeStack(); + ref = new Ref(); + inputStream = new InputStream(); + outputStream = new OutputStream(); + } + + /** + * Copyconstructor + * + * @param m + * {@link MachineConfiguration} which should be copied. + */ + public MachineConfiguration(MachineConfiguration m) { + if (m != null) { + programCounter = new ProgramCounter(m.getProgramCounter()); + stack = new Stack(m.getStack()); + runtimeStack = new RuntimeStack(m.getRuntimeStack()); + ref = new Ref(m.getRef()); + inputStream = new InputStream(m.getInputStream()); + outputStream = new OutputStream(m.getOutputStream()); + } else { + throw new IllegalArgumentException( + "Null argument is not allowed here!"); + } + } + + /** + * Create a new machine configuration with filled values. Use a parameter + * with null will create a new and empty element in the abstract + * machine. + * + * @param programCounter + * Use 0 here to set it to initial value. + * @param stack + * @param runtimeStack + * @param ref + * @param inputStream + * @param outputStream + */ + public MachineConfiguration(int programCounter, LinkedList stack, + LinkedList runtimeStack, int ref, + LinkedList inputStream, LinkedList outputStream) { + if (programCounter != 0) { + this.programCounter = new ProgramCounter(programCounter); + } else { + this.programCounter = new ProgramCounter(); + } + + if (stack != null) { + this.stack = new Stack(stack); + } else { + this.stack = new Stack(); + } + + if (runtimeStack != null) { + this.runtimeStack = new RuntimeStack(runtimeStack); + } else { + this.runtimeStack = new RuntimeStack(); + } + + if (ref != 1) { + this.ref = new Ref(ref); + } else { + this.ref = new Ref(); + } + + if (inputStream != null) { + this.inputStream = new InputStream(inputStream); + } else { + this.inputStream = new InputStream(); + } + + if (outputStream != null) { + this.outputStream = new OutputStream(outputStream); + } else { + this.outputStream = new OutputStream(); + } + } + + public ProgramCounter getProgramCounter() { + return programCounter; + } + + public Stack getStack() { + return stack; + } + + public RuntimeStack getRuntimeStack() { + return runtimeStack; + } + + public Ref getRef() { + return ref; + } + + public InputStream getInputStream() { + return inputStream; + } + + public OutputStream getOutputStream() { + return outputStream; + } + + /** + * Returns a HTML formatted string containing all components with their + * contents. + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "( " + programCounter.toString() + + "" + ",  " + "" + + stack.toString() + "" + ",  " + + "" + runtimeStack.toString() + + "" + ",  " + "" + + ref.toString() + "" + ",  " + + "" + inputStream.toString() + + "" + ",  " + "" + + outputStream + "" + " )"; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.java b/src/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.java new file mode 100644 index 0000000..f5c1c97 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/MemoryCell.java @@ -0,0 +1,52 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +/** + * This class represents a memory cell which is used in the following abstract + * machine elements:
    • {@link Stack}
    • {@link Stream}
    • + * {@link InputStream}
    • {@link OutputStream}
    • + * + * @author Max Leuthäuser + */ +public class MemoryCell { + private int value; + + public MemoryCell(final int value) { + set(value); + } + + /** + * @return the value saved in this cell + */ + public int get() { + return value; + } + + /** + * Set a new value for this cell + * + * @param value + */ + public void set(final int value) { + this.value = value; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.java b/src/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.java new file mode 100644 index 0000000..dbf5e29 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/OutputStream.java @@ -0,0 +1,72 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.List; + +/** + * This class represents an input stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public class OutputStream extends Stream { + + /** + * Create a new empty output stream + */ + public OutputStream() { + super(); + } + + /** + * Copyconstructor + * + * @param i + * {@link OutputStream} which should be copied. + */ + public OutputStream(OutputStream i) { + super(); + for (MemoryCell m : i.stream) { + this.stream.add(new MemoryCell(m.get())); + } + } + + /** + * Create a new output stream based on an already existing and filled list + * of values. + * + * @param initList + */ + public OutputStream(final List initList) { + for (int i : initList) { + stream.add(new MemoryCell(i)); + } + } + + /** + * Write a new value on the output stream. + * + * @param value + */ + public void write(final int value) { + stream.add(new MemoryCell(value)); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.java b/src/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.java new file mode 100644 index 0000000..881fe81 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/ProgramCounter.java @@ -0,0 +1,87 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +/** + * Class which represents the program counter in an abstract machine. + * + * @author Max Leuthäuser + */ +public class ProgramCounter { + private int pc; + + /** + * Create a new program counter which is set to 1. + */ + public ProgramCounter() { + pc = 1; + } + + /** + * Copyconstructor + * + * @param i + * {@link ProgramCounter} which should be copied. + */ + public ProgramCounter(ProgramCounter i) { + pc = i.get(); + } + + /** + * Create a new program counter which is set to the given value. + * + * @param value + */ + public ProgramCounter(final int value) { + pc = value; + } + + /** + * @return the current program counter + */ + public int get() { + return pc; + } + + /** + * Set a new program counter. + * + * @param value + */ + public void set(final int value) { + pc = value; + } + + /** + * Increase the program counter. + */ + public void inc() { + pc++; + } + + /** + * @return the program counter as String + */ + @Override + public String toString() { + return "" + pc; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/Ref.java b/src/org/jalgo/module/am1simulator/model/am1/machine/Ref.java new file mode 100644 index 0000000..55b389d --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/Ref.java @@ -0,0 +1,80 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +/** + * Class which represents the referenz counter in an abstract machine. + * + * @author Max Leuthäuser + */ +public class Ref { + private int ref; + + /** + * Create a new program counter which is set to 0 initially. + */ + public Ref() { + ref = 0; + } + + /** + * Copyconstructor + * + * @param i + * {@link Ref} which should be copied. + */ + public Ref(Ref i) { + ref = i.get(); + } + + /** + * Create a new program counter which is set to the given value. + * + * @param value + */ + public Ref(final int value) { + ref = value; + } + + /** + * @return the current program counter + */ + public int get() { + return ref; + } + + /** + * Set a new program counter. + * + * @param value + */ + public void set(final int value) { + ref = value; + } + + /** + * @return the program counter as String + */ + @Override + public String toString() { + return "" + ref; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.java b/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.java new file mode 100644 index 0000000..7d8d33d --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStack.java @@ -0,0 +1,319 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.List; +import java.util.LinkedList; + +/** + * Class which represents the runtime stack in an abstract machine. + * + * @author Max Leuthäuser + */ +public class RuntimeStack { + private List values; + + /** + * Create a new empty runtime stack. + */ + public RuntimeStack() { + values = new LinkedList(); + } + + /** + * Copyconstructor + * + * @param i + * {@link RuntimeStack} which should be copied. + */ + public RuntimeStack(RuntimeStack i) { + values = new LinkedList(); + + for (RuntimeStackEntry c : i.getRuntimeStackAsList()) { + values.add(new RuntimeStackEntry(c)); + } + } + + /** + * Create a new runtime stack based on an already existing and filled list + * of values. + * + * @param v + * {@link List} which already holds some values. + */ + public RuntimeStack(final List v) { + values = new LinkedList(); + + for (RuntimeStackEntry c : v) { + values.add(new RuntimeStackEntry(c)); + } + } + + /** + * Store a new entry in the runtime stack. (STORE) + * + * @param b + * @param o + * @param r + * @param z + * @return -1 of the operation fails. + */ + public int store(final String b, final int o, final int r, final int z) { + return exchangeAtCount(adr(r, b, o), z); + } + + /** + * Store a new entry in the runtime stack. (STOREI + * + * @param o + * @param r + * @param z + * @return -1 of the operation fails. + */ + public int storei(final int o, final int r, final int z) { + return exchangeAtCount(getAtCount(r + o), z); + } + + /** + * Returns the value at this index in the runtime stack. (LOAD) + * + * @param b + * @param o + * @param r + * @return the value for the given index, -1 if there is no entry at + * this index. + */ + public int load(final String b, final int o, final int r) { + return getAtCount(adr(r, b, o)); + } + + /** + * Returns the value at this index in the runtime stack. (LOADI) + * + * @param o + * @param r + * @return the value for the given index, -1 if there is no entry at + * this index. + */ + public int loadi(final int o, final int r) { + return getAtCount(getAtCount(r + o)); + } + + /** + * Pushes a new value to the runtime stack. (PUSH) + * + * @param z + */ + public void push(final int z) { + if (values.isEmpty()) { + RuntimeStackEntry r = new RuntimeStackEntry(z, false); + values.add(r); + return; + } + RuntimeStackEntry r = values.get(values.size() - 1); + if (r.isClosed()) { + RuntimeStackEntry n = new RuntimeStackEntry(z, false); + values.add(n); + } else { + r.add(z); + } + } + + /** + * Call new values to the runtime stack. (CALL) + * + * @param m + * @param r + */ + public void call(final int m, final int r) { + if (values.isEmpty()) { + LinkedList a = new LinkedList(); + a.add(m); + a.add(r); + RuntimeStackEntry n = new RuntimeStackEntry(a, true); + values.add(n); + return; + } + RuntimeStackEntry l = values.get(values.size() - 1); + if (l.isClosed()) { + LinkedList a = new LinkedList(); + a.add(m); + a.add(r); + RuntimeStackEntry n = new RuntimeStackEntry(a, true); + values.add(n); + } else { + l.add(m); + l.add(r); + l.setClosed(); + } + } + + /** + * Add 'count' times zero to the runtime stack (INIT) + * + * @param count + */ + public void init(final int count) { + if (count > 0) { + if (values.isEmpty()) { + LinkedList a = new LinkedList(); + for (int i = 0; i < count; i++) { + a.add(0); + } + RuntimeStackEntry n = new RuntimeStackEntry(a, true); + values.add(n); + return; + } + RuntimeStackEntry l = values.get(values.size() - 1); + if (l.isClosed()) { + for (int i = 0; i < count; i++) { + l.add(0); + } + } else { + for (int i = 0; i < count; i++) { + l.add(0); + } + l.setClosed(); + } + } + } + + /** + * Removes the last {@link RuntimeStackEntry}. (RET) Calling this will + * change the result e.g. for getLength(). + */ + public void ret() { + values.remove(values.size() - 1); + } + + /** + * @return the length of the runtime stack + */ + public int getLength() { + int result = 0; + for (RuntimeStackEntry r : values) { + result += r.size(); + } + return result; + } + + /** + * Returns the value at this count in the runtime stack. + * + * @param count + * @return the value for the given count + * @throws IndexOutOfBoundsException + * if there is no entry at this index + */ + public int getAtCount(int count) throws IndexOutOfBoundsException { + if (count > getLength() || count == -1) + throw new IndexOutOfBoundsException(); + else { + LinkedList t = new LinkedList(); + for (RuntimeStackEntry r : values) { + t.addAll(r); + } + return t.get(count - 1); + } + } + + /** + * Exchanges a value at this count in the runtime stack. + * + * @param count + * @param value + * @return -1 if there is no entry at this index, 0 otherwise. + */ + public int exchangeAtCount(int count, int value) { + if (getAtCount(count) == -1) + return -1; + else { + LinkedList t = new LinkedList(); + for (RuntimeStackEntry r : values) { + t.addAll(r); + } + t.set(count - 1, value); + int start = 0; + int end = 0; + for (RuntimeStackEntry r : values) { + end = start + r.size() - 1; + r.clear(); + r.addAll(t.subList(start, end + 1)); + start = end + 1; + } + } + return 0; + } + + /** + * @return the ram as list. + */ + public List getRuntimeStackAsList() { + return values; + } + + /** + * adr(r,b,o) = r + o if b='lokal', o otherwise. + * + * @param r + * @param b + * @param o + * @return the result of the function 'adr' as defined by the script. + */ + public static int adr(int r, String b, int o) { + if (b.equals("lokal")) { + return r + o; + } + if (b.equals("global")) { + return o; + } + throw new IllegalArgumentException("b must be 'lokal or 'global'!"); + } + + /** + * @return the runtime stack as String + */ + @Override + public String toString() { + if (values.isEmpty()) { + return "Æ"; + } + StringBuilder result = new StringBuilder(); + for (RuntimeStackEntry i : values) { + result.append(i); + result.append(":"); + } + return result.toString().substring(0, result.toString().length() - 1); + } + + /** + * Print a List containing {@link RuntimeStackEntry}s and format them like a + * real {@link RuntimeStack} using {@link RuntimeStack#toString()}. + * + * @param in + * @return a String that looks like {@link RuntimeStack#toString()}. + */ + public static String printAListAsRuntimeStack(List in) { + RuntimeStack r = new RuntimeStack(in); + return r.toString(); + } + +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.java b/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.java new file mode 100644 index 0000000..5c0865c --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/RuntimeStackEntry.java @@ -0,0 +1,141 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents a runtime stack entry which is used in the following + * abstract machine element:
    • {@link RuntimeStack}
    • + * + * @author Max Leuthäuser + */ +public class RuntimeStackEntry extends LinkedList { + private static final long serialVersionUID = 1L; + private boolean isClosed = false; + + /** + * Create a new {@link RuntimeStackEntry} with an already filled List of + * Integer and a flag (isClosed) which specifies if this stack entry is + * closed or not. + * + * @param in + * @param isClosed + */ + public RuntimeStackEntry(List in, boolean isClosed) { + this.isClosed = isClosed; + for (int i : in) { + add(i); + } + } + + /** + * Create a new {@link RuntimeStackEntry} with only the first value (in) and + * a flag (isClosed) which specifies if this stack entry is closed or not. + * + * @param in + * @param isClosed + */ + public RuntimeStackEntry(int in, boolean isClosed) { + this.isClosed = isClosed; + add(in); + } + + /** + * Copyconstructor + * + * @param in + */ + public RuntimeStackEntry(RuntimeStackEntry in) { + this.isClosed = in.isClosed(); + for (int i : in) { + add(i); + } + } + + /** + * @return true if this {@link RuntimeStackEntry} is closed, false + * otherwise. + */ + public boolean isClosed() { + return isClosed; + } + + /** + * Close this {@link RuntimeStackEntry} finally. There is no way back. + */ + public void setClosed() { + isClosed = true; + } + + /** + * Return a String representation for this {@link RuntimeStackEntry}.
      + *
      + *
        + * This uses the following rules: + *

        + *

      • The {@link RuntimeStackEntry} is empty: return an empty String + *
      • + *
      • The {@link RuntimeStackEntry} contains one or more values: + * return this values separated with ":", leading with an open parentheses.
      • + *
      • The String ends with a closed parentheses if the + * {@link RuntimeStackEntry} is closed.
      • + *

        + *
      + *
      + * + * @return a String formatted as written above. + */ + @Override + public String toString() { + if (isEmpty()) { + return ""; + } else { + StringBuilder b = new StringBuilder(); + b.append("("); + for (int i : this) { + b.append(i); + b.append(":"); + } + String result = b.toString() + .substring(0, b.toString().length() - 1); + if (isClosed) { + result += ")"; + } + return result; + } + } + + @Override + public int hashCode() { + throw new AssertionError( + "This class is not ment to be used in an hash data structure!"); + } + + @Override + public boolean equals(Object o) { + if (o instanceof RuntimeStackEntry) { + return ((RuntimeStackEntry) o).toString().equals(toString()); + } + return false; + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/Stack.java b/src/org/jalgo/module/am1simulator/model/am1/machine/Stack.java new file mode 100644 index 0000000..5f9d20c --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/Stack.java @@ -0,0 +1,115 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents a stack which is used in a {@link MachineConfiguration} + * . + * + * @author Max Leuthäuser + */ +public class Stack { + private List values; + + /** + * Create a new empty stack. + */ + public Stack() { + values = new LinkedList(); + } + + /** + * Copyconstructor + * + * @param i + * {@link Stack} which should be copied. + */ + public Stack(Stack i) { + values = new LinkedList(); + + for (MemoryCell c : i.getStackAsList()) { + push(c.get()); + } + } + + /** + * Create a new stack based on an already existing and filled list of + * values. + * + * @param values + * {@link LinkedList} which already holds some values. + */ + public Stack(final List values) { + this.values = new LinkedList(); + for (int i : values) { + push(i); + } + } + + /** + * Adds a single element at the top of the stack. + * + * @param value + */ + public void push(final int value) { + values.add(new MemoryCell(value)); + } + + /** + * @return the current element from the top of the stack + */ + public int pop() { + return values.remove(values.size() - 1).get(); + } + + /** + * @return the stack as list. + */ + public List getStackAsList() { + return this.values; + } + + /** + * @return the stack as String + */ + @Override + public String toString() { + if (values.isEmpty()) { + return "Æ"; + } + StringBuilder result = new StringBuilder(); + ArrayList l = new ArrayList(); + for (MemoryCell i : values) { + l.add(i.get()); + } + Collections.reverse(l); + for (int s : l) { + result.append(s); + result.append(":"); + } + return result.toString().substring(0, result.length() - 1); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/Stream.java b/src/org/jalgo/module/am1simulator/model/am1/machine/Stream.java new file mode 100644 index 0000000..855a77a --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/Stream.java @@ -0,0 +1,55 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.model.am1.machine; + +import java.util.LinkedList; +import java.util.List; + +/** + * This class represents a non specific stream for an abstract machine. + * + * @author Max Leuthäuser + */ +public abstract class Stream { + protected List stream; + + /** + * Creates a new empty stream. + */ + public Stream() { + stream = new LinkedList(); + } + + /** + * @return the stream as String + */ + @Override + public String toString() { + if (stream.isEmpty()) { + return "Æ"; + } + StringBuilder result = new StringBuilder(); + for (MemoryCell i : stream) { + result.append("," + i.get()); + } + return result.toString().replaceFirst(",", ""); + } +} diff --git a/src/org/jalgo/module/am1simulator/model/am1/machine/package-info.java b/src/org/jalgo/module/am1simulator/model/am1/machine/package-info.java new file mode 100644 index 0000000..7b63f70 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/machine/package-info.java @@ -0,0 +1,25 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Classes that represent an abstract machine (AM1) as introduced in the lectures. + */ +package org.jalgo.module.am1simulator.model.am1.machine; + diff --git a/src/org/jalgo/module/am1simulator/model/am1/package-info.java b/src/org/jalgo/module/am1simulator/model/am1/package-info.java new file mode 100644 index 0000000..7b9a2ee --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/am1/package-info.java @@ -0,0 +1,25 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Classes that represent an abstract machine (AM1) as introduced in the lectures and classes that handle an AM1 simulation. + */ +package org.jalgo.module.am1simulator.model.am1; + diff --git a/src/org/jalgo/module/am1simulator/model/package-info.java b/src/org/jalgo/module/am1simulator/model/package-info.java new file mode 100644 index 0000000..e1ad2db --- /dev/null +++ b/src/org/jalgo/module/am1simulator/model/package-info.java @@ -0,0 +1,25 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Classes to store and handle data of different types. + */ +package org.jalgo.module.am1simulator.model; + diff --git a/src/org/jalgo/module/am1simulator/package-info.java b/src/org/jalgo/module/am1simulator/package-info.java new file mode 100644 index 0000000..4a2104f --- /dev/null +++ b/src/org/jalgo/module/am1simulator/package-info.java @@ -0,0 +1,24 @@ +/** +* AM1 Simulator - simulating am1 code in an abstract machine based on the +* definitions of the lectures 'Programmierung' at TU Dresden. +* Copyright (C) 2010 Max Leuthäuser +* Contact: s7060241@mail.zih.tu-dresden.de +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +/** + * Main entry point of the application. + */ +package org.jalgo.module.am1simulator; diff --git a/src/org/jalgo/module/am1simulator/parser/AM1Lexer.java b/src/org/jalgo/module/am1simulator/parser/AM1Lexer.java new file mode 100644 index 0000000..2a4a0b0 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/AM1Lexer.java @@ -0,0 +1,740 @@ +/* The following code was generated by JFlex 1.4.3 on 21.01.11 21:44 */ + +package org.jalgo.module.am1simulator.parser; +import jsyntaxpane.Token; +import jsyntaxpane.TokenType; +import jsyntaxpane.lexers.DefaultJFlexLexer; + + + +/** + * This class is a scanner generated by + * JFlex 1.4.3 + * on 21.01.11 21:44 from the specification file + * C:/Users/Max/Desktop/jsyntaxpane/jsyntaxpane/src/main/jflex/jsyntaxpane/lexers/am1.flex + */ +public final class AM1Lexer extends DefaultJFlexLexer { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\7\1\3\1\2\1\0\1\3\1\1\16\7\4\0\1\3\3\0"+ + "\1\6\3\0\1\37\1\40\1\5\1\0\1\41\1\41\1\0\1\4"+ + "\1\10\11\11\1\0\1\41\5\0\1\12\1\20\1\34\1\13\1\24"+ + "\1\6\1\30\1\36\1\21\1\32\1\6\1\16\1\14\1\26\1\23"+ + "\1\33\1\25\1\31\1\17\1\27\1\15\1\22\1\35\3\6\4\0"+ + "\1\6\1\0\1\45\1\47\4\6\1\46\3\6\1\44\1\42\2\6"+ + "\1\43\13\6\4\0\41\7\2\0\4\6\4\0\1\6\2\0\1\7"+ + "\7\0\1\6\4\0\1\6\5\0\27\6\1\0\37\6\1\0\u013f\6"+ + "\31\0\162\6\4\0\14\6\16\0\5\6\11\0\1\6\21\0\130\7"+ + "\5\0\23\7\12\0\1\6\13\0\1\6\1\0\3\6\1\0\1\6"+ + "\1\0\24\6\1\0\54\6\1\0\46\6\1\0\5\6\4\0\202\6"+ + "\1\0\4\7\3\0\105\6\1\0\46\6\2\0\2\6\6\0\20\6"+ + "\41\0\46\6\2\0\1\6\7\0\47\6\11\0\21\7\1\0\27\7"+ + "\1\0\3\7\1\0\1\7\1\0\2\7\1\0\1\7\13\0\33\6"+ + "\5\0\3\6\15\0\4\7\14\0\6\7\13\0\32\6\5\0\13\6"+ + "\16\7\7\0\12\7\4\0\2\6\1\7\143\6\1\0\1\6\10\7"+ + "\1\0\6\7\2\6\2\7\1\0\4\7\2\6\12\7\3\6\2\0"+ + "\1\6\17\0\1\7\1\6\1\7\36\6\33\7\2\0\3\6\60\0"+ + "\46\6\13\7\1\6\u014f\0\3\7\66\6\2\0\1\7\1\6\20\7"+ + "\2\0\1\6\4\7\3\0\12\6\2\7\2\0\12\7\21\0\3\7"+ + "\1\0\10\6\2\0\2\6\2\0\26\6\1\0\7\6\1\0\1\6"+ + "\3\0\4\6\2\0\1\7\1\6\7\7\2\0\2\7\2\0\3\7"+ + "\11\0\1\7\4\0\2\6\1\0\3\6\2\7\2\0\12\7\4\6"+ + "\15\0\3\7\1\0\6\6\4\0\2\6\2\0\26\6\1\0\7\6"+ + "\1\0\2\6\1\0\2\6\1\0\2\6\2\0\1\7\1\0\5\7"+ + "\4\0\2\7\2\0\3\7\13\0\4\6\1\0\1\6\7\0\14\7"+ + "\3\6\14\0\3\7\1\0\11\6\1\0\3\6\1\0\26\6\1\0"+ + "\7\6\1\0\2\6\1\0\5\6\2\0\1\7\1\6\10\7\1\0"+ + "\3\7\1\0\3\7\2\0\1\6\17\0\2\6\2\7\2\0\12\7"+ + "\1\0\1\6\17\0\3\7\1\0\10\6\2\0\2\6\2\0\26\6"+ + "\1\0\7\6\1\0\2\6\1\0\5\6\2\0\1\7\1\6\6\7"+ + "\3\0\2\7\2\0\3\7\10\0\2\7\4\0\2\6\1\0\3\6"+ + "\4\0\12\7\1\0\1\6\20\0\1\7\1\6\1\0\6\6\3\0"+ + "\3\6\1\0\4\6\3\0\2\6\1\0\1\6\1\0\2\6\3\0"+ + "\2\6\3\0\3\6\3\0\10\6\1\0\3\6\4\0\5\7\3\0"+ + "\3\7\1\0\4\7\11\0\1\7\17\0\11\7\11\0\1\6\7\0"+ + "\3\7\1\0\10\6\1\0\3\6\1\0\27\6\1\0\12\6\1\0"+ + "\5\6\4\0\7\7\1\0\3\7\1\0\4\7\7\0\2\7\11\0"+ + "\2\6\4\0\12\7\22\0\2\7\1\0\10\6\1\0\3\6\1\0"+ + "\27\6\1\0\12\6\1\0\5\6\2\0\1\7\1\6\7\7\1\0"+ + "\3\7\1\0\4\7\7\0\2\7\7\0\1\6\1\0\2\6\4\0"+ + "\12\7\22\0\2\7\1\0\10\6\1\0\3\6\1\0\27\6\1\0"+ + "\20\6\4\0\6\7\2\0\3\7\1\0\4\7\11\0\1\7\10\0"+ + "\2\6\4\0\12\7\22\0\2\7\1\0\22\6\3\0\30\6\1\0"+ + "\11\6\1\0\1\6\2\0\7\6\3\0\1\7\4\0\6\7\1\0"+ + "\1\7\1\0\10\7\22\0\2\7\15\0\60\6\1\7\2\6\7\7"+ + "\4\0\10\6\10\7\1\0\12\7\47\0\2\6\1\0\1\6\2\0"+ + "\2\6\1\0\1\6\2\0\1\6\6\0\4\6\1\0\7\6\1\0"+ + "\3\6\1\0\1\6\1\0\1\6\2\0\2\6\1\0\4\6\1\7"+ + "\2\6\6\7\1\0\2\7\1\6\2\0\5\6\1\0\1\6\1\0"+ + "\6\7\2\0\12\7\2\0\2\6\42\0\1\6\27\0\2\7\6\0"+ + "\12\7\13\0\1\7\1\0\1\7\1\0\1\7\4\0\2\7\10\6"+ + "\1\0\42\6\6\0\24\7\1\0\2\7\4\6\4\0\10\7\1\0"+ + "\44\7\11\0\1\7\71\0\42\6\1\0\5\6\1\0\2\6\1\0"+ + "\7\7\3\0\4\7\6\0\12\7\6\0\6\6\4\7\106\0\46\6"+ + "\12\0\51\6\7\0\132\6\5\0\104\6\5\0\122\6\6\0\7\6"+ + "\1\0\77\6\1\0\1\6\1\0\4\6\2\0\7\6\1\0\1\6"+ + "\1\0\4\6\2\0\47\6\1\0\1\6\1\0\4\6\2\0\37\6"+ + "\1\0\1\6\1\0\4\6\2\0\7\6\1\0\1\6\1\0\4\6"+ + "\2\0\7\6\1\0\7\6\1\0\27\6\1\0\37\6\1\0\1\6"+ + "\1\0\4\6\2\0\7\6\1\0\47\6\1\0\23\6\16\0\11\7"+ + "\56\0\125\6\14\0\u026c\6\2\0\10\6\12\0\32\6\5\0\113\6"+ + "\3\0\3\6\17\0\15\6\1\0\4\6\3\7\13\0\22\6\3\7"+ + "\13\0\22\6\2\7\14\0\15\6\1\0\3\6\1\0\2\7\14\0"+ + "\64\6\40\7\3\0\1\6\3\0\2\6\1\7\2\0\12\7\41\0"+ + "\3\7\2\0\12\7\6\0\130\6\10\0\51\6\1\7\126\0\35\6"+ + "\3\0\14\7\4\0\14\7\12\0\12\7\36\6\2\0\5\6\u038b\0"+ + "\154\6\224\0\234\6\4\0\132\6\6\0\26\6\2\0\6\6\2\0"+ + "\46\6\2\0\6\6\2\0\10\6\1\0\1\6\1\0\1\6\1\0"+ + "\1\6\1\0\37\6\2\0\65\6\1\0\7\6\1\0\1\6\3\0"+ + "\3\6\1\0\7\6\3\0\4\6\2\0\6\6\4\0\15\6\5\0"+ + "\3\6\1\0\7\6\17\0\4\7\32\0\5\7\20\0\2\6\23\0"+ + "\1\6\13\0\4\7\6\0\6\7\1\0\1\6\15\0\1\6\40\0"+ + "\22\6\36\0\15\7\4\0\1\7\3\0\6\7\27\0\1\6\4\0"+ + "\1\6\2\0\12\6\1\0\1\6\3\0\5\6\6\0\1\6\1\0"+ + "\1\6\1\0\1\6\1\0\4\6\1\0\3\6\1\0\7\6\3\0"+ + "\3\6\5\0\5\6\26\0\44\6\u0e81\0\3\6\31\0\11\6\6\7"+ + "\1\0\5\6\2\0\5\6\4\0\126\6\2\0\2\7\2\0\3\6"+ + "\1\0\137\6\5\0\50\6\4\0\136\6\21\0\30\6\70\0\20\6"+ + "\u0200\0\u19b6\6\112\0\u51a6\6\132\0\u048d\6\u0773\0\u2ba4\6\u215c\0\u012e\6"+ + "\2\0\73\6\225\0\7\6\14\0\5\6\5\0\1\6\1\7\12\6"+ + "\1\0\15\6\1\0\5\6\1\0\1\6\1\0\2\6\1\0\2\6"+ + "\1\0\154\6\41\0\u016b\6\22\0\100\6\2\0\66\6\50\0\15\6"+ + "\3\0\20\7\20\0\4\7\17\0\2\6\30\0\3\6\31\0\1\6"+ + "\6\0\5\6\1\0\207\6\2\0\1\7\4\0\1\6\13\0\12\7"+ + "\7\0\32\6\4\0\1\6\1\0\32\6\12\0\132\6\3\0\6\6"+ + "\2\0\6\6\2\0\6\6\2\0\3\6\3\0\2\6\3\0\2\6"+ + "\22\0\3\7\4\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\1\1\3\2\4\16\3\1\5"+ + "\1\6\1\7\2\3\1\10\1\0\5\3\1\11\12\3"+ + "\2\10\2\0\7\3\1\0\1\11\1\3\1\11\1\3"+ + "\1\12"; + + private static int [] zzUnpackAction() { + int [] result = new int[61]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\50\0\120\0\170\0\240\0\50\0\310\0\360"+ + "\0\u0118\0\u0140\0\u0168\0\u0190\0\u01b8\0\u01e0\0\u0208\0\u0230"+ + "\0\u0258\0\u0280\0\u02a8\0\u02d0\0\u02f8\0\50\0\50\0\50"+ + "\0\u0320\0\u0348\0\u0370\0\u0398\0\u03c0\0\u03e8\0\u0410\0\u0438"+ + "\0\u0460\0\240\0\u0488\0\u04b0\0\u04d8\0\u0500\0\u0528\0\u0550"+ + "\0\u0578\0\u05a0\0\u05c8\0\u05f0\0\u0618\0\50\0\u0640\0\u0668"+ + "\0\u0690\0\u06b8\0\u06e0\0\u0708\0\u0730\0\u0758\0\u0780\0\u07a8"+ + "\0\u07d0\0\u07f8\0\u0820\0\u0848\0\240"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[61]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\3\3\1\4\1\2\1\5\1\2\1\6\1\7"+ + "\1\10\1\11\1\12\1\5\1\13\1\14\1\5\1\15"+ + "\2\5\1\16\1\5\1\17\1\5\1\20\1\21\1\22"+ + "\1\23\1\24\1\25\1\5\1\26\1\27\1\30\1\31"+ + "\3\5\1\32\1\5\51\0\3\3\50\0\1\33\1\34"+ + "\50\0\31\5\3\0\6\5\10\0\2\7\44\0\5\5"+ + "\1\35\23\5\3\0\6\5\6\0\13\5\1\36\15\5"+ + "\3\0\6\5\6\0\7\5\1\37\5\5\1\35\13\5"+ + "\3\0\6\5\6\0\13\5\1\40\1\5\1\41\1\42"+ + "\2\5\1\42\7\5\3\0\6\5\6\0\7\5\1\43"+ + "\11\5\1\44\7\5\3\0\6\5\6\0\20\5\1\45"+ + "\10\5\3\0\6\5\6\0\17\5\1\42\11\5\3\0"+ + "\6\5\6\0\16\5\1\42\12\5\3\0\6\5\6\0"+ + "\16\5\1\42\2\5\1\42\7\5\3\0\6\5\6\0"+ + "\16\5\1\46\12\5\3\0\6\5\6\0\6\5\1\47"+ + "\22\5\3\0\6\5\6\0\7\5\1\50\21\5\3\0"+ + "\6\5\6\0\4\5\1\51\24\5\3\0\6\5\6\0"+ + "\23\5\1\52\5\5\3\0\6\5\6\0\31\5\3\0"+ + "\1\5\1\53\4\5\6\0\31\5\3\0\1\54\5\5"+ + "\1\33\1\55\1\56\45\33\5\57\1\60\42\57\6\0"+ + "\5\5\1\42\23\5\3\0\6\5\6\0\14\5\1\42"+ + "\14\5\3\0\6\5\6\0\10\5\1\42\20\5\3\0"+ + "\6\5\6\0\21\5\1\42\7\5\3\0\6\5\6\0"+ + "\4\5\1\61\24\5\3\0\6\5\6\0\12\5\1\42"+ + "\16\5\3\0\6\5\6\0\15\5\1\62\13\5\3\0"+ + "\6\5\6\0\13\5\1\40\15\5\3\0\6\5\6\0"+ + "\4\5\1\63\14\5\1\42\7\5\3\0\6\5\6\0"+ + "\25\5\2\42\2\5\3\0\6\5\6\0\11\5\1\64"+ + "\17\5\3\0\6\5\6\0\10\5\1\37\20\5\3\0"+ + "\6\5\6\0\13\5\1\65\15\5\3\0\6\5\6\0"+ + "\31\5\3\0\2\5\1\66\3\5\6\0\31\5\3\0"+ + "\1\5\1\67\4\5\2\0\1\56\45\0\5\57\1\70"+ + "\42\57\4\0\1\56\1\60\50\0\5\5\1\71\23\5"+ + "\3\0\6\5\6\0\23\5\1\72\5\5\3\0\6\5"+ + "\6\0\5\5\1\73\23\5\3\0\6\5\6\0\30\5"+ + "\1\42\3\0\6\5\6\0\21\5\1\72\7\5\3\0"+ + "\6\5\6\0\31\5\3\0\3\5\1\74\2\5\6\0"+ + "\31\5\3\0\5\5\1\66\4\57\1\56\1\70\42\57"+ + "\6\0\4\5\1\42\6\5\1\42\15\5\3\0\6\5"+ + "\6\0\16\5\1\73\12\5\3\0\6\5\6\0\13\5"+ + "\1\42\15\5\3\0\6\5\6\0\31\5\3\0\1\75"+ + "\5\5"; + + private static int [] zzUnpackTrans() { + int [] result = new int[2160]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\3\1\1\11\17\1\3\11\3\1\1\0"+ + "\21\1\1\11\2\0\7\1\1\0\5\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[61]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + + public AM1Lexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + public Token token(TokenType type) { + return new Token(type, yychar, yylength()); + } + + public Token token(TokenType type, int pairValue) { + return new Token(type, yychar, yylength(), (byte)pairValue); + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + public AM1Lexer(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + public AM1Lexer(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 1746) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Token yylex() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 9: + { return token(TokenType.KEYWORD); + } + case 11: break; + case 2: + { /* ignore */ + } + case 12: break; + case 7: + { return token(TokenType.OPERATOR); + } + case 13: break; + case 6: + { return token(TokenType.OPERATOR, -PARAN); + } + case 14: break; + case 3: + { return token(TokenType.IDENTIFIER); + } + case 15: break; + case 5: + { return token(TokenType.OPERATOR, PARAN); + } + case 16: break; + case 10: + { return token(TokenType.STRING); + } + case 17: break; + case 8: + { return token(TokenType.COMMENT); + } + case 18: break; + case 4: + { return token(TokenType.NUMBER); + } + case 19: break; + case 1: + { + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + { + return null; + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/src/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.java b/src/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.java new file mode 100644 index 0000000..45cf98d --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/AM1SyntaxKit.java @@ -0,0 +1,20 @@ +package org.jalgo.module.am1simulator.parser; + +import jsyntaxpane.DefaultSyntaxKit; +import jsyntaxpane.Lexer; + +/** + * + * @author Max Leuthäuser + */ +public class AM1SyntaxKit extends DefaultSyntaxKit { + private static final long serialVersionUID = 1L; + + public AM1SyntaxKit() { + super(new AM1Lexer()); + } + + AM1SyntaxKit(Lexer lexer) { + super(lexer); + } +} diff --git a/src/org/jalgo/module/am1simulator/parser/CVS/Entries b/src/org/jalgo/module/am1simulator/parser/CVS/Entries new file mode 100644 index 0000000..ba8d2a8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/CVS/Entries @@ -0,0 +1,9 @@ +/AM1Lexer.java/1.1/Mon Mar 7 19:57:18 2011// +/AM1SyntaxKit.java/1.1/Mon Mar 7 19:57:18 2011// +/ErrorEvents.java/1.1/Mon Mar 7 19:57:18 2011// +/Parser.java/1.1/Mon Mar 7 19:57:18 2011// +/ParserConstants.java/1.1/Mon Mar 7 19:57:18 2011// +/ParserUtils.java/1.1/Mon Mar 7 19:57:18 2011// +D/am1//// +/package-info.java/1.1/Mon Mar 7 19:57:18 2011// +D/parsersrc//// diff --git a/src/org/jalgo/module/am1simulator/parser/CVS/Repository b/src/org/jalgo/module/am1simulator/parser/CVS/Repository new file mode 100644 index 0000000..daacc02 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/parser diff --git a/src/org/jalgo/module/am1simulator/parser/CVS/Root b/src/org/jalgo/module/am1simulator/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/parser/ErrorEvents.java b/src/org/jalgo/module/am1simulator/parser/ErrorEvents.java new file mode 100644 index 0000000..8614465 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/ErrorEvents.java @@ -0,0 +1,300 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.parser; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; +import beaver.Scanner; +import beaver.Symbol; +import beaver.Parser.Events; +import org.jalgo.module.am1simulator.parser.am1.GeneratedAM1Parser; + +/** + * Provides a replacement for the standard error reporting gateway of the Beaver + * parser generator. This class is not intended to be instantiated directly + * (since it is abstract), use {@link #forAm1()} to get instances of this class + * that are specialized for AM1 error reporting, respectively. + * + * @author Martin Morgenstern + * @author Max Leuthäuser + */ +public abstract class ErrorEvents extends Events { + /** + * CSS style for highlighted user input (tokens) in error messages. + */ + private final static String STYLE_TOKEN = "background-color:#fff3af;font-size:100%;font-weight:bold;"; + + /** + * CSS style for words indicating an error. + */ + private final static String STYLE_ERROR = "color: #ff0000;"; + + /** + * Collects all syntax errors. + */ + private List syntaxErrors = new ArrayList(); + + /** + * Collects all lexer errors. + */ + private List lexicalErrors = new ArrayList(); + + /** + * Caches forbidden input sequences. + */ + private StringBuilder forbiddenInput = new StringBuilder(); + + /** + * Marker for the last line where an unmatched character was found (i.e. the + * "catch-all" rule of the lexer matched) and a lexer error occured. + */ + private int lastScannerErrorLine = 1; + + /** + * Handles scanner errors. Unmatched characters are collected per line and + * printed together. + */ + @Override + public void scannerError(Scanner.Exception e) { + if (e.line != lastScannerErrorLine) { + finishScannerErrorLine(); + } + + forbiddenInput.append(e.getMessage()); + lastScannerErrorLine = e.line; + } + + /** + * Add an error message with the cached characters in {@code forbiddenInput} + * to the lexer error list and clear the cache. If the cache is empty, do + * nothing. + */ + private void finishScannerErrorLine() { + if (forbiddenInput.length() > 0) { + final String error = String + .format("Can't process input \"%s\" on line %d.", + STYLE_TOKEN, escapeHtml(forbiddenInput.toString()), + lastScannerErrorLine); + lexicalErrors.add(error); + forbiddenInput = new StringBuilder(); + } + } + + /** + * Handle syntax errors. + */ + @Override + public void syntaxError(Symbol token) { + final String tokenValue = (token.value != null) ? token.value + .toString() : "#" + token.getId(); + + int line = Symbol.getLine(token.getStart()); + int col = Symbol.getColumn(token.getStart()); + + String error; + + if (ParserConstants.EOF.equals(tokenValue)) { + error = String.format( + "Unexpected end-of-file at line %d, column %d.", line, col); + } else if (ParserConstants.EOL.equals(tokenValue)) { + error = String.format( + "Unexpected end-of-line at line %d, column %d.", line, col); + } else { + error = String + .format("Unexpected token \"%s\" at line %d, column %d.", + STYLE_TOKEN, escapeHtml(tokenValue), line, col); + } + + syntaxErrors.add(error); + } + + /** + * Handle the deletion of unexpected tokens. Here an error message is + * appended to the last error message to give the user a hint. + */ + @Override + public void unexpectedTokenRemoved(Symbol token) { + extendLastErrorMessage("Delete it to correct this error."); + } + + /** + * Helper method that appends a string to the last element of the syntax + * error list. + * + * @param extension + * the string to append + */ + protected void extendLastErrorMessage(String extension) { + int replacePosition = syntaxErrors.size() - 1; + + if (replacePosition >= 0) { + String error = syntaxErrors.get(replacePosition) + " " + extension; + syntaxErrors.set(replacePosition, error); + } + } + + /** + * Specific implementation of AM1 error events. + */ + private static class AM1ErrorEvents extends ErrorEvents { + /** + * Contains a mapping of hints for terminal symbols that should be + * inserted by the user. + */ + private static final Map hints; + + static { + final Map m = new HashMap(); + + m.put(GeneratedAM1Parser.Terminals.NUMBER, + "Insert a number to correct this error."); + m.put(GeneratedAM1Parser.Terminals.SEMICOLON, + "Insert \";\" to complete this AM1 statement."); + m.put(GeneratedAM1Parser.Terminals.COMMA, + "Insert \",\" to correct this error."); + m.put(GeneratedAM1Parser.Terminals.NUMBER, + "Insert a number to complete this AM1 statement."); + hints = Collections.unmodifiableMap(m); + } + + @Override + public void missingTokenInserted(Symbol token) { + final Short id = token.getId(); + if (hints.containsKey(id)) { + extendLastErrorMessage(hints.get(id)); + } + } + } + + /** + * Indicates that an error can be recovered if {@code token} is inserted at + * the position of the syntax error. + */ + @Override + public abstract void missingTokenInserted(Symbol token); + + /** + * Indicates that an error can be recovered if the error token is replaced + * by {@code token}. + */ + @Override + public void misspelledTokenReplaced(Symbol token) { + } + + @Override + public void errorPhraseRemoved(Symbol error) { + } + + /** + * Used to collect string to int conversion errors because of too large + * integers. + * + * @param number + * the string containing the number that was too large to convert + * @param line + * the line on which the error occured + * @param col + * the column in which the error occured + */ + public void conversionError(final String number, final int line, + final int col) { + lexicalErrors + .add(String + .format("The number %s at line %d, column %d is too large: the maximum possible value is %d.", + STYLE_TOKEN, escapeHtml(number), line, col, + Integer.MAX_VALUE)); + } + + /** + * Get the total amount of errors collected. + * + * @return total amount of errors + */ + private int getErrorCount() { + return lexicalErrors.size() + syntaxErrors.size(); + } + + /** + * Check wether an error occured during parsing. + * + * @return {@code true}, if there was at least one error, otherwise + * {@code false} + */ + public boolean hasErrors() { + // update internal state + finishScannerErrorLine(); + return getErrorCount() > 0; + } + + /** + * Get a summarizing error text (HTML formatted) for all the errors that + * occured during parsing or {@code null}, if no error occured. Use + * {@link #hasErrors()} to check if errors occured. + * + * @return summarizing error text or {@code null}, if no error occured + */ + public String getErrorText() { + if (!hasErrors()) { + return null; + } + + StringBuilder result = new StringBuilder("

      "); + + if (getErrorCount() > 1) { + result.append(String + .format("The following errors occured during validation:", + STYLE_ERROR)); + } else { + result.append(String + .format("The following error occured during validation:", + STYLE_ERROR)); + } + + result.append("
      "); + final String itemFormat = " - %s: %s
      "; + + for (String error : lexicalErrors) { + result.append(String.format(itemFormat, "Lexical Analysis", error)); + } + + for (String error : syntaxErrors) { + result.append(String + .format(itemFormat, "Syntactic Analysis", error)); + } + + result.append("

      "); + + return result.toString(); + } + + /** + * Get a fresh {@link ErrorEvents} instance specialized for AM0 parsers. + * + * @return a new {@link ErrorEvents} instance + */ + public static ErrorEvents forAm1() { + return new AM1ErrorEvents(); + } +} diff --git a/src/org/jalgo/module/am1simulator/parser/Parser.java b/src/org/jalgo/module/am1simulator/parser/Parser.java new file mode 100644 index 0000000..4f54b95 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/Parser.java @@ -0,0 +1,53 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.parser; + +/** + * The {@code Parser} interface provides common methods for dealing with the AM1 + * parser. + * + * @author Martin Morgenstern + * @author Max Leuthäuser + * @see org.jalgo.module.am1simulator.parser.am1.AM1Parser + */ +public interface Parser { + /** + * Parse the source code contained in {@code text} and check the source code + * for syntax errors. If there was no syntax error, {@code true} is + * returned, else {@code false} is returned and a detailed error message + * will be available by invoking the method {@link #getErrorText()}. + * + * @param text + * the program source code + * @return {@code true}, if the program source code contains no syntax + * errors, {@code false} otherwise + */ + public boolean parse(String text); + + /** + * If a previous call to {@link #parse(String)} returned {@code false}, this + * method returns a detailed message describing the error that occured while + * parsing. Otherwise it will return {@code null}. + * + * @return a detailed error message from the parser + */ + public String getErrorText(); +} diff --git a/src/org/jalgo/module/am1simulator/parser/ParserConstants.java b/src/org/jalgo/module/am1simulator/parser/ParserConstants.java new file mode 100644 index 0000000..4d64ade --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/ParserConstants.java @@ -0,0 +1,46 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.parser; + +/** + * Set of constants that are used by the parser package. + * + * @author Martin Morgenstern + */ +public final class ParserConstants { + /** + * This class is not designed to be instantiated, therefore it's constructor + * is private. + */ + private ParserConstants() { + throw new AssertionError(); + } + + /** + * Constant used as the value for end-of-file symbols (i.e. tokens). + */ + public static final String EOF = "end-of-file"; + + /** + * Constant used as the value for end-of-line symbols (i.e. tokens). + */ + public static final String EOL = "end-of-line"; +} diff --git a/src/org/jalgo/module/am1simulator/parser/ParserUtils.java b/src/org/jalgo/module/am1simulator/parser/ParserUtils.java new file mode 100644 index 0000000..38c9cdc --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/ParserUtils.java @@ -0,0 +1,64 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.parser; + +import beaver.Symbol; + +/** + * Utility class for parser-related work. + * + * @author Martin Morgenstern + */ +public class ParserUtils { + /** + * Utility method that safely converts symbols into numbers. If the + * conversion is not successful, the error is reported through the error + * reporting gateway. + * + * @param symbol + * the symbol that should be converted + * @param report + * the error reporting gateway to use + * @return the corresponding integer value, or {@code 0} if conversion + * failed + * @see ErrorEvents + */ + public static int safeSymbolToInt(final Symbol symbol, + final ErrorEvents report) { + int result = 0; + + if ((null == symbol) || (null == symbol.value)) { + return result; + } + + final String number = symbol.value.toString(); + final int line = Symbol.getLine(symbol.getStart()); + final int col = Symbol.getColumn(symbol.getStart()); + + try { + result = Integer.parseInt(number); + } catch (NumberFormatException e) { + report.conversionError(number, line, col); + } + + return result; + } +} diff --git a/src/org/jalgo/module/am1simulator/parser/am1/AM1Parser.java b/src/org/jalgo/module/am1simulator/parser/am1/AM1Parser.java new file mode 100644 index 0000000..7b62266 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/AM1Parser.java @@ -0,0 +1,116 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.parser.am1; + +import java.io.IOException; +import java.io.StringReader; + +import org.jalgo.module.am1simulator.model.am1.AM1Program; +import org.jalgo.module.am1simulator.parser.ErrorEvents; +import org.jalgo.module.am1simulator.parser.Parser; + +/** + * Provides an abstraction to the generated AM1 lexer and parser as well as an + * implementation of the {@code Parser} interface. + * + * @author Martin Morgenstern + * @author Max Leuthäuser + * @see Parser + */ +public class AM1Parser implements Parser { + /** + * The resulting AM1 program. + */ + private AM1Program program = null; + + /** + * Contains the parser error message in case of an error, otherwise + * {@code null}. + */ + private String errorText; + + /** + * Get the abstract representation of the parsed program, or {@code null} if + * there was an error while parsing. + * + *

      + * Note: You must invoke {@link #parse(String)} first and + * do error handling as needed. + * + * @return an AM1Program containing the abstract representation of the + * parsed program + * + * @throws IllegalAccessException + * if you call this method before calling {@link #parse(String)} + * . + */ + public AM1Program getProgram() throws IllegalAccessException { + if (program == null) { + throw new IllegalAccessException( + "You must not call this method before calling parse()!"); + } + return program; + } + + /** + * {@inheritDoc} + */ + @Override + public String getErrorText() { + return errorText; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean parse(final String text) { + boolean errorFlag = false; + + GeneratedAM1Parser parser = new GeneratedAM1Parser(); + AM1Scanner scanner = new AM1Scanner(new StringReader(text.trim())); + + errorText = ""; + program = null; + + try { + program = (AM1Program) parser.parse(scanner); + } catch (beaver.Parser.Exception e) { + errorFlag = true; + } catch (IOException e) { + errorFlag = true; + } + + ErrorEvents errors = parser.getErrorEvents(); + + if (errors.hasErrors()) { + errorFlag = true; + errorText += errors.getErrorText(); + } + + if (!errorFlag) { + errorText = null; + return true; + } + + return false; + } +} diff --git a/src/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.java b/src/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.java new file mode 100644 index 0000000..7daead3 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/AM1Scanner.java @@ -0,0 +1,837 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* The following code was generated by JFlex 1.4.3 on 26.08.10 23:29 */ + +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +/* Author: Max Leuthäuser */ + +package org.jalgo.module.am1simulator.parser.am1; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.am1simulator.parser.ParserConstants; +import org.jalgo.module.am1simulator.parser.am1.GeneratedAM1Parser.Terminals; + +/** + * This class is a scanner generated by JFlex + * 1.4.3 on 26.08.10 23:29 from the specification file + * ../src/parser/parsersrc/am1-lexer.l + */ +class AM1Scanner extends Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l at the + * beginning of a line l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { 0, 0 }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = "\11\0\1\5\1\1\1\0\1\5\1\2\22\0\1\5\7\0\1\11" + + "\1\12\2\0\1\10\1\7\2\0\1\3\11\4\1\0\1\6\5\0" + + "\1\21\1\27\1\43\1\22\1\33\1\0\1\37\1\45\1\30\1\41" + + "\1\0\1\25\1\23\1\35\1\32\1\42\1\34\1\40\1\26\1\36" + + "\1\24\1\31\1\44\11\0\1\16\1\20\4\0\1\17\3\0\1\15" + + "\1\13\2\0\1\14\uff90\0"; + + /** + * Translates characters to character classes + */ + private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int[] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\2\2\2\3\1\4\1\5\1\6\1\7" + + "\1\10\1\11\20\1\10\0\1\12\1\13\3\0\1\14" + + "\1\15\1\16\1\17\7\0\1\20\1\21\1\22\1\23" + + "\1\24\1\0\1\25\3\0\1\26\1\27\1\30\5\0" + + "\1\31\1\0\1\32\1\33\1\34\1\35\1\0\1\36" + + "\1\0\1\37\1\40\1\41\1\42\1\43\1\44\1\45" + "\1\46"; + + private static int[] zzUnpackAction() { + int[] result = new int[87]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int[] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /** + * Translates a state to a row index in the transition table + */ + private static final int[] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\46\0\46\0\114\0\46\0\162\0\230\0\46" + + "\0\46\0\46\0\46\0\46\0\276\0\344\0\u010a\0\u0130" + + "\0\u0156\0\u017c\0\u01a2\0\u01c8\0\u01ee\0\u0214\0\u023a\0\u0260" + + "\0\u0286\0\u02ac\0\u02d2\0\u02f8\0\u031e\0\u0344\0\u036a\0\u0390" + + "\0\u03b6\0\u03dc\0\u0402\0\u0428\0\46\0\46\0\u044e\0\u0474" + + "\0\u049a\0\46\0\46\0\46\0\46\0\u04c0\0\u04e6\0\u050c" + + "\0\u0532\0\u0558\0\u057e\0\u05a4\0\46\0\46\0\46\0\46" + + "\0\46\0\u05ca\0\46\0\u05f0\0\u0616\0\u063c\0\46\0\46" + + "\0\46\0\u0662\0\u0688\0\u06ae\0\u06d4\0\u06fa\0\u0720\0\u0746" + + "\0\46\0\u076c\0\46\0\46\0\u0792\0\46\0\u07b8\0\46" + + "\0\46\0\u07de\0\46\0\u0804\0\46\0\46\0\46"; + + private static int[] zzUnpackRowMap() { + int[] result = new int[87]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int[] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int[] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11" + + "\1\12\1\13\1\14\1\15\3\2\1\16\1\2\1\17" + + "\1\20\1\21\1\2\1\22\1\23\1\2\1\24\2\2" + + "\1\25\1\2\1\26\1\2\1\27\1\30\1\31\1\32" + + "\1\33\1\34\1\2\47\0\1\3\47\0\2\6\46\0" + + "\1\7\54\0\1\35\44\0\1\36\54\0\1\37\53\0" + + "\1\40\41\0\1\41\5\0\1\42\43\0\1\43\1\0" + + "\1\44\1\45\2\0\1\46\33\0\1\47\11\0\1\50" + + "\44\0\1\51\44\0\1\52\44\0\1\53\45\0\1\54" + + "\2\0\1\55\42\0\1\56\35\0\1\57\46\0\1\60" + + "\42\0\1\61\64\0\1\62\22\0\1\63\44\0\1\64" + + "\53\0\1\65\54\0\1\66\41\0\1\67\42\0\1\70" + + "\61\0\1\71\30\0\1\72\53\0\1\73\50\0\1\74" + + "\43\0\1\75\36\0\1\76\14\0\1\77\51\0\1\100" + + "\1\101\30\0\1\102\44\0\1\103\50\0\1\104\33\0" + + "\1\105\47\0\1\106\47\0\1\107\63\0\1\110\43\0" + + "\1\111\31\0\1\112\70\0\1\113\25\0\1\114\56\0" + + "\1\115\22\0\1\116\50\0\1\117\50\0\1\120\6\0" + + "\1\121\50\0\1\122\42\0\1\123\50\0\1\124\25\0" + + "\1\125\62\0\1\126\45\0\1\127\15\0"; + + private static int[] zzUnpackTrans() { + int[] result = new int[2090]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int[] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", "Error: could not match input", + "Error: pushback value was too large" }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\2\11\1\1\1\11\2\1\5\11\20\1\10\0" + + "\2\11\3\0\4\11\7\0\5\11\1\0\1\11\3\0" + + "\3\11\5\0\1\1\1\0\1\11\1\1\2\11\1\0" + + "\1\11\1\0\2\11\1\1\1\11\1\1\3\11"; + + private static int[] zzUnpackAttribute() { + int[] result = new int[87]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int[] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do + result[j++] = value; + while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** + * this buffer contains the current text to be matched and is the source of + * the yytext() string + */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** + * endRead marks the last character in the buffer, that has been read from + * input + */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + @SuppressWarnings("unused") + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + @SuppressWarnings("unused") + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + @SuppressWarnings("unused") + private boolean zzEOFDone; + + /* user code: */ + private Symbol symbol(short id, Object value) { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } + + /** + * Creates a new scanner There is also a java.io.InputStream version of this + * constructor. + * + * @param in + * the java.io.Reader to read input from. + */ + AM1Scanner(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. There is also java.io.Reader version of this + * constructor. + * + * @param in + * the java.io.Inputstream to read input from. + */ + AM1Scanner(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed + * the packed character translation table + * @return the unpacked character translation table + */ + private static char[] zzUnpackCMap(String packed) { + char[] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 108) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do + map[j++] = value; + while (--count > 0); + } + return map; + } + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException + * if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead + - zzStartRead); + + /* translate stored positions */ + zzEndRead -= zzStartRead; + zzCurrentPos -= zzStartRead; + zzMarkedPos -= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos * 2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length + - zzEndRead); + + if (numRead > 0) { + zzEndRead += numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of + // stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + /** + * Resets the scanner to read from a new input stream. Does not close the + * old reader. + * + * All internal variables are reset, the old input stream cannot be + * reused (internal buffer is discarded and lost). Lexical state is set to + * ZZ_INITIAL. + * + * @param reader + * the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + /** + * Enters a new lexical state + * + * @param newState + * the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); + } + + /** + * Returns the character at position pos from the matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos + * the position of the character to fetch. A value from 0 to + * yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead + pos]; + } + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos - zzStartRead; + } + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of yypushback(int) and + * a match-all fallback rule) this method will only be called with things + * that "Can't Possibly Happen". If this method is called, something is + * seriously wrong (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done in error + * fallback rules. + * + * @param errorCode + * the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number + * the number of characters to be read again. This number must + * not be greater than yylength()! + */ + public void yypushback(int number) { + if (number > yylength()) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + /** + * Resumes scanning until the next regular expression is matched, the end of + * input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException + * if any I/O-Error occurs + */ + public Symbol nextToken() throws java.io.IOException, Scanner.Exception { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char[] zzBufferL = zzBuffer; + char[] zzCMapL = ZZ_CMAP; + + int[] zzTransL = ZZ_TRANS; + int[] zzRowMapL = ZZ_ROWMAP; + int[] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one + // line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) + yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]]; + if (zzNext == -1) + break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ((zzAttributes & 1) == 1) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ((zzAttributes & 8) == 8) + break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 4: { /* ignore */ + } + case 39: + break; + case 33: { + return symbol(Terminals.STORE, "STORE"); + } + case 40: + break; + case 20: { + return symbol(Terminals.LIT, "LIT"); + } + case 41: + break; + case 3: { + return symbol(Terminals.NUMBER, yytext()); + } + case 42: + break; + case 24: { + return symbol(Terminals.JMC, "JMC"); + } + case 43: + break; + case 32: { + return symbol(Terminals.LOADI, "LOADI"); + } + case 44: + break; + case 18: { + return symbol(Terminals.MUL, "MUL"); + } + case 45: + break; + case 23: { + return symbol(Terminals.JMP, "JMP"); + } + case 46: + break; + case 34: { + return symbol(Terminals.READI, "READI"); + } + case 47: + break; + case 13: { + return symbol(Terminals.NE, "NE"); + } + case 48: + break; + case 19: { + return symbol(Terminals.MOD, "MOD"); + } + case 49: + break; + case 15: { + return symbol(Terminals.GT, "GT"); + } + case 50: + break; + case 25: { + return symbol(Terminals.LOAD, "LOAD"); + } + case 51: + break; + case 21: { + return symbol(Terminals.SUB, "SUB"); + } + case 52: + break; + case 10: { + return symbol(Terminals.LE, "LE"); + } + case 53: + break; + case 29: { + return symbol(Terminals.CALL, "CALL"); + } + case 54: + break; + case 35: { + return symbol(Terminals.WRITE, "WRITE"); + } + case 55: + break; + case 2: { + return symbol(Terminals.EOL, ParserConstants.EOL); + } + case 56: + break; + case 27: { + return symbol(Terminals.READ, "READ"); + } + case 57: + break; + case 9: { + return symbol(Terminals.RBRAKET, ")"); + } + case 58: + break; + case 26: { + return symbol(Terminals.INIT, "INIT"); + } + case 59: + break; + case 31: { + return symbol(Terminals.LOADA, "LOADA"); + } + case 60: + break; + case 7: { + return symbol(Terminals.COMMA, ","); + } + case 61: + break; + case 28: { + return symbol(Terminals.PUSH, "PUSH"); + } + case 62: + break; + case 37: { + return symbol(Terminals.STOREI, "STOREI"); + } + case 63: + break; + case 14: { + return symbol(Terminals.GE, "GE"); + } + case 64: + break; + case 8: { + return symbol(Terminals.LBRAKET, "("); + } + case 65: + break; + case 22: { + return symbol(Terminals.RET, "RET"); + } + case 66: + break; + case 16: { + return symbol(Terminals.ADD, "ADD"); + } + case 67: + break; + case 30: { + return symbol(Terminals.LOCAL, "lokal"); + } + case 68: + break; + case 6: { + return symbol(Terminals.MINUS, "-"); + } + case 69: + break; + case 12: { + return symbol(Terminals.EQ, "EQ"); + } + case 70: + break; + case 38: { + return symbol(Terminals.WRITEI, "WRITEI"); + } + case 71: + break; + case 17: { + return symbol(Terminals.DIV, "DIV"); + } + case 72: + break; + case 11: { + return symbol(Terminals.LT, "LT"); + } + case 73: + break; + case 5: { + return symbol(Terminals.SEMICOLON, ";"); + } + case 74: + break; + case 36: { + return symbol(Terminals.GLOBAL, "global"); + } + case 75: + break; + case 1: { + throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); + } + case 76: + break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + { + return symbol(Terminals.EOF, ParserConstants.EOF); + } + } else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + +} diff --git a/src/org/jalgo/module/am1simulator/parser/am1/CVS/Entries b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Entries new file mode 100644 index 0000000..d687bc0 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Entries @@ -0,0 +1,4 @@ +/AM1Parser.java/1.1/Mon Mar 7 19:57:18 2011// +/AM1Scanner.java/1.1/Mon Mar 7 19:57:18 2011// +/GeneratedAM1Parser.java/1.1/Mon Mar 7 19:57:18 2011// +/package-info.java/1.1/Mon Mar 7 19:57:18 2011// diff --git a/src/org/jalgo/module/am1simulator/parser/am1/CVS/Repository b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Repository new file mode 100644 index 0000000..7db5974 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/parser/am1 diff --git a/src/org/jalgo/module/am1simulator/parser/am1/CVS/Root b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.java b/src/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.java new file mode 100644 index 0000000..e9a8098 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/GeneratedAM1Parser.java @@ -0,0 +1,412 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ + +package org.jalgo.module.am1simulator.parser.am1; + +import org.jalgo.module.am1simulator.parser.ParserUtils; +import org.jalgo.module.am1simulator.parser.ErrorEvents; +import org.jalgo.module.am1simulator.model.am1.*; +import org.jalgo.module.am1simulator.model.AddressException; +import org.jalgo.module.am1simulator.model.LineAddress; +import beaver.*; +import org.jalgo.module.am1simulator.model.am1.AbstractStatementFactory.Statement; + +/** + * This class is a LALR parser generated by Beaver v0.9.6.1 from the grammar + * specification "am1-parser.g". + */ +public class GeneratedAM1Parser extends Parser { + static public class Terminals { + static public final short EOF = 0; + static public final short SEMICOLON = 1; + static public final short NUMBER = 2; + static public final short MINUS = 3; + static public final short LBRAKET = 4; + static public final short RBRAKET = 5; + static public final short COMMA = 6; + static public final short LOCAL = 7; + static public final short GLOBAL = 8; + static public final short LOAD = 9; + static public final short LOADA = 10; + static public final short STORE = 11; + static public final short WRITE = 12; + static public final short READ = 13; + static public final short LOADI = 14; + static public final short STOREI = 15; + static public final short WRITEI = 16; + static public final short READI = 17; + static public final short ADD = 18; + static public final short MUL = 19; + static public final short SUB = 20; + static public final short DIV = 21; + static public final short MOD = 22; + static public final short EQ = 23; + static public final short NE = 24; + static public final short LT = 25; + static public final short GT = 26; + static public final short LE = 27; + static public final short GE = 28; + static public final short JMP = 29; + static public final short JMC = 30; + static public final short PUSH = 31; + static public final short CALL = 32; + static public final short INIT = 33; + static public final short RET = 34; + static public final short LIT = 35; + static public final short EOL = 36; + } + + static final ParsingTables PARSING_TABLES = new ParsingTables( + "U9ojrETF544O1l1dpxkpeuA89o3YUGKGss4vK50FHL6mOGAVnCGFVh1tOiDEWht7NZweqMZ" + + "K#D$OU##A$VNPlJcoZdSc4EVocsVctTdDxcnk0Tn03sGZ3qDHWW06emZZu4PRj4DxT417T4" + + "9d9A4Bkg8RkcCYoZ4PbPZQohEcmo4tHP25FaX19ZBGoqfpdW6VgkNOZWzK6RBLmbOwqORZK" + + "RPwH6MPocbmoG$vBj$agtoH9laid#IZV93tI4QAl4Cg#xVeYJJc6$I61#dm8b$koXtqHJ$u" + + "vJM2yWgvw8$XyX93C023v0KAC0mZv3aACLAUOGoAKOhHyXJZCHOJv8aynYHUyH4gs3$45FO" + + "Fv3vcnDaRtWVt9vMxcSRxy70tqddVcRmNywcoUHVULfuLv2xc0jOxSN2dVF1RQSvZOpFru$" + + "5gGUv5ehMnD1ByV5mHwmDyPz6P6oxE0amtQ#RCO1fC9wj6SyrbZQ9fdkzIezZnFwyVxSqVK" + + "5NFJaIQ665AflbcZMq1BQH5j9YMq59QHijf1QsaLLH7gzLvQsWThQKGhQT2sa0RrPfwbPje" + + "CssZ8jfAnTH0EwYHIcaxxQAT5A7TL4vxQH$jeKhQJuVe85NG0VCPwJ0TfIDKJSVe19sa6Zf" + + "5jNISpj9fcaDdw1oTfmjqaIxHPRf2LsakNQFhvZEfvqfIMH2hjGJRJDkusZQkKUdHri#ASu" + + "rQbLbQtQlDPwlCqUhvsdoUof1M3slpEfKbMZsYpRUeR53PgB9CMrU5vYO$aR39lRygj#bMu" + + "ZF#RvDVxBpycXZyfZZ8oI#2qG8EnQqu$v7szL4#wvyVvRSuaFSR#VQ$gm=="); + + private ArithmeticStatementFactory arithmetic = new ArithmeticStatementFactory(); + private CompareStatementFactory compare = new CompareStatementFactory(); + private IOStatementFactory io = new IOStatementFactory(); + private JumpStatementFactory jump = new JumpStatementFactory(); + private MemoryStatementFactory memory = new MemoryStatementFactory(); + private ProceduralStatementFactory procedural = new ProceduralStatementFactory(); + + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + + private final Action[] actions; + + public GeneratedAM1Parser() { + super(PARSING_TABLES); + actions = new Action[] { Action.RETURN, // [0] Program = CommandList + new Action() { // [1] CommandList = Command.a SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final SimulationStatement a = (SimulationStatement) _symbol_a.value; + AM1Program program = new AM1Program(); + program.add(a); + return new Symbol(program); + } + }, new Action() { // [2] CommandList = CommandList.a EOL + // Command.b SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final AM1Program a = (AM1Program) _symbol_a.value; + final Symbol _symbol_b = _symbols[offset + 3]; + final SimulationStatement b = (SimulationStatement) _symbol_b.value; + a.add(b); + return new Symbol(a); + } + }, new Action() { // [3] Command = ADD.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(arithmetic.newStatement( + Statement.ADD, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [4] Command = MUL.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(arithmetic.newStatement( + Statement.MUL, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [5] Command = SUB.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(arithmetic.newStatement( + Statement.SUB, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [6] Command = DIV.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(arithmetic.newStatement( + Statement.DIV, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [7] Command = MOD.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(arithmetic.newStatement( + Statement.MOD, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [8] Command = EQ.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement(Statement.EQUAL, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [9] Command = NE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement( + Statement.NOTEQUAL, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [10] Command = LT.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement( + Statement.LESSERTHEN, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [11] Command = GT.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement( + Statement.GREATERTHEN, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [12] Command = LE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement( + Statement.LESSEREQUAL, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [13] Command = GE.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(compare.newStatement( + Statement.GREATEREQUAL, + new StatementResource.Builder(address(a)) + .build())); + } + }, new Action() { // [14] Command = JMP.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(jump.newStatement(Statement.JMP, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [15] Command = JMC.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(jump.newStatement(Statement.JMC, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [16] Command = LOAD.a LBRAKET Location.b + // COMMA Number.c RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final String b = (String) _symbol_b.value; + final Symbol _symbol_c = _symbols[offset + 5]; + final Integer c = (Integer) _symbol_c.value; + return new Symbol(memory.newStatement(Statement.LOAD, + new StatementResource.Builder(address(a)) + .location(b).value(c).build())); + } + }, new Action() { // [17] Command = LOADA.a LBRAKET Location.b + // COMMA Number.c RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final String b = (String) _symbol_b.value; + final Symbol _symbol_c = _symbols[offset + 5]; + final Integer c = (Integer) _symbol_c.value; + return new Symbol(memory.newStatement(Statement.LOADA, + new StatementResource.Builder(address(a)) + .location(b).value(c).build())); + } + }, new Action() { // [18] Command = LOADI.a LBRAKET Number.b + // RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(memory.newStatement(Statement.LOADI, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [19] Command = STORE.a LBRAKET Location.b + // COMMA Number.c RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final String b = (String) _symbol_b.value; + final Symbol _symbol_c = _symbols[offset + 5]; + final Integer c = (Integer) _symbol_c.value; + return new Symbol(memory.newStatement(Statement.STORE, + new StatementResource.Builder(address(a)) + .location(b).value(c).build())); + } + }, new Action() { // [20] Command = STOREI.a LBRAKET Number.b + // RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(memory.newStatement(Statement.STOREI, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [21] Command = WRITE.a LBRAKET Location.b + // COMMA Number.c RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final String b = (String) _symbol_b.value; + final Symbol _symbol_c = _symbols[offset + 5]; + final Integer c = (Integer) _symbol_c.value; + return new Symbol(io.newStatement(Statement.WRITE, + new StatementResource.Builder(address(a)) + .location(b).value(c).build())); + } + }, new Action() { // [22] Command = WRITEI.a LBRAKET Number.b + // RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(io.newStatement(Statement.WRITEI, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [23] Command = READ.a LBRAKET Location.b + // COMMA Number.c RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final String b = (String) _symbol_b.value; + final Symbol _symbol_c = _symbols[offset + 5]; + final Integer c = (Integer) _symbol_c.value; + return new Symbol(io.newStatement(Statement.READ, + new StatementResource.Builder(address(a)) + .location(b).value(c).build())); + } + }, new Action() { // [24] Command = READI.a LBRAKET Number.b + // RBRAKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 3]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(io.newStatement(Statement.READI, + new StatementResource.Builder(address(a)) + .value(b).build())); + } + }, new Action() { // [25] Command = PUSH.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(procedural.newStatement( + Statement.PUSH, new StatementResource.Builder( + address(a)).build())); + } + }, new Action() { // [26] Command = CALL.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(procedural.newStatement( + Statement.CALL, new StatementResource.Builder( + address(a)).value(b).build())); + } + }, new Action() { // [27] Command = INIT.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(procedural.newStatement( + Statement.INIT, new StatementResource.Builder( + address(a)).value(b).build())); + } + }, new Action() { // [28] Command = RET.a UnsignedNumber.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(procedural.newStatement( + Statement.RET, new StatementResource.Builder( + address(a)).value(b).build())); + } + }, new Action() { // [29] Command = LIT.a Number.b + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + final Symbol _symbol_b = _symbols[offset + 2]; + final Integer b = (Integer) _symbol_b.value; + return new Symbol(procedural.newStatement( + Statement.LIT, new StatementResource.Builder( + address(a)).value(b).build())); + } + }, new Action() { // [30] UnsignedNumber = NUMBER.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol a = _symbols[offset + 1]; + return new Symbol(ParserUtils.safeSymbolToInt(a, + (ErrorEvents) report)); + } + }, new Action() { // [31] Location = LOCAL + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol("lokal"); + } + }, new Action() { // [32] Location = GLOBAL + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol("global"); + } + }, new Action() { // [33] Number = UnsignedNumber.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 1]; + final Integer a = (Integer) _symbol_a.value; + return new Symbol(a); + } + }, new Action() { // [34] Number = MINUS UnsignedNumber.a + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_a = _symbols[offset + 2]; + final Integer a = (Integer) _symbol_a.value; + return new Symbol(-a); + } + } }; + + this.report = ErrorEvents.forAm1(); + } + + protected Symbol invokeReduceAction(int rule_num, int offset) { + return actions[rule_num].reduce(_symbols, offset); + } +} diff --git a/src/org/jalgo/module/am1simulator/parser/am1/package-info.java b/src/org/jalgo/module/am1simulator/parser/am1/package-info.java new file mode 100644 index 0000000..f812940 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/am1/package-info.java @@ -0,0 +1,25 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Lexer, parser and related classes for analyzing AM1 source code. + */ +package org.jalgo.module.am1simulator.parser.am1; + diff --git a/src/org/jalgo/module/am1simulator/parser/package-info.java b/src/org/jalgo/module/am1simulator/parser/package-info.java new file mode 100644 index 0000000..28e1f39 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/package-info.java @@ -0,0 +1,24 @@ +/** +* AM1 Simulator - simulating am1 code in an abstract machine based on the +* definitions of the lectures 'Programmierung' at TU Dresden. +* Copyright (C) 2010 Max Leuthäuser +* Contact: s7060241@mail.zih.tu-dresden.de +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +*/ + +/** + * Lexer and parser for AM1. + */ +package org.jalgo.module.am1simulator.parser; diff --git a/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Entries b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Entries new file mode 100644 index 0000000..8ba9d2c --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Entries @@ -0,0 +1,2 @@ +/am1-lexer.l/1.1/Mon Mar 7 19:57:18 2011/-kb/ +/am1-parser.g/1.1/Mon Mar 7 19:57:18 2011/-kb/ diff --git a/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Repository b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Repository new file mode 100644 index 0000000..bc570ea --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/parser/parsersrc diff --git a/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Root b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/parsersrc/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l b/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l new file mode 100644 index 0000000..fbcc888 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-lexer.l @@ -0,0 +1,76 @@ +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +/* Author: Max Leuthäuser */ + +package parser.am1; + +import beaver.Symbol; +import beaver.Scanner; +import parser.ParserConstants; +import parser.am1.GeneratedAM1Parser.Terminals; + +%% + +%class AM1Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Number = 0 | [1-9][0-9]* +Whitespace = [\t\f ] + +%% + +{Whitespace}+ { /* ignore */ } +{LineTerminator} { return symbol(Terminals.EOL, ParserConstants.EOL); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"," { return symbol(Terminals.COMMA, ","); } +"(" { return symbol(Terminals.LBRAKET, "("); } +")" { return symbol(Terminals.RBRAKET, ")"); } +"lokal" { return symbol(Terminals.LOCAL, "lokal"); } +"global" { return symbol(Terminals.GLOBAL, "global"); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +"ADD" { return symbol(Terminals.ADD, "ADD"); } +"MUL" { return symbol(Terminals.MUL, "MUL"); } +"SUB" { return symbol(Terminals.SUB, "SUB"); } +"DIV" { return symbol(Terminals.DIV, "DIV"); } +"MOD" { return symbol(Terminals.MOD, "MOD"); } +"EQ" { return symbol(Terminals.EQ, "EQ"); } +"NE" { return symbol(Terminals.NE, "NE"); } +"LT" { return symbol(Terminals.LT, "LT"); } +"GT" { return symbol(Terminals.GT, "GT"); } +"LE" { return symbol(Terminals.LE, "LE"); } +"GE" { return symbol(Terminals.GE, "GE"); } +"LOAD" { return symbol(Terminals.LOAD, "LOAD"); } +"LOADA" { return symbol(Terminals.LOADA, "LOADA"); } +"LOADI" { return symbol(Terminals.LOADI, "LOADI"); } +"STORE" { return symbol(Terminals.STORE, "STORE"); } +"STOREI" { return symbol(Terminals.STOREI, "STOREI"); } +"LIT" { return symbol(Terminals.LIT, "LIT"); } +"JMP" { return symbol(Terminals.JMP, "JMP"); } +"JMC" { return symbol(Terminals.JMC, "JMC"); } +"WRITE" { return symbol(Terminals.WRITE, "WRITE"); } +"WRITEI" { return symbol(Terminals.WRITEI, "WRITEI"); } +"READ" { return symbol(Terminals.READ, "READ"); } +"READI" { return symbol(Terminals.READI, "READI"); } +"PUSH" { return symbol(Terminals.PUSH, "PUSH"); } +"CALL" { return symbol(Terminals.CALL, "CALL"); } +"INIT" { return symbol(Terminals.INIT, "INIT"); } +"RET" { return symbol(Terminals.RET, "RET"); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } + diff --git a/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g b/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g new file mode 100644 index 0000000..b461615 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/parser/parsersrc/am1-parser.g @@ -0,0 +1,145 @@ +// Author: Max Leuthäuser +%header {: +/* WARNING: This is generated code. DO *NOT* MODIFY IT! */ +:}; +%package "parser.am1"; +%import "parser.ErrorEvents"; +%import "parser.ParserUtils"; +%import "model.LineAddress"; +%import "model.AddressException"; +%import "model.am1.*"; +%import "model.am1.AbstractStatementFactory.Statement"; + +%class "GeneratedAM1Parser"; + +%embed {: + private ArithmeticStatementFactory arithmetic = new ArithmeticStatementFactory(); + private CompareStatementFactory compare = new CompareStatementFactory(); + private IOStatementFactory io = new IOStatementFactory(); + private JumpStatementFactory jump = new JumpStatementFactory(); + private MemoryStatementFactory memory = new MemoryStatementFactory(); + private ProceduralStatementFactory procedural = new ProceduralStatementFactory(); + + private LineAddress address(Symbol symbol) { + try { + return new LineAddress(Symbol.getLine(symbol.getStart())); + } catch (AddressException e) { + return null; + } + } + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } +:}; + +%init {: + this.report = ErrorEvents.forAm1(); +:}; + +%terminals ADD, MUL, SUB, DIV, MOD; +%terminals EQ, NE, LT, GT, LE, GE; +%terminals LOAD, STORE, LIT; +%terminals LOADA, LOADI, STOREI; +%terminals JMP, JMC; +%terminals WRITE, READ; +%terminals WRITEI, READI; +%terminals PUSH, CALL, INIT, RET; +%terminals EOL, SEMICOLON, COMMA; +%terminals NUMBER, MINUS, LBRAKET, RBRAKET; +%terminals GLOBAL, LOCAL; + +%goal Program; + +%typeof CommandList, Program = "AM1Program"; +%typeof Command = "SimulationStatement"; +%typeof UnsignedNumber, Number = "Integer"; +%typeof Location = "String"; + +Program + = CommandList + ; + +CommandList + = Command.a SEMICOLON + {: AM1Program program = new AM1Program(); program.add(a); return new Symbol(program); :} + | CommandList.a EOL Command.b SEMICOLON + {: a.add(b); return new Symbol(a); :} + ; + +Command + = ADD.a + {: return new Symbol(arithmetic.newStatement(Statement.ADD, new StatementResource.Builder(address(a)).build())); :} + | MUL.a + {: return new Symbol(arithmetic.newStatement(Statement.MUL, new StatementResource.Builder(address(a)).build())); :} + | SUB.a + {: return new Symbol(arithmetic.newStatement(Statement.SUB, new StatementResource.Builder(address(a)).build())); :} + | DIV.a + {: return new Symbol(arithmetic.newStatement(Statement.DIV, new StatementResource.Builder(address(a)).build())); :} + | MOD.a + {: return new Symbol(arithmetic.newStatement(Statement.MOD, new StatementResource.Builder(address(a)).build())); :} + | EQ.a + {: return new Symbol(compare.newStatement(Statement.EQUAL, new StatementResource.Builder(address(a)).build())); :} + | NE.a + {: return new Symbol(compare.newStatement(Statement.NOTEQUAL, new StatementResource.Builder(address(a)).build())); :} + | LT.a + {: return new Symbol(compare.newStatement(Statement.LESSERTHEN, new StatementResource.Builder(address(a)).build())); :} + | GT.a + {: return new Symbol(compare.newStatement(Statement.GREATERTHEN, new StatementResource.Builder(address(a)).build())); :} + | LE.a + {: return new Symbol(compare.newStatement(Statement.LESSEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | GE.a + {: return new Symbol(compare.newStatement(Statement.GREATEREQUAL, new StatementResource.Builder(address(a)).build())); :} + | JMP.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMP, new StatementResource.Builder(address(a)).value(b).build())); :} + | JMC.a UnsignedNumber.b + {: return new Symbol(jump.newStatement(Statement.JMC, new StatementResource.Builder(address(a)).value(b).build())); :} + | LOAD.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOAD, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADA.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADA, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | LOADI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.LOADI, new StatementResource.Builder(address(a)).value(b).build())); :} + | STORE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(memory.newStatement(Statement.STORE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | STOREI.a LBRAKET Number.b RBRAKET + {: return new Symbol(memory.newStatement(Statement.STOREI, new StatementResource.Builder(address(a)).value(b).build())); :} + | WRITE.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITE, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | WRITEI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.WRITEI, new StatementResource.Builder(address(a)).value(b).build())); :} + | READ.a LBRAKET Location.b COMMA Number.c RBRAKET + {: return new Symbol(io.newStatement(Statement.READ, new StatementResource.Builder(address(a)).location(b).value(c).build())); :} + | READI.a LBRAKET Number.b RBRAKET + {: return new Symbol(io.newStatement(Statement.READI, new StatementResource.Builder(address(a)).value(b).build())); :} + | PUSH.a + {: return new Symbol(procedural.newStatement(Statement.PUSH, new StatementResource.Builder(address(a)).build())); :} + | CALL.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.CALL, new StatementResource.Builder(address(a)).value(b).build())); :} + | INIT.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.INIT, new StatementResource.Builder(address(a)).value(b).build())); :} + | RET.a UnsignedNumber.b + {: return new Symbol(procedural.newStatement(Statement.RET, new StatementResource.Builder(address(a)).value(b).build())); :} + | LIT.a Number.b + {: return new Symbol(procedural.newStatement(Statement.LIT, new StatementResource.Builder(address(a)).value(b).build())); :} + ; + +UnsignedNumber + = NUMBER.a + {: return new Symbol(ParserUtils.safeSymbolToInt(a, (ErrorEvents) report)); :} + ; + +Location + = LOCAL + {: return new Symbol("lokal"); :} + | GLOBAL + {: return new Symbol("global"); :} + ; + +Number + = UnsignedNumber.a + {: return new Symbol(a); :} + | MINUS UnsignedNumber.a + {: return new Symbol(-a); :} + ; + diff --git a/src/org/jalgo/module/am1simulator/presenter/CVS/Entries b/src/org/jalgo/module/am1simulator/presenter/CVS/Entries new file mode 100644 index 0000000..f82eea8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/CVS/Entries @@ -0,0 +1,5 @@ +/Simulator.java/1.1/Mon Mar 7 19:57:18 2011// +/UpdateEvent.java/1.1/Mon Mar 7 19:57:18 2011// +/UpdateEventCreater.java/1.1/Mon Mar 7 19:57:18 2011// +/UpdateListener.java/1.1/Mon Mar 7 19:57:18 2011// +/package-info.java/1.1/Mon Mar 7 19:57:18 2011// diff --git a/src/org/jalgo/module/am1simulator/presenter/CVS/Repository b/src/org/jalgo/module/am1simulator/presenter/CVS/Repository new file mode 100644 index 0000000..01420c7 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/presenter diff --git a/src/org/jalgo/module/am1simulator/presenter/CVS/Root b/src/org/jalgo/module/am1simulator/presenter/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/presenter/Simulator.java b/src/org/jalgo/module/am1simulator/presenter/Simulator.java new file mode 100644 index 0000000..6c2c445 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/Simulator.java @@ -0,0 +1,732 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.presenter; + +import org.jalgo.module.am1simulator.view.components.PresentationAction; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; + +import org.jalgo.module.am1simulator.parser.am1.AM1Parser; +import org.jalgo.module.am1simulator.view.GUIBuilder; +import org.jalgo.module.am1simulator.view.GuiUtilities; +import org.jalgo.module.am1simulator.view.ViewContainer; +import org.jalgo.module.am1simulator.view.components.AM1InputDialog; +import org.jalgo.module.am1simulator.view.components.TablePanel; +import org.jalgo.module.am1simulator.view.components.Toolbar.ButtonType; +import org.jalgo.module.am1simulator.model.AM1History; +import org.jalgo.module.am1simulator.model.SimulationSet; +import org.jalgo.module.am1simulator.model.am1.*; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; + +/** + * Presenter (MVP-Pattern) to handle the AM1 simulation. + * + * @author Max Leuthäuser + */ +public class Simulator implements UpdateEventCreater { + /** + * The view in the MVP-Pattern which actually a {@link ViewContainer}. + */ + private ViewContainer view; + + /** + * This history ({@link AM1History}) is used to store already calculated + * steps of the simulation.s + */ + private AM1History history; + private int currentStep; + private AM1Program am1Program; + private MachineConfiguration currentMc; + /** + * Flag to allow or disallow scrolling, printing descriptions and + * highlighting. This flag is set to false during a simulation in one single + * step to avoid performance issues. + */ + private boolean drawAddon = true; + /** + * Flag which is used to handle jump command failures. + */ + private boolean jumpFails = false; + + /** + * Value of steps the user wants to simulate in one single step before he + * gets ask to continue. (avoids endless loops) + */ + private int steps; + + /** + * The current state. Either {@link Editing} or {@link Simulating}. + */ + private State currentState = new Editing(); + + public Simulator() { + } + + /** + * @return the maximal available program counter; + */ + public int getMaxPC() { + return am1Program.size(); + } + + /** + * @return the history of the simulation. + */ + public AM1History getHistory() { + return history; + } + + /** + * @return the view ({@link ViewContainer}). + */ + public ViewContainer getView() { + return view; + } + + /** + * @param m + * {@link MachineConfiguration} which is used here. + */ + public void setCurrentMachineConfiguration(MachineConfiguration m) { + currentMc = m; + } + + /** + * Show an error message to the user because an command could not be + * executed. + * + * @param reason + */ + private void showError(String reason) { + JOptionPane.showMessageDialog( + null, + "There was an error while simulating.\n" + + "The following command could not be executed:\n" + + am1Program.get( + currentMc.getProgramCounter().get() - 1) + .getCodeText() + "\n\n" + "Reason:\n" + reason); + } + + /** + * @param program + * The {@link AM1Program} which should be used during the + * simulation. + * + * @throws IllegalArgumentException + */ + public void setAM1Program(AM1Program program) + throws IllegalArgumentException { + if (program != null) { + am1Program = program; + } else + throw new IllegalArgumentException( + "Null argument is not allowed for AM1Program."); + } + + /** + * Show the description for the corresponding statement. + * + * @param i + * Position of the statement in the {@link AM1Program}. + */ + private void showDescription(int i) { + if (drawAddon) { + if (am1Program.size() < 1) { + return; + } + + if (i <= 0) { + i = 1; + } + + if (i > am1Program.size()) { + i = am1Program.size(); + } + view.getConsolePanel() + .getDescriptionEditor() + .setText( + am1Program.get(i - 1).getCodeText() + "

      " + + am1Program.get(i - 1).getDescription() + + "

      "); + } + } + + /** + * Show the currently visible page range. + */ + private void showRange() { + int t = 0; + if (view.getTablePanel().getTableModel().getPageOffset() == 0) { + t = 1; + } else { + t = view.getTablePanel().getTableModel().getPageSize() + * view.getTablePanel().getTableModel().getPageOffset(); + } + + view.getTablePanel() + .setRange( + "  Showing steps from " + + t + + " to " + + (view.getTablePanel().getTableModel() + .getPageSize() * (view.getTablePanel() + .getTableModel().getPageOffset() + 1)) + + ""); + } + + /** + * @param m + * The {@link MachineConfiguration} to draw in the + * {@link TablePanel}. + */ + public void addResultToTable(MachineConfiguration m, int position) { + view.getTablePanel().getTableModel().addRow(m); + if (drawAddon) { + showRange(); + if (position >= 1) { + view.getTablePanel().setStep( + "Latest step: " + (position + 1) + " "); + showRange(); + fireUpdateEvent(new UpdateEvent(currentMc + .getProgramCounter().get())); + } + if (currentMc.getProgramCounter().get() <= getMaxPC() + && currentMc.getProgramCounter().get() >= 1) { + showDescription(currentMc.getProgramCounter().get()); + } + } + + } + + /** + * Removes the last line in the table. + */ + public void removeLastTableEntry(int position) { + view.getTablePanel().getTableModel().removeLastRow(); + if (drawAddon) { + showRange(); + view.getTablePanel().setStep( + "Latest step: " + (position + 1) + " "); + fireUpdateEvent(new UpdateEvent(currentMc + .getProgramCounter().get())); + showDescription(currentMc.getProgramCounter().get()); + } + + } + + /** + * Do the next step and draw the result. We only calculate something new + * if the step is not already in the {@link AM1History}. + * + * @return true if the next step could executed correctly, false otherwise. + */ + public boolean nextStep() { + if (currentMc.getProgramCounter().get() > getMaxPC() + || currentMc.getProgramCounter().get() < 1) { + jumpFails = true; + return false; + } + currentStep++; + if (!history.stepExists(currentStep)) { + jumpFails = false; + try { + currentMc = am1Program.get( + currentMc.getProgramCounter().get() - 1).apply( + new MachineConfiguration(currentMc)); + history.add(currentMc); + } catch (IllegalArgumentException e) { + // If an am1 statement fail we show this: + view.getToolbar().setButtonsDisabledAfterError(); + showError(e.getMessage()); + return false; + } catch (ArithmeticException e) { + // In the special case of DIV with 0 we will crash here: + view.getToolbar().setButtonsDisabledAfterError(); + showError(e.getMessage()); + return false; + } + } else { + currentMc = history.getAtStep(currentStep); + } + addResultToTable(currentMc, currentStep); + return true; + } + + /** + * Do the previous step and draw the result. Nothing is calculated here, + * we just using the {@link AM1History}. + * + * @return true if the previous step could executed correctly, false + * otherwise. + */ + public boolean previousStep() { + if (currentStep >= 1) { + currentStep--; + currentMc = history.getAtStep(currentStep); + removeLastTableEntry(currentStep); + jumpFails = false; + return true; + } + return false; + } + + /** + * Do the full (remaining) simulation in one single step. Basically we just + * use {@link Simulator#nextStep()}. + * + * @return true if all steps could executed correctly, false otherwise. + */ + public boolean stepToEnd() { + drawAddon = false; + boolean result = true; + while (result) { + result = nextStep(); + if (currentStep % steps == 0) { + drawAddon = true; + showDescription(currentMc.getProgramCounter().get()); + view.getTablePanel().setStep( + "Latest step: " + currentStep + " "); + fireUpdateEvent(new UpdateEvent(currentMc + .getProgramCounter().get())); + drawAddon = false; + int s = JOptionPane + .showConfirmDialog( + null, + currentStep + + " steps are calculated.\n" + + "Do you want to continue?\n\n" + + "Choose 'no' to stop the simulation or 'yes' if you want to go on.", + "Simulation", JOptionPane.YES_NO_OPTION); + if (s == JOptionPane.NO_OPTION + || s == JOptionPane.CANCEL_OPTION) { + result = true; + break; + } + } + } + drawAddon = true; + view.getTablePanel() + .setStep("Latest step: " + (currentStep + 1) + " "); + fireUpdateEvent(new UpdateEvent(currentMc.getProgramCounter() + .get())); + // We want to show the description of the jump command which failed or + // or if the command failed itself so we can not use '-1' always. + showDescription(currentMc.getProgramCounter().get() + - (jumpFails || !result ? 0 : 1)); + showRange(); + return result; + } + + /** + * Clear the whole simulation. Warning: this will destroy the current + * simulation data. Use this with care! + */ + public void clear() { + view.getTablePanel().getTableModel().clear(); + history.clear(); + view.getTablePanel().setStep("Not started yet."); + view.getTablePanel().setRange(""); + view.getConsolePanel().getDescriptionEditor().setText(""); + currentStep = 0; + } + + /** + * @return true if the simulation needs an initial configuration. + */ + public boolean simulatorNeedsInitialConfig() { + return history.getCount() == 0; + } + + public AM1Program getAM1Program() { + return am1Program; + } + + public void init(final JComponent contentPane, final JMenu menu, final JToolBar toolbar) { + view = new ViewContainer.Builder(GUIBuilder.newMainPanel()) + .console(GUIBuilder.newConsolePanel()) + .editor(GUIBuilder.newEditorPanel(this)) + .file(GUIBuilder.newFileJLabel()) + .postion(GUIBuilder.newDefaultJLabel()) + .table(GUIBuilder.newTablePanel(this)) + .toolbar(GUIBuilder.newToolbar()).build(); + + view.getToolbar().addUserInputListener(new UserInputListener()); + view.getTablePanel().getTableModel() + .addUserInputListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + view.getTablePanel().getTableModel().pageUp(); + showRange(); + } + }, new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + view.getTablePanel().getTableModel().pageDown(); + showRange(); + } + }); + history = new AM1History(); + currentStep = 0; + menu.add(new PresentationAction(this)); + contentPane.add(view.getMainPanel()); + } + + /** + * Abstract state class to handle different behavior between editing and + * simulating in general. + * + * @see Simulating + * @see Editing + */ + private abstract class State { + /** + * Run the simulation which means do one step forward after parsing and + * so on. + */ + public void run() { + }; + + /** + * Scroll to the top of the machine configuration table. + */ + public void top() { + view.getTablePanel().getTableModel().showFirstPage(); + view.getTablePanel() + .getTable() + .scrollRectToVisible( + view.getTablePanel() + .getTable() + .getCellRect( + 0, + view.getTablePanel().getTable() + .getColumnCount(), true)); + }; + + /** + * Scroll to the bottom of the machine configuration table. + */ + public void bottom() { + view.getTablePanel().getTableModel().showLastPage(); + view.getTablePanel() + .getTable() + .scrollRectToVisible( + view.getTablePanel() + .getTable() + .getCellRect( + view.getTablePanel().getTable() + .getRowCount() - 1, + view.getTablePanel().getTable() + .getColumnCount(), true)); + }; + + /** + * Enter a new inital configuration. + */ + public void initial() { + SimulationSet s = AM1InputDialog.showAndWaitForReturn(); + MachineConfiguration r = s.getMachineConfiguration(); + if (r != null) { + view.getToolbar().setButtonStatus(ButtonType.INITIAL, true); + view.getEditorPanel().removeMarkers(); + Simulator.this.clear(); + view.getToolbar().setButtonStatus(ButtonType.FORWARD, true); + view.getToolbar().setButtonStatus(ButtonType.BACK, false); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, true); + view.getTablePanel().setInitialConfiguration( + "" + r.toString() + ""); + setCurrentMachineConfiguration(r); + steps = s.getSteps(); + getHistory().add(new MachineConfiguration(r)); + addResultToTable(r, 0); + } else { + view.getTablePanel().setInitialConfiguration( + "No initial configuration"); + } + }; + + /** + * Clear / delete the current simulation progress completely. + */ + public void clear() { + view.getToolbar().setButtonStatus(ButtonType.INITIAL, true); + view.getEditorPanel().removeMarkers(); + view.getTablePanel().setInitialConfiguration( + "No initial configuration."); + Simulator.this.clear(); + view.getToolbar().setButtonStatus(ButtonType.FORWARD, true); + view.getToolbar().setButtonStatus(ButtonType.BACK, false); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, true); + }; + + /** + * Do one step backward in the simulation history. + */ + public void back() { + view.getTablePanel().getTableModel().showLastPage(); + if (!previousStep()) { + view.getToolbar().setButtonStatus(ButtonType.BACK, false); + } else { + view.getToolbar().setButtonStatus(ButtonType.FORWARD, true); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, true); + } + }; + + /** + * Do one step forward in the simulation history. + */ + public void forward() { + if (simulatorNeedsInitialConfig()) { + SimulationSet s = AM1InputDialog.showAndWaitForReturn(); + MachineConfiguration m = s.getMachineConfiguration(); + if (m != null) { + view.getTablePanel().setInitialConfiguration( + "" + m.toString() + ""); + steps = s.getSteps(); + view.getToolbar() + .setButtonStatus(ButtonType.INITIAL, false); + getHistory().add(new MachineConfiguration(m)); + setCurrentMachineConfiguration(m); + addResultToTable(m, 0); + view.getTablePanel().getTableModel().showLastPage(); + view.getToolbar().setButtonStatus(ButtonType.CLEAR, true); + view.getToolbar().setButtonStatus(ButtonType.BACK, true); + if (!nextStep()) { + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, + false); + view.getToolbar().setButtonStatus(ButtonType.FORWARD, + false); + } + } + } else { + view.getTablePanel().getTableModel().showLastPage(); + view.getToolbar().setButtonStatus(ButtonType.CLEAR, true); + view.getToolbar().setButtonStatus(ButtonType.BACK, true); + if (!nextStep()) { + view.getToolbar() + .setButtonStatus(ButtonType.ONESTEP, false); + view.getToolbar() + .setButtonStatus(ButtonType.FORWARD, false); + } + } + view.getConsolePanel().switchToDescription(); + }; + + /** + * Do the simulation in one single step. + */ + public void onestep() { + if (simulatorNeedsInitialConfig()) { + SimulationSet s = AM1InputDialog.showAndWaitForReturn(); + MachineConfiguration m = s.getMachineConfiguration(); + if (m != null) { + steps = s.getSteps(); + view.getTablePanel().setInitialConfiguration( + "" + m.toString() + ""); + getHistory().add(new MachineConfiguration(m)); + setCurrentMachineConfiguration(m); + addResultToTable(m, 0); + view.getToolbar() + .setButtonStatus(ButtonType.FORWARD, false); + view.getToolbar() + .setButtonStatus(ButtonType.ONESTEP, false); + view.getToolbar() + .setButtonStatus(ButtonType.INITIAL, false); + view.getToolbar().setButtonStatus(ButtonType.BACK, true); + view.getToolbar().setButtonStatus(ButtonType.CLEAR, true); + stepToEnd(); + view.getTablePanel().getTableModel().showLastPage(); + } + } else { + view.getToolbar().setButtonStatus(ButtonType.FORWARD, false); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, false); + view.getToolbar().setButtonStatus(ButtonType.INITIAL, false); + view.getToolbar().setButtonStatus(ButtonType.CLEAR, true); + stepToEnd(); + view.getToolbar().setButtonStatus(ButtonType.BACK, true); + view.getTablePanel().getTableModel().showLastPage(); + } + view.getConsolePanel().switchToDescription(); + }; + + /** + * Open a new file. + */ + public void open() { + String in = view.getEditorPanel().loadCode(); + if (!in.isEmpty()) { + view.writeFileName(in); + } + }; + + /** + * Save the currently open and maybe edited file. + */ + public void save() { + String out = view.getEditorPanel().saveCode(); + if (!out.isEmpty()) { + view.writeFileName(out); + } + }; + } + + /** + * The state which indicates the user is in editing mode. + */ + private class Editing extends State { + @Override + public void run() { + AM1Parser am1Parser = new AM1Parser(); + String text = view.getEditorPanel().getEditor().getText(); + if (!text.isEmpty()) { + if (am1Parser.parse(text)) { + currentState = new Simulating(); + view.getToolbar().setRunButtonToStop(); + view.getToolbar().setButtonStatus(ButtonType.INITIAL, true); + view.getToolbar().setButtonStatus(ButtonType.FORWARD, true); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, true); + view.getToolbar().setButtonStatus(ButtonType.TOP, true); + view.getToolbar().setButtonStatus(ButtonType.BOTTOM, true); + view.getToolbar().setButtonStatus(ButtonType.OPEN, false); + + view.getEditorPanel().getEditor().setEditable(false); + view.getConsolePanel() + .getConsole() + .setText( + "

      Validation OK!

      "); + try { + setAM1Program(am1Parser.getProgram()); + } catch (IllegalAccessException e) { + System.err + .println("You must not call this method before calling parse()!"); + e.printStackTrace(); + } + String p = getAM1Program().toString(); + view.getEditorPanel().getEditor() + .setText(p.substring(0, p.length() - 1)); + if (text.equals(p.substring(0, p.length() - 1))) { + view.getEditorPanel().setModified(false); + view.setStatusbarModified(false); + } + } else { + view.getConsolePanel().getConsole() + .setText(am1Parser.getErrorText()); + } + } + } + } + + /** + * The state which indicates the user is in simulating mode. + */ + private class Simulating extends State { + @Override + public void run() { + currentState = new Editing(); + view.getEditorPanel().getEditor().setEditable(true); + view.getToolbar().setRunButtonToRun(); + view.getToolbar().setButtonStatus(ButtonType.INITIAL, false); + view.getToolbar().setButtonStatus(ButtonType.FORWARD, false); + view.getToolbar().setButtonStatus(ButtonType.ONESTEP, false); + view.getToolbar().setButtonStatus(ButtonType.BACK, false); + view.getToolbar().setButtonStatus(ButtonType.CLEAR, false); + view.getToolbar().setButtonStatus(ButtonType.TOP, false); + view.getToolbar().setButtonStatus(ButtonType.BOTTOM, false); + view.getToolbar().setButtonStatus(ButtonType.OPEN, true); + + view.getEditorPanel().removeMarkers(); + Simulator.this.clear(); + view.getTablePanel().setInitialConfiguration( + "No initial configuration."); + + view.getConsolePanel().switchToConsole(); + } + } + + /** + * Class which handles all incoming user input and manipulates the model as + * specified in the MVP-Pattern as part of the presenter. + * + * @author Max Leuthäuser + */ + private class UserInputListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent e) { + String cmd = e.getActionCommand(); + if (ButtonType.RUN.isButtonEvent(cmd)) { + currentState.run(); + } + if (ButtonType.TOP.isButtonEvent(cmd)) { + currentState.top(); + } + if (ButtonType.BOTTOM.isButtonEvent(cmd)) { + currentState.bottom(); + } + if (ButtonType.INITIAL.isButtonEvent(cmd)) { + currentState.initial(); + } + if (ButtonType.CLEAR.isButtonEvent(cmd)) { + currentState.clear(); + } + if (ButtonType.BACK.isButtonEvent(cmd)) { + currentState.back(); + } + if (ButtonType.FORWARD.isButtonEvent(cmd)) { + currentState.forward(); + } + if (ButtonType.ONESTEP.isButtonEvent(cmd)) { + currentState.onestep(); + } + if (ButtonType.OPEN.isButtonEvent(cmd)) { + currentState.open(); + } + if (ButtonType.SAVE.isButtonEvent(cmd)) { + currentState.save(); + } + } + } + + @Override + public void fireUpdateEvent(UpdateEvent update) { + view.getTablePanel().handleUpdateEvent(update); + } + + public void setPresentationMode(boolean selected) { + if (selected) { + view.getEditorPanel().getEditor().setFont(GuiUtilities.PRESENTATIONEDITORFONT); + view.getTablePanel().getTable().setFont(GuiUtilities.PRESENTATIONFONT); + view.getConsolePanel().getDescriptionEditor().setFont(GuiUtilities.PRESENTATIONFONT); + view.getConsolePanel().getConsole().setFont(GuiUtilities.PRESENTATIONFONT); + } else { + view.getEditorPanel().getEditor().setFont(GuiUtilities.STANDARDEDITORFONT); + view.getTablePanel().getTable().setFont(GuiUtilities.STANDARDFONT); + view.getConsolePanel().getDescriptionEditor().setFont(GuiUtilities.STANDARDFONT); + view.getConsolePanel().getConsole().setFont(GuiUtilities.STANDARDFONT); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/presenter/UpdateEvent.java b/src/org/jalgo/module/am1simulator/presenter/UpdateEvent.java new file mode 100644 index 0000000..8d7dbc9 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/UpdateEvent.java @@ -0,0 +1,54 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.presenter; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Class which carry update events used by the communication between presenter + * and view in the MVP-Pattern. + * + * @author Max Leuthäuser + */ +public class UpdateEvent { + List updates; + + public UpdateEvent(E value) { + updates = new LinkedList(); + updates.add(value); + } + + public List getValues() { + return updates; + } + + /** + * @param arg0 + * @param args never seen varargs? i lol'd + */ + public void setValues(E arg0, E... args) { + updates.add(arg0); + if (args != null && args.length > 0) + updates.addAll(Arrays.asList(args)); + } +} diff --git a/src/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.java b/src/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.java new file mode 100644 index 0000000..be91596 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/UpdateEventCreater.java @@ -0,0 +1,37 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.presenter; + +/** + * Small interface which is a blueprint for MVP presenter components to fire an + * update after they changed some important values of type E. + * + * @author Max Leuthäuser + */ + +public interface UpdateEventCreater { + /** + * Fire a new {@link UpdateEvent} to all {@link UpdateListener} you want. + * + * @param update + */ + void fireUpdateEvent(UpdateEvent update); +} diff --git a/src/org/jalgo/module/am1simulator/presenter/UpdateListener.java b/src/org/jalgo/module/am1simulator/presenter/UpdateListener.java new file mode 100644 index 0000000..2383ad3 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/UpdateListener.java @@ -0,0 +1,36 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.presenter; + +/** + * Small interface which is a blueprint for MVP view components to get updated + * after the presenter changed some important values. + * + * @author Max Leuthäuser + */ +public interface UpdateListener { + /** + * Handle an incoming {@link UpdateEvent}. + * + * @param event + */ + void handleUpdateEvent(UpdateEvent event); +} diff --git a/src/org/jalgo/module/am1simulator/presenter/package-info.java b/src/org/jalgo/module/am1simulator/presenter/package-info.java new file mode 100644 index 0000000..82e6fe7 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/presenter/package-info.java @@ -0,0 +1,28 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Classes which control the whole program. + * Represents the presenter of the MVP-Pattern. + * The view is passing calls to it. The presenter + * updated the view and manipulates the model. + */ +package org.jalgo.module.am1simulator.presenter; + diff --git a/src/org/jalgo/module/am1simulator/res.properties b/src/org/jalgo/module/am1simulator/res.properties new file mode 100644 index 0000000..dacc26a --- /dev/null +++ b/src/org/jalgo/module/am1simulator/res.properties @@ -0,0 +1,15 @@ +HelpSet_Name=/help/jhelp/am1simulator_help.hs +back_Icon=/am1simulator_pix/back.png +bottom_Icon=/am1simulator_pix/bottom.png +clear_Icon=/am1simulator_pix/clear.png +editor_Icon=/am1simulator_pix/editor.png +file_Icon=/am1simulator_pix/file.png +forward_Icon=/am1simulator_pix/forward.png +initial_Icon=/am1simulator_pix/initial.png +onestep_Icon=/am1simulator_pix/onestep.png +open_Icon=/am1simulator_pix/open.png +run_Icon=/am1simulator_pix/run.png +save_Icon=/am1simulator_pix/save.png +stop_Icon=/am1simulator_pix/stop.png +top_Icon=/am1simulator_pix/top.png +Main_Icon=/am1simulator_pix/logo.gif \ No newline at end of file diff --git a/src/org/jalgo/module/am1simulator/view/CVS/Entries b/src/org/jalgo/module/am1simulator/view/CVS/Entries new file mode 100644 index 0000000..fdb761b --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/CVS/Entries @@ -0,0 +1,5 @@ +/GUIBuilder.java/1.1/Mon Mar 7 19:57:19 2011// +/GuiUtilities.java/1.1/Mon Mar 7 19:57:19 2011// +/ViewContainer.java/1.1/Mon Mar 7 19:57:19 2011// +D/components//// +/package-info.java/1.1/Mon Mar 7 19:57:19 2011// diff --git a/src/org/jalgo/module/am1simulator/view/CVS/Repository b/src/org/jalgo/module/am1simulator/view/CVS/Repository new file mode 100644 index 0000000..fb9c9da --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/view diff --git a/src/org/jalgo/module/am1simulator/view/CVS/Root b/src/org/jalgo/module/am1simulator/view/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/view/GUIBuilder.java b/src/org/jalgo/module/am1simulator/view/GUIBuilder.java new file mode 100644 index 0000000..5866ecb --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/GUIBuilder.java @@ -0,0 +1,84 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view; + +import java.awt.Dimension; +import javax.swing.ImageIcon; +import javax.swing.JLabel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am1simulator.presenter.Simulator; +import org.jalgo.module.am1simulator.view.components.ConsolePanel; +import org.jalgo.module.am1simulator.view.components.EditorPanel; +import org.jalgo.module.am1simulator.view.components.MainPanel; +import org.jalgo.module.am1simulator.view.components.TablePanel; +import org.jalgo.module.am1simulator.view.components.Toolbar; + +/** + * Class which builds the complete GUI with all its elements. Implementation is + * characterized through static factory methods. + * + * @author Max Leuthäuser + */ +public final class GUIBuilder { + private GUIBuilder() { + throw new AssertionError("This class is not ment to be initilized!"); + } + + public static MainPanel newMainPanel() { + return new MainPanel(); + } + + public static JLabel newDefaultJLabel() { + return new JLabel(); + } + + public static JLabel newFileJLabel() { + JLabel result = new JLabel(new ImageIcon(Messages.getResourceURL( + "am1simulator", "file_Icon"))); + result.setText("New file"); + return result; + } + + public static ConsolePanel newConsolePanel() { + ConsolePanel result = new ConsolePanel(); + result.setMaximumSize(new Dimension(800, 200)); + result.setMinimumSize(new Dimension(800, 180)); + return result; + } + + public static TablePanel newTablePanel(Simulator simulator) { + TablePanel result = new TablePanel(simulator); + result.setMinimumSize(new Dimension(500, 370)); + return result; + } + + public static EditorPanel newEditorPanel(Simulator simulator) { + EditorPanel result = new EditorPanel(simulator); + result.setMaximumSize(new Dimension(180, 370)); + result.setMinimumSize(new Dimension(220, 370)); + return result; + } + + public static Toolbar newToolbar() { + return new Toolbar(); + } +} diff --git a/src/org/jalgo/module/am1simulator/view/GuiUtilities.java b/src/org/jalgo/module/am1simulator/view/GuiUtilities.java new file mode 100644 index 0000000..7f605da --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/GuiUtilities.java @@ -0,0 +1,55 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view; + +import java.awt.Font; +import java.awt.Frame; + +import org.jalgo.main.gui.JAlgoWindow; + +/** + * All constants for GUI elements are defined here. + * + * @author Max Leuthäuser + */ +public final class GuiUtilities { + /** The presentation font */ + public static final Font PRESENTATIONFONT = new Font("Courier", Font.BOLD, + 18); + /** The standard font */ + public static final Font STANDARDFONT = new Font("Courier", Font.PLAIN, 12); + + public static final Font STANDARDEDITORFONT = new Font("Monospaced", Font.PLAIN, 12); + public static final Font PRESENTATIONEDITORFONT = new Font("Monospaced", Font.PLAIN, 18); + /** + * This method returns the {@link JAlgoWindow} or throw a + * {@link RuntimeException} if it was unable to find it. + * + * @return the {@link JAlgoWindow} + */ + public static JAlgoWindow getJAlgoWindow() { + for (Frame f : Frame.getFrames()) + if (f instanceof JAlgoWindow) + return (JAlgoWindow) f; + + throw new RuntimeException("JAlgoWindow not found"); //$NON-NLS-1$ + } +} diff --git a/src/org/jalgo/module/am1simulator/view/ViewContainer.java b/src/org/jalgo/module/am1simulator/view/ViewContainer.java new file mode 100644 index 0000000..b8cbd63 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/ViewContainer.java @@ -0,0 +1,235 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSplitPane; + +import jsyntaxpane.actions.CaretMonitor; + +import org.jalgo.module.am1simulator.view.components.MainPanel; +import org.jalgo.module.am1simulator.view.components.ConsolePanel; +import org.jalgo.module.am1simulator.view.components.EditorPanel; +import org.jalgo.module.am1simulator.view.components.TablePanel; +import org.jalgo.module.am1simulator.view.components.Toolbar; + +/** + * Class which contains all view elements and regulate the access on them. This + * class uses a builder pattern. Null arguments are not allowed and + * causes an {@link IllegalArgumentException}. + * + * @author Max Leuthäuser + */ +public class ViewContainer { + private final ConsolePanel console; + private final EditorPanel editor; + private final TablePanel table; + private final Toolbar toolbar; + private final MainPanel mainPanel; + private final JLabel position, file; + + public static class Builder { + // Required Parameters + private final MainPanel mainPanel; + + // Optional parameters - not initialized + private ConsolePanel console; + private EditorPanel editor; + private TablePanel table; + private Toolbar toolbar; + private JLabel position, file; + + public Builder(MainPanel mainPanel) { + if (mainPanel == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + this.mainPanel = mainPanel; + } + + public Builder console(ConsolePanel con) { + if (con == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + console = con; + return this; + } + + public Builder editor(EditorPanel edit) { + if (edit == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + editor = edit; + return this; + } + + public Builder table(TablePanel tab) { + if (tab == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + table = tab; + return this; + } + + public Builder toolbar(Toolbar tool) { + if (tool == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + toolbar = tool; + return this; + } + + public Builder postion(JLabel pos) { + if (pos == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + position = pos; + return this; + } + + public Builder file(JLabel f) { + if (f == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + file = f; + return this; + } + + public ViewContainer build() { + return new ViewContainer(this); + } + } + + private ViewContainer(Builder builder) { + if (builder == null) { + throw new IllegalArgumentException( + "Null arguments are not allowed!"); + } + mainPanel = builder.mainPanel; + console = builder.console; + editor = builder.editor; + table = builder.table; + toolbar = builder.toolbar; + position = builder.position; + file = builder.file; + + assembleInterface(); + } + + /** + * Build the interface of this application. + */ + private void assembleInterface() { + editor.getEditor().addCaretListener( + new CaretMonitor(editor.getEditor(), position)); + + JSplitPane vSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + true, editor, table); + JSplitPane hSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, + vSplitPane, console); + hSplitPane.setOneTouchExpandable(true); + vSplitPane.setOneTouchExpandable(true); + + table.add(toolbar, BorderLayout.NORTH); + mainPanel.add(hSplitPane, BorderLayout.CENTER); + + JPanel statusBar = new JPanel(new BorderLayout()); + statusBar.add(position, BorderLayout.WEST); + statusBar.add(file, BorderLayout.EAST); + statusBar.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + mainPanel.add(statusBar, BorderLayout.SOUTH); + + mainPanel.doLayout(); + } + + /** + * Write the filename of the currently opened file at the statusbar. + * + * @param path + */ + public void writeFileName(String path) { + file.setText(path); + file.setToolTipText(path); + } + + /** + * Change to look of the statusbar to show the user the file he has opened + * was edited. + * + * @param m + */ + public void setStatusbarModified(boolean m) { + if (m) { + file.setForeground(Color.RED); + file.setFont(file.getFont().deriveFont(Font.ITALIC)); + } else { + file.setForeground(Color.BLACK); + file.setFont(file.getFont().deriveFont(Font.PLAIN)); + } + } + + /** + * @return the {@link MainPanel} + */ + public MainPanel getMainPanel() { + return mainPanel; + } + + /** + * @return the {@link EditorPanel} + */ + public EditorPanel getEditorPanel() { + return editor; + } + + /** + * @return the {@link ConsolePanel} + */ + public ConsolePanel getConsolePanel() { + return console; + } + + /** + * @return the {@link TablePanel} + */ + public TablePanel getTablePanel() { + return table; + } + + /** + * @return the {@link Toolbar} + */ + public Toolbar getToolbar() { + return toolbar; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/am1simulator/view/components/AM1InputDialog.java b/src/org/jalgo/module/am1simulator/view/components/AM1InputDialog.java new file mode 100644 index 0000000..beb380e --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/AM1InputDialog.java @@ -0,0 +1,558 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.LinkedList; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JTextField; + +import org.jalgo.module.am1simulator.view.GuiUtilities; +import org.jalgo.module.am1simulator.model.SimulationSet; +import org.jalgo.module.am1simulator.model.am1.machine.MachineConfiguration; +import org.jalgo.module.am1simulator.model.am1.machine.RuntimeStack; +import org.jalgo.module.am1simulator.model.am1.machine.RuntimeStackEntry; +import org.jalgo.module.am1simulator.model.am1.machine.Stream; + +/** + * Modal dialog to allow the user to type in a new AM1 configuration. Returns a + * {@link SimulationSet} + * + * @see AM1InputDialog#showAndWaitForReturn() + * + * @author Max Leuthäuser + */ +public class AM1InputDialog extends JComponent implements ActionListener { + private static final long serialVersionUID = 1L; + private static MachineConfiguration machineConfiguration = null; + private JButton ok, cancel, rsAdd, rsDel; + private JLabel pcDesc, stackDesc, rsDesc, refDesc, inDesc, outDesc, rsOut; + private JTextField pcInput, stackInput, inInput, outInput, rsInput, + refInput; + private JPanel inputs, buttons; + private JDialog dialog; + private static JSlider steps; + + private String EMPTY = "Æ"; + private String INTEGER = "(0|-?[1-9]{1}[0-9]*)"; + static final int STEPS_MIN = 1000; + /** + * Constant value to stop the presentation after the given number of steps + * and ask the user if he wants to go on. + */ + static final int STEPS_MAX = 2000; + static final int STEPS_INIT = 1000; + + /** + * Constant value which represents the maximum string length where all GUI + * relevant strings should be shortened. + */ + static final int MAX_STRING_LENGTH = 15; + + private LinkedList runStack = new LinkedList(); + + private AM1InputDialog() { + dialog = new JDialog(); + dialog.setTitle("AM1 - Initial configuration"); + dialog.setResizable(false); + dialog.setModal(true); + dialog.setLayout(new BorderLayout()); + ((JPanel) dialog.getContentPane()).setBorder(BorderFactory + .createEmptyBorder(10, 10, 10, 10)); + createBaseLayout(); + createInputLayout(); + + dialog.pack(); + int posX = GuiUtilities.getJAlgoWindow().getWidth() / 2 + - (dialog.getSize().width / 2); + int posY = GuiUtilities.getJAlgoWindow().getHeight() / 2 + - (dialog.getSize().height / 2); + dialog.setLocation(posX, posY); + dialog.setVisible(true); + } + + /** + * Create the input layout including text fields and description to enter a + * new AM0 configuration. + */ + private void createInputLayout() { + inputs = new JPanel(); + inputs.setLayout(new BoxLayout(inputs, BoxLayout.Y_AXIS)); + pcDesc = new JLabel("Program counter"); + pcDesc.setFont(new Font(pcDesc.getFont().getFontName(), Font.BOLD, + pcDesc.getFont().getSize())); + stackDesc = new JLabel("Data stack (values separated whith ':')"); + stackDesc.setFont(new Font(stackDesc.getFont().getFontName(), + Font.BOLD, stackDesc.getFont().getSize())); + rsDesc = new JLabel("Runtime stack"); + rsDesc.setFont(new Font(rsDesc.getFont().getFontName(), Font.BOLD, + rsDesc.getFont().getSize())); + refDesc = new JLabel("Reference counter"); + refDesc.setFont(new Font(refDesc.getFont().getFontName(), Font.BOLD, + refDesc.getFont().getSize())); + inDesc = new JLabel("Input (values separated whith ',')"); + inDesc.setFont(new Font(inDesc.getFont().getFontName(), Font.BOLD, + inDesc.getFont().getSize())); + outDesc = new JLabel("Output (values separated whith ',')"); + outDesc.setFont(new Font(outDesc.getFont().getFontName(), Font.BOLD, + outDesc.getFont().getSize())); + + pcInput = new JTextField(); + pcInput.setHorizontalAlignment(JTextField.CENTER); + pcInput.setText(" 1 "); + pcInput.setCaretPosition(3); + stackInput = new JTextField(); + stackInput.setText("Æ"); + rsOut = new JLabel("Æ"); + refInput = new JTextField(); + refInput.setText(" 0 "); + pcInput.setCaretPosition(3); + pcInput.setHorizontalAlignment(JTextField.CENTER); + inInput = new JTextField(); + inInput.setText("Æ"); + outInput = new JTextField(); + outInput.setText("Æ"); + + rsInput = new JTextField(); + + rsAdd = new JButton("+"); + rsAdd.addActionListener(this); + rsDel = new JButton("-"); + rsDel.addActionListener(this); + + JPanel pc = new JPanel(); + pc.setLayout(new BorderLayout(5, 5)); + pc.add(pcDesc, BorderLayout.NORTH); + pc.add(pcInput, BorderLayout.WEST); + + JPanel stack = new JPanel(); + stack.setLayout(new BorderLayout(5, 5)); + stack.add(stackDesc, BorderLayout.NORTH); + stack.add(stackInput, BorderLayout.CENTER); + + JPanel rs = new JPanel(); + JPanel holdA = new JPanel(); + holdA.setLayout(new GridLayout(1, 3)); + holdA.add(rsInput); + holdA.add(rsAdd); + holdA.add(rsDel); + JPanel holdB = new JPanel(); + holdB.setLayout(new BorderLayout()); + holdB.add(rsOut, BorderLayout.CENTER); + rs.setLayout(new GridLayout(3, 1, 5, 0)); + rs.add(rsDesc); + rs.add(holdA); + rs.add(holdB); + + JPanel ref = new JPanel(); + ref.setLayout(new BorderLayout(5, 5)); + ref.add(refDesc, BorderLayout.NORTH); + ref.add(refInput, BorderLayout.WEST); + + JPanel in = new JPanel(); + in.setLayout(new BorderLayout(5, 5)); + in.add(inDesc, BorderLayout.NORTH); + in.add(inInput, BorderLayout.CENTER); + + JPanel out = new JPanel(); + out.setLayout(new BorderLayout(5, 5)); + out.add(outDesc, BorderLayout.NORTH); + out.add(outInput, BorderLayout.CENTER); + + inputs.add(pc); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(stack); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(rs); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(ref); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(in); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(out); + + dialog.add(inputs, BorderLayout.CENTER); + + JLabel desc = new JLabel( + "Enter a new AM1 configuration.
      " + + "Use ',' to separate the values at the input/output stream.
      " + + "Use the same form for the runtime stack as written in the script. (e.g. '(1:0)')
      " + + "Please do not use whitespaces. They won't get accepted!

      "); + dialog.add(desc, BorderLayout.NORTH); + + steps = new JSlider(JSlider.HORIZONTAL, STEPS_MIN, STEPS_MAX, + STEPS_INIT); + steps.setMajorTickSpacing(200); + steps.setMinorTickSpacing(100); + steps.setPaintTicks(true); + steps.setPaintLabels(true); + + JPanel holder = new JPanel(); + holder.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createLineBorder(Color.gray), + "Option to avoid endless loops")); + holder.setLayout(new BorderLayout()); + holder.add(new JLabel(" Ask after"), BorderLayout.WEST); + holder.add(steps, BorderLayout.CENTER); + holder.add(new JLabel("steps. "), BorderLayout.EAST); + inputs.add(Box.createRigidArea(new Dimension(10, 10))); + inputs.add(holder); + } + + /** + * Create the base layout including the 'OK' and 'Cancel' button. + */ + private void createBaseLayout() { + buttons = new JPanel(); + buttons.setLayout(new GridLayout(1, 3)); + + ok = new JButton("OK"); + ok.addActionListener(this); + cancel = new JButton("Cancel"); + cancel.addActionListener(this); + + buttons.add(new JPanel()); + buttons.add(ok); + buttons.add(cancel); + buttons.add(new JPanel()); + + buttons.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); + + dialog.add(buttons, BorderLayout.SOUTH); + } + + /** + * Use this method to show this dialog and wait for the result. + * + * @return a new {@link SimulationSet} or null if the user cancels + * this dialog. + */ + public static SimulationSet showAndWaitForReturn() { + new AM1InputDialog(); + return new SimulationSet(machineConfiguration, steps.getValue()); + } + + /** + * Show an error dialog if the am1 configuration is not valid. + * + * @param description + */ + private void showError(String description) { + JOptionPane.showMessageDialog(null, description, "Invalid input", + JOptionPane.ERROR_MESSAGE); + } + + /** + * Cut the String in after 15 characters and add "..." at the end.
      + * Example:
      + * "12345678910111213" -> "123456789101112..." + * + * @param in + * @return a shortened String with "..." added + */ + private String beautifyString(String in) { + if (in.length() > MAX_STRING_LENGTH) { + return in.substring(0, MAX_STRING_LENGTH) + "..."; + } + return in; + } + + /** + * Check a String if its a valid program counter. + * + * @param pc + * @return true if the given string is a valid program counter, false + * otherwise. + */ + private boolean checkPc(String pc) { + if (pc == null || pc.isEmpty()) { + showError("The program counter must not be empty!"); + return false; + } + try { + int i = Integer.parseInt(pc); + if (i == 0) { + showError("The program counter must not be '0'!"); + return false; + } + } catch (NumberFormatException e) { + showError("This value is not a valid program counter:\n\n\"" + + beautifyString(pc) + "\""); + return false; + } + return true; + } + + /** + * Check a String if its a valid stack. + * + * @param stack + * @return true if the given string is a valid stack, false otherwise. + */ + private boolean checkStack(String stack) { + if (stack.isEmpty() + || stack.trim().matches( + EMPTY + "|(" + INTEGER + ":)*" + INTEGER)) { + return true; + } + showError("This value is not a valid stack configuration:\n\n\"" + + beautifyString(stack) + "\""); + return false; + } + + /** + * Check a String if its a valid runtime stack entry. + * + * @param run + * @return true if the given string is a valid runtime stack entry, false + * otherwise. + */ + private boolean checkRuntimeStackInput(String run) { + if (run.isEmpty()) { + showError("This value is not a valid runtime stack configuration.\nIt must not be empty!\n"); + return false; + } + if (run.matches("\\((" + INTEGER + ":)*" + INTEGER + "(\\))?")) { + return true; + } + showError("This value is not a valid runtime stack configuration:\n\n\"" + + beautifyString(run) + "\""); + return false; + } + + /** + * Check a String if its a valid reference counter. + * + * @param run + * @return true if the given string is a valid reference counter, false + * otherwise. + */ + private boolean checkRef(String ref) { + if (ref == null || ref.isEmpty()) { + showError("The reference counter must not be empty!"); + return false; + } + try { + Integer.parseInt(ref); + } catch (NumberFormatException e) { + showError("This value is not a valid reference counter:\n\n\"" + + beautifyString(ref) + "\""); + return false; + } + return true; + } + + /** + * Check a String if its a valid input/output stream entry. + * + * @param run + * @return true if the given string is a valid input/output stream entry, + * false otherwise. + */ + private boolean checkStream(String stream) { + if (stream.isEmpty() + || stream.trim().matches( + EMPTY + "|(" + INTEGER + ",)*" + INTEGER)) { + return true; + } + showError("This value is not a valid input/ouput stream configuration:\n\n\"" + + beautifyString(stream) + "\""); + return false; + } + + /** + * Checks the elements the users wants to type in as new AM1 configuration. + * + * @param pc + * @param stack + * @param ref + * @param in + * @param out + * @return true if everything is valid, false otherwise. + */ + private boolean checkInput(String pc, String stack, String ref, String in, + String out) { + return checkPc(pc) && checkStack(stack) && checkRef(ref) + && checkStream(in) && checkStream(out); + } + + /** + * Create a new {@link RuntimeStackEntry} based on a string. + * + * @param rse + * @return a new valid {@link RuntimeStackEntry} if the string is a valid + * runtime stack entry, null otherwise. + */ + private RuntimeStackEntry buildRuntimeStackEntry(String rse) { + if (checkRuntimeStackInput(rse)) { + rse = rse.replace("(", ""); + boolean closed = rse.contains(")"); + rse = rse.replace(")", ""); + + LinkedList result = new LinkedList(); + String delims = "[:]"; + String[] tokens = rse.split(delims); + for (String s : tokens) { + if (!s.isEmpty()) + try { + result.add(Integer.parseInt(s)); + } catch (NumberFormatException e) { + showError("This value is not a valid integer:\n\n\"" + + beautifyString(s) + "\""); + return null; + } + } + RuntimeStackEntry r = new RuntimeStackEntry(result, closed); + return r; + } else { + return null; + } + } + + /** + * Handle 'OK' and 'Cancel' click and handle runtime stack input/delete + * buttons + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent arg0) { + if (arg0.getSource() == rsAdd) { + RuntimeStackEntry e = buildRuntimeStackEntry(rsInput.getText() + .trim()); + if (e != null) { + if (!runStack.isEmpty()) { + if (runStack.getLast().isClosed()) { + runStack.add(e); + rsOut.setText(RuntimeStack + .printAListAsRuntimeStack(runStack)); + } else { + showError("This element could not be added!\nThe last element in the runtime stack has to be closed."); + } + } else { + runStack.add(e); + rsOut.setText(RuntimeStack + .printAListAsRuntimeStack(runStack)); + } + } + } + + if (arg0.getSource() == rsDel) { + RuntimeStackEntry e = buildRuntimeStackEntry(rsInput.getText() + .trim()); + if (e != null) { + if (!runStack.remove(e)) { + showError("The runtime stack does not contain this entry!\nIt could not be removed."); + } else { + rsOut.setText(RuntimeStack + .printAListAsRuntimeStack(runStack)); + } + } + } + + if (arg0.getSource() == cancel) { + machineConfiguration = null; + dialog.setVisible(false); + dialog.dispose(); + } + + if (arg0.getSource() == ok) { + machineConfiguration = buildMachineConfiguration(pcInput.getText() + .trim(), stackInput.getText(), refInput.getText().trim(), + inInput.getText(), outInput.getText()); + if (machineConfiguration != null) { + dialog.setVisible(false); + dialog.dispose(); + } + } + } + + /** + * Create a new {@link LinkedList} based on a string and a delimiter. + * + * @param st + * @param delim + * @return a new {@link LinkedList} which could be used to create a new + * {@link Stream}. + */ + private LinkedList createStream(String st, String delim) { + if (st.trim().equals(EMPTY)) { + return new LinkedList(); + } + LinkedList result = new LinkedList(); + String delims = "[" + delim + "]"; + String[] tokens = st.split(delims); + for (String s : tokens) { + if (!s.isEmpty()) + try { + result.add(Integer.parseInt(s)); + } catch (NumberFormatException e) { + showError("This value is not a valid integer:\n\n\"" + + beautifyString(s) + "\""); + return null; + } + } + return result; + } + + /** + * Create a new {@link MachineConfiguration} based on several strings. + * + * @param pc + * @param stack + * @param ref + * @param in + * @param out + * @return a new {@link MachineConfiguration} if all given parameter are + * valid machine components. + */ + private MachineConfiguration buildMachineConfiguration(String pc, + String stack, String ref, String in, String out) { + if (checkInput(pc, stack, ref, in, out)) { + LinkedList stackList = createStream(stack, ":"); + LinkedList inList = createStream(in, ","); + LinkedList outList = createStream(out, ","); + if (stackList != null && inList != null && outList != null) + // Integer.parseInt is save here because + // the Strings are checked in checkInput already! + return new MachineConfiguration(Integer.parseInt(pc), + stackList, runStack, Integer.parseInt(ref), inList, + outList); + return null; + } + return null; + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/AMTableRenderer.java b/src/org/jalgo/module/am1simulator/view/components/AMTableRenderer.java new file mode 100644 index 0000000..ad6bf19 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/AMTableRenderer.java @@ -0,0 +1,87 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.Color; +import java.awt.Component; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableCellRenderer; + +/** + * Custom table renderer to show rows in different colors. + * + * @author Max Leuthäuser + */ +class AMTableRenderer extends DefaultTableCellRenderer { + private static final long serialVersionUID = 1L; + /** + * Standard grey for our am1 table + */ + public static final Color TABLE_ODD = new Color(237, 237, 237); + /** + * Standard white for our am1 table + */ + public static final Color TABLE_EVEN = new Color(255, 255, 255); + private final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int column) { + Component cell; + cell = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, + isSelected, hasFocus, row, column); + + cell.setForeground(Color.BLACK); + + if (!isSelected) { + if (row % 2 == 0) { + cell.setBackground(TABLE_EVEN); + } else { + cell.setBackground(TABLE_ODD); + } + } else { + if (row % 2 == 0) { + cell.setBackground(Color.YELLOW); + } else { + cell.setBackground(Color.ORANGE); + } + } + + if (row == table.getRowCount() - 1) { + cell.setBackground(Color.ORANGE); + } + + if (column == 0) { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.CENTER); + return cell; + } else { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.LEFT); + } + if (column == 1) { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.RIGHT); + return cell; + } else { + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.LEFT); + } + return cell; + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/CVS/Entries b/src/org/jalgo/module/am1simulator/view/components/CVS/Entries new file mode 100644 index 0000000..99d0318 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/CVS/Entries @@ -0,0 +1,8 @@ +/AM1InputDialog.java/1.1/Mon Mar 7 19:57:18 2011// +/AMTableRenderer.java/1.1/Mon Mar 7 19:57:18 2011// +/ConsolePanel.java/1.1/Mon Mar 7 19:57:18 2011// +/EditorPanel.java/1.1/Mon Mar 7 19:57:18 2011// +/MainPanel.java/1.1/Mon Mar 7 19:57:18 2011// +/PresentationAction.java/1.1/Mon Mar 7 19:57:18 2011// +/TablePanel.java/1.1/Mon Mar 7 19:57:18 2011// +/Toolbar.java/1.1/Mon Mar 7 19:57:18 2011// diff --git a/src/org/jalgo/module/am1simulator/view/components/CVS/Repository b/src/org/jalgo/module/am1simulator/view/components/CVS/Repository new file mode 100644 index 0000000..962d8f0 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/am1simulator/view/components diff --git a/src/org/jalgo/module/am1simulator/view/components/CVS/Root b/src/org/jalgo/module/am1simulator/view/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/am1simulator/view/components/ConsolePanel.java b/src/org/jalgo/module/am1simulator/view/components/ConsolePanel.java new file mode 100644 index 0000000..8d67fc6 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/ConsolePanel.java @@ -0,0 +1,105 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import javax.swing.BorderFactory; +import javax.swing.JEditorPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import org.jalgo.module.am1simulator.presenter.UpdateEvent; +import org.jalgo.module.am1simulator.presenter.UpdateListener; + +/** + * Panel which is used to show some text to the user, like AM1 statement + * descriptions and parser output. + * + * @author Max Leuthäuser + */ +public class ConsolePanel extends JPanel implements UpdateListener { + private static final long serialVersionUID = 1L; + private JEditorPane description, console; + private JTabbedPane tabbet; + + public ConsolePanel() { + setLayout(new GridLayout(1, 2)); + description = new JEditorPane(); + console = new JEditorPane(); + + description.setEditable(false); + description.setContentType("text/html"); + description.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, + true); + console.setEditable(false); + console.setContentType("text/html"); + console.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); + + tabbet = new JTabbedPane(); + tabbet.add("Console", new JScrollPane(console)); + tabbet.add("Description", new JScrollPane(description)); + + JPanel output = new JPanel(); + output.setLayout(new BorderLayout()); + output.setBorder(BorderFactory.createTitledBorder("Output:")); + output.add(tabbet, BorderLayout.CENTER); + + add(output); + } + + /** + * @return the {@link JEditorPane} which is used to show AM1 statement + * descriptions to the user. + */ + public JEditorPane getDescriptionEditor() { + return description; + } + + /** + * @return the {@link JEditorPane} which is used to show the parser output + * to the user. + */ + public JEditorPane getConsole() { + return console; + } + + /** + * Switch to the {@link JEditorPane} which is used to show the parser output + * to the user. + */ + public void switchToConsole() { + tabbet.setSelectedIndex(0); + } + + /** + * Switch to the {@link JEditorPane} which is used to show AM1 statement + * descriptions to the user. + */ + public void switchToDescription() { + tabbet.setSelectedIndex(1); + } + + @Override + public void handleUpdateEvent(UpdateEvent event) { + description.setText(event.getValues().get(0)); + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/EditorPanel.java b/src/org/jalgo/module/am1simulator/view/components/EditorPanel.java new file mode 100644 index 0000000..1ad81df --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/EditorPanel.java @@ -0,0 +1,303 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import javax.swing.BorderFactory; +import javax.swing.JEditorPane; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.filechooser.FileFilter; +import javax.swing.text.BadLocationException; + +import org.jalgo.module.am1simulator.parser.AM1SyntaxKit; +import org.jalgo.module.am1simulator.presenter.Simulator; +import org.jalgo.module.am1simulator.presenter.UpdateEvent; +import org.jalgo.module.am1simulator.presenter.UpdateEventCreater; +import org.jalgo.module.am1simulator.model.am1.SimulationStatement; + +import jsyntaxpane.actions.ActionUtils; +import jsyntaxpane.components.Markers; +import jsyntaxpane.components.Markers.SimpleMarker; + +/** + * Panel which is used for the editor. + * + * @author Max Leuthäuser + */ +public class EditorPanel extends JPanel implements UpdateEventCreater { + private JEditorPane codeEditor; + private JFileChooser fileChooser; + private boolean modified = false; + private Simulator simulator; + + private static final long serialVersionUID = 1L; + private static final String EXAMPLES_PATH = "examples/am1simulator"; + + public EditorPanel(final Simulator simulator) { + this.simulator = simulator; + setLayout(new BorderLayout()); + codeEditor = new JEditorPane(); + add(new JScrollPane(codeEditor), BorderLayout.CENTER); + AM1SyntaxKit.initKit(); + codeEditor.setContentType("text/am1"); + codeEditor.setAutoscrolls(true); + codeEditor.addMouseListener(new MouseListener() { + + @Override + public void mouseReleased(MouseEvent e) { + try { + int line = ActionUtils.getLineNumber(codeEditor, + codeEditor.getCaretPosition()); + if (simulator.getAM1Program() != null) { + String s = simulator.getAM1Program().get(line) + .getDescription(); + fireUpdateEvent(new UpdateEvent(simulator + .getAM1Program().get(line).getCodeText() + + "

      " + s + "

      ")); + } + } catch (BadLocationException e1) { + // Ignored here if the user clicks at an invalid position! + } + } + + @Override + public void mousePressed(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseExited(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseEntered(MouseEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void mouseClicked(MouseEvent e) { + // TODO Auto-generated method stub + + } + }); + codeEditor.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + setModified(true); + } + + @Override + public void insertUpdate(DocumentEvent e) { + setModified(true); + } + + @Override + public void changedUpdate(DocumentEvent e) { + setModified(true); + } + }); + setBorder(BorderFactory.createTitledBorder("Editor")); + fileChooser = new JFileChooser(); + fileChooser.setCurrentDirectory(new File(EXAMPLES_PATH)); + fileChooser.addChoosableFileFilter(new FileFilter() { + @Override + public String getDescription() { + return "AM1 source code (*.am1)"; + } + + @Override + public boolean accept(File f) { + return f.isDirectory() || f.getName().endsWith(".am1"); + } + }); + } + + /** + * @return true if the user has modified the code, false otherwise. + */ + public boolean isModified() { + return modified; + } + + /** + * Set the modified flag to m. + * + * @param m + */ + public void setModified(boolean m) { + modified = m; + } + + /** + * @return the editor which is used here to type in new code or load/save + * and edit files. + */ + public JEditorPane getEditor() { + return codeEditor; + } + + /** + * @param line + * @return the caret position in the editor at the given line. + */ + private int getCaretAtLine(int line) { + int lines = 0; + char[] chararr = codeEditor.getText().toCharArray(); + for (int i = 0; i < chararr.length; i++) { + if (chararr[i] == '\n') { + lines++; + } + if (lines == line) + return i; + } + return 0; + } + + /** + * Remove all markers from the editor. + */ + public void removeMarkers() { + Markers.removeMarkers(codeEditor); + } + + /** + * Mark a specific {@link SimulationStatement} in the editor. + * + * @param s + */ + public void markStatement(SimulationStatement s) { + int start = getCaretAtLine(s.getAddress().getLine() - 1); + int end = s.getCodeText().length() + 1; + SimpleMarker a = new SimpleMarker(Color.ORANGE); + Markers.markText(codeEditor, start, start + end, a); + codeEditor.setCaretPosition(start + end - 1); + } + + /** + * Loads new code if the user confirms the respective dialog. + * + * @return the path to the selected file or a empty string if no file was + * selected + */ + public String loadCode() { + if (isModified()) { + int saveBeforeClose = JOptionPane + .showConfirmDialog( + this, + "The current code has been modified.\nDo you want to save it?", + "Confirm", JOptionPane.YES_NO_CANCEL_OPTION); + + switch (saveBeforeClose) { + case JOptionPane.YES_OPTION: + saveCode(); + setModified(false); + break; + case JOptionPane.CANCEL_OPTION: + return ""; + default: + break; + } + } + + boolean result = fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION; + + if (result) { + File file = fileChooser.getSelectedFile(); + + BufferedReader reader; + try { + reader = new BufferedReader(new FileReader(file)); + + codeEditor.setText(""); + boolean firstLine = true; + + for (String line; (line = reader.readLine()) != null;) { + if (firstLine) { + codeEditor.setText(line); + firstLine = false; + } else + codeEditor.setText(codeEditor.getText() + "\n" + line); + } + reader.close(); + setModified(false); + return fileChooser.getSelectedFile().getAbsolutePath(); + } catch (IOException e) { + JOptionPane.showMessageDialog(this, e.getMessage(), + "The file could not be loaded.", + JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + return ""; + } + + } + return ""; + } + + /** + * Saves the entered code if the user confirms the respective dialog. + * + * @return the path if the user confirmed the dialog or "" if not + */ + public String saveCode() { + boolean result = fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION; + String ret = ""; + if (result) { + File file = fileChooser.getSelectedFile(); + ret = file.getAbsolutePath(); + PrintWriter printWriter; + try { + printWriter = new PrintWriter(new FileWriter(file)); + printWriter.print(codeEditor.getText()); + printWriter.close(); + setModified(false); + } catch (IOException e) { + JOptionPane.showMessageDialog(this, e.getMessage(), + "File could not be saved.", JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + return ""; + } + } + return ret; + } + + @Override + public void fireUpdateEvent(UpdateEvent update) { + simulator.getView().getConsolePanel().handleUpdateEvent(update); + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/MainPanel.java b/src/org/jalgo/module/am1simulator/view/components/MainPanel.java new file mode 100644 index 0000000..388469a --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/MainPanel.java @@ -0,0 +1,38 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.BorderLayout; +import javax.swing.JPanel; + +/** + * This class is the main panel of the application. It contains all GUI + * elements. + * + * @author Max Leuthäuser + */ +public class MainPanel extends JPanel { + private static final long serialVersionUID = 1L; + + public MainPanel() { + setLayout(new BorderLayout()); + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/PresentationAction.java b/src/org/jalgo/module/am1simulator/view/components/PresentationAction.java new file mode 100644 index 0000000..ebf1d17 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/PresentationAction.java @@ -0,0 +1,60 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2010 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.am1simulator.view.components; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.am1simulator.presenter.Simulator; + +/** + * Handle the presentation mode. + * + * @author Max Leuthäuser + */ +public class PresentationAction extends JCheckBoxMenuItem implements + ActionListener { + private static final long serialVersionUID = 1L; + private Simulator simulator; + + public PresentationAction(Simulator simulator) { + super("Toggle presentation mode", new ImageIcon(Messages + .getResourceURL("main", "Icon.Beamer_mode")), false); + this.simulator = simulator; + addActionListener(this); + } + + /** + * Toggles the presentation mode. + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + @Override + public void actionPerformed(ActionEvent e) { + simulator.setPresentationMode(isSelected()); + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/TablePanel.java b/src/org/jalgo/module/am1simulator/view/components/TablePanel.java new file mode 100644 index 0000000..c0489cd --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/TablePanel.java @@ -0,0 +1,134 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import org.jalgo.module.am1simulator.presenter.Simulator; +import org.jalgo.module.am1simulator.presenter.UpdateEvent; +import org.jalgo.module.am1simulator.presenter.UpdateListener; +import org.jalgo.module.am1simulator.model.AM1PagingTableModel; + +/** + * Panel which is used to show the simulation steps with their specific AM1 + * configurations. + * + * @author Max Leuthäuser + */ +public class TablePanel extends JPanel implements UpdateListener { + private static final long serialVersionUID = 1L; + private JLabel steps, currentStep; + private AM1PagingTableModel amTableModel; + private JTable amTable; + private JLabel initialeConfig; + private Simulator simulator; + + public TablePanel(Simulator simulator) { + this.simulator = simulator; + setBorder(BorderFactory.createTitledBorder("Simulation")); + setLayout(new BorderLayout(10, 10)); + + JPanel stepsPanel = new JPanel(); + stepsPanel.setLayout(new BorderLayout(10, 10)); + stepsPanel.setBorder(BorderFactory.createTitledBorder("Progress:")); + + steps = new JLabel(); + initialeConfig = new JLabel("No initial configuration."); + initialeConfig.setHorizontalAlignment(SwingConstants.RIGHT); + currentStep = new JLabel("Not started yet."); + + stepsPanel.add(steps, BorderLayout.WEST); + stepsPanel.add(currentStep, BorderLayout.EAST); + + amTableModel = new AM1PagingTableModel(); + amTable = new JTable(amTableModel); + amTable.setDefaultRenderer(Object.class, new AMTableRenderer()); + + amTable.setRowHeight(amTable.getRowHeight() + 5); + amTable.setShowGrid(false); + amTable.setIntercellSpacing(new Dimension(12, 2)); + amTable.getTableHeader().setReorderingAllowed(false); + + add(initialeConfig, BorderLayout.NORTH); + add(amTableModel.createPagingScrollPaneForTable(amTable), + BorderLayout.CENTER); + add(stepsPanel, BorderLayout.SOUTH); + } + + /** + * Set the range label to s. + * + * @param s + */ + public void setRange(String s) { + steps.setText(s); + } + + /** + * Set the step label to s. + * + * @param s + */ + public void setStep(String s) { + currentStep.setText(s); + } + + /** + * Set a new initial configuration to the config label. + * + * @param s + */ + public void setInitialConfiguration(String s) { + initialeConfig.setText(s); + } + + /** + * @return the used {@link AM1PagingTableModel}. + */ + public AM1PagingTableModel getTableModel() { + return amTableModel; + } + + /** + * @return the used {@link JTable}. + */ + public JTable getTable() { + return amTable; + } + + @Override + public void handleUpdateEvent(UpdateEvent event) { + int pc = event.getValues().get(0); + amTable.scrollRectToVisible(amTable.getCellRect( + amTable.getRowCount() - 1, amTable.getColumnCount(), true)); + int p = pc < 1 ? 1 : pc; + simulator.getView().getEditorPanel().removeMarkers(); + if (p <= simulator.getAM1Program().size()) { + simulator.getView().getEditorPanel() + .markStatement(simulator.getAM1Program().get(p - 1)); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/view/components/Toolbar.java b/src/org/jalgo/module/am1simulator/view/components/Toolbar.java new file mode 100644 index 0000000..c869302 --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/components/Toolbar.java @@ -0,0 +1,229 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.jalgo.module.am1simulator.view.components; + +import java.awt.event.ActionListener; +import javax.swing.AbstractButton; +import javax.swing.Box; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JToolBar; + +import org.jalgo.main.util.Messages; + +/** + * A toolbar which is used to handle the user input. + * + * @author Max Leuthäuser + */ +public class Toolbar extends JToolBar { + private static final long serialVersionUID = 1L; + + /** + * Enumeration that holds all kinds of buttons which are used here. + * + * @author Max Leuthäuser + */ + public static enum ButtonType { + RUN, TOP, BOTTOM, INITIAL, CLEAR, BACK, FORWARD, ONESTEP, OPEN, SAVE; + + @Override + public String toString() { + return name().toLowerCase(); + } + + public String iconName() { + return toString() + "_Icon"; + } + + /** + * Check if a String equals the string representation of this specific + * button. (use getActionCommand()) + * + * @param o + * @return true of the String equals this specific button, false + * otherwise. + */ + public boolean isButtonEvent(String o) { + return o != null && o.equals(toString()); + } + } + + private JButton run, top, bottom, initial, clear, back, forward, onestep, + open, save; + + public Toolbar() { + run = makeButton(ButtonType.RUN, + "Parse the code and run the simulation.", "Parse and run", true); + top = makeButton(ButtonType.TOP, + "Scroll to the top of the simulation table.", + "Scroll to the top", false); + bottom = makeButton(ButtonType.BOTTOM, + "Scroll to the bottom of the simulation table.", + "Scroll to the bottom", false); + initial = makeButton(ButtonType.INITIAL, + "Enter an initial configuration for the AM1.", "Configuration", + false); + clear = makeButton(ButtonType.CLEAR, "Delete the current simulation.", + "Clear", false); + back = makeButton(ButtonType.BACK, "Do one step back.", "Back", false); + forward = makeButton(ButtonType.FORWARD, "Do on step forward.", + "Forward", false); + onestep = makeButton(ButtonType.ONESTEP, + "Run the whole simulation in one step.", "One step", false); + open = makeButton(ButtonType.OPEN, + "Open a file and load it to the editor.", "Open", true); + save = makeButton(ButtonType.SAVE, "Save the source code to a file.", + "Save", true); + + add(open); + add(save); + addSeparator(); + add(run); + addSeparator(); + add(initial); + add(clear); + add(back); + add(forward); + add(onestep); + add(Box.createHorizontalGlue()); + add(top); + add(bottom); + } + + /** + * Change the image and text of the run button to show the user could stop + * the simulation here. + */ + public void setRunButtonToStop() { + run.setIcon(new ImageIcon(Messages.getResourceURL("am1simulator", + "stop_Icon"))); + run.setText("Stop"); + run.setToolTipText("Stop the current simulation.
      This will delete your current simulation!"); + } + + /** + * Change the image and text of the run button to show the user could run + * the simulation here. + */ + public void setRunButtonToRun() { + run.setIcon(new ImageIcon(Messages.getResourceURL("am1simulator", + "run_Icon"))); + run.setText("Parse and run"); + run.setToolTipText("Parse the code and run the simulation."); + } + + /** + * Create a new {@link JButton} with the given attributes. + * + * @param actionCommand + * @param toolTipText + * @param altText + * @param enabled + * @return a new {@link JButton} with the given attributes. + */ + private JButton makeButton(ButtonType actionCommand, String toolTipText, + String altText, boolean enabled) { + JButton button = new JButton(altText); + button.setActionCommand(actionCommand.toString()); + button.setToolTipText(toolTipText); + button.setIcon(new ImageIcon(Messages.getResourceURL("am1simulator", + actionCommand.iconName()))); + button.setVerticalTextPosition(AbstractButton.BOTTOM); + button.setHorizontalTextPosition(AbstractButton.CENTER); + button.setEnabled(enabled); + return button; + } + + /** + * Add an {@link ActionListener} to all buttons to handle user input + * correctly. + * + * @param a + */ + public void addUserInputListener(ActionListener a) { + run.addActionListener(a); + top.addActionListener(a); + bottom.addActionListener(a); + initial.addActionListener(a); + clear.addActionListener(a); + back.addActionListener(a); + forward.addActionListener(a); + onestep.addActionListener(a); + open.addActionListener(a); + save.addActionListener(a); + } + + /** + * Method which set all important buttons to the initial state after a + * simulation error was found. + */ + public void setButtonsDisabledAfterError() { + setButtonStatus(ButtonType.BACK, false); + setButtonStatus(ButtonType.FORWARD, false); + setButtonStatus(ButtonType.ONESTEP, false); + setButtonStatus(ButtonType.CLEAR, true); + setButtonStatus(ButtonType.INITIAL, false); + } + + /** + * Set the specific button disabled/enabled. + * + * @param button + * @param enabled + */ + public void setButtonStatus(ButtonType button, boolean enabled) { + switch (button) { + case BACK: + back.setEnabled(enabled); + break; + case RUN: + run.setEnabled(enabled); + break; + case TOP: + top.setEnabled(enabled); + break; + case BOTTOM: + bottom.setEnabled(enabled); + break; + case ONESTEP: + onestep.setEnabled(enabled); + break; + case OPEN: + open.setEnabled(enabled); + break; + case SAVE: + save.setEnabled(enabled); + break; + case FORWARD: + forward.setEnabled(enabled); + break; + case CLEAR: + clear.setEnabled(enabled); + break; + case INITIAL: + initial.setEnabled(enabled); + break; + default: + throw new AssertionError("Unkown button type: " + button); + } + } +} diff --git a/src/org/jalgo/module/am1simulator/view/package-info.java b/src/org/jalgo/module/am1simulator/view/package-info.java new file mode 100644 index 0000000..f98d79b --- /dev/null +++ b/src/org/jalgo/module/am1simulator/view/package-info.java @@ -0,0 +1,27 @@ +/** + * AM1 Simulator - simulating am1 code in an abstract machine based on the + * definitions of the lectures 'Programmierung' at TU Dresden. + * Copyright (C) 2010 Max Leuthäuser + * Contact: s7060241@mail.zih.tu-dresden.de + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Classes which represents the view of the MVP-Pattern. + * The view is passing calls to the presenter and + * gets updated from there. + */ +package org.jalgo.module.am1simulator.view; + diff --git a/src/org/jalgo/module/app/CVS/Entries b/src/org/jalgo/module/app/CVS/Entries new file mode 100644 index 0000000..3a9628b --- /dev/null +++ b/src/org/jalgo/module/app/CVS/Entries @@ -0,0 +1,10 @@ +/ModuleConnector.java/1.1/Wed Oct 29 18:05:24 2008// +/ModuleInfo.java/1.1/Wed Oct 29 18:05:24 2008// +D/controller//// +D/core//// +D/coreTest//// +/de.properties/1.1/Wed Oct 29 18:05:24 2008// +/en.properties/1.1/Wed Oct 29 18:05:24 2008// +/package.html/1.1/Wed Oct 29 18:05:24 2008// +/res.properties/1.1/Wed Oct 29 18:05:24 2008// +D/view//// diff --git a/src/org/jalgo/module/app/CVS/Repository b/src/org/jalgo/module/app/CVS/Repository new file mode 100644 index 0000000..0c3cbb4 --- /dev/null +++ b/src/org/jalgo/module/app/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app diff --git a/src/org/jalgo/module/app/CVS/Root b/src/org/jalgo/module/app/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/ModuleConnector.java b/src/org/jalgo/module/app/ModuleConnector.java new file mode 100644 index 0000000..4f1acb2 --- /dev/null +++ b/src/org/jalgo/module/app/ModuleConnector.java @@ -0,0 +1,110 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.app; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.MainController; +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.graph.Graph; + +/** + * Provides the connection to j-Algo. + */ +public class ModuleConnector extends AbstractModuleConnector { + + private MainController mainController; + + @Override + public void init() { + mainController = new MainController(this); + } + + @Override + public void run() { + } + + @Override + public boolean close() { + mainController.close(); + return true; + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + Graph graph = null; + SemiRing semiring = null; + try { + ObjectInputStream ois = new ObjectInputStream(data); + graph = (Graph) ois.readObject(); + semiring = (SemiRing) ois.readObject(); + ois.close(); + } catch (IOException e) { + JOptionPane.showMessageDialog(new JFrame(), Messages.getString( + "app", "ModuleConnector.IOError"), Messages.getString( + "app", "ModuleConnector.Error"), JOptionPane.ERROR_MESSAGE); + } catch (ClassNotFoundException e) { + JOptionPane.showMessageDialog(new JFrame(), Messages.getString( + "app", "ModuleConnector.ClassError"), Messages.getString( + "app", "ModuleConnector.Error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + + mainController.load(graph, semiring); + } + + @Override + public ByteArrayOutputStream getDataForFile() { + Graph graph = mainController.getGraphController().getGraph(); + SemiRing semiring = mainController.getSemiringController() + .getSemiRing(); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oos; + try { + oos = new ObjectOutputStream(out); + oos.writeObject(graph); + oos.writeObject(semiring); + oos.close(); + } catch (IOException e) { + JOptionPane.showMessageDialog(new JFrame(), Messages.getString( + "app", "ModuleConnector.SavingError"), Messages.getString( + "app", "ModuleConnector.Error"), JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + return out; + } + + @Override + public void print() { + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/ModuleInfo.java b/src/org/jalgo/module/app/ModuleInfo.java new file mode 100644 index 0000000..e2adccd --- /dev/null +++ b/src/org/jalgo/module/app/ModuleInfo.java @@ -0,0 +1,83 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.app; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * Provides informations about the module. + */ +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return Messages.getString("app","ModuleInfo.Name"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public String getVersion() { + return "1.0"; //$NON-NLS-1$ + } + + public String getAuthor() { + return Messages.getString("app","ModuleInfo.Author"); //$NON-NLS-1$ + } + + public String getDescription() { + return Messages.getString("app","ModuleInfo.Description"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public URL getLogoURL() { + return Messages.getResourceURL("app", "Module_logo"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public String getLicense() { + return "GPL"; //$NON-NLS-1$ + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("app","helpSet_name"); //$NON-NLS-1$ //$NON-NLS-2$ + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/controller/AlgorithmController.java b/src/org/jalgo/module/app/controller/AlgorithmController.java new file mode 100644 index 0000000..8e6fb0a --- /dev/null +++ b/src/org/jalgo/module/app/controller/AlgorithmController.java @@ -0,0 +1,498 @@ +package org.jalgo.module.app.controller; + +import java.awt.BorderLayout; +import java.awt.Point; +import java.util.HashSet; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +import javax.swing.JPanel; + +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.Operation.Notation; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.core.step.Step; +import org.jalgo.module.app.view.run.ControlToolbar; +import org.jalgo.module.app.view.run.FormulaComponent; +import org.jalgo.module.app.view.run.FormulaWindow; +import org.jalgo.module.app.view.run.MatrixComponent; +import org.jalgo.module.app.view.run.StepHighlighting; + +/** + * Controls the two Panels, which are in the right panel of the User Interface. + * The AlgorithmController initializes the three components, + * which are involved in these panels. + */ +public class AlgorithmController { + + // Connection to the MainController to communicate with the Core and the + // InterfaceController. + private MainController mainCtrl; + + private AnimationTimerTask timerTask; + private Timer animationTimer; + + // Components, which are controlled by this Controller. + private ControlToolbar controlToolbar; + private MatrixComponent matrixComponent; + private FormulaComponent formulaComponent; + private FormulaWindow formulaWindow; + + // to remember the currentStep + private RootStep rootStep; + private Step currentStep; + + private Set highlightedViews; + + // The Panels, which are initialized by the InterfaceController. + private JPanel algorithmPanel, algorithmToolPanel; + + /** + * Instantiates the two Panels, which are in the right panel of the User + * Interface (in InterfaceMode.ALGORITM_MODE). He also + * initializes the three components involved in the panels. + */ + public AlgorithmController(MainController mainController, + JPanel algorithmPanel, + JPanel algorithmToolPanel + ) + { + BorderLayout layout; + + mainCtrl = mainController; + + this.algorithmPanel = algorithmPanel; + this.algorithmToolPanel = algorithmToolPanel; + + highlightedViews = new HashSet(); + + controlToolbar = new ControlToolbar(this); + matrixComponent = new MatrixComponent(this); + formulaComponent = new FormulaComponent(this); + + layout = new BorderLayout(); + algorithmPanel.setLayout(layout); + algorithmPanel.add(matrixComponent, BorderLayout.CENTER); + algorithmPanel.add(formulaComponent, BorderLayout.SOUTH); + algorithmToolPanel.add(controlToolbar); + } + + private void updateToolbarButtons(boolean hasPrev, boolean hasNext) { + controlToolbar.setButtonState( + ControlToolbar.ControlButtons.AnimateButton, hasNext); + + controlToolbar.setButtonState( + ControlToolbar.ControlButtons.FastForwardButton, hasNext); + controlToolbar.setButtonState( + ControlToolbar.ControlButtons.ForwardButton, hasNext); + controlToolbar.setButtonState( + ControlToolbar.ControlButtons.BackwardButton, hasPrev); + controlToolbar.setButtonState( + ControlToolbar.ControlButtons.FastBackwardButton, hasPrev); + + if (!hasNext) + pauseAnimation(); + } + + /** + * Changes the look of the components owned by this controller based upon + * the InterfaceMode. If interfaceMode is set to + * InterfaceMode.ALGORITHM_DISPLAY, the calculation will be + * started and the components will be made visible. + * + * @param interfaceMode + * the current mode of the Interface + */ + public void updateDisplay(InterfaceMode interfaceMode) { + SemiRing semiring; + Operation plusOperation, dotOperation; + + if (interfaceMode == InterfaceMode.ALGORITHM_DISPLAY) { + rootStep = mainCtrl.getCalculation().calculateRootStep(); + + currentStep = rootStep; + + semiring = mainCtrl.getCalculation().getSemiring(); + plusOperation = semiring.getPlusOperation(); + dotOperation = semiring.getDotOperation(); + + matrixComponent.setVisible(true); + formulaComponent.setOperators(plusOperation + .getSymbolicRepresentation(), + (plusOperation.getNotation() == Notation.INFIX), + dotOperation.getSymbolicRepresentation(), (dotOperation + .getNotation() == Notation.INFIX)); + notifyViewsEnterHighlightMode(); + notifyViewsFirstStep(); + } else { + pauseAnimation(); + matrixComponent.setVisible(false); + + notifyViewsLeaveHighlightMode(); + setToolbarEnabled(false); + } + } + + /** + * Opens up the popUp formula window, which displays the formula in a bigger + * font. + */ + public void initFormulaWindow() { + if (mainCtrl.getInterfaceController().getDisplayMode() != InterfaceMode.ALGORITHM_DISPLAY + || (formulaWindow != null && formulaWindow.isDisplayable())) { + return; + } + SemiRing semiring; + Operation plusOperation, dotOperation; + + semiring = mainCtrl.getCalculation().getSemiring(); + plusOperation = semiring.getPlusOperation(); + dotOperation = semiring.getDotOperation(); + + int x, y; + x = formulaComponent.getLocationOnScreen().x; + y = formulaComponent.getLocationOnScreen().y + + formulaComponent.getHeight(); + + formulaWindow = new FormulaWindow(this, + formulaComponent.getGraphicsConfiguration(), + new Point(x, y), + mainCtrl.getInterfaceController().isBeamerLayout()); + formulaWindow.setOperators(plusOperation.getSymbolicRepresentation(), + (plusOperation.getNotation() == Notation.INFIX), dotOperation + .getSymbolicRepresentation(), (dotOperation + .getNotation() == Notation.INFIX)); + formulaWindow.setVisible(true); + + if (currentStep instanceof RootStep) + formulaWindow.highlightGroupStep( + (GroupStep) ((GroupStep) currentStep).getStep(0), false); + else if (currentStep instanceof GroupStep) + formulaWindow.highlightGroupStep((GroupStep) currentStep, false); + else if (currentStep instanceof AtomicStep) + formulaWindow.highlightAtomicStep((AtomicStep) currentStep, false); + } + + /** + * Notification if formula window was closed. + */ + public void formulaWindowClosed() { + removeStepHighlighting(formulaWindow); + formulaWindow = null; + } + + /** + * Closes the formula window. + */ + public void closeFormulaWindow() { + + if (formulaWindow != null) + formulaWindow.dispose(); + + formulaWindowClosed(); + } + + + /** + * Enables the controlToolbar so that it is visible in the User Interface. + * + * @param state + * true to enable toolbar, false to + * disable it. + */ + public void setToolbarEnabled(boolean state) { + controlToolbar.setEnabled(state); + } + + /** + * Turns the beamer mode on or off. + * + * @param beamerMode A boolean that says, whether the beamer mode should turn on or off. + */ + public void setBeamerMode(boolean beamerMode) { + matrixComponent.updateBeamerMode(beamerMode); + formulaComponent.updateBeamerMode(beamerMode); + if (formulaWindow != null) + formulaWindow.updateBeamerMode(beamerMode); + } + + /** + * Adds a new highlighting element to the set of highlighting elements. + * + * @param highlighting + */ + public void addStepHighlighting(StepHighlighting highlighting) { + highlightedViews.add(highlighting); + } + + /** + * Removes a new highlighting element to the set of highlighting elements. + * + * @param highlighting + */ + public void removeStepHighlighting(StepHighlighting highlighting) { + highlightedViews.remove(highlighting); + } + + private void notifyViewsEnterHighlightMode() { + for (StepHighlighting o : highlightedViews) { + o.enterHighlightMode(rootStep); + } + + updateToolbarButtons(false, true); + } + + private void notifyViewsLeaveHighlightMode() { + for (StepHighlighting o : highlightedViews) { + o.leaveHighlightMode(); + } + + updateToolbarButtons(false, true); + } + + private void notifyViewsFirstStep() { + for (StepHighlighting o : highlightedViews) { + o.highlightFirstStep((RootStep) currentStep); + } + + updateToolbarButtons(false, true); + } + + private void notifyViewsLastStep() { + for (StepHighlighting o : highlightedViews) { + o.highlightLastStep((RootStep) currentStep); + } + + updateToolbarButtons(true, false); + } + + private void notifyViewsAtomicStep(boolean isForward) { + for (StepHighlighting o : highlightedViews) { + o.highlightAtomicStep((AtomicStep) currentStep, isForward); + } + + updateToolbarButtons(true, true); + } + + private void notifyViewsGroupStep(boolean isForward) { + for (StepHighlighting o : highlightedViews) { + o.highlightGroupStep((GroupStep) currentStep, isForward); + } + + updateToolbarButtons(true, true); + } + + /** + * Gets the event "next Step" of the Components, which are controlled by + * this Controller, and send it up to the MainController, which can transfer + * it to the Core. + */ + public void nextStep() { + Step nextStep; + + // Start + if (currentStep == rootStep) { + currentStep = ((GroupStep) rootStep.getStep(0)).getStep(0); + notifyViewsAtomicStep(true); + + return; + } + + // Entering group step + if (currentStep.getGroupStep() == rootStep) { + currentStep = ((GroupStep) currentStep).getStep(0); + notifyViewsAtomicStep(true); + + return; + } + + nextStep = currentStep.getGroupStep().getStepAfterStep(currentStep); + + // Reached the end + if (nextStep == null) { + currentStep = rootStep; + notifyViewsLastStep(); + return; + } + + // Changing to the next group step + if (nextStep instanceof GroupStep) { + currentStep = nextStep; + notifyViewsGroupStep(true); + return; + } + + // Changing atomic step + currentStep = nextStep; + notifyViewsAtomicStep(true); + } + + /** + * Gets the event "previous Step" of the Components, which are controlled by + * this Controller, and send it up to the MainController, which can transfer + * it to the Core. + */ + public void previousStep() { + Step prevStep; + + // End + if (currentStep == rootStep) { + int rootStepCount; + int lastCount; + GroupStep lastGroupStep; + + rootStepCount = rootStep.getStepCount(); + lastGroupStep = ((GroupStep) rootStep.getStep(rootStepCount - 1)); + lastCount = lastGroupStep.getStepCount(); + + currentStep = lastGroupStep.getStep(lastCount - 1); + notifyViewsAtomicStep(false); + + return; + } + + // Entering (previous) group step + if (currentStep.getGroupStep() == rootStep) { + GroupStep currentGroupStep; + + currentGroupStep = (GroupStep) currentStep; + currentGroupStep = (GroupStep) currentStep.getGroupStep() + .getStepBeforeStep(currentGroupStep); + + // Reached the start + if (currentGroupStep == null) { + currentStep = rootStep; + notifyViewsFirstStep(); + return; + } + + currentStep = currentGroupStep.getStep(currentGroupStep + .getStepCount() - 1); + notifyViewsAtomicStep(false); + + return; + } + + prevStep = currentStep.getGroupStep().getStepBeforeStep(currentStep); + + // Reached the start + if (prevStep == null) { + currentStep = rootStep; + notifyViewsFirstStep(); + return; + } + + // Changing to the previous group step + if (prevStep instanceof GroupStep) { + currentStep = currentStep.getGroupStep(); + notifyViewsGroupStep(false); + return; + } + + // Changing atomic step + currentStep = prevStep; + notifyViewsAtomicStep(false); + } + + /** + * Gets the event "next GroupStep" from the Components, which are controlled + * by this Controller, and send it up to the MainController, which can + * transfer it to the Core. + */ + public void nextGroupStep() { + // At the beginning + if (currentStep == rootStep) { + currentStep = rootStep.getStep(0); + notifyViewsGroupStep(true); + return; + } + + // Inside a step, just select the parent + if (currentStep.getGroupStep() != rootStep) { + currentStep = currentStep.getGroupStep(); + } + + currentStep = currentStep.getGroupStep().getStepAfterStep(currentStep); + + // Reached the end + if (currentStep == null) { + currentStep = rootStep; + notifyViewsLastStep(); + return; + } + + notifyViewsGroupStep(true); + } + + /** + * Gets the event "previous GroupStep" of the Components, which are + * controlled by this Controller, and send it up to the MainController, + * which can transfer it to the Core. + */ + public void previousGroupStep() { + // At the end + if (currentStep == rootStep) { + currentStep = rootStep.getStep(rootStep.getStepCount() - 1); + notifyViewsGroupStep(false); + return; + } + + // Inside a step, just select the parent + if (currentStep.getGroupStep() != rootStep) { + currentStep = currentStep.getGroupStep(); + notifyViewsGroupStep(false); + return; + } + + currentStep = currentStep.getGroupStep().getStepBeforeStep(currentStep); + + // Reached the start + if (currentStep == null) { + currentStep = rootStep; + notifyViewsFirstStep(); + return; + } + + notifyViewsGroupStep(false); + } + + /** + * Starts the animation, which goes through the Atomic Steps. Only the timer + * and the scheduler are set here. + */ + public void startAnimation() { + animationTimer = new Timer(); + timerTask = new AnimationTimerTask(); + + animationTimer.schedule(timerTask, 0, 1000); + + controlToolbar.toggleAnimationState(false); + } + + /** + * Pauses the animation. The timer is cancelled. + */ + public void pauseAnimation() { + if (animationTimer == null) + return; + + animationTimer.cancel(); + animationTimer.purge(); + + controlToolbar.toggleAnimationState(true); + } + + private class AnimationTimerTask extends TimerTask { + + @Override + public void run() { + nextStep(); + } + + } + +} diff --git a/src/org/jalgo/module/app/controller/CVS/Entries b/src/org/jalgo/module/app/controller/CVS/Entries new file mode 100644 index 0000000..ebe6a44 --- /dev/null +++ b/src/org/jalgo/module/app/controller/CVS/Entries @@ -0,0 +1,10 @@ +/AlgorithmController.java/1.1/Wed Oct 29 18:05:25 2008// +/GraphActionListener.java/1.1/Wed Oct 29 18:05:25 2008// +/GraphController.java/1.1/Wed Oct 29 18:05:25 2008// +/GraphObserver.java/1.1/Wed Oct 29 18:05:25 2008// +/InterfaceController.java/1.1/Wed Oct 29 18:05:25 2008// +/InterfaceMode.java/1.1/Wed Oct 29 18:05:25 2008// +/MainController.java/1.1/Wed Oct 29 18:05:25 2008// +/SemiringController.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// +D/undoRedo//// diff --git a/src/org/jalgo/module/app/controller/CVS/Repository b/src/org/jalgo/module/app/controller/CVS/Repository new file mode 100644 index 0000000..490a4b7 --- /dev/null +++ b/src/org/jalgo/module/app/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/controller diff --git a/src/org/jalgo/module/app/controller/CVS/Root b/src/org/jalgo/module/app/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/controller/GraphActionListener.java b/src/org/jalgo/module/app/controller/GraphActionListener.java new file mode 100644 index 0000000..ceb661a --- /dev/null +++ b/src/org/jalgo/module/app/controller/GraphActionListener.java @@ -0,0 +1,237 @@ +package org.jalgo.module.app.controller; + +import java.awt.geom.Point2D; + +import org.jalgo.module.app.controller.undoRedo.UndoManager; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; + +/** + * This interface is used for notifying changes made in the graph (core, + * GraphComponent or GraphTextComponent) to the + * core and the components which display the graph. + * + */ +public interface GraphActionListener { + + /** + * Returns the graph all actions below deal with. + * + * @return the graph of the listener + */ + public Graph getGraph(); + + /** + * Returns the data type of all edge weights in the graph. + * + * @return the weight data type + */ + public Class getDataType(); + + /** + * Adds newObserver to the listener as observer, notifying it + * of all changes done to the graph (also initiated by itself). + * + * @param newObserver + * the observer to add + */ + public void addGraphObserver(GraphObserver newObserver); + + /** + * Provides the mode that says which element is edited. + */ + public enum EditMode { + /** + * No element is currently edited. + */ + NONE, + /** + * A node is edited. + */ + EDITING_NODES, + /** + * A edge is edited. + */ + EDITING_EDGES, + /** + * The weight of an edge is edited. + */ + EDITING_WEIGHT, + }; + + /** + * Gets the current edit mode. + * + * @return the current edit mode. + */ + public EditMode getEditMode(); + + /** + * Sets the current edit mode. + * + * @param mode + * the new edit mode. + */ + public void setEditMode(EditMode mode); + + /** + * Gets the node that is currently selected. + * + * @return the currently selected node. If no node is selected, + * null is returned. + */ + public Node getSelectedNode(); + + /** + * Sets the currently selected node. + * + * @param node + * the currently selected node. If no node is selected, + * node has to be set to null. + */ + public void setSelectedNode(Node node); + + /** + * Gets the edge that is currently selected. + * + * @return the currently selected edge. If no edge is selected, + * null is returned. + */ + public Edge getSelectedEdge(); + + /** + * Sets the currently selected edge. + * + * @param edge + * the currently selected edge. If no edge is selected, + * edge has to be set to null. + */ + public void setSelectedEdge(Edge edge); + + /** + * Begins grouping of change notifications. Makes only sense when editing + * multiple things. + * + * @see #endEditing() + */ + public void beginEditing(); + + /** + * Ends grouping of change notifications. + * + * @see #beginEditing() + */ + public void endEditing(); + + /* + * NODES + * + */ + + /** + * Adds a new node to the graph. + * + * @return the new node. + */ + public Node addNode(); + + /** + * Adds a new node to the graph, setting the given position. + * + * @param position + * the position of the new node + */ + public Node addNode(Point2D position); + + /** + * Changes the position of the given node to position. + * + * @param node + * the node to change + * @param position + * the position to set + */ + public void alterNodePosition(Node node, Point2D position); + + /** + * Removes the given node from the graph. This also removes all attached + * edges as well. + * + * @param node + * the node to remove + */ + public void removeNode(Node node); + + /* + * EDGES + * + */ + + /** + * Adds a edge between the given start and end node to the graph. + * + * @param start + * the start node + * @param end + * the end node + */ + public Edge addEdge(Node start, Node end); + + /** + * Adds a edge between the given start and end node to the graph, setting + * it's weight to weight. + * + * @param start + * the start node + * @param end + * the end node + * @param weight + * the weight for the new edge + */ + public Edge addEdge(Node start, Node end, DataType weight); + + /** + * Changes the weight of the given edge to weight. + * + * @param edge + * the edge to change + * @param weight + * the weight to set + */ + public void alterEdgeWeight(Edge edge, DataType weight); + + /** + * Removes the given edge from the graph. + * + * @param edge + * the edge to remove + */ + public void removeEdge(Edge edge); + + /** + * Gets the undo manager to provide undo redo actions. + * + * @return The undo manager. + */ + public UndoManager getUndoManager(); + + /** + * Sets the position of a node before dragging to remember for undo/redo. + * + * @param previousPosition + * the previousPosition to set + */ + public void setPreviousPosition(Point2D previousPosition); + + /** + * Method which is called when a dragged node has reached its actual + * position. + * + * @param node The node which was dragged. + * @param point The final position. + */ + public void setFinalNodePosition(Node node, Point2D point); + +} diff --git a/src/org/jalgo/module/app/controller/GraphController.java b/src/org/jalgo/module/app/controller/GraphController.java new file mode 100644 index 0000000..899e6e3 --- /dev/null +++ b/src/org/jalgo/module/app/controller/GraphController.java @@ -0,0 +1,753 @@ +package org.jalgo.module.app.controller; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Point; +import java.awt.geom.Point2D; +import java.util.HashSet; +import java.util.Set; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; + +import org.jalgo.module.app.controller.undoRedo.UndoManager; +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.view.graph.EditToolbar; +import org.jalgo.module.app.view.graph.GraphComponent; +import org.jalgo.module.app.view.graph.GraphTextComponent; +import org.jalgo.module.app.view.run.MatrixPreviewComponent; + +/** + * Controls the three Panels, which are on the right and left panel of the User + * Interface. The GraphController initializes the four components + * which are involved in these Panels. + */ +public class GraphController implements GraphActionListener { + + /** + * Connection to the MainController to communicate with the Core and the + * InterfaceController. + */ + private MainController mainCtrl; + + // Components, in which the process of editing the graph is shown. + private EditToolbar editToolbar; + private MatrixPreviewComponent matrixPreviewComponent; + private GraphTextComponent graphTextComponent; + private GraphComponent graphComponent; + + /** + * To remember the state of the components + */ + private boolean isSetUp; + private boolean notificationGroupingActive; + private boolean groupedChangeDone; + + private EditMode editMode; + private EditMode oldEditMode; + private Node selectedNode; + private Edge selectedEdge; + + // The Panels, which are initialized by the InterfaceController + private JPanel textualGraphPanel, graphPanel, graphToolPanel; + + private Set observers; + + private UndoManager undoManager; + + private boolean beamerMode; + private InterfaceMode interfaceMode; + + Point2D previousPosition; + + /** + * Instantiates the three Panels, which are in the right panel of the User + * Interface (in InterfaceMode.GRAPH_EDITING. He also + * initializes the four components involved in the panels. + */ + public GraphController(MainController mainController, + JPanel textualGraphPanel, JPanel graphPanel, JPanel graphToolPanel) { + mainCtrl = mainController; + + // Init properties + this.textualGraphPanel = textualGraphPanel; + this.graphPanel = graphPanel; + this.graphToolPanel = graphToolPanel; + + this.observers = new HashSet(); + mainController.getInterfaceController().getModeSwitchComponent() + .setGraphActionListener(this); + + this.isSetUp = false; + this.beamerMode = false; + this.notificationGroupingActive = false; + this.editMode = EditMode.EDITING_NODES; + + this.undoManager = new UndoManager(this); + + // Init interface + initInterface(); + } + + /** + * Initializes the graph editing View with components for the graph, the + * textual representation, the toolbar and the matrix preview. + */ + private void initInterface() { + BorderLayout layout; + + editToolbar = new EditToolbar(this); + matrixPreviewComponent = new MatrixPreviewComponent(this); + graphTextComponent = new GraphTextComponent(this); + graphComponent = new GraphComponent(this); + + layout = new BorderLayout(); + textualGraphPanel.setLayout(layout); + textualGraphPanel.add(graphTextComponent, BorderLayout.CENTER); + textualGraphPanel.add(matrixPreviewComponent, BorderLayout.SOUTH); + + matrixPreviewComponent.setBorder(BorderFactory.createMatteBorder(1, -1, + 1, 1, Color.LIGHT_GRAY)); + + graphPanel.add(graphComponent); + graphToolPanel.add(editToolbar); + + mainCtrl.getAlgorithmController().addStepHighlighting(graphComponent); + } + + /** + * Changes the look of the components owned by this controller based upon + * the InterfaceMode. If interfaceMode is set to + * InterfaceMode.GRAPH_EDITING, the calculation will be + * started and the components will be made visible. + * + * @param interfaceMode + * the current mode of the Interface + */ + public void updateDisplay(InterfaceMode interfaceMode) { + this.interfaceMode = interfaceMode; + + if (interfaceMode == InterfaceMode.GRAPH_EDITING && !isSetUp) { + DataType dataType; + isSetUp = true; + + try { + dataType = mainCtrl.getCalculation().getSemiring().getType() + .newInstance(); + editToolbar.setSpecialCharButtons(dataType + .getSpecialCharacter()); + } catch (InstantiationException e) { + } catch (IllegalAccessException e) { + } + + editToolbar.setGraphActionListener(this); + graphTextComponent.setGraphActionListener(this); + graphComponent.setGraphActionListener(this); + } + + // Remember the last edit mode but disable editing while the algorithm + // runs + if (interfaceMode == InterfaceMode.GRAPH_EDITING) { + if (oldEditMode == null || oldEditMode == EditMode.NONE) + oldEditMode = EditMode.EDITING_NODES; + + setEditMode(oldEditMode); + graphComponent.highlightAtomicStep(null, false); + } else { + oldEditMode = getEditMode(); + setEditMode(EditMode.NONE); + } + + for (GraphObserver observer : observers) { + observer.graphUpdated(); + } + + updateDynamicScaling(); + } + + /** + * Gets the current graph from the calculation in the core. + * + * @return the current Graph. + */ + public Graph getGraph() { + return mainCtrl.getCalculation().getGraph(); + } + + /** + * Gets the data type of all edge weights in the graph. + * + * @return the weight data type + */ + public Class getDataType() { + return mainCtrl.getCalculation().getSemiring().getType(); + } + + /** + * Gets the initial Matrix (adjacency matrix). This matrix is needed for + * displaying it in the graph editing mode. + * + * @return the initial Matrix (adjacency matrix). + */ + public Matrix getInitialMatrix() { + return mainCtrl.getCalculation().calculateInitialMatrix(); + } + + /** + * Adds newObserver to the list of graph observers, which is + * managed in this controller. + * + * @param newObserver + * the observer to be added. + */ + public void addGraphObserver(GraphObserver newObserver) { + observers.add(newObserver); + } + + /** + * Enables/Disables the editToolbar (to make it + * visible/invisible) in the User Interface. The use of this method depends + * on the currentDisplaymode. + * + * @param state + * true to enable it, false to + * disable it. + * @param redo + * The state of the undo button. + * @param undo + * The state of the redo button. + */ + public void setToolbarEnabled(boolean state, boolean undo, boolean redo) { + editToolbar.setEnabled(state, undo, redo); + } + + /** + * If the graphTextComponent currently has focus, + * true is returned, false otherwise. + * + * @return true, if the graphTextComponent + * currently has focus. + */ + public boolean getGraphTextComponentFocusState() { + return graphTextComponent.isFocusOwner(); + } + + /** + * Changes the font of the current GraphTextComponent by calling + * graphTextComponent.setTextAreaFont(). + * + * @see GraphTextComponent#setTextAreaFont() + */ + public void changeTextComponentFont() { + graphTextComponent.setTextAreaFont(); + } + + public EditMode getEditMode() { + return editMode; + } + + public void setEditMode(EditMode mode) { + editMode = mode; + } + + private void updateDynamicScaling() { + if (interfaceMode == InterfaceMode.ALGORITHM_DISPLAY && beamerMode) + graphComponent.setDynamicScaling(true); + else + graphComponent.setDynamicScaling(false); + } + + /** + * Turns the beamer mode on or off. + * + * @param beamerMode A boolean which should be true to enable the beamer mode. + */ + public void setBeamerMode(boolean beamerMode){ + this.beamerMode = beamerMode; + updateDynamicScaling(); + + graphComponent.updateBeamerMode(beamerMode); + graphTextComponent.updateBeamerMode(beamerMode); + matrixPreviewComponent.updateBeamerMode(beamerMode); + } + + public Node getSelectedNode() { + return selectedNode; + } + + public void setSelectedNode(Node node) { + selectedNode = node; + selectedEdge = null; + + for (GraphObserver o : observers) + o.graphSelectionChanged(); + + editToolbar.updateButtons(); + } + + public Edge getSelectedEdge() { + return selectedEdge; + } + + public void setSelectedEdge(Edge edge) { + selectedEdge = edge; + selectedNode = null; + + for (GraphObserver o : observers) + o.graphSelectionChanged(); + + editToolbar.updateButtons(); + } + + public void beginEditing() { + if (!notificationGroupingActive) { + notificationGroupingActive = true; + groupedChangeDone = false; + } + } + + public void endEditing() { + if (notificationGroupingActive && groupedChangeDone) { + notificationGroupingActive = false; + + for (GraphObserver o : observers) + o.graphUpdated(); + } + } + + public Node addNode() { + Point position = getAppropriateNodePosition(); + return addNode(position); + } + + /** + * Finds a place for a new node with enough distance to other nodes and the + * borders of the graph component. + * + * @return an appropriate Position for a new Node in the graph component. + */ + private Point getAppropriateNodePosition() { + int paintAreaDimensions = 900; + int distanceBetweenNodes = 60; + int fieldWidth = 300; + boolean positionFound = false; + int newX = 0; + int newY = 0; + + // divide the paint area into a 3 x 3 field of subareas + int[][] area = { { 20, 20 }, { 170, 20 }, { 320, 20 }, { 320, 170 }, + { 320, 320 }, { 170, 320 }, { 20, 320 }, { 20, 170 }, + { 170, 170 } }; + Point pos = new Point(); + Set nodes = getGraph().getNodes(); + + // Find an empty area + if (nodes.isEmpty()) { + newX = (int) (Math.random() * fieldWidth + area[0][0]); + newY = (int) (Math.random() * fieldWidth + area[0][1]); + } else { + int i = 0; + while (i < area.length && !positionFound) { + boolean areaTaken = false; + for (Node existingNode : nodes) { + if (((existingNode.getLocation().getX() > area[i][0]) && existingNode + .getLocation().getX() < (area[i][0] + fieldWidth)) + && (existingNode.getLocation().getY() > area[i][1]) + && existingNode.getLocation().getY() < (area[i][1] + fieldWidth)) { + areaTaken = true; + break; + } + } + if (!areaTaken) { + newX = (int) (Math.random() * fieldWidth + area[i][0]); + newY = (int) (Math.random() * fieldWidth + area[i][1]); + positionFound = true; + } + i++; + } + } + // if no empty area found + if (!positionFound) { + for (int i = 0; i < 10; i++) { + for (Node existingNode : nodes) { + if (newX > (existingNode.getLocation().getX() - distanceBetweenNodes) + || newX < (existingNode.getLocation().getX() + distanceBetweenNodes)) { + newX = (int) (Math.random() * paintAreaDimensions + 20); + } + if (newY > (existingNode.getLocation().getY() - distanceBetweenNodes) + || newY < (existingNode.getLocation().getY() + distanceBetweenNodes)) { + newY = (int) (Math.random() * paintAreaDimensions + 20); + } + } + } + } + pos.x = newX; + pos.y = newY; + return pos; + } + + /** + * Adds a node to the model, without any checking and undo tracking. Informs + * all observers of change. + * + * @param node + * the node to be added. + */ + public void addNode(Node node) { + // set the runToggle enabled + if (getGraph().getNodes().isEmpty()) + mainCtrl.getInterfaceController().getModeSwitchComponent() + .setCurrentModeButtonEnable( + mainCtrl.getInterfaceController().getDisplayMode(), + false); + + getGraph().addNode(node); + + setSelectedNode(node); + + for (GraphObserver o : observers) { + o.nodeAdded(getGraph(), node); + o.graphUpdated(); + o.graphSelectionChanged(); + } + mainCtrl.setChangesToSave(); + } + + /** + * This method is called by undo actions. Adds a node to the model, adjusts + * the node IDs. Informs all observers of change. + */ + public void addUndoNode(Node node) { + + // consider that this is the special undo adding + getGraph().addUndoNode(node); + + for (GraphObserver o : observers) { + o.nodeAdded(getGraph(), node); + o.graphUpdated(); + } + mainCtrl.setChangesToSave(); + } + + /** + * Adds the node on a specific position. Also adds an Undo-Action. + */ + public Node addNode(Point2D position) { + Node node; + + node = getGraph().newNode(false); + node.setLocation(position); + + addNode(node); + + undoManager.addUndoAddAction(node); + editToolbar.setUndoState(); + + return node; + } + + /** + * Changes the position of the node. + * + * @param node + * the node of which the position should be changed. + * @param position + * the new coordinates for node. + */ + public void alterNodePosition(Node node, Point2D position) { + setNodePosition(node, position); + } + + /** + * Method which is called when a dragged node has reached its actual + * position. + * + * @param node + * the dragged node. + * @param position + * the final position after dragging node. + */ + public void setFinalNodePosition(Node node, Point2D position) { + setNodePosition(node, position); + + undoManager.addUndoNodePositionAlteredAction(node, previousPosition); + editToolbar.setUndoState(); + } + + /** + * Sets the node position by undo actions. + * + * @param node + * @param position + */ + public void alterUndoNodePosition(Node node, Point2D position) { + setNodePosition(node, position); + } + + /** + * Sets the position of the node. Informs all graphObservers of this change. + * + * @param node + * the node. + * @param position + * the new position. + */ + public void setNodePosition(Node node, Point2D position) { + node.setLocation(position); + + for (GraphObserver o : observers) { + o.nodeAltered(getGraph(), node); + + if (!notificationGroupingActive) + o.graphUpdated(); + else + groupedChangeDone = true; + } + mainCtrl.setChangesToSave(); + } + + public void removeNode(Node node) { + Graph graph = getGraph(); + + Set relatedEdges = new HashSet(); + + for (Edge e : graph.getEdges()) { + if (e.getBegin() == node || e.getEnd() == node) { + relatedEdges.add(e); + } + } + + doRemoveNode(node); + undoManager.addUndoRemoveAction(node, relatedEdges); + editToolbar.setUndoState(); + } + + /** + * Removes a node without affecting the undo/redo manager. + * + * @param node + * The node to remove. + */ + public void doRemoveNode(Node node) { + Set oldEdges; + Graph graph; + + graph = getGraph(); + + // Remember edges that will be removed + oldEdges = new HashSet(); + for (Edge e : graph.getEdges()) { + if (e.getBegin() == node || e.getEnd() == node) { + oldEdges.add(e); + } + } + + // Actually remove the node + // if (node == selectedNode) + graph.removeNode(node); + + if (node == selectedNode) { + selectedNode = null; + // setSelectedNode(graph.getNode(graph.getBiggestID())); + } + + // set save status + if (graph.getNodes().isEmpty()) { + mainCtrl.setNothingToSave(); + } else { + mainCtrl.setChangesToSave(); + } + + // Inform all observers + for (GraphObserver o : observers) { + for (Edge e : oldEdges) { + o.edgeRemoved(graph, e); + } + o.nodeRemoved(graph, node); + + if (!notificationGroupingActive) + o.graphUpdated(); + else + groupedChangeDone = true; + } + + // set the runToggle disable, when there is no edge or node + if (graph.getEdges().isEmpty()) + mainCtrl.getInterfaceController().getModeSwitchComponent() + .setCurrentModeButtonEnable( + mainCtrl.getInterfaceController().getDisplayMode(), + true); + + } + + public Edge addEdge(Node start, Node end) { + DataType weight; + + weight = null; + + try { + weight = getDataType().newInstance(); + } catch (InstantiationException e) { + } catch (IllegalAccessException e) { + } + + return addEdge(start, end, weight); + } + + /** + * Method called by the undo actions. + */ + public void addEdge(Edge edge) { + // set the runToggle enabled + if (getGraph().getEdges().isEmpty()) + mainCtrl.getInterfaceController().getModeSwitchComponent() + .setCurrentModeButtonEnable( + mainCtrl.getInterfaceController().getDisplayMode(), + false); + + getGraph().addEdge(edge); + + for (GraphObserver o : observers) { + o.edgeAdded(getGraph(), edge); + + if (!notificationGroupingActive) + o.graphUpdated(); + else + groupedChangeDone = true; + } + mainCtrl.setChangesToSave(); + } + + public Edge addEdge(Node start, Node end, DataType weight) { + Edge edge; + + edge = getGraph().newEdge(start, end, weight, false); + addEdge(edge); + + undoManager.addUndoAddAction(edge); + editToolbar.setUndoState(); + + return edge; + } + + public void alterEdgeWeight(Edge edge, DataType weight) { + DataType previousWeight = edge.getWeight(); + setEdgeWeight(edge, weight); + + undoManager.addUndoWeightAlteredAction(edge, previousWeight); + editToolbar.setUndoState(); + } + + /** + * Sets the edge weight by undo actions. + * + * @param edge + * the edge where the weight should be changed. + * @param weight + * the new weight. + */ + public void alterUndoEdgeWeight(Edge edge, DataType weight) { + setEdgeWeight(edge, weight); + } + + /** + * Sets the weight of the edge. + * + * @param edge + * the edge where the weight should be changed. + * @param weight + * the new weight of type DataType. + */ + public void setEdgeWeight(Edge edge, DataType weight) { + edge.setWeight(weight); + + for (GraphObserver o : observers) { + o.edgeAltered(getGraph(), edge); + + if (!notificationGroupingActive) + o.graphUpdated(); + else + groupedChangeDone = true; + } + mainCtrl.setChangesToSave(); + } + + public void removeEdge(Edge edge) { + + undoManager.addUndoRemoveAction(edge); + editToolbar.setUndoState(); + + doRemoveEdge(edge); + } + + /** + * Removes an edge without affecting the undo/redo manager. + * + * @param edge + * The edge to remove. + */ + public void doRemoveEdge(Edge edge) { + Graph graph; + + graph = getGraph(); + + // removes the edge + graph.removeEdge(edge); + if (edge == selectedEdge) + selectedEdge = null; + + mainCtrl.setChangesToSave(); + + // Inform all observers + for (GraphObserver o : observers) { + o.edgeRemoved(graph, edge); + + if (!notificationGroupingActive) + o.graphUpdated(); + else + groupedChangeDone = true; + } + + // set the runToggle disable, when there is no Edge or Node + if (graph.getNodes().isEmpty() || graph.getEdges().isEmpty()) + mainCtrl.getInterfaceController().getModeSwitchComponent() + .setCurrentModeButtonEnable( + mainCtrl.getInterfaceController().getDisplayMode(), + true); + + } + + /** + * Gets the current undoManager. + * + * @return the current undoManager. + */ + public UndoManager getUndoManager() { + return undoManager; + } + + /** + * Sets the global UndoManager. + * + * @param undoManager + * the new UndoManager. + */ + public void setUndoManager(UndoManager undoManager) { + this.undoManager = undoManager; + } + + /** + * Sets the position of a node before dragging to remember for undo/redo. + * + * @param previousPosition + * the previousPosition to set + */ + public void setPreviousPosition(Point2D previousPosition) { + this.previousPosition = previousPosition; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/controller/GraphObserver.java b/src/org/jalgo/module/app/controller/GraphObserver.java new file mode 100644 index 0000000..38734bd --- /dev/null +++ b/src/org/jalgo/module/app/controller/GraphObserver.java @@ -0,0 +1,89 @@ +package org.jalgo.module.app.controller; + +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; + +/** + * This interface is used for notifying all components which need to be + * consistent with the graph. Every time a change is made in the graph, the + * GraphController notifies all components that something in the + * graph has changed. It is part of the GoF Observer-Pattern. + */ +public interface GraphObserver { + + /** + * Notifies components that a node has been added to the graph. + * + * @param graph + * the current graph. + * @param node + * the new node. + */ + public void nodeAdded(Graph graph, Node node); + + /** + * Notifies components that a node has been altered, i.e. when its + * position has been changed. + * + * @param graph + * the current graph. + * @param node + * the altered node. + */ + public void nodeAltered(Graph graph, Node node); + + /** + * Notifies components that a node has been removed from the graph. + * + * @param graph + * the current graph. + * @param node + * the node that has to be removed from all components. + */ + public void nodeRemoved(Graph graph, Node node); + + /** + * Notifies components that an edge has been added to the graph. + * + * @param graph + * the current graph. + * @param edge + * the new edge. + */ + public void edgeAdded(Graph graph, Edge edge); + + /** + * Notifies components that an edge has been altered, i.e. when its weight + * has been changed. + * + * @param graph + * the current graph. + * @param edge + * the altered edge. + */ + public void edgeAltered(Graph graph, Edge edge); + + /** + * Notifies components that an edge has been removed from the graph. + * + * @param graph + * the current graph. + * @param edge + * the edge that has to be removed from all components. + */ + public void edgeRemoved(Graph graph, Edge edge); + + /** + * Notifies components that something has been changed in the graph (when a + * node/edge has been added, removed or altered). + */ + public void graphUpdated(); + + /** + * Notifies components that the focus of a graph element (node or edge) has + * be changed, i.e. whenever an element has been colored red in the graph + * editor. + */ + public void graphSelectionChanged(); +} diff --git a/src/org/jalgo/module/app/controller/InterfaceController.java b/src/org/jalgo/module/app/controller/InterfaceController.java new file mode 100644 index 0000000..e26bd84 --- /dev/null +++ b/src/org/jalgo/module/app/controller/InterfaceController.java @@ -0,0 +1,428 @@ +package org.jalgo.module.app.controller; + +import java.awt.*; + +import javax.swing.*; + +import org.jalgo.module.app.view.graph.ModeSwitchComponent; + +/** + * Initializes the superior panels for the allocation of the user interface. The + * InterfaceController coordinates the main actions of the user + * interface. + */ +public class InterfaceController { + + // Connection to the MainController to communicate with the core and the + // specific controllers. + private MainController mainCtrl; + + // Panels and Components, which the InterfaceController initializes. + private JToolBar toolBar; + private JMenu menu; + private JPanel graphPanel, graphToolPanel; + private JPanel formalGraphPanel, algorithmPanel, algorithmToolPanel; + private JPanel semiringPanel; + private ModeSwitchComponent modePanel; + + // Superior panels, which divide the User Interface. + private JComponent rootPanel; + private JPanel headPanel; + private JPanel workPanel; + private JPanel leftPanel, rightPanel; + private BorderLayout leftLayout, rightLayout; + private BorderLayout beamerLayout; + private BorderLayout layout; + private boolean isBeamerLayout; + + // Setting by this Controller the current display state. + private InterfaceMode currentDisplay; + + /** + * Instantiates the jAlgo Module with a "basic interface": a menu, the + * toolbar and a rootpane for all other components) + * + * @param menu + * the menu entry for this module. + * @param toolbar + * the toolbar on the button that can be used in this module. + * + * @param rootPane + * the pane to put all components in. + * @param mainCtrl + * connection to the MainController + */ + public InterfaceController(JMenu menu, + JToolBar toolbar, + JComponent rootPane, + MainController mainCtrl + ) + { + this.mainCtrl = mainCtrl; + this.rootPanel = rootPane; + this.menu = menu; + this.toolBar = toolbar; + + isBeamerLayout = false; + + initLayout(); + } + + /** + * Initializes the main panels and arranges them in the layout. + * + */ + private void initLayout() { + + workPanel = new JPanel(); + + leftPanel = new JPanel(); + graphPanel = new JPanel(); + graphToolPanel = new JPanel(); + + rightPanel = new JPanel(); + algorithmPanel = new JPanel(); + algorithmToolPanel = new JPanel(); + formalGraphPanel = new JPanel(); + + headPanel = new JPanel(); + semiringPanel = new JPanel(); + modePanel = new ModeSwitchComponent(mainCtrl, menu); + + // Arrange layouts + beamerLayout = new BorderLayout(); + layout = new BorderLayout(); + beamerLayout.setHgap(7); + rootPanel.setLayout(layout); + + rootPanel.add(workPanel, BorderLayout.CENTER); + rootPanel.add(headPanel, BorderLayout.NORTH); + + arrangeWorkPanelLayout(); + + leftLayout = new BorderLayout(); + leftPanel.setLayout(leftLayout); + leftPanel.add(graphPanel, BorderLayout.CENTER); + leftPanel.add(graphToolPanel, BorderLayout.SOUTH); + + rightLayout = new BorderLayout(); + rightPanel.setLayout(rightLayout); + rightPanel.add(semiringPanel, BorderLayout.NORTH); + rightPanel.add(algorithmPanel, BorderLayout.CENTER); + rightPanel.add(algorithmToolPanel, BorderLayout.SOUTH); + rightPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + semiringPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + layout = new BorderLayout(); + headPanel.setLayout(layout); + headPanel.add(Box.createRigidArea(new Dimension(1, 5)), + BorderLayout.NORTH); + headPanel.add(modePanel, BorderLayout.CENTER); + headPanel.add(Box.createRigidArea(new Dimension(1, 5)), + BorderLayout.SOUTH); + + // Set Borders + leftPanel.setBorder(BorderFactory.createMatteBorder(1, -1, 1, 1, + Color.LIGHT_GRAY)); + rightPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, -1, + Color.LIGHT_GRAY)); + + semiringPanel.setBorder(BorderFactory.createMatteBorder(-1, -1, 1, -1, + Color.LIGHT_GRAY)); + graphToolPanel.setBorder(BorderFactory.createMatteBorder(1, -1, -1, -1, + Color.LIGHT_GRAY)); + algorithmToolPanel.setBorder(BorderFactory.createMatteBorder(1, -1, -1, + -1, Color.LIGHT_GRAY)); + + graphPanel.setLayout(new GridLayout()); + } + + /** + * Creates a new GridLayout and assigns it to the workPanel. + */ + public void arrangeWorkPanelLayout() { + GridLayout workLayout; + workLayout = new GridLayout(1, 2); + workLayout.setHgap(7); + workPanel.setLayout(workLayout); + workPanel.add(leftPanel); + workPanel.add(rightPanel); + } + + /** + * Enables the editToolbar, so that it's invisible in the + * User Interface. The use of this method depends on the + * currentDisplaymode. + * + * @param state + * true if enabled, false if + * disabled. + */ + public void setToolbarEnabled(boolean state) { + modePanel.setToolbarEnabled(state); + } + + /** + * Method to make all panels visible again. + */ + private void makePanelsVisible() { + graphPanel.setVisible(true); + formalGraphPanel.setVisible(true); + algorithmPanel.setVisible(true); + graphToolPanel.setVisible(true); + algorithmToolPanel.setVisible(true); + modePanel.setVisible(true); + + setToolbarEnabled(true); + } + + /** + * Enables/disables all component of root recursively. + * + * @param root + * the Container in which all + * Components should be enabled/disabled. + * + * @param enabled + * true to enable all Components, + * false to disable them. + */ + private void setEnabledRecursively(Container root, boolean enabled) { + root.setEnabled(enabled); + for (Component c : root.getComponents()) { + if (c instanceof Container) + setEnabledRecursively((Container) c, enabled); + else + c.setEnabled(enabled); + } + } + + /** + * Sets SemiRingPanel visible and all other panel invisible. On this you can + * see Semiring selection. + */ + public void setSemiringLayout() { + graphPanel.setVisible(false); + formalGraphPanel.setVisible(false); + algorithmPanel.setVisible(false); + graphToolPanel.setVisible(false); + algorithmToolPanel.setVisible(false); + modePanel.setEnabled(false); + + currentDisplay = InterfaceMode.SEMIRING_EDITING; + + setToolbarEnabled(false); + mainCtrl.displayModeChanged(); + } + + /** + * Sets the panels visible depending on the currentDisplayMode. Prepare the + * Graph-Editing-Mode. + */ + public void setEditLayout() { + + boolean undo; + boolean redo; + if (currentDisplay == InterfaceMode.ALGORITHM_DISPLAY) { + rightPanel.remove(algorithmPanel); + + } + + makePanelsVisible(); + + algorithmToolPanel.setEnabled(false); + graphToolPanel.setEnabled(true); + + workPanel.remove(rightPanel); + workPanel.remove(leftPanel); + arrangeWorkPanelLayout(); + + rightPanel.add(formalGraphPanel, BorderLayout.CENTER); + rightPanel.repaint(); + rightPanel.revalidate(); + + workPanel.repaint(); + workPanel.revalidate(); + + currentDisplay = InterfaceMode.GRAPH_EDITING; + + setEnabledRecursively(algorithmToolPanel, false); + // setEnabledRecursively(graphToolPanel, true); + modePanel.setCurrentModeButtonEnable(currentDisplay, true); + + undo = mainCtrl.getGraphController().getUndoManager().isUndoable(); + redo = mainCtrl.getGraphController().getUndoManager().isRedoable(); + mainCtrl.getGraphController().setToolbarEnabled(true, undo, redo); + + mainCtrl.displayModeChanged(); + } + + /** + * Sets the panels visible depending on the currentDisplayMode. Prepare the + * Algorithm-Process-Mode. + */ + public void setAlgorithmLayout() { + + if (currentDisplay == InterfaceMode.GRAPH_EDITING) { + rightPanel.remove(formalGraphPanel); + } + + makePanelsVisible(); + algorithmToolPanel.setEnabled(true); + graphToolPanel.setEnabled(false); + + rightPanel.add(algorithmPanel, BorderLayout.CENTER); + rightPanel.repaint(); + rightPanel.revalidate(); + + if (isBeamerLayout) { + workPanel.remove(rightPanel); + workPanel.remove(leftPanel); + + BorderLayout beamerLayout = new BorderLayout(); + + workPanel.setLayout(beamerLayout); + + workPanel.add(leftPanel, BorderLayout.WEST); + workPanel.add(rightPanel, BorderLayout.CENTER); + beamerLayout.setVgap(10); + + } + + else { + workPanel.remove(rightPanel); + workPanel.remove(leftPanel); + + arrangeWorkPanelLayout(); + } + + workPanel.repaint(); + workPanel.revalidate(); + + currentDisplay = InterfaceMode.ALGORITHM_DISPLAY; + modePanel.setCurrentModeButtonEnable(currentDisplay, false); + + setEnabledRecursively(algorithmToolPanel, true); + setEnabledRecursively(graphToolPanel, false); + + mainCtrl.displayModeChanged(); + + } + + /** + * Changes the layout after the beamerLayout has been switched on or off. + */ + public void changeLayout() { + if (isBeamerLayout) { + mainCtrl.getGraphController().changeTextComponentFont(); + } else { + mainCtrl.getGraphController().changeTextComponentFont(); + } + + if (currentDisplay == InterfaceMode.ALGORITHM_DISPLAY) { + setAlgorithmLayout(); + } else if (currentDisplay == InterfaceMode.GRAPH_EDITING) { + setEditLayout(); + } else if (currentDisplay == InterfaceMode.SEMIRING_EDITING) { + setSemiringLayout(); + } + } + + /** + * Gets the panel of the semiring. + * + * @return The semiring panel. + */ + public JPanel getSemiringPanel() { + return semiringPanel; + } + + /** + * Gets the panel of the formular. + * + * @return The formular panel. + */ + public JPanel getFormalGraphPanel() { + return formalGraphPanel; + } + + /** + * Gets the panel of the graph. + * + * @return The graph panel. + */ + public JPanel getGraphPanel() { + return graphPanel; + } + + /** + * Gets the panel of the graph tools. + * + * @return The graph tool panel. + */ + public JPanel getGraphToolPanel() { + return graphToolPanel; + } + + /** + * Gets the panel of the algorithm. + * + * @return The algorithm panel. + */ + public JPanel getAlgorithmPanel() { + return algorithmPanel; + } + + /** + * Gets the panel of the algorithm tools. + * + * @return The algorithm tool panel. + */ + public JPanel getAlgorithmToolPanel() { + return algorithmToolPanel; + } + + /** + * Gets the current display mode. This can be SEMIRING_EDITING, GRAPH_EDITING or ALGORITHM_DISPLAY. + * + * @return The display mode. + */ + public InterfaceMode getDisplayMode() { + return currentDisplay; + } + + /** + * Gets the component which displays the toggle button for switching between editing and algorithm mode. + * + * @return The mode switch component. + */ + public ModeSwitchComponent getModeSwitchComponent() { + return modePanel; + } + + /** + * Returns the current beamerLayout state. + * + * @return true if beamerLayout is enabled, + * false otherwise. + */ + public boolean isBeamerLayout() { + return isBeamerLayout; + } + + /** + * Sets the beamerLayout state. + * + * @param layout + * if true, the beamerLayout will be enabled, if + * false, it will be disabled. + */ + public void setBeamerLayout(boolean layout) { + isBeamerLayout = layout; + changeLayout(); + mainCtrl.getGraphController().setBeamerMode(isBeamerLayout); + mainCtrl.getSemiringController().setBeamerMode(isBeamerLayout); + mainCtrl.getAlgorithmController().setBeamerMode(isBeamerLayout); + } + +} diff --git a/src/org/jalgo/module/app/controller/InterfaceMode.java b/src/org/jalgo/module/app/controller/InterfaceMode.java new file mode 100644 index 0000000..69014a6 --- /dev/null +++ b/src/org/jalgo/module/app/controller/InterfaceMode.java @@ -0,0 +1,22 @@ +package org.jalgo.module.app.controller; + +/** + * Provides the current state of the module. First, a Semiring is selected (mode + * SEMIRING_EDITING), then the Graph is edited (GRAPH_EDITING), and then the + * Aho-Algorithm is run and visualized (ALGORITHM_DISPLAY). The user can switch + * between the last two modes. + */ +public enum InterfaceMode { + /** + * Selection of a semiring. + */ + SEMIRING_EDITING, + /** + * Editing of the graph. + */ + GRAPH_EDITING, + /** + * Running of the aho algorithm. + */ + ALGORITHM_DISPLAY +} diff --git a/src/org/jalgo/module/app/controller/MainController.java b/src/org/jalgo/module/app/controller/MainController.java new file mode 100644 index 0000000..5e09f28 --- /dev/null +++ b/src/org/jalgo/module/app/controller/MainController.java @@ -0,0 +1,291 @@ +package org.jalgo.module.app.controller; + +import java.awt.geom.Point2D; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.app.ModuleConnector; +import org.jalgo.module.app.core.AvailableSemiRings; +import org.jalgo.module.app.core.Calculation; +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.dataType.formalLanguage.FormalLanguage; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; + +/** + * The MainController is the communicator between the specific controllers and + * the InterfaceController and observes also the actions, which he gets from the + * specific controllers and the InterfaceController, to send them to the core. + * Also the core gives the Information to him, so that he can arrange the + * transfer to the other controller. Furthermore the MainController initializes + * all controller. + */ +public class MainController { + + private AlgorithmController algorithmCtrl; + + private GraphController graphCtrl; + + private SemiringController semiringCtrl; + + private InterfaceController interfaceCtrl; + + // Class in the core to get all information from the controller. + private Calculation calculation; + + // Connector to JAlgo + private ModuleConnector moduleConnector; + + /** + * Creates a main controller which holds all other controller. + * + * @param module The module connector as the link to j-Algo. + */ + public MainController(ModuleConnector module) { + moduleConnector = module; + calculation = new Calculation(); + + initControllers(); + interfaceCtrl.setSemiringLayout(); + + // dummyInit(0); + } + + // Initialize the Tool with hard coded graphs. + @SuppressWarnings("unused") + private void dummyInit(int id) { + SemiRing ring = null; + Graph graph = new Graph(); + Node node; + + switch (id) { + case 0: + ring = AvailableSemiRings + .getSemiRing(AvailableSemiRings.SHORTEST_PATH_PROBLEM_ID); + + // Build Graph + node = graph.newNode(); + node.setLocation(new Point2D.Float(300, 150)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(50, 150)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(175, 350)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(175, 50)); + + graph.addEdge(0, 2, new PositiveRationalNumber(5)); + graph.addEdge(2, 0, new PositiveRationalNumber(1)); + graph.addEdge(1, 0, new PositiveRationalNumber(8)); + graph.addEdge(1, 3, new PositiveRationalNumber(3)); + graph.addEdge(2, 1, new PositiveRationalNumber(2)); + graph.addEdge(3, 0, new PositiveRationalNumber(2)); + graph.addEdge(0, 1, new PositiveRationalNumber(8)); + break; + + case 1: + ring = AvailableSemiRings + .getSemiRing(AvailableSemiRings.PROCESS_PROBLEM_ID); + + // Build Graph + node = graph.newNode(); + node.setLocation(new Point2D.Float(300, 150)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(50, 150)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(175, 250)); + + node = graph.newNode(); + node.setLocation(new Point2D.Float(175, 50)); + + graph.addEdge(0, 2, new FormalLanguage("a")); + graph.addEdge(1, 0, new FormalLanguage("c")); + graph.addEdge(1, 3, new FormalLanguage("a")); + graph.addEdge(2, 1, new FormalLanguage("b")); + graph.addEdge(3, 0, new FormalLanguage("b")); + break; + + default: + throw new IllegalArgumentException(); + } + + // Create calculation + calculation.setSemiring(ring); + calculation.setGraph(graph); + + // Notify + interfaceCtrl.setEditLayout(); + } + + /** + * Initializes all Controllers (InterfaceController, SemringController, + * GraphController, AlgorithmController) and sets j-Algo's toolbar and menu. + */ + private void initControllers() { + JComponent rootPane; + JToolBar toolbar; + JMenu menu; + + rootPane = JAlgoGUIConnector.getInstance().getModuleComponent(moduleConnector); + toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar(moduleConnector); + menu = JAlgoGUIConnector.getInstance().getModuleMenu(moduleConnector); + + interfaceCtrl = new InterfaceController(menu, toolbar, rootPane, this); + + semiringCtrl = new SemiringController(this, interfaceCtrl + .getSemiringPanel()); + + algorithmCtrl = new AlgorithmController(this, + interfaceCtrl.getAlgorithmPanel(), + interfaceCtrl.getAlgorithmToolPanel() + ); + + graphCtrl = new GraphController(this, interfaceCtrl + .getFormalGraphPanel(), interfaceCtrl.getGraphPanel(), + interfaceCtrl.getGraphToolPanel()); + + } + + /** + * Closes the APP module (used to remove the formula windows after closing) + */ + public void close() { + algorithmCtrl.closeFormulaWindow(); + } + + /** + * Creates a new Graph in the model, sets the Semiring and the graph for the + * calculation and notifies the InterfaceController to change + * the layout to the EditLayout. + * + * @param semiring + * the semiring needed to initialize the calculation. + */ + public void newGraph(SemiRing semiring) { + Graph graph = new Graph(); + + // Create calculation + calculation.setSemiring(semiring); + calculation.setGraph(graph); + + // Notify + interfaceCtrl.setEditLayout(); + } + + /** + * Loads a saved graph including its semiring. + * + * @param graph + * @param semiring + */ + public void load(Graph graph, SemiRing semiring) { + calculation.setGraph(graph); + calculation.setSemiring(semiring); + + if (semiring != null) + interfaceCtrl.setEditLayout(); + else + interfaceCtrl.setSemiringLayout(); + } + + /** + * Updates all three Controllers (and therefore their respective components) + * according to the new display mode. + */ + public void displayModeChanged() { + semiringCtrl.updateDisplay(interfaceCtrl.getDisplayMode()); + graphCtrl.updateDisplay(interfaceCtrl.getDisplayMode()); + algorithmCtrl.updateDisplay(interfaceCtrl.getDisplayMode()); + } + + /** + * Gets the precalculated calculation of the aho algorithm. + * + * @return The calculation. + */ + public Calculation getCalculation() { + return calculation; + } + + /** + * Sets the calculation. + * + * @param calculation The new calculation. + */ + public void setCalculation(Calculation calculation) { + this.calculation = calculation; + } + + /** + * Gets the interface controller. + * + * @return The interface controller. + */ + public InterfaceController getInterfaceController() { + return interfaceCtrl; + } + + /** + * Gets the graph controller. + * + * @return The graph controller. + */ + public GraphController getGraphController() { + return graphCtrl; + } + + /** + * Gets the semiring controller. + * + * @return The semiring controller. + */ + public SemiringController getSemiringController() { + return semiringCtrl; + } + + /** + * Gets the algorithm controller. + * + * @return The algorithm controller. + */ + public AlgorithmController getAlgorithmController() { + return algorithmCtrl; + } + + /** + * Sets the save status to "nothing to save". All save buttons will be disabled. + * This happens when there is nothing to save. + */ + public void setNothingToSave() { + moduleConnector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + } + + /** + * Sets the save status to "no changes". The save button will be disabled, + * but the "save as" button remains enabled. + * This state is set automatically with every save operation. + */ + public void setNoChanges() { + moduleConnector.setSaveStatus(SaveStatus.NO_CHANGES); + + } + + /** + * Sets the save status to "changes to save". All save buttons will be enabled. + * This method have to called with every change that can be saved. + */ + public void setChangesToSave() { + moduleConnector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + } + +} diff --git a/src/org/jalgo/module/app/controller/SemiringController.java b/src/org/jalgo/module/app/controller/SemiringController.java new file mode 100644 index 0000000..38ff29d --- /dev/null +++ b/src/org/jalgo/module/app/controller/SemiringController.java @@ -0,0 +1,79 @@ +package org.jalgo.module.app.controller; + +import java.awt.BorderLayout; + +import javax.swing.JPanel; + +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.view.SemiringComponent; + +/** + * Controls the panel, which is on the left side of the user interface. The + * SemiringController initializes the one component, which is involved in these + * Panel. + */ +public class SemiringController { + + // Connection to the MainController to communicate with the Core and the + // InterfaceController. + private MainController mainCtrl; + + private JPanel semiringPanel; + + SemiringComponent semiringComponent; + + /** + * Creates a new controller for the semiring. + * + * @param mainController The link back to the main controller. + * @param panel The panel which holds the semiring components. + */ + public SemiringController(MainController mainController, JPanel panel) { + mainCtrl = mainController; + semiringPanel = panel; + + semiringComponent = new SemiringComponent(this); + semiringPanel.setLayout(new BorderLayout()); + semiringPanel.add(semiringComponent, BorderLayout.CENTER); + } + + /** + * Gets the semiring from the calculation. + * + * @return The semiring. + */ + public SemiRing getSemiRing() { + return mainCtrl.getCalculation().getSemiring(); + } + + /** + * Sets the Semiring, which is given by the User (either by choosing it from + * the drop-down menu or from a saved file). + */ + public void setSemiRing(SemiRing semiring) { + mainCtrl.getCalculation().setSemiring(semiring); + + updateDisplay(null); + mainCtrl.newGraph(semiring); + } + + /** + * Forwards the beamer mode to the semiring components. + * + * @param beamerMode A boolean which should be true to enable the beamer mode. + */ + public void setBeamerMode(boolean beamerMode){ + semiringComponent.updateBeamerMode(beamerMode); + } + + + /** + * Redraws the semiring component with the given interface mode. + * + * @param interfaceMode The interface mode. + */ + public void updateDisplay(InterfaceMode interfaceMode) { + semiringComponent.updateDisplay(getSemiRing()); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/controller/package.html b/src/org/jalgo/module/app/controller/package.html new file mode 100644 index 0000000..5ddde5d --- /dev/null +++ b/src/org/jalgo/module/app/controller/package.html @@ -0,0 +1,10 @@ + + + + + + +The controller, which connects the core with the view. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.java new file mode 100644 index 0000000..bdef75f --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/AddEdgeUndoAction.java @@ -0,0 +1,32 @@ +package org.jalgo.module.app.controller.undoRedo; + +import org.jalgo.module.app.core.graph.Edge; + +/** + * Represents the action that an edge was added. + */ +public class AddEdgeUndoAction implements UndoableAction { + + private Edge edge; + private UndoManager undoManager; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param edge The edge which was added. + */ + public AddEdgeUndoAction(UndoManager undoManager, Edge edge) { + this.undoManager = undoManager; + this.edge = edge; + } + + public void redo() { + undoManager.getGraphController().addEdge(edge); + } + + public void undo() { + undoManager.getGraphController().doRemoveEdge(edge); + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.java new file mode 100644 index 0000000..2773d09 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/AddNodeUndoAction.java @@ -0,0 +1,32 @@ +package org.jalgo.module.app.controller.undoRedo; + +import org.jalgo.module.app.core.graph.Node; + +/** + * Represents the action that a node was added. + */ +public class AddNodeUndoAction implements UndoableAction { + + private Node node; + private UndoManager undoManager; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param node The node which was added. + */ + public AddNodeUndoAction(UndoManager undoManager, Node node) { + this.undoManager = undoManager; + this.node = node; + } + + public void redo() { + undoManager.getGraphController().addNode(node); + } + + public void undo() { + undoManager.getGraphController().doRemoveNode(node); + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.java new file mode 100644 index 0000000..0ad0ad6 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/AlterEdgeWeightUndoAction.java @@ -0,0 +1,39 @@ +package org.jalgo.module.app.controller.undoRedo; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; + +/** + * Represents the action that an edge has changed its weight. + */ +public class AlterEdgeWeightUndoAction implements UndoableAction { + + private UndoManager undoManager; + private Edge edge; + private DataType previousWeight; + private DataType newWeight; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param edge The edge which weight was altered. + * @param previousWeight The weight before alteration. + */ + public AlterEdgeWeightUndoAction(UndoManager undoManager, Edge edge, + DataType previousWeight) { + this.undoManager = undoManager; + this.edge = edge; + this.previousWeight = previousWeight; + this.newWeight = edge.getWeight(); + } + + public void redo() { + undoManager.getGraphController().alterUndoEdgeWeight(edge, newWeight); + } + + public void undo() { + undoManager.getGraphController().alterUndoEdgeWeight(edge, previousWeight); + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.java new file mode 100644 index 0000000..36c9f7e --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/AlterNodePositionUndoAction.java @@ -0,0 +1,40 @@ +package org.jalgo.module.app.controller.undoRedo; + +import java.awt.geom.Point2D; + +import org.jalgo.module.app.core.graph.Node; + +/** + * Represents the action that a node has changed its position. + */ +public class AlterNodePositionUndoAction implements UndoableAction { + + UndoManager undoManager; + Node node; + Point2D previousPosition; + Point2D newPosition; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param node The node which position was altered. + * @param previousPosition The node position before the alteration. + */ + public AlterNodePositionUndoAction(UndoManager undoManager, Node node, + Point2D previousPosition) { + this.undoManager = undoManager; + this.node = node; + this.previousPosition = previousPosition; + this.newPosition = node.getLocation(); + } + + public void redo() { + undoManager.getGraphController().alterUndoNodePosition(node, newPosition); + } + + public void undo() { + undoManager.getGraphController().alterUndoNodePosition(node, previousPosition); + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/CVS/Entries b/src/org/jalgo/module/app/controller/undoRedo/CVS/Entries new file mode 100644 index 0000000..175cfdf --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/CVS/Entries @@ -0,0 +1,9 @@ +/AddEdgeUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/AddNodeUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/AlterEdgeWeightUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/AlterNodePositionUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/RemoveEdgeUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/RemoveNodeUndoAction.java/1.1/Wed Oct 29 18:05:25 2008// +/UndoManager.java/1.1/Wed Oct 29 18:05:25 2008// +/UndoableAction.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/controller/undoRedo/CVS/Repository b/src/org/jalgo/module/app/controller/undoRedo/CVS/Repository new file mode 100644 index 0000000..00c4732 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/controller/undoRedo diff --git a/src/org/jalgo/module/app/controller/undoRedo/CVS/Root b/src/org/jalgo/module/app/controller/undoRedo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.java new file mode 100644 index 0000000..ab36a63 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/RemoveEdgeUndoAction.java @@ -0,0 +1,32 @@ +package org.jalgo.module.app.controller.undoRedo; + +import org.jalgo.module.app.core.graph.Edge; + +/** + * Represents the action that an edge was removed. + */ +public class RemoveEdgeUndoAction implements UndoableAction { + + private Edge edge; + private UndoManager undoManager; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param edge The edge which was removed. + */ + public RemoveEdgeUndoAction(UndoManager undoManager, Edge edge) { + this.undoManager = undoManager; + this.edge = edge; + } + + public void redo() { + undoManager.getGraphController().doRemoveEdge(edge); + } + + public void undo() { + undoManager.getGraphController().addEdge(edge); + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.java b/src/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.java new file mode 100644 index 0000000..8673d64 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/RemoveNodeUndoAction.java @@ -0,0 +1,41 @@ +package org.jalgo.module.app.controller.undoRedo; + +import java.util.Set; + +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Node; + +/** + * Represents the action that a node was removed. + */ +public class RemoveNodeUndoAction implements UndoableAction { + + private Node node; + private UndoManager undoManager; + private Set relatedEdges; + + /** + * Creates a new undo action. + * + * @param undoManager The Manager which controls the action. + * @param node The node which was added. + * @param relatedEdges A Set of all edges belonging to the node. + */ + public RemoveNodeUndoAction(UndoManager undoManager, Node node, Set relatedEdges) { + this.undoManager = undoManager; + this.node = node; + this.relatedEdges = relatedEdges; + } + + public void redo() { + undoManager.getGraphController().doRemoveNode(node); + } + + public void undo() { + undoManager.getGraphController().addUndoNode(node); + for (Edge edge : relatedEdges) { + undoManager.getGraphController().addEdge(edge); + } + } + +} diff --git a/src/org/jalgo/module/app/controller/undoRedo/UndoManager.java b/src/org/jalgo/module/app/controller/undoRedo/UndoManager.java new file mode 100644 index 0000000..b1272a7 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/UndoManager.java @@ -0,0 +1,188 @@ +package org.jalgo.module.app.controller.undoRedo; + +import java.awt.geom.Point2D; +import java.util.LinkedList; +import java.util.Set; + +import org.jalgo.module.app.controller.GraphController; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Node; + +/** + * Represents an object, which can handle undo and redo operations. + */ +public class UndoManager { + + /** + * The undo stack. + */ + private LinkedList undoableActions; + + /** + * The redo stack. + */ + private LinkedList redoableActions; + private GraphController graphController; + + /** + * Initialized the undo and redo stacks and sets the reference to the + * controller. + * + * @param graphController The link back to the graph controller. + */ + public UndoManager(GraphController graphController) { + this.graphController = graphController; + undoableActions = new LinkedList(); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an add action on the undo stack + * and clears the redo stack. + * + * @param node + * The node which was added. + */ + public void addUndoAddAction(Node node) { + undoableActions.addFirst(new AddNodeUndoAction(this, node)); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an remove action on the undo + * stack and clears the redo stack. + * + * @param node + * The node which was removed. + * @param relatedEdges + * The edges belonging to the node which will removed. They are + * needed for restoring. + */ + public void addUndoRemoveAction(Node node, Set relatedEdges) { + undoableActions.addFirst(new RemoveNodeUndoAction(this, node, + relatedEdges)); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an add action on the undo stack + * and clears the redo stack. + * + * @param edge + * The edge which was added. + */ + public void addUndoAddAction(Edge edge) { + undoableActions.addFirst(new AddEdgeUndoAction(this, edge)); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an remove action on the undo + * stack and clears the redo stack. + * + * @param edge + * The edge which was removed. + */ + public void addUndoRemoveAction(Edge edge) { + undoableActions.addFirst(new RemoveEdgeUndoAction(this, edge)); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an action that altered the + * weight of an edge on the undo stack and clears the redo stack. + * + * @param edge + * @param previousWeight + */ + public void addUndoWeightAlteredAction(Edge edge, DataType previousWeight) { + undoableActions.addFirst(new AlterEdgeWeightUndoAction(this, edge, + previousWeight)); + redoableActions = new LinkedList(); + } + + /** + * Puts a new undo object which represented an action that altered the + * position of a node on the undo stack and clears the redo stack. + * + * @param node + * @param previousPosition + */ + public void addUndoNodePositionAlteredAction(Node node, + Point2D previousPosition) { + undoableActions.addFirst(new AlterNodePositionUndoAction(this, node, + previousPosition)); + redoableActions = new LinkedList(); + } + + /** + * Gets the undo action number. + * + * @return The number of possible undo actions. + */ + public int possibleUndos() { + return undoableActions.size(); + } + + /** + * Gets the redo action number. + * + * @return The number of possible redo actions. + */ + public int possibleRedos() { + return redoableActions.size(); + } + + /** + * Gets the possibility of a undo action. + * + * @return true if possibleUndos() greater + * than 0. + */ + public boolean isUndoable() { + return possibleUndos() > 0; + } + + /** + * Gets the possibility of a redo action. + * + * @return true if possibleRedos() greater + * than 0. + */ + public boolean isRedoable() { + return possibleRedos() > 0; + } + + /** + * Performs an undo action. + */ + public void undo() { + if (isUndoable()) { + UndoableAction action = undoableActions.removeFirst(); + action.undo(); + redoableActions.addFirst(action); + } + } + + /** + * Performs an redo action. + */ + public void redo() { + if (isRedoable()) { + UndoableAction action = redoableActions.removeFirst(); + action.redo(); + undoableActions.addFirst(action); + } + } + + /** + * Provides the link to the GraphController. + * + * @return The GraphController. + */ + public GraphController getGraphController() { + return graphController; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/controller/undoRedo/UndoableAction.java b/src/org/jalgo/module/app/controller/undoRedo/UndoableAction.java new file mode 100644 index 0000000..aa60940 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/UndoableAction.java @@ -0,0 +1,19 @@ +package org.jalgo.module.app.controller.undoRedo; + +/** + * You can undo or redo an undoable action. + */ +public interface UndoableAction { + + /** + * Performs the steps to undo a happened action. + */ + public void undo(); + + /** + * Performs the steps to redo a undone action. + */ + public void redo(); + +} + diff --git a/src/org/jalgo/module/app/controller/undoRedo/package.html b/src/org/jalgo/module/app/controller/undoRedo/package.html new file mode 100644 index 0000000..fc863b0 --- /dev/null +++ b/src/org/jalgo/module/app/controller/undoRedo/package.html @@ -0,0 +1,10 @@ + + + + + + +Provides the undo/redo functionality. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/AvailableSemiRings.java b/src/org/jalgo/module/app/core/AvailableSemiRings.java new file mode 100644 index 0000000..3309265 --- /dev/null +++ b/src/org/jalgo/module/app/core/AvailableSemiRings.java @@ -0,0 +1,180 @@ +package org.jalgo.module.app.core; + +import java.util.HashMap; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.booleanType.BooleanType; +import org.jalgo.module.app.core.dataType.formalLanguage.FormalLanguage; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.PercentageType; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; + +/** + * Provides static methods to get supported Semirings. + */ +public class AvailableSemiRings { + + public static String AVAILABILITY_PROBLEM_ID = "availability"; + public static String CAPACITY_PROBLEM_ID = "capacity"; + public static String PROCESS_PROBLEM_ID = "process"; + public static String RELIABILITY_PROBLEM_ID = "reliability"; + public static String SHORTEST_PATH_PROBLEM_ID = "shortestPath"; + + private static Map semiRings = null; + + /** + * Delivers all supported semirings. + * @return The map whose values are semirings and keys are the problem-IDs. + */ + public static Map getSemiRings() { + if (semiRings == null) + buildSemiRings(); + + return semiRings; + } + + /** + * @param semiringID + * The ID of the semiring. This is a string and is available as a + * static field of AvailableSemiRings. + * @return The semiring with the given ID. + */ + public static SemiRing getSemiRing(String semiringID) { + if (semiRings == null) + buildSemiRings(); + + return semiRings.get(semiringID); + } + + /** + * Creates a new Map of all supported semirings. The keys are the + * problem-ids which are hold as static fields. For each value is a new + * semiring created. + * + * This method defines the specific properties of each semiring, like name, + * description and definition. + */ + private static void buildSemiRings() { + semiRings = new HashMap(); + SemiRing ring; + String definition; + + // FIXME: Remove definition + definition = "(" + PositiveRationalNumber.getSymbolicRepresentation(); + definition += "," + PositiveRationalNumber.getOperationByID("min").getSymbolicRepresentation(); + definition += "," + PositiveRationalNumber.getOperationByID("add").getSymbolicRepresentation(); + definition += ",\u221E"; + definition += ",0)"; + ring = newSemiRing(PositiveRationalNumber.class, + PositiveRationalNumber.getOperationByID("min"), + PositiveRationalNumber.getOperationByID("add"), + Messages.getString("app","AvailableSemiRings.ShortestPathName"), + definition, + Messages.getString("app","AvailableSemiRings.ShortestPathDescription"), + PositiveRationalNumber.getSymbolicRepresentation() + ); + semiRings.put(SHORTEST_PATH_PROBLEM_ID, ring); + + definition = "(" + NaturalNumber.getSymbolicRepresentation(); + definition += "," + NaturalNumber.getOperationByID("max").getSymbolicRepresentation(); + definition += "," + NaturalNumber.getOperationByID("min").getSymbolicRepresentation(); + definition += ",0"; + definition += ",\u221E)"; + ring = newSemiRing(NaturalNumber.class, + NaturalNumber.getOperationByID("max"), + NaturalNumber.getOperationByID("min"), + Messages.getString("app","AvailableSemiRings.CapacityName"), + definition, + Messages.getString("app","AvailableSemiRings.CapacityDescription"), + NaturalNumber.getSymbolicRepresentation() + ); + semiRings.put(CAPACITY_PROBLEM_ID, ring); + + definition = "(" + BooleanType.getSymbolicRepresentation(); + definition += "," + BooleanType.getOperationByID("disjunct").getSymbolicRepresentation(); + definition += "," + BooleanType.getOperationByID("conjunct").getSymbolicRepresentation(); + definition += ",false"; + definition += ",true)"; + ring = newSemiRing(BooleanType.class, + BooleanType.getOperationByID("disjunct"), + BooleanType.getOperationByID("conjunct"), + Messages.getString("app","AvailableSemiRings.AvailabilityName"), + definition, + Messages.getString("app","AvailableSemiRings.AvailabilityDescription"), + BooleanType.getSymbolicRepresentation() + ); + semiRings.put(AVAILABILITY_PROBLEM_ID, ring); + + definition = "(" + PercentageType.getSymbolicRepresentation(); + definition += "," + PercentageType.getOperationByID("max").getSymbolicRepresentation(); + definition += "," + PercentageType.getOperationByID("mult").getSymbolicRepresentation(); + definition += ",0"; + definition += ",1)"; + ring = newSemiRing(PercentageType.class, + PercentageType.getOperationByID("max"), + PercentageType.getOperationByID("mult"), + Messages.getString("app","AvailableSemiRings.ReliabilityName"), + definition, + Messages.getString("app","AvailableSemiRings.ReliabilityDescription"), + PercentageType.getSymbolicRepresentation() + ); + semiRings.put(RELIABILITY_PROBLEM_ID, ring); + + definition = "(" + FormalLanguage.getSymbolicRepresentation(); + definition += "," + FormalLanguage.getOperationByID("union").getSymbolicRepresentation(); + definition += "," + FormalLanguage.getOperationByID("concat").getSymbolicRepresentation(); + definition += ",\u2205"; + definition += ",(\u03B5))"; + ring = newSemiRing(FormalLanguage.class, + FormalLanguage.getOperationByID("union"), + FormalLanguage.getOperationByID("concat"), + Messages.getString("app","AvailableSemiRings.ProcessName"), + definition, + Messages.getString("app","AvailableSemiRings.ProcessDescription"), + FormalLanguage.getSymbolicRepresentation() + ); + semiRings.put(PROCESS_PROBLEM_ID, ring); + } + + /** + * @param cl + * The class the DataType. + * @param plus + * The plus operation. + * @param dot + * The dot operation. + * @param name + * The name as a string. + * @param definiton + * The formal definition in form of a tuple. + * @param description + * The description in a non formal speech. + * @return An Object form type SemiRing with the given properties. + */ + private static SemiRing newSemiRing(Class cl, + Operation plus, + Operation dot, + String name, + String definiton, + String description, + String[] representation + ) + { + SemiRing ring; + + if (plus == null || dot == null) + throw new NullPointerException(); + + ring = new SemiRing(cl, plus, dot); + ring.setName(name); + ring.setDefinition(definiton); + ring.setDescription(description); + ring.setTypeRepresentation(representation); + + return ring; + } + +} diff --git a/src/org/jalgo/module/app/core/CVS/Entries b/src/org/jalgo/module/app/core/CVS/Entries new file mode 100644 index 0000000..ef488ce --- /dev/null +++ b/src/org/jalgo/module/app/core/CVS/Entries @@ -0,0 +1,9 @@ +/AvailableSemiRings.java/1.1/Wed Oct 29 18:05:25 2008// +/Calculation.java/1.1/Wed Oct 29 18:05:25 2008// +/Matrix.java/1.1/Wed Oct 29 18:05:25 2008// +/SemiRing.java/1.1/Wed Oct 29 18:05:25 2008// +D/dataType//// +D/formalLanguage//// +D/graph//// +/package.html/1.1/Wed Oct 29 18:05:25 2008// +D/step//// diff --git a/src/org/jalgo/module/app/core/CVS/Repository b/src/org/jalgo/module/app/core/CVS/Repository new file mode 100644 index 0000000..215df2b --- /dev/null +++ b/src/org/jalgo/module/app/core/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core diff --git a/src/org/jalgo/module/app/core/CVS/Root b/src/org/jalgo/module/app/core/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/Calculation.java b/src/org/jalgo/module/app/core/Calculation.java new file mode 100644 index 0000000..b03f59b --- /dev/null +++ b/src/org/jalgo/module/app/core/Calculation.java @@ -0,0 +1,268 @@ +package org.jalgo.module.app.core; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; + +/** + * The Calculation class is responsible for calculating the + * Steps and the Matrices for a given Graph and + * its SemiRing. + * + */ +public class Calculation { + + private SemiRing semiring; + private RootStep rootStep; + private Graph graph; + + /** + * Instantiates a new Calculation. + */ + public Calculation() { + } + + /** + * Gets the graph used in this calculation. + * + * @return the graph. + */ + public Graph getGraph() { + return graph; + } + + /** + * Sets the Graph for the calculation and resets the + * rootStep. + * + * @param graph + * the given Graph for the calculation + */ + public void setGraph(Graph graph) { + this.graph = graph; + this.rootStep = null; + } + + /** + * Gets the Semiring used in this calculation. + * + * @return the semiring. + */ + public SemiRing getSemiring() { + return semiring; + } + + /** + * Sets the SemiRing, resets the rootStep and + * tries to convert the Graph weights, if possible. + * + * @param semiring + * the given SemiRing + */ + public void setSemiring(SemiRing semiring) { + this.semiring = semiring; + this.rootStep = null; + + // try { + // convertGraphWeights(); + // } catch (InstantiationException e) { + // e.printStackTrace(); + // } catch (IllegalAccessException e) { + // e.printStackTrace(); + // } + } + + /* + * We don't need this Method, since we don't convert a graph from one + * semiring to another. + */ + + // /** + // * Converts the weights of the given graph, if possible (the weights must + // be + // * a subclass of NumericDataType). + // * + // * @throws InstantiationException + // * @throws IllegalAccessException + // */ + // private void convertGraphWeights() throws InstantiationException, + // IllegalAccessException { + // Class type; + // boolean numeric; + // + // if (graph == null) + // return; + // + // type = semiring.getType(); + // numeric = ((Object) type instanceof NumericDataType); + // + // for (Edge e : graph.getEdges()) { + // if (numeric && (e.getWeight() instanceof NumericDataType)) { + // + // NumericDataType numValue = (NumericDataType) type.newInstance(); + // numValue.setFromNumeric((NumericDataType) e.getWeight()); + // e.setWeight(numValue); + // } else { + // e.setWeight(type.newInstance()); + // } + // } + // } + public RootStep calculateRootStep() { + calculate(); + + return rootStep; + } + + /** + * Gets the Root Step used in this calculation. + * + * @return the root step. + */ + public RootStep getRootStep() { + if (rootStep == null) + calculateRootStep(); + + return rootStep; + } + + /** + * Calculates the adjacency matrix from the graph edges and nodes + * + * @return the adjacency matrix. + */ + public Matrix calculateInitialMatrix() { + int size; + Matrix matrix; + DataType neutral, zero; + Operation plus, dot; + + if (semiring == null || graph == null) + return null; + + plus = semiring.getPlusOperation(); + dot = semiring.getDotOperation(); + + zero = dot.getNeutralElement(); + neutral = plus.getNeutralElement(); + + size = graph.getNodes().size(); + matrix = new Matrix(size); + + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + if (i == j) { + matrix.setValueAt(i, j, zero); + matrix.setNodesAt(i, j, new ArrayList()); + } else + matrix.setValueAt(i, j, neutral); + } + } + + for (Edge e : graph.getEdges()) { + int i, j; + + i = e.getBegin().getId(); + j = e.getEnd().getId(); + + matrix.setValueAt(i, j, e.getWeight()); + matrix.setNodesAt(i, j, new ArrayList()); + } + + return matrix; + } + + /** + * Calculates the Matrices, the AtomicSteps and the + * GroupSteps for the given Graph and + * SemiRing. + */ + private void calculate() { + Operation plus, dot; + Matrix matrix, oldMatrix; + int size; + + if (semiring == null || graph == null) + return; + + // Fetch some calculation parameters + size = graph.getNodes().size(); + + plus = semiring.getPlusOperation(); + dot = semiring.getDotOperation(); + + // Init start matrix + matrix = calculateInitialMatrix(); + + // Init root step + rootStep = new RootStep(); + oldMatrix = matrix.clone(); + rootStep.setBeforeMatrix(oldMatrix); + + // Calculate + for (int k = 0; k < size; k++) { + GroupStep nodeStep; + nodeStep = new GroupStep(); + + for (int u = 0; u < size; u++) { + for (int v = 0; v < size; v++) { + AtomicStep cellStep; + List ops; + List nodes; + DataType orig, val; + boolean changed; + + // Calculate the new value + val = plus.star(oldMatrix.getValueAt(k, k), dot); + + ops = new ArrayList(); + ops.add(oldMatrix.getValueAt(u, k)); + ops.add(val); + ops.add(oldMatrix.getValueAt(k, v)); + val = dot.op(ops); + + orig = oldMatrix.getValueAt(u, v); + val = plus.op(orig, val); + changed = !val.equals(orig); + + // Calculate the node list + nodes = new ArrayList(); + if (oldMatrix.getNodesAt(u, k) != null) + nodes.addAll(oldMatrix.getNodesAt(u, k)); + nodes.add(k); + if (oldMatrix.getNodesAt(k, v) != null) + nodes.addAll(oldMatrix.getNodesAt(k, v)); + + // Update the matrix + if (changed) { + matrix.setValueAt(u, v, val); + matrix.setNodesAt(u, v, nodes); + } + + // Create the step item + cellStep = new AtomicStep(); + cellStep.setKUV(k, u, v); + cellStep.setValue(val); + cellStep.setNodes(nodes); + cellStep.setChanged(changed); + + // Add the step + nodeStep.addStep(cellStep); + } + } + + oldMatrix = matrix.clone(); + nodeStep.setAfterMatrix(oldMatrix); + rootStep.addStep(nodeStep); + } + + rootStep.setAfterMatrix(oldMatrix); + } + +} diff --git a/src/org/jalgo/module/app/core/Matrix.java b/src/org/jalgo/module/app/core/Matrix.java new file mode 100644 index 0000000..480e6c2 --- /dev/null +++ b/src/org/jalgo/module/app/core/Matrix.java @@ -0,0 +1,170 @@ +package org.jalgo.module.app.core; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; + +/** + * Represents two n by n Matrices for a Graph with n + * Nodes. The first matrix represents the values (of + * DataType calculated in Calculation, whereas + * the second Matrix contains a List for every element, which + * represents the path from one Node to another. + */ +public class Matrix { + + private int size; + private DataType values[][]; + private List viaNodes[][]; + + /** + * Initiates a matrix of given size. + * + * @param sz + * The size of the Matrix. + */ + @SuppressWarnings(value = { "unchecked" }) + public Matrix(int sz) { + size = sz; + values = new DataType[sz][sz]; + viaNodes = new List[sz][sz]; // A bit hacky, misses a cast... + } + + /** + * Initiates a Matrix by copying another one. + * + * @param other + */ + @SuppressWarnings(value = { "unchecked" }) + public Matrix(Matrix other) { + this(other.size); + + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + values[x][y] = other.values[x][y].clone(); + viaNodes[x][y] = other.viaNodes[x][y]; + } + } + } + + public Matrix clone() { + return new Matrix(this); + } + + /** + * @return The size of the symmetrical Matrix. + */ + public int getSize() { + return size; + } + + /** + * + * @param x + * the x-coordinate in the matrix. + * @param y + * the y-coordinate in the matrix. + * @return the value (of DataType) of the given coordinates + * in the Matrix. + */ + public DataType getValueAt(int x, int y) { + return values[x][y]; + } + + /** + * + * @param x + * the x-coordinate in the matrix. + * @param y + * the y-coordinate in the matrix. + * @param val + * the value for the coordinate. + */ + public void setValueAt(int x, int y, DataType val) { + values[x][y] = val; + } + + /** + * + * @param x + * the x-coordinate in the matrix. + * @param y + * the y-coordinate in the matrix. + * @return the List of the intermediate nodes between + * Node x and Node y. + */ + public List getNodesAt(int x, int y) { + return viaNodes[x][y]; + } + + /** + * + * @param x + * the x-coordinate in the matrix. + * @param y + * the y-coordinate in the matrix. + * @param nodes + * the List of the intermediate nodes between + * Node x and Node y. + */ + public void setNodesAt(int x, int y, List nodes) { + viaNodes[x][y] = nodes; + } + + /** + * Prints the Matrix row-aligned. + */ + public String toString() { + String str; + int maxLength; + + // determine max. length of a matrix element + maxLength = 0; + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + if (values[i][j].toString().length() > maxLength) + maxLength = values[i][j].toString().length(); + } + } + + str = "Matrix:{size = " + size + "}\n"; + + for (int i = 0; i < size; i++) { + str += "( "; + for (int j = 0; j < size; j++) { + for (int k = values[i][j].toString().length(); k < maxLength; k++) + str += " "; + str += values[i][j] + " "; + } + str += ")\n"; + } + + return str; + } + + /** + * Compares two matrices based on their element values. + */ + public boolean equals(Object o) { + Matrix other; + + if (!(o instanceof Matrix) || o == null) + return false; + + other = (Matrix) o; + + if (size != other.size) + return false; + + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + if (!(values[x][y].equals(other.values[x][y]))) // || + // !viaNodes[x][y].equals(other.viaNodes[x][y])) + return false; + } + } + + return true; + } + +} diff --git a/src/org/jalgo/module/app/core/SemiRing.java b/src/org/jalgo/module/app/core/SemiRing.java new file mode 100644 index 0000000..5506173 --- /dev/null +++ b/src/org/jalgo/module/app/core/SemiRing.java @@ -0,0 +1,142 @@ +package org.jalgo.module.app.core; + +import java.io.Serializable; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; + +/** + * Represents a SemiRing, which is a algebraic structure + * consisting of a DataType, two Operations (and + * their neutral elements, which are stored in the corresponding + * Operation). + * + */ +public class SemiRing implements Serializable, Comparable { + + /** + * important for load/save operations. + */ + private static final long serialVersionUID = -8445924133073074815L; + private Operation plus; + private Operation dot; + private Class type; + + // e.g. Shortest Path Problem + private String name; + + // description referring to the Problem + private String description; + + // tuple containing Set, operations and their neutral elements + private String definition; + private String[] typeRepresentation; + + /** + * Constructs a Semiring from a DataType class and two + * Operations. + * + * @param type + * a class inheriting from DataType. + * @param plus + * the additive Operation. + * @param dot + * the multiplicative Operation. + */ + public SemiRing(Class type, Operation plus, + Operation dot) { + this.type = type; + this.plus = plus; + this.dot = dot; + this.name = "No Name"; + } + + public Operation getPlusOperation() { + return plus; + } + + public void setPlusOperation(Operation plus) { + this.plus = plus; + } + + public Operation getDotOperation() { + return dot; + } + + public void setDotOperation(Operation dot) { + this.dot = dot; + } + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + /** + * @return the name (e.g. Shortest Path Problem). + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the description of the the Semiring (e.g..a Non-formal description + * of the Shortest Path Problem). + * + * @return the description of the Semiring. + */ + public String getDescription() { + return description; + } + + /** + * + * @param description + * the description. + */ + public void setDescription(String description) { + this.description = description; + } + + public void setTypeRepresentation(String[] representation) { + this.typeRepresentation = representation; + } + + public String[] getTypeRepresentation() { + return this.typeRepresentation; + } + + /** + * + * @return a formal tuple containing the Set, the two Operations and their + * neutral elements. + */ + public String getDefinition() { + return definition; + } + + public void setDefinition(String definition) { + this.definition = definition; + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(SemiRing compareSemiring) { + if (compareSemiring == null) { + throw new NullPointerException(); + } + return this.getName().compareTo(compareSemiring.getName()); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/AvailableDataTypes.java b/src/org/jalgo/module/app/core/dataType/AvailableDataTypes.java new file mode 100644 index 0000000..70827bd --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/AvailableDataTypes.java @@ -0,0 +1,40 @@ +package org.jalgo.module.app.core.dataType; + +import java.util.HashSet; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.booleanType.BooleanType; +import org.jalgo.module.app.core.dataType.formalLanguage.FormalLanguage; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.PercentageType; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalNumber; + +/** + * Provides static methods to get supported Data Types. + * + */ +public class AvailableDataTypes { + + private static Set> dataTypes = null; + + /** + * Returns all available DataTypes as a set of classes. + * + * @return the available DataTypes. + */ + public static Set> getDataTypes() { + if (dataTypes == null) { + dataTypes = new HashSet>(); + + dataTypes.add(BooleanType.class); + dataTypes.add(FormalLanguage.class); + dataTypes.add(NaturalNumber.class); + dataTypes.add(RationalNumber.class); + dataTypes.add(PositiveRationalNumber.class); + dataTypes.add(PercentageType.class); + } + + return dataTypes; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/CVS/Entries b/src/org/jalgo/module/app/core/dataType/CVS/Entries new file mode 100644 index 0000000..5a4ce21 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/CVS/Entries @@ -0,0 +1,11 @@ +/AvailableDataTypes.java/1.1/Wed Oct 29 18:05:25 2008// +/DataType.java/1.1/Wed Oct 29 18:05:25 2008// +/Infinity.java/1.1/Wed Oct 29 18:05:25 2008// +/MaxValues.java/1.1/Wed Oct 29 18:05:25 2008// +/NumericDataType.java/1.1/Wed Oct 29 18:05:25 2008// +/Operation.java/1.2/Fri Oct 31 16:12:36 2008// +D/booleanType//// +D/formalLanguage//// +D/naturalNumber//// +/package.html/1.1/Wed Oct 29 18:05:25 2008// +D/rationalNumber//// diff --git a/src/org/jalgo/module/app/core/dataType/CVS/Repository b/src/org/jalgo/module/app/core/dataType/CVS/Repository new file mode 100644 index 0000000..de8b73f --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/dataType diff --git a/src/org/jalgo/module/app/core/dataType/CVS/Root b/src/org/jalgo/module/app/core/dataType/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/dataType/DataType.java b/src/org/jalgo/module/app/core/dataType/DataType.java new file mode 100644 index 0000000..4a83a78 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/DataType.java @@ -0,0 +1,73 @@ +package org.jalgo.module.app.core.dataType; + +import java.io.Serializable; +import java.util.Set; + +/** + * Represents an element of a mathematical set (which is needed for the + * SemiRing). + * + */ +public abstract class DataType implements Serializable { + + /** + * A set of available Operations for this + * DataType. + */ + protected static Set operations = null; + + /** + * + * @return the available Operations for this + * DataType. + */ + public static Set getOperations() { + throw new UnsupportedOperationException(); + } + + public static Operation getOperationByID(String id) { + throw new UnsupportedOperationException(); + } + + /** + * + * @return the name of the set (e.g. Natural Number, Formal Language) + */ + public static String getName() { + throw new UnsupportedOperationException(); + } + + /** + * + * @return the formal representation of the data type. Whereas - the first + * entry represents the used set, - the seconds entry represents the + * restriction of the set, e.g. plus for positive numbers (printed + * on top) - the third entry represents an extended symbol, e.g. + * infinity (printed on bottom) + * + */ + public static String[] getSymbolicRepresentation() { + throw new UnsupportedOperationException(); + } + + public abstract DataType clone(); + + public abstract String toString(); + + /** + * + * @param str + * the String to be converted to the + * DataType + * @return true, if input correct, false + * otherwise + */ + public abstract boolean setFromString(String str); + + /** + * + * @return a list of special characters (e.g. epsilon or infinity) used in + * this DataType. + */ + public abstract String[] getSpecialCharacter(); +} diff --git a/src/org/jalgo/module/app/core/dataType/Infinity.java b/src/org/jalgo/module/app/core/dataType/Infinity.java new file mode 100644 index 0000000..93b5db9 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/Infinity.java @@ -0,0 +1,10 @@ +package org.jalgo.module.app.core.dataType; + +/** + * Provides three alternatives of infinity for a number: positive infinite, + * negative infinite or a real number (the "normal" kind). + * + */ +public enum Infinity { + POSITIVE_INFINITE, NEGATIVE_INFINITE, REAL +} diff --git a/src/org/jalgo/module/app/core/dataType/MaxValues.java b/src/org/jalgo/module/app/core/dataType/MaxValues.java new file mode 100644 index 0000000..940f6b8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/MaxValues.java @@ -0,0 +1,30 @@ +package org.jalgo.module.app.core.dataType; + +/** + * A class used to store maximum (and minimum) input values for natural and + * rational numbers. + * + */ +public class MaxValues { + + /** + * @return the maximum input number for natural numbers. + */ + public static int getNaturalNumberMaximum() { + return 65536; + } + + /** + * @return the maximum input number for rational numbers. + */ + public static float getRationalNumberMaximum() { + return 65536.0f; + } + + /** + * @return the minimum input number for rational numbers. + */ + public static float getRationalNumberMinimum() { + return -65536.0f; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/NumericDataType.java b/src/org/jalgo/module/app/core/dataType/NumericDataType.java new file mode 100644 index 0000000..9839d3a --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/NumericDataType.java @@ -0,0 +1,84 @@ +package org.jalgo.module.app.core.dataType; + +/** + * An abstract subclass of DataType, which represents numbers. + * Numbers can be converted into each other. + */ +public abstract class NumericDataType extends DataType { + + /** + * Converts the NumericDataType instance to an + * Integer representation. + * + * @return the Integer representation. + */ + public abstract int toInt(); + + /** + * Converts the NumericDataType instance to a + * Float representation. + * + * @return the Float representation. + */ + public abstract float toFloat(); + + /** + * Sets the NumericDataType object to an integer value. + * + * @param value + * the integer value to set the NumericDataType + * instance to. + * @return true if value correct, + * false otherwise + */ + public abstract boolean setFromInt(int value); + + /** + * Sets the NumericDataType object to an floating-point + * value. + * + * @param value + * the floating-point value to set the + * NumericDataType instance to. + * @return true if value correct, false otherwise + */ + public abstract boolean setFromFloat(float value); + + /** + * Sets the NumericDataType object to the generic value + * numeric. value. + * + * @param numeric + * @return true if numeric correct, false otherwise + */ + public abstract boolean setFromNumeric(NumericDataType numeric); + + /** + * Returns the kind of Infinity of this number. + * + * @return the kind of Infinity of this number. + */ + public abstract Infinity getInfinity(); + + /** + * Sets the Infinity to inf. If inf is + * Infinity.Real, then the number is set to its default + * value. + * + * @param inf + * @return true, if setting Infinity was + * sucessful, otherwise false. + */ + public abstract boolean setInfinity(Infinity inf); + + public boolean equals(Object ot) { + NumericDataType other; + + if (!(ot instanceof NumericDataType)) + return false; + + other = (NumericDataType) ot; + return (getInfinity() == other.getInfinity() && (getInfinity() != Infinity.REAL || toFloat() == other + .toFloat())); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/Operation.java b/src/org/jalgo/module/app/core/dataType/Operation.java new file mode 100644 index 0000000..52de25d --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/Operation.java @@ -0,0 +1,120 @@ +package org.jalgo.module.app.core.dataType; + +import java.io.Serializable; +import java.util.List; + +/** + * A class, which allows the execution of an operation. It is also a container + * for their neutral elements, their Notation and different + * identifications. + * + */ +public abstract class Operation implements Serializable { + + /** + * Returns the ID of the Operation. + * + * @return the ID of the Operation. + */ + public abstract String getID(); + + /** + * Returns the name of the Operation (e.g. Addition, + * Conjunction). + * + * @return the name of the Operation + */ + public abstract String getName(); + + /** + * Returns the symbolic representation of the Operation, + * e.g. "+", " \u2227"). + * + * @return the symbolic representation of the Operation. + */ + public abstract String getSymbolicRepresentation(); + + /** + * An Operation can either be prefix (e.g. min{a,b,..}), infix (e.g. a + b) + * or postfix (just for completeness). + * + */ + public enum Notation { + PREFIX, INFIX, POSTFIX + }; + + /** + * Returns the Notation used for this Operation. + * + * @return the used Notation. + */ + public abstract Notation getNotation(); + + /** + * Returns the neutral element of the operation or null if no + * such element exists. + * + * A neutral element makes no change to a operations result. + * + * @return the neutral element + */ + public abstract DataType getNeutralElement(); + + /** + * Returns a descriptive string of the neutral element of the operation or null if no + * such element exists. + * + * @return the description of neutral element + */ + public String getNeutralElementDescription() { + return getNeutralElement().toString(); + } + + /** + * Returns the absorbing element of the operation or null if + * no such element exists. + * + * A absorbing element consumes every operation and so is always the result + * of an operation when it is included in the arguments. + * + * @return the absorbing element + */ + public abstract DataType getAbsorbingElement(); + + /** + * Returns true if the operation is associative, + * false otherwise. + * + * @return true if operation is associative + */ + public abstract boolean isAssociative(); + + /** + * Returns true if the operation is commutative, + * false otherwise. + * + * @return true if operation is commutative + */ + public abstract boolean isCommutative(); + + /** + * Performs the operation using two arguments. + * + * @return the operation result + */ + public abstract DataType op(DataType arg1, DataType arg2); + + /** + * Performs the operation using a list of arguments. + * + * @return the operation result + */ + public abstract DataType op(List args); + + /** + * Performs the star operation using one argument. + * + * @return the operation result + */ + public abstract DataType star(DataType arg, Operation other); +} diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/BooleanType.java b/src/org/jalgo/module/app/core/dataType/booleanType/BooleanType.java new file mode 100644 index 0000000..092d10e --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/BooleanType.java @@ -0,0 +1,193 @@ +package org.jalgo.module.app.core.dataType.booleanType; + +import java.util.*; + +import org.jalgo.module.app.core.dataType.*; + +/** + * A DataType, which represents a boolean value (true, + * false). + * + */ +public class BooleanType extends DataType { + + private static final long serialVersionUID = -545227017196474005L; + + /** + * @see DataType#getOperations() + */ + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new Conjunction()); + operations.add(new Disjunction()); + + return operations; + } + + /** + * @see DataType#getOperationByID(String) + */ + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + /** + * @see DataType#getName() + */ + public static String getName() { + return "Boolean Type"; + } + + /** + * @see DataType#getSymbolicRepresentation() + */ + public static String[] getSymbolicRepresentation() { + String[] returnValue = {"{true, false}", "", ""}; + + return returnValue; + } + + private Boolean value; + + /** + * Instantiates BooleanType with the default value + * true. + */ + public BooleanType() { + this.value = true; + } + + /** + * Instantiates BooleanType with the given value. + * + * @param value + * a boolean value (true or false). + */ + public BooleanType(Boolean value) { + this.value = value; + } + + /** + * @see DataType#clone() + */ + public BooleanType clone() { + return new BooleanType(value); + } + + /** + * Sets the BooleanType instance to val + * @param val + * @return true + */ + public boolean setFromBoolean(boolean val) { + value = val; + return true; + } + + /** + * Sets BooleanType from Integer. 1 equals + * true, 0 equals false. + * + * @param val + * the value to be converted to BooleanType. + * @return true, if val either 1 or 0. + */ + public boolean setFromInt(int val) { + if (val == 0) { + value = false; + } else if (val == 1) { + value = true; + } else { + return false; + } + return true; + } + + /** + * Sets BooleanType from String. + * + * @param str + * A String, which has to be either 1, true or True for + * true or 0, false or False for + * false. + * + * + * @return true, if str was in proper format. + */ + @Override + public boolean setFromString(String str) { + if (str.equals("1") || str.toLowerCase().equals("t")) { + value = true; + return true; + } + if (str.equals("0") || str.toLowerCase().equals("f")) { + value = false; + return true; + } + if ((str.compareToIgnoreCase("true") != 0) + && (str.compareToIgnoreCase("false") != 0)) { + return false; + } + value = Boolean.parseBoolean(str); + return true; + } + + /** + * + * @return the boolean representation of BooleanType + */ + public boolean toBoolean() { + return value; + } + + /** + * @see DataType#toString() + */ + @Override + public String toString() { + return Boolean.toString(value); + } + + /** + * Returns 1 if value is true, 0 otherwise. + * + * @return 1 if value is true, 0 otherwise. + */ + public int toInt() { + if (value) { + return 1; + } else { + return 0; + } + } + + /** + * @see DataType#equals(Object) + */ + @Override + public boolean equals(Object ot) { + BooleanType other; + + if (!(ot instanceof BooleanType)) + return false; + + other = (BooleanType) ot; + return (value == other.value); + } + + /** + * @see DataType#getSpecialCharacter() + */ + + public String[] getSpecialCharacter() { + return null; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Entries b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Entries new file mode 100644 index 0000000..57d9d6f --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Entries @@ -0,0 +1,4 @@ +/BooleanType.java/1.1/Wed Oct 29 18:05:24 2008// +/Conjunction.java/1.2/Fri Oct 31 16:12:36 2008// +/Disjunction.java/1.1/Wed Oct 29 18:05:24 2008// +/package.html/1.1/Wed Oct 29 18:05:24 2008// diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Repository b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Repository new file mode 100644 index 0000000..b4c8851 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/dataType/booleanType diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Root b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/Conjunction.java b/src/org/jalgo/module/app/core/dataType/booleanType/Conjunction.java new file mode 100644 index 0000000..64c0997 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/Conjunction.java @@ -0,0 +1,104 @@ +package org.jalgo.module.app.core.dataType.booleanType; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.*; + +/** + * The binary operation Conjunction (or Boolean And), which can + * be executed on BooleanType. + * + */ +public class Conjunction extends Operation { + + private static final long serialVersionUID = 1022585504793412750L; + + /** + * @see Operation#getID() + */ + public String getID() { + return "conjunct"; + } + + /** + * @see Operation#getName() + */ + public String getName() { + return "Conjunction"; + } + + /** + * @see Operation#getSymbolicRepresentation() + */ + public String getSymbolicRepresentation() { + return "\u2227"; + } + + /** + * @see Operation#getNotation() + */ + public Notation getNotation() { + return Notation.INFIX; + } + + /** + * @see Operation#getNeutralElement() + */ + public DataType getNeutralElement() { + return new BooleanType(true); + } + + /** + * @see Operation#getAbsorbingElement() + */ + public DataType getAbsorbingElement() { + return new BooleanType(false); + } + + /** + * @see Operation#isAssociative() + */ + public boolean isAssociative() { + return true; + } + + /** + * @see Operation#isCommutative() + */ + public boolean isCommutative() { + return true; + } + + /** + * @see Operation#op(DataType, DataType) + */ + public DataType op(DataType arg1, DataType arg2) { + Boolean result = ((BooleanType) arg1).toBoolean() + && ((BooleanType) arg2).toBoolean(); + return new BooleanType(result); + } + + /** + * @see Operation#op(List) + */ + public DataType op(List args) { + boolean result = true; + + for (DataType dt : args) { + if (!((BooleanType) dt).toBoolean()) { + result = false; + break; + } + } + + return new BooleanType(result); + } + + /** + * @see Operation#star(DataType, Operation) + */ + public DataType star(DataType arg, Operation other) { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/Disjunction.java b/src/org/jalgo/module/app/core/dataType/booleanType/Disjunction.java new file mode 100644 index 0000000..bfabb82 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/Disjunction.java @@ -0,0 +1,103 @@ +package org.jalgo.module.app.core.dataType.booleanType; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.*; + +/** + * The binary operation Disjunction (or Boolean Or), which can + * be executed on BooleanType. + * + */ +public class Disjunction extends Operation { + + private static final long serialVersionUID = -6252134530049745634L; + + /** + * @see Operation#getID() + */ + public String getID() { + return "disjunct"; + } + + /** + * @see Operation#getName() + */ + public String getName() { + return "Disjunction"; + } + + /** + * @see Operation#getSymbolicRepresentation() + */ + public String getSymbolicRepresentation() { + return "\u2228"; + } + + /** + * @see Operation#getNotation() + */ + public Notation getNotation() { + return Notation.INFIX; + } + + /** + * @see Operation#getNeutralElement() + */ + public DataType getNeutralElement() { + return new BooleanType(false); + } + + /** + * @see Operation#getAbsorbingElement() + */ + public DataType getAbsorbingElement() { + return new BooleanType(true); + } + + /** + * @see Operation#isAssociative() + */ + public boolean isAssociative() { + return true; + } + + /** + * @see Operation#isCommutative() + */ + public boolean isCommutative() { + return true; + } + + /** + * @see Operation#op(DataType, DataType) + */ + public DataType op(DataType arg1, DataType arg2) { + Boolean result = ((BooleanType) arg1).toBoolean() || ((BooleanType) arg2).toBoolean(); + return new BooleanType(result); + } + + /** + * @see Operation#op(List) + */ + public DataType op(List args) { + boolean result = false; + + for (DataType dt : args) { + if (((BooleanType) dt).toBoolean()) { + result = true; + break; + } + } + + return new BooleanType(result); + } + + /** + * @see Operation#star(DataType, Operation) + */ + public DataType star(DataType arg, Operation other) { + return new BooleanType(true); + } + +} diff --git a/src/org/jalgo/module/app/core/dataType/booleanType/package.html b/src/org/jalgo/module/app/core/dataType/booleanType/package.html new file mode 100644 index 0000000..f27352d --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/booleanType/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of true and false and the appropriate operations. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Entries b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Entries new file mode 100644 index 0000000..1bfbb9d --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Entries @@ -0,0 +1,9 @@ +/Concatenate.java/1.2/Fri Oct 31 16:12:36 2008// +/ConcatenationLanguageObject.java/1.1/Wed Oct 29 18:05:25 2008// +/FormalLanguage.java/1.1/Wed Oct 29 18:05:25 2008// +/FormalLanguageObject.java/1.1/Wed Oct 29 18:05:25 2008// +/OptionLanguageObject.java/1.1/Wed Oct 29 18:05:25 2008// +/StarLanguageObject.java/1.1/Wed Oct 29 18:05:25 2008// +/StringLanguageObject.java/1.1/Wed Oct 29 18:05:25 2008// +/Union.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Repository b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Repository new file mode 100644 index 0000000..38f5966 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/dataType/formalLanguage diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Root b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.java new file mode 100644 index 0000000..ef0027e --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/Concatenate.java @@ -0,0 +1,87 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; + + +public class Concatenate extends Operation { + + private static final long serialVersionUID = -803641693937107202L; + + public String getID() { + return "concat"; + } + + public String getName() { + return "Concatenate"; + } + + public String getSymbolicRepresentation() { + return "\u2218"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return new FormalLanguage("\u03b5"); + } + + /** + * @see Operation#getNeutralElementDescription() + */ + public String getNeutralElementDescription() { + return "{"+getNeutralElement().toString()+"}"; + } + + public DataType getAbsorbingElement() { + return new FormalLanguage(); + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + //not commutative !!! + return false; + } + + public DataType op(DataType arg1, DataType arg2) { + FormalLanguage first, second; + String result; + + first = (FormalLanguage)arg1; + second = (FormalLanguage)arg2; + + if (first.isEmpty() || second.isEmpty()) + return getAbsorbingElement(); + + if (first.toString().equals("\u03b5")) + result = second.toString(); + else if (second.toString().equals("\u03b5")) + result = first.toString(); + else + result = first.toString()+second.toString(); + + return new FormalLanguage(result); + } + + public DataType op(List args) { + DataType newSet = getNeutralElement(); + + for (DataType dt : args) { + newSet = op(newSet, dt); + } + + return newSet; + } + + public DataType star(DataType arg, Operation other) { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.java new file mode 100644 index 0000000..7b1a137 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/ConcatenationLanguageObject.java @@ -0,0 +1,313 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +class ConcatenationLanguageObject extends FormalLanguageObject { + + private static final long serialVersionUID = 544559843466005098L; + private List parts; + + public ConcatenationLanguageObject() { + parts = new ArrayList(); + } + + public ConcatenationLanguageObject(String str) { + this(); + setFromString(str); + } + + public ConcatenationLanguageObject(List strParts) { + this(); + setFromParts(strParts); + } + + public ConcatenationLanguageObject(Collection parts) { + this(); + this.parts.addAll(parts); + } + + public ConcatenationLanguageObject(ConcatenationLanguageObject other) { + this(); + + for (FormalLanguageObject obj : other.parts) + parts.add(obj.clone()); + } + + public ConcatenationLanguageObject clone() { + return new ConcatenationLanguageObject(this.toString()); + } + + public boolean equals(Object other) { + ConcatenationLanguageObject ot; + + if (!(other instanceof ConcatenationLanguageObject)) + return false; + + ot = (ConcatenationLanguageObject) other; + return parts.equals(ot.parts); + } + + public String toString() { + String out; + + out = ""; + for (FormalLanguageObject obj : parts) + out += obj; + + return out; + } + + public void setFromString(String str) { + List strParts; + + strParts = FormalLanguage.splitLanguageString(str); + setFromParts(strParts); + } + + public void setFromParts(List strParts) { + parts.clear(); + + for (String strPart : strParts) + parts.add(FormalLanguage.languageFromString(strPart)); + } + + public List getParts() { + return parts; + } + + public void setParts(List parts) { + this.parts = parts; + } + + private enum StarAlignment { + STAR_ALIGNMENT_LEFT, + STAR_ALIGNMENT_RIGHT + } + + public FormalLanguageObject simplify() { + List newParts; + StarAlignment alignment; + boolean change; + + alignment = StarAlignment.STAR_ALIGNMENT_RIGHT; + + do { + change = false; + + /* + * Simplify all parts separately + */ + newParts = new ArrayList(); + + for (FormalLanguageObject obj : parts) { + FormalLanguageObject ret; + + ret = obj.simplify(); + if (ret != null) + newParts.add(ret); + } + + change = !(parts.equals(newParts)); + parts = newParts; + + /* + * Simplify combinations + */ + for (int i = 1; i < parts.size(); i++) { + FormalLanguageObject prev, curr, child, other; + + prev = parts.get(i - 1); + curr = parts.get(i); + + /* + * ALIGNMENT_LEFT: + * Match for pattern ...a(...a)*... + * Reduce to ...(a...)*a... + */ + if (alignment == StarAlignment.STAR_ALIGNMENT_LEFT + && (prev instanceof StringLanguageObject) + && (curr instanceof StarLanguageObject) + + && (other = prev) != null + && ((StringLanguageObject) other).getString().length() > 0 + + && (child = ((StarLanguageObject) curr).child) != null + && (child instanceof OptionLanguageObject) + && ((OptionLanguageObject)child).getOptions().size() == 1 + && (((OptionLanguageObject)child).getOptions().toArray()[0] instanceof StringLanguageObject) + ) { + StringLanguageObject otherObj, childObj; + String otherString, childString; + char c; + + otherObj = (StringLanguageObject)other; + childObj = (StringLanguageObject)((OptionLanguageObject)child).getOptions().toArray()[0]; + + otherString = otherObj.getString(); + childString = childObj.getString(); + c = otherString.charAt(otherString.length() - 1); + + if (c == childString.charAt(childString.length() - 1)) { + FormalLanguageObject next; + + /* + * Finally matches our pattern + */ + + otherString = otherString.substring(0, otherString.length() - 1); + childString = c + childString.substring(0, childString.length() - 1); + + otherObj.setString(otherString); + childObj.setString(childString); + + if (i < parts.size() - 1) + next = parts.get(i+1); + else + next = null; + + if (next != null && next instanceof StringLanguageObject) { + String nextString; + + nextString = ((StringLanguageObject)next).getString(); + nextString = c + nextString; + ((StringLanguageObject)next).setString(nextString); + } + else { + next = new StringLanguageObject(c + ""); + parts.add(i+1, next); + } + + change = true; + continue; + } + } + + /* + * ALIGNMENT_RIGHT: + * Match for pattern ...(a...)*a... + * Reduce to ...a(...a)*... + */ + + if (alignment == StarAlignment.STAR_ALIGNMENT_RIGHT + && (curr instanceof StringLanguageObject) + && (prev instanceof StarLanguageObject) + + && (other = curr) != null + && ((StringLanguageObject) other).getString().length() > 0 + + && (child = ((StarLanguageObject) prev).child) != null + && (child instanceof OptionLanguageObject) + && ((OptionLanguageObject)child).getOptions().size() == 1 + && (((OptionLanguageObject)child).getOptions().toArray()[0] instanceof StringLanguageObject) + ) { + StringLanguageObject otherObj, childObj; + String otherString, childString; + char c; + + otherObj = (StringLanguageObject)other; + childObj = (StringLanguageObject)((OptionLanguageObject)child).getOptions().toArray()[0]; + + otherString = otherObj.getString(); + childString = childObj.getString(); + c = otherString.charAt(0); + + if (c == childString.charAt(0)) { + FormalLanguageObject prePrev; + + /* + * Finally matches our pattern + */ + + otherString = otherString.substring(1, otherString.length()); + childString = childString.substring(1, childString.length()) + c; + + otherObj.setString(otherString); + childObj.setString(childString); + + if (i > 1) + prePrev = parts.get(i-2); + else + prePrev = null; + + if (prePrev != null && prePrev instanceof StringLanguageObject) { + String nextString; + + nextString = ((StringLanguageObject)prePrev).getString(); + nextString = nextString + c; + ((StringLanguageObject)prePrev).setString(nextString); + } + else { + prePrev = new StringLanguageObject("" + c); + parts.add(i-1, prePrev); + } + + change = true; + continue; + } + } + + /* + * Match for pattern ...(x+E)(x)*... and ...(x)*(x+E)... + * Reduce to ...(x)*... + */ + if (( // (z)y* + ((prev instanceof OptionLanguageObject) + && (curr instanceof StarLanguageObject) + && (other = prev) != null + && (child = ((StarLanguageObject) curr).child) != null) + || // y*(z) + ((curr instanceof OptionLanguageObject) + && (prev instanceof StarLanguageObject) + && (other = curr) != null + && (child = ((StarLanguageObject) prev).child) != null)) + // y == (x) + && ((child instanceof OptionLanguageObject) + && ((OptionLanguageObject)child).getOptions().size() == 1 + && (((OptionLanguageObject)child).getOptions().toArray()[0] instanceof StringLanguageObject))) { + StringLanguageObject childStringObject; + OptionLanguageObject optionObject; + + childStringObject = (StringLanguageObject) ((OptionLanguageObject)child).getOptions().toArray()[0]; + optionObject = (OptionLanguageObject)other; + + if (optionObject.getOptions().size() == 2 + && optionObject.getOptions().contains(childStringObject) + && optionObject.getOptions().contains(new StringLanguageObject("\uu03b5"))) { + parts.remove(optionObject); + + i--; + change = true; + continue; + } + } + } + + /* + * Remove special parts + */ + if (parts.size() > 1) + parts.remove(new StringLanguageObject("\u03b5")); + + /* + * Check parts + */ + + /* + * If nothing changed switch the alignment + */ + if (!change && alignment != StarAlignment.STAR_ALIGNMENT_LEFT) { + alignment = StarAlignment.STAR_ALIGNMENT_LEFT; + change = true; + } + } while (change); + + if (parts.size() == 0) + return null; + if (parts.size() == 1) + return parts.get(0); + + return this; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.java new file mode 100644 index 0000000..95d682f --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguage.java @@ -0,0 +1,348 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; + +public class FormalLanguage extends DataType { + + /* + * (non-Javadoc) CLASS METHODS + */ + + private static final long serialVersionUID = 4065198973755158572L; + + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new Union()); + operations.add(new Concatenate()); + + return operations; + } + + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + public static String getName() { + return "Formal Language"; + } + + public static String[] getSymbolicRepresentation() { + String[] returnValue = { "P(\u03A3*)", "", "" }; + + return returnValue; + } + + /* + * (non-Javadoc) INSTANCE METHODS + */ + + private FormalLanguageObject language; + + /** + * Sets the default value for a formal language of the set with epsilon. + */ + public FormalLanguage() { + language = emptyLanguage(); + } + + public FormalLanguage(String value) { + this(); + setFromString(value); + } + + public FormalLanguage(FormalLanguage other) { + if (other.language != null) + language = other.language.clone(); + } + + /** + * Sets the language by parsing the given string. + * + * @param str + * the string to parse + * @return true if successful, false otherwise + */ + public boolean setFromString(String str) { + if (str == "\u2205") + str = ""; + + try { + language = languageFromString(str); + + simplify(); + + return true; + } catch (Exception e) { + return false; + } + } + + public boolean isEmpty() { + return (language == null); + } + + public String toString() { + if (language != null) + return language.toString(); + else + return "\u2205"; + } + + public boolean equals(Object ot) { + FormalLanguage other; + + if (ot == null || !(ot instanceof FormalLanguage)) { + return false; + } + + other = (FormalLanguage) ot; + if (language == null) { + if (other.language == null) + return true; + else + return false; + } else { + return (language.equals(other.language)); + } + } + + public FormalLanguage clone() { + return new FormalLanguage(this); + } + + /** + * Simplifies the whole language. + */ + private void simplify() { + if (language == null) + return; + + /* + * Simplify language + */ + FormalLanguageObject newLanguage; + boolean change; + + do { + newLanguage = language.simplify(); + change = (newLanguage != null && !newLanguage.equals(language)); + language = newLanguage; + } while (change); + + /* + * Simplify root element + */ + if ((language instanceof OptionLanguageObject) + && ((OptionLanguageObject) language).getOptions().size() == 1) { + language = ((OptionLanguageObject) language).getOptions().first(); + } + if ((language instanceof ConcatenationLanguageObject) + && ((ConcatenationLanguageObject) language).getParts().size() == 1) { + language = ((ConcatenationLanguageObject) language).getParts().get( + 0); + } + } + + /** + * Creates empty FormalLanguageObject. + * + * @return a empty formal language object + */ + static FormalLanguageObject emptyLanguage() { + return null; + } + + /** + * Creates a FormalLanguageObject from the given string. + * + * @param str + * the formal language as string + * @return a formal language object + */ + static FormalLanguageObject languageFromString(String str) { + List parts; + + parts = splitLanguageString(str); + + if (parts.size() == 0) + return emptyLanguage(); + if (parts.size() >= 2) + return new ConcatenationLanguageObject(parts); + + // Single Object + if (str.charAt(str.length() - 1) == '*') + return new StarLanguageObject(str); + else if (str.charAt(0) == '(' && str.charAt(str.length() - 1) == ')') + return new OptionLanguageObject(str); + else + return new StringLanguageObject(str); + } + + /** + * Splits str by divider, retaining the + * parenthesis structure of the contained elements + * + * @param str + * the string to split + * @param divider + * the character to split by + * @return the split string or null if parenthesis do not + * match + */ + public static List sensitiveSplit(String str, char divider) { + int count, index, begin; + List parts; + + index = begin = 0; + count = 0; + parts = new ArrayList(); + + while (index < str.length()) { + char character; + + character = str.charAt(index); + if (character == '(') + count++; + if (character == ')') + count--; + if (character == divider && count == 0) { + if (begin < index) + parts.add(str.substring(begin, index)); + begin = index + 1; + } + + index++; + } + + if (begin < index) + parts.add(str.substring(begin, index)); + + if (count != 0) + return null; + else + return parts; + } + + /** + * Combination of String.indexOf, + * String.matches and String.replace. Runs + * through string and matches at every position for + * reg. If found, the occurrence is replaced by a substring + * from the offset newStart to newEnd. + * + * @param string + * the string to search in + * @param reg + * the regular expression to match with + * @param origLen + * the fixed length of all possible matches to reg + * @param newStart + * the replacement substring start index + * @param newEnd + * the replacement substring end index + * @return the string with all replacements + */ + public static String findAndReplaceRegEx(String string, String reg, + int origLen, int newStart, int newEnd) { + int index; + + for (index = 0; index + origLen <= string.length(); index++) { + String part; + + part = string.substring(index, index + origLen); + if (!part.matches(reg)) + continue; + + string = string.replace(part, string.substring(index + newStart, + index + newEnd)); + index--; + } + + return string; + } + + /** + * Splits up the given string into parts, so that each part is again a + * formal language, with special attention parenthesis pairs and star + * operations. + * + * @param str + * the string to split + * @return a List of Strings + */ + public static List splitLanguageString(String str) { + int count, index, begin; + + List strParts; + + index = begin = 0; + count = 0; + strParts = new ArrayList(); + + while (index < str.length()) { + char character; + + character = str.charAt(index); + + if (character == '(') { + if (count == 0 && begin < index) { + strParts.add(str.substring(begin, index)); + begin = index; + } + + count++; + } + + if (character == ')') { + count--; + + if (count == 0 && begin < index) { + strParts.add(str.substring(begin, index + 1)); + begin = index + 1; + } + } + + if (character == '*' && count == 0) { + int max; + + if (begin < index) + strParts.add(str.substring(begin, index)); + + max = strParts.size() - 1; + if (max >= 0) + strParts.set(max, strParts.get(max) + "*"); + else + throw new IllegalArgumentException(); + + begin = index + 1; + } + + index++; + } + + if (begin < index) + strParts.add(str.substring(begin, index)); + + return strParts; + } + + public String[] getSpecialCharacter() { + String[] out = { "\u03b5" }; + + return out; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.java new file mode 100644 index 0000000..1c03e6e --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/FormalLanguageObject.java @@ -0,0 +1,51 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.io.Serializable; + +abstract class FormalLanguageObject implements Comparable, Serializable { + /** + * Returns a string representation of the language. + */ + public abstract String toString(); + + /** + * Sets the value of the object to the language represented by + * str. + * + * Throws a InvalidArgumentException if language does not match the object's + * language type. + * + * @param str + * the string to set the object value from + */ + public abstract void setFromString(String str); + + /** + * Try to simplify the language object. Actual implementation might give + * more information about the things actually done. + * + * The returned object might be the same as the object that was called, but + * it might also be a replacement or null if the object has + * become empty. + * + * @return the simplified object + */ + public abstract FormalLanguageObject simplify(); + + /** + * @see Object.clone + */ + public abstract FormalLanguageObject clone(); + + /** + * @see Object.equals + */ + public abstract boolean equals(Object other); + + /** + * @see Comparable.compareTo + */ + public int compareTo(FormalLanguageObject other) { + return this.toString().compareTo(other.toString()); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.java new file mode 100644 index 0000000..edb215f --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/OptionLanguageObject.java @@ -0,0 +1,250 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.Iterator; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +class OptionLanguageObject extends FormalLanguageObject { + private static final long serialVersionUID = 36142298841024703L; + SortedSet options; + + public OptionLanguageObject() { + options = new TreeSet(); + } + + public OptionLanguageObject(String str) { + this(); + setFromString(str); + } + + public OptionLanguageObject(OptionLanguageObject other) { + this(); + + for (FormalLanguageObject obj : other.options) + options.add(obj.clone()); + } + + public OptionLanguageObject clone() { + return new OptionLanguageObject(this.toString()); + } + + public boolean equals(Object other) { + OptionLanguageObject ot; + + if (!(other instanceof OptionLanguageObject)) + return false; + + ot = (OptionLanguageObject) other; + return options.equals(ot.options); + } + + public SortedSet getOptions() { + return options; + } + + public void setOptions(SortedSet options) { + this.options = options; + } + + public String toString() { + String out; + + out = "("; + + for (FormalLanguageObject obj : options) + out += obj + "+"; + + if (out.length() > 1) + out = out.substring(0, out.length() - 1); + out += ")"; + + return out; + } + + public void setFromString(String str) { + List strings; + + if (str.charAt(0) != '(' || str.charAt(str.length() - 1) != ')') + throw new IllegalArgumentException(); + + str = str.substring(1, str.length() - 1); + + strings = FormalLanguage.sensitiveSplit(str, '+'); + options.clear(); + + for (String aStr : strings) + options.add(FormalLanguage.languageFromString(aStr)); + } + + public FormalLanguageObject simplify() { + SortedSet newOptions; + boolean change; + + do { + change = false; + + /* + * Simplify all options separately + */ + newOptions = new TreeSet(); + + for (FormalLanguageObject obj : options) { + FormalLanguageObject ret; + + ret = obj.simplify(); + if (ret != null) { + if (ret instanceof OptionLanguageObject) + newOptions.addAll(((OptionLanguageObject)ret).getOptions()); + else + newOptions.add(ret); + } + } + + change = !(options.equals(newOptions)); + options = newOptions; + + /* + * Simplify combinations + */ + Iterator it; + + it = options.iterator(); + + while (it.hasNext()) { + FormalLanguageObject curr, child; + + curr = it.next(); + + /* + * Match for pattern (a(x)*xb, aEb) and (a(x)*b, aEb) + * Reduce to (a(x)*b) + */ + if (curr instanceof ConcatenationLanguageObject) { + FormalLanguageObject pre, post, conc; + FormalLanguageObject p1, p2; + ConcatenationLanguageObject obj; + String innerString, outerString; + int i; + + obj = (ConcatenationLanguageObject)curr; + pre = post = null; + p1 = p2 = child = null; + innerString = outerString = null; + + for (i=0; i 0) + pre = new ConcatenationLanguageObject(obj.getParts().subList(0, i)); + if (obj.getParts().size() > i+2) + post = new ConcatenationLanguageObject(obj.getParts().subList(i+2, obj.getParts().size())); + if (outerString == null && obj.getParts().size() > i+1) + post = new ConcatenationLanguageObject(obj.getParts().subList(i+1, obj.getParts().size())); + + if (outerString != null && !outerString.equals(innerString)) { + StringLanguageObject remainder; + + remainder = new StringLanguageObject(outerString.substring(innerString.length())); + + if (post != null) + ((ConcatenationLanguageObject)post).getParts().add(0, remainder); + else + post = remainder; + } + + if (pre == null && post == null) + pre = new StringLanguageObject("\u03b5"); + + if (pre == null) + conc = post; + else if (post == null) + conc = pre; + else { + conc = new ConcatenationLanguageObject(); + ((ConcatenationLanguageObject)conc).getParts().add(pre); + ((ConcatenationLanguageObject)conc).getParts().add(post); + conc.simplify(); + } + + if (options.contains(conc)) { + options.remove(conc); + if (outerString != null) + ((StringLanguageObject)p2).setString(outerString.substring(innerString.length())); + + it = options.iterator(); + change = true; + } + } + + + /* + * Match for pattern (..., (x)*[, x][, E], ...) + * Reduce to (..., (x)*, ...) + */ + if (curr instanceof StarLanguageObject + && ( + ((((StarLanguageObject)curr).getChild() instanceof StringLanguageObject) + && (child = ((StarLanguageObject)curr).getChild()) != null) + || + ((((StarLanguageObject)curr).getChild() instanceof OptionLanguageObject) + && (child = ((StarLanguageObject)curr).getChild()) != null + && ((OptionLanguageObject)child).getOptions().size() == 1 + && (((OptionLanguageObject)child).getOptions().toArray()[0] instanceof StringLanguageObject) + && (child = (FormalLanguageObject)((OptionLanguageObject)child).getOptions().toArray()[0]) != null + ) + )) { + if (options.contains(child)) { + options.remove(child); + change = true; + it = options.iterator(); + } + if (options.contains(new StringLanguageObject("\u03b5"))) { + options.remove(new StringLanguageObject("\u03b5")); + change = true; + it = options.iterator(); + } + } + } + } while (change); + + if (options.size() == 0) + return null; + + return this; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.java new file mode 100644 index 0000000..2021894 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/StarLanguageObject.java @@ -0,0 +1,126 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.SortedSet; + +class StarLanguageObject extends FormalLanguageObject { + + private static final long serialVersionUID = -3034912517665116911L; + FormalLanguageObject child; + + public StarLanguageObject() { + child = null; + } + + public StarLanguageObject(FormalLanguageObject child) { + this.child = child; + } + + public StarLanguageObject(String str) { + setFromString(str); + } + + public StarLanguageObject clone() { + return new StarLanguageObject(this.toString()); + } + + public boolean equals(Object other) { + StarLanguageObject ot; + + if (!(other instanceof StarLanguageObject)) + return false; + + ot = (StarLanguageObject) other; + return child.equals(ot.child); + } + + public FormalLanguageObject getChild() { + return child; + } + + public void setChild(FormalLanguageObject child) { + this.child = child; + } + + public String toString() { + return child + "*"; + } + + public void setFromString(String str) { + if (str.charAt(str.length() - 1) != '*') + throw new IllegalArgumentException(); + + child = FormalLanguage.languageFromString(str.substring(0, + str.length() - 1)); + } + + public FormalLanguageObject simplify() { + FormalLanguageObject newChild; + boolean change; + + if (child == null) + return new StringLanguageObject("\u03b5"); + + change = false; + + do { + /* + * Remember that something changed + */ + change = false; + + /* + * Simplify child + */ + newChild = child.simplify(); + change = !newChild.equals(child); + child = newChild; + + if (child == null) + return new StringLanguageObject("\u03b5"); + + /* + * Check child + */ + if (child instanceof StarLanguageObject) + child = ((StarLanguageObject) child).child; + + if (child instanceof OptionLanguageObject) { + SortedSet options; + + options = ((OptionLanguageObject) child).getOptions(); + + if (options.size() == 1) { + FormalLanguageObject baby; + + baby = options.first(); + + if ((baby instanceof StringLanguageObject) + && ((StringLanguageObject) baby).getString() + .length() == 1) { + child = baby; + change = true; + continue; + } + if ((baby instanceof StarLanguageObject)) { + child = ((StarLanguageObject) baby).getChild(); + change = true; + continue; + } + } + + options.remove(new StringLanguageObject("\u03b5")); + } + + if (child instanceof StringLanguageObject) { + StringLanguageObject strObject; + + strObject = (StringLanguageObject) child; + if (strObject.getString().equals("\u03b5")) + return strObject; + } + + } while (change); + + return this; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.java new file mode 100644 index 0000000..7c73a40 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/StringLanguageObject.java @@ -0,0 +1,96 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +class StringLanguageObject extends FormalLanguageObject { + + private static final long serialVersionUID = -7090260348441367569L; + private static final String epsilon = "\u03B5"; + private String str; + + public StringLanguageObject() { + str = ""; + } + + public StringLanguageObject(String str) { + setFromString(str); + } + + /** + * @see FormalLanguageObject.toString + */ + public String toString() { + return getString(); + } + + /** + * @see FormalLanguageObject.setFromString + */ + public void setFromString(String str) { + setString(str); + } + + /** + * @see FormalLanguageObject.clone + */ + public StringLanguageObject clone() { + return new StringLanguageObject(str); + } + + /** + * @see FormalLanguageObject.equals + */ + public boolean equals(Object other) { + StringLanguageObject ot; + + if (!(other instanceof StringLanguageObject)) + return false; + + ot = (StringLanguageObject) other; + return str.equals(ot.str); + } + + public String getString() { + return str; + } + + public void setString(String str) { + // "E" will be replaced by "\u03B5" in simplify() + if (!str.matches("[\u03B5a-zE]*")) + throw new IllegalArgumentException(); + + this.str = new String(str); + } + + /** + * Simplifies object by removing whitespace and epsilon occurrences in + * concatenation with literals. + * + * @see FormalLanguageObject.simplify + */ + public FormalLanguageObject simplify() { + String value; + + value = str; + value = value.replaceAll(" ", ""); + value = value.replaceAll("E", "\u03B5"); + + String before; + do { + before = value; + //ET: "E" replaced by "\u03B5" + value = FormalLanguage + .findAndReplaceRegEx(value, "\u03B5[\u03B5a-z]", 2, 1, 2); + //ET: "E" replaced by "\u03B5" + value = FormalLanguage + .findAndReplaceRegEx(value, "[\u03B5a-z]\u03B5", 2, 0, 1); + + } while (!value.equals(before)); + + if (value.length() == 0) + return null; + + if (!value.equals(str)) + return new StringLanguageObject(value); + else + return this; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/Union.java b/src/org/jalgo/module/app/core/dataType/formalLanguage/Union.java new file mode 100644 index 0000000..70331fe --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/Union.java @@ -0,0 +1,93 @@ +package org.jalgo.module.app.core.dataType.formalLanguage; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; + + +public class Union extends Operation { + + private static final long serialVersionUID = -102320253876107809L; + + public String getID() { + return "union"; + } + + public String getName() { + return "Union"; + } + + public String getSymbolicRepresentation() { + return "\u222A"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return new FormalLanguage(); + } + + public DataType getAbsorbingElement() { + return null; + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + return true; + } + + public DataType op(DataType arg1, DataType arg2) { + FormalLanguage first, second; + String result; + + first = (FormalLanguage)arg1; + second = (FormalLanguage)arg2; + + if (first.isEmpty()) + return second; + if (second.isEmpty()) + return first; + + result = "("+first.toString()+"+"+second.toString()+")"; + return new FormalLanguage(result); + } + + public DataType op(List args) { + String result; + + result = "("; + for (DataType dt : args) { + if (!((FormalLanguage)dt).isEmpty()) + result += (FormalLanguage)dt + "+"; + } + + if (result.length() > 1) + result = result.substring(0, result.length()-1); + result += ")"; + + return new FormalLanguage(result); + } + + /** + * The star operation on formal languages. + */ + public DataType star(DataType arg, Operation other) { + FormalLanguage lang; + + lang = (FormalLanguage)arg; + + if (lang.isEmpty()) { + return new FormalLanguage("\u03b5"); + } + + String result = "("+lang+")*"; + return new FormalLanguage(result); + } + +} diff --git a/src/org/jalgo/module/app/core/dataType/formalLanguage/package.html b/src/org/jalgo/module/app/core/dataType/formalLanguage/package.html new file mode 100644 index 0000000..f4429f8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/formalLanguage/package.html @@ -0,0 +1,10 @@ + + + + + + +A formal language and the appropriate operations. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Entries b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Entries new file mode 100644 index 0000000..f996725 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Entries @@ -0,0 +1,6 @@ +/NaturalAdd.java/1.1/Wed Oct 29 18:05:25 2008// +/NaturalMaximum.java/1.1/Wed Oct 29 18:05:25 2008// +/NaturalMinimum.java/1.1/Wed Oct 29 18:05:25 2008// +/NaturalMultiply.java/1.1/Wed Oct 29 18:05:25 2008// +/NaturalNumber.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Repository b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Repository new file mode 100644 index 0000000..ac52cfb --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/dataType/naturalNumber diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Root b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.java b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.java new file mode 100644 index 0000000..6e906b4 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalAdd.java @@ -0,0 +1,76 @@ +package org.jalgo.module.app.core.dataType.naturalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.*; + +/** + * Represents the addition in the natural numbers. + * + */ +public class NaturalAdd extends Operation { + + private static final long serialVersionUID = -4126828819528924337L; + + public String getID() { + return "add"; + } + + public String getName() { + return "Addition"; + } + + public String getSymbolicRepresentation() { + return "+"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return new NaturalNumber(0); + } + + public DataType getAbsorbingElement() { + return new NaturalNumber(Infinity.POSITIVE_INFINITE); + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + return true; + } + + public DataType op(DataType arg1, DataType arg2) { + int value; + + if (((NaturalNumber)arg1).getInfinity() != Infinity.REAL || ((NaturalNumber)arg2).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + value = ((NaturalNumber)arg1).toInt(); + value += ((NaturalNumber)arg2).toInt(); + + return new NaturalNumber(value); + } + + public DataType op(List args){ + int value; + + value = 0; + for(DataType dt : args) { + if (((NaturalNumber)dt).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + value += ((NaturalNumber)dt).toInt(); + } + + return new NaturalNumber(value); + } + + public DataType star(DataType arg, Operation other) { + return getAbsorbingElement(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.java b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.java new file mode 100644 index 0000000..ad43dc4 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMaximum.java @@ -0,0 +1,111 @@ +package org.jalgo.module.app.core.dataType.naturalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + +/** + * Represents the maximum operation in the natural numbers (e.g. max{2,3} = 3). + * + */ +public class NaturalMaximum extends Operation { + + private static final long serialVersionUID = 6775657970133861189L; + + /** + * @see Operation#getID() + */ + public String getID() { + return "max"; + } + + /** + * @see Operation#getName() + */ + public String getName() { + return "Maximum"; + } + + /** + * @see Operation#getSymbolicRepresentation() + */ + public String getSymbolicRepresentation() { + return "max"; + } + + /** + * @see Operation#getNotation() + */ + public Notation getNotation() { + return Notation.PREFIX; + } + + /** + * @see Operation#getNeutralElement() + */ + public DataType getNeutralElement() { + return new NaturalNumber(0); + } + + /** + * @see Operation#getAbsorbingElement() + */ + public DataType getAbsorbingElement() { + return new NaturalNumber(Infinity.POSITIVE_INFINITE); + } + + /** + * @see Operation#isAssociative() + */ + public boolean isAssociative() { + return true; + } + + /** + * @see Operation#isCommutative() + */ + public boolean isCommutative() { + return true; + } + + /** + * @see Operation#op(DataType, DataType) + */ + public DataType op(DataType arg1, DataType arg2) { + int value; + + if (((NaturalNumber) arg1).getInfinity() != Infinity.REAL + || ((NaturalNumber) arg2).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + value = Math.max(((NaturalNumber) arg1).toInt(), ((NaturalNumber) arg2) + .toInt()); + return new NaturalNumber(value); + } + + /** + * @see Operation#op(List) + */ + public DataType op(List args) { + int value; + + value = 0; + for (DataType dt : args) { + if (((NaturalNumber) dt).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + value = Math.max(value, ((NaturalNumber) dt).toInt()); + } + + return new NaturalNumber(value); + } + + /** + * @see Operation#star(DataType, Operation) + */ + public DataType star(DataType arg, Operation other) { + return getAbsorbingElement(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.java b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.java new file mode 100644 index 0000000..cf3a0e5 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMinimum.java @@ -0,0 +1,75 @@ +package org.jalgo.module.app.core.dataType.naturalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.*; + +/** + * Represents the minimum operation in the natural numbers (e.g. min{2,3} = 2). + * + */ +public class NaturalMinimum extends Operation { + + private static final long serialVersionUID = 1671869633291013726L; + + public String getID() { + return "min"; + } + + public String getName() { + return "Minimum"; + } + + public String getSymbolicRepresentation() { + return "min"; + } + + public Notation getNotation() { + return Notation.PREFIX; + } + + public DataType getNeutralElement() { + return new NaturalNumber(Infinity.POSITIVE_INFINITE); + } + + public DataType getAbsorbingElement() { + return new NaturalNumber(0); + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + return true; + } + + public DataType op(DataType arg1, DataType arg2) { + int value; + + if (((NaturalNumber)arg1).getInfinity() != Infinity.REAL) + return arg2; + if (((NaturalNumber)arg2).getInfinity() != Infinity.REAL) + return arg1; + + value = Math.min(((NaturalNumber)arg1).toInt(), ((NaturalNumber)arg2).toInt()); + return new NaturalNumber(value); + } + + public DataType op(List args){ + int value; + + value = Integer.MAX_VALUE; + for(DataType dt : args) { + if (((NaturalNumber)dt).getInfinity() == Infinity.REAL) + value = Math.min(value, ((NaturalNumber)dt).toInt()); + } + + return new NaturalNumber(value); + } + + + public DataType star(DataType arg, Operation other) { + return getAbsorbingElement(); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.java b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.java new file mode 100644 index 0000000..0af6279 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalMultiply.java @@ -0,0 +1,77 @@ +package org.jalgo.module.app.core.dataType.naturalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.*; + +/** + * Represents the multiply operation on natural numbers. + * + */ +public class NaturalMultiply extends Operation { + + private static final long serialVersionUID = 4281150139970963974L; + + public String getID() { + return "mult"; + } + + public String getName() { + return "Multiplication"; + } + + public String getSymbolicRepresentation() { + return "\u2219"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return new NaturalNumber(1); + } + + public DataType getAbsorbingElement() { + return new NaturalNumber(Infinity.POSITIVE_INFINITE); + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + return true; + } + + public DataType op(DataType arg1, DataType arg2) { + int value; + + if (((NaturalNumber)arg1).getInfinity() != Infinity.REAL || ((NaturalNumber)arg2).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + + value = ((NaturalNumber)arg1).toInt(); + value *= ((NaturalNumber)arg2).toInt(); + + return new NaturalNumber(value); + } + + public DataType op(List args){ + int value; + + value = 1; + for(DataType dt : args) { + if (((NaturalNumber)dt).getInfinity() != Infinity.REAL) + return getAbsorbingElement(); + + value *= ((NaturalNumber)dt).toInt(); + } + + return new NaturalNumber(value); + } + + public DataType star(DataType arg, Operation other) { + return getAbsorbingElement(); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.java b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.java new file mode 100644 index 0000000..1d09ae7 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/NaturalNumber.java @@ -0,0 +1,197 @@ +package org.jalgo.module.app.core.dataType.naturalNumber; + +import java.util.*; + +import org.jalgo.module.app.core.dataType.*; + +/** + * Represents a natural number (an int >= 0). + * + */ +public class NaturalNumber extends NumericDataType { + + private static final long serialVersionUID = 5634981613906809570L; + + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new NaturalAdd()); + operations.add(new NaturalMultiply()); + operations.add(new NaturalMinimum()); + operations.add(new NaturalMaximum()); + + return operations; + } + + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + public static String getName() { + return "Natural Number"; + } + + public static String[] getSymbolicRepresentation() { + String[] returnValue = {"\u2115", "", "\u221e"}; + + return returnValue; + } + + private int value; + + /** + * Instantiates a new natural number. + */ + public NaturalNumber() { + value = 0; + } + + /** + * Instantiates a new natural number with the value val + * @param val the start value of the instance + */ + public NaturalNumber(int val) { + if (val >= 0) { + value = val; + } else { + throw new IllegalArgumentException(); + } + } + + /** + * Instantiates a new natural number with a kind of Infinity. + * @param inf the kind of {@link Infinity} + */ + public NaturalNumber(Infinity inf) { + setInfinity(inf); + } + + public NaturalNumber clone() { + NaturalNumber num; + + num = new NaturalNumber(); + num.setFromNumeric(this); + + return num; + } + + @Override + public boolean setFromFloat(float val) { + if (val >= 0) { + value = (int) val; + return true; + } + else { + return false; + } + } + + @Override + public boolean setFromInt(int val) { + if (val >= 0) { + value = val; + return true; + } + else { + return false; + } + } + + @Override + public boolean setFromNumeric(NumericDataType num) { + Infinity inf; + int val; + + val = num.toInt(); + inf = num.getInfinity(); + + if (inf != Infinity.REAL) { + return setInfinity(inf); + } + if (val >= 0) { + value = val; + return true; + } + else { + return false; + } + } + + @Override + public float toFloat() { + return value; + } + + @Override + public int toInt() { + return value; + } + + @Override + public boolean setFromString(String str) { + int val; + + // Input is infinite + if (str.equals("\u221e")) { + setInfinity(Infinity.POSITIVE_INFINITE); + return true; + } + + // Input is real + try { + val = Integer.parseInt(str); + } + catch (NumberFormatException ex) { + return false; + } + + if (val >= 0 && val <= MaxValues.getNaturalNumberMaximum()) { + value = val; + return true; + } else { + return false; + } + } + + @Override + public String toString() { + if (value != Integer.MAX_VALUE) { + return String.valueOf(value); + } else { + return "\u221e"; + } + } + + @Override + public Infinity getInfinity() { + if (value != Integer.MAX_VALUE) + return Infinity.REAL; + else + return Infinity.POSITIVE_INFINITE; + } + + @Override + public boolean setInfinity(Infinity inf) { + if (inf == Infinity.POSITIVE_INFINITE) + value = Integer.MAX_VALUE; + else if (inf == Infinity.REAL) + value = 0; + else + return false; + + return true; + } + + public String[] getSpecialCharacter() { + String[] out = {"\u221e"}; + + return out; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/naturalNumber/package.html b/src/org/jalgo/module/app/core/dataType/naturalNumber/package.html new file mode 100644 index 0000000..f95ea98 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/naturalNumber/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of natural numbers and the appropriate operations. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/package.html b/src/org/jalgo/module/app/core/dataType/package.html new file mode 100644 index 0000000..c94687f --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/package.html @@ -0,0 +1,10 @@ + + + + + + +Provides several sets of mathematical structures and the appropriate operations. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Entries b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Entries new file mode 100644 index 0000000..23ed60e --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Entries @@ -0,0 +1,9 @@ +/PercentageType.java/1.1/Wed Oct 29 18:05:24 2008// +/PositiveRationalNumber.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalAdd.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalMaximum.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalMinimum.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalMultiply.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalNumber.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalOperation.java/1.1/Wed Oct 29 18:05:24 2008// +/package.html/1.1/Wed Oct 29 18:05:24 2008// diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Repository b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Repository new file mode 100644 index 0000000..c8619b2 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/dataType/rationalNumber diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Root b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.java new file mode 100644 index 0000000..51a9605 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/PercentageType.java @@ -0,0 +1,71 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.HashSet; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class PercentageType extends RationalNumber { + + private static final long serialVersionUID = 6885280182754231240L; + + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new RationalAdd(PercentageType.class)); + operations.add(new RationalMultiply(PercentageType.class)); + operations.add(new RationalMinimum(PercentageType.class)); + operations.add(new RationalMaximum(PercentageType.class)); + + return operations; + } + + public static String getName() { + return "Percentage"; + } + + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + public static String[] getSymbolicRepresentation() { + String[] returnValue = {"[0,1]","", ""}; + + return returnValue; + } + + @Override + protected float minimumValue() { + return 0f; + } + + @Override + protected float maximumValue() { + return 1f; + } + + public PercentageType() { + super(); + } + + public PercentageType(float val) { + super(val); + } + + public PercentageType(Infinity inf) { + super(inf); + } + + public String[] getSpecialCharacter() { + return null; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.java new file mode 100644 index 0000000..93fc7ce --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/PositiveRationalNumber.java @@ -0,0 +1,66 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.HashSet; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class PositiveRationalNumber extends RationalNumber { + + /* + * (non-Javadoc) CLASS METHODS + */ + + private static final long serialVersionUID = -3314801881292434525L; + + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new RationalAdd(PositiveRationalNumber.class)); + operations.add(new RationalMultiply(PositiveRationalNumber.class)); + operations.add(new RationalMinimum(PositiveRationalNumber.class)); + operations.add(new RationalMaximum(PositiveRationalNumber.class)); + + return operations; + } + + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + public static String getName() { + return "Positive Rational Number"; + } + + public static String[] getSymbolicRepresentation() { + String[] returnValue = {"\u211d","+", "\u221e"}; + + return returnValue; + } + + @Override + protected float minimumValue() { + return 0f; + } + + public PositiveRationalNumber() { + super(); + } + + public PositiveRationalNumber(float val) { + super(val); + } + + public PositiveRationalNumber(Infinity inf) { + super(inf); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.java new file mode 100644 index 0000000..38a37f1 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalAdd.java @@ -0,0 +1,60 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class RationalAdd extends RationalOperation { + + private static final long serialVersionUID = -4062506241253643485L; + + public RationalAdd(Class aClass) { + super(aClass); + } + + public String getID() { + return "add"; + } + + public String getName() { + return "Addition"; + } + + public String getSymbolicRepresentation() { + return "+"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return newNumber(0.0f); + } + + public DataType getAbsorbingElement() { + return newNumber(Infinity.POSITIVE_INFINITE); + } + + public DataType op(DataType arg1, DataType arg2) { + float value = ((RationalNumber)arg1).toFloat() + ((RationalNumber)arg2).toFloat(); + return newNumber(value); + } + + public DataType op(List args) { + float value; + + value = 0.f; + for (DataType dt : args) { + if (((RationalNumber)dt).getInfinity() != Infinity.REAL) + return dt; + + value += ((RationalNumber)dt).toFloat(); + } + + return newNumber(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.java new file mode 100644 index 0000000..2bc5406 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMaximum.java @@ -0,0 +1,57 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class RationalMaximum extends RationalOperation { + + private static final long serialVersionUID = 1368560676570531780L; + + public RationalMaximum(Class aClass) { + super(aClass); + } + + public String getID() { + return "max"; + } + + public String getName() { + return "Maximum"; + } + + public String getSymbolicRepresentation() { + return "max"; + } + + public Notation getNotation() { + return Notation.PREFIX; + } + + public DataType getNeutralElement() { + return newNumber(Infinity.NEGATIVE_INFINITE); + } + + public DataType getAbsorbingElement() { + return newNumber(Infinity.POSITIVE_INFINITE); + } + + public DataType op(DataType arg1, DataType arg2) { + float value = Math.max(((RationalNumber)arg1).toFloat(), ((RationalNumber)arg2).toFloat()); + return newNumber(value); + } + + public DataType op(List args) { + float value; + + value = ((RationalNumber)getNeutralElement()).toFloat(); + + for (DataType dt : args) + value = Math.max(value, ((RationalNumber)dt).toFloat()); + + return newNumber(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.java new file mode 100644 index 0000000..d165c7b --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMinimum.java @@ -0,0 +1,56 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class RationalMinimum extends RationalOperation { + + private static final long serialVersionUID = -8101248622263077182L; + + public RationalMinimum(Class aClass) { + super(aClass); + } + + public String getID() { + return "min"; + } + + public String getName() { + return "Minimum"; + } + + public String getSymbolicRepresentation() { + return "min"; + } + + public Notation getNotation() { + return Notation.PREFIX; + } + + public DataType getNeutralElement() { + return newNumber(Infinity.POSITIVE_INFINITE); + } + + public DataType getAbsorbingElement() { + return newNumber(Infinity.NEGATIVE_INFINITE); + } + + public DataType op(DataType arg1, DataType arg2) { + float value = Math.min(((RationalNumber)arg1).toFloat(), ((RationalNumber)arg2).toFloat()); + return newNumber(value); + } + + public DataType op(List args) { + float value; + + value = ((RationalNumber)getNeutralElement()).toFloat(); + for (DataType dt : args) + value = Math.min(value, ((RationalNumber)dt).toFloat()); + + return newNumber(value); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.java new file mode 100644 index 0000000..6d6bb9b --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalMultiply.java @@ -0,0 +1,77 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public class RationalMultiply extends RationalOperation { + + private static final long serialVersionUID = 3133209844705037342L; + + public RationalMultiply(Class aClass) { + super(aClass); + } + + public String getID() { + return "mult"; + } + + public String getName() { + return "Multiplication"; + } + + public String getSymbolicRepresentation() { + return "\u2219"; + } + + public Notation getNotation() { + return Notation.INFIX; + } + + public DataType getNeutralElement() { + return newNumber(1.f); + } + + public DataType getAbsorbingElement() { + return newNumber(Infinity.POSITIVE_INFINITE); + } + + public DataType op(DataType arg1, DataType arg2) { + Infinity inf1, inf2; + float value; + + // This extra test is necessary as we don't want exceptions + inf1 = ((RationalNumber)arg1).getInfinity(); + inf2 = ((RationalNumber)arg2).getInfinity(); + + if (inf1 != Infinity.REAL) + return newNumber(inf1); + if (inf2 != Infinity.REAL) + return newNumber(inf2); + + value = ((RationalNumber)arg1).toFloat(); + value *= ((RationalNumber)arg2).toFloat(); + + return newNumber(value); + } + + public DataType op(List args){ + Infinity inf; + float value; + + value = 1.f; + for (DataType dt : args) { + // This extra test is necessary as we don't want exceptions + inf = ((RationalNumber)dt).getInfinity(); + if (inf != Infinity.REAL) + return newNumber(inf); + + value *= ((RationalNumber)dt).toFloat(); + } + + return newNumber(value); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.java new file mode 100644 index 0000000..61feae1 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalNumber.java @@ -0,0 +1,240 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.NumericDataType; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.MaxValues; + + +public class RationalNumber extends NumericDataType { + + private static final long serialVersionUID = 6771153631961177659L; + + public static Set getOperations() { + Set operations; + + operations = new HashSet(); + + operations.add(new RationalAdd(RationalNumber.class)); + operations.add(new RationalMultiply(RationalNumber.class)); + operations.add(new RationalMinimum(RationalNumber.class)); + operations.add(new RationalMaximum(RationalNumber.class)); + + return operations; + } + + public static Operation getOperationByID(String id) { + for (Operation op : getOperations()) { + if (op.getID().equals(id)) + return op; + } + + return null; + } + + public static String getName() { + return "Rational Number"; + } + + public static String[] getSymbolicRepresentation() { + String[] returnValue = {"\u211d", "", ""}; + + return returnValue; + } + + protected boolean isValidValue(float value) { + return (value >= minimumValue() && value <= maximumValue()); + } + + protected float defaultValue() { + return 0f; + } + + protected float minimumValue() { + return Float.NEGATIVE_INFINITY; + } + + protected float maximumValue() { + return Float.POSITIVE_INFINITY; + } + + /** + * INSTANCE METHODES + */ + + private float value; + + public RationalNumber() + { + value = defaultValue(); + } + + public RationalNumber(float val) + { + if (isValidValue(val)) { + value = val; + } else { + throw new IllegalArgumentException(); + } + } + + public RationalNumber(Infinity inf) + { + setInfinity(inf); + } + + @Override + public boolean setFromFloat(float val) { + if (isValidValue(val)) { + value = val; + return true; + } + else { + return false; + } + } + + @Override + public boolean setFromInt(int val) { + if (isValidValue(val)) { + value = val; + return true; + } + else { + return false; + } + } + + @Override + public boolean setFromNumeric(NumericDataType num) { + Infinity inf; + float val; + + val = num.toFloat(); + inf = num.getInfinity(); + + if (inf != Infinity.REAL) { + return setInfinity(inf); + } + + if (isValidValue(val)) { + value = val; + return true; + } + else { + return false; + } + } + + @Override + public float toFloat() { + return value; + } + + @Override + public int toInt() { + return (int) value; + } + + @Override + public RationalNumber clone() { + RationalNumber num = null; + + try { + num = this.getClass().newInstance(); + num.setFromNumeric(this); + } + catch (InstantiationException e) { + } + catch (IllegalAccessException e) { + } + + return num; + } + + @Override + public boolean setFromString(String str) { + float val; + + // Input is infinite + if (str.equals("\u221e")) { + setInfinity(Infinity.POSITIVE_INFINITE); + return true; + } + if (str.equals("-\u221e")) { + setInfinity(Infinity.NEGATIVE_INFINITE); + return true; + } + + if (str.matches("[0-9]+\\,?[0-9]+")) { + str = str.replace(',', '.'); + } + + // Input is real + try { + val = Float.parseFloat(str); + } + catch (NumberFormatException ex) { + return false; + } + + if (isValidValue(val) + && val >= MaxValues.getRationalNumberMinimum() + && val <= MaxValues.getRationalNumberMaximum() + ) { + value = val; + return true; + } else { + return false; + } + } + + @Override + public String toString() { + switch (getInfinity()) { + case POSITIVE_INFINITE: + return "\u221e"; + case NEGATIVE_INFINITE: + return "-\u221e"; + default: + return (new DecimalFormat("#####0.##", new DecimalFormatSymbols(new Locale("en")))).format(value); + } + } + + @Override + public Infinity getInfinity() { + if (value == Float.POSITIVE_INFINITY) + return Infinity.POSITIVE_INFINITE; + else if (value == Float.NEGATIVE_INFINITY) + return Infinity.NEGATIVE_INFINITE; + else + return Infinity.REAL; + } + + @Override + public boolean setInfinity(Infinity inf) { + float val; + + if (inf == Infinity.POSITIVE_INFINITE) + val = maximumValue(); + else if (inf == Infinity.NEGATIVE_INFINITE) + val = minimumValue(); + else + val = defaultValue(); + + value = val; + return true; + } + + public String[] getSpecialCharacter() { + String[] out = {"\u221e"}; + + return out; + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.java b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.java new file mode 100644 index 0000000..e4e3acc --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/RationalOperation.java @@ -0,0 +1,88 @@ +package org.jalgo.module.app.core.dataType.rationalNumber; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; + + +public abstract class RationalOperation extends Operation { + + Class numClass; + + public RationalOperation(Class aClass) { + numClass = aClass; + } + + protected DataType newNumber(float value) { + try { + return numClass.getConstructor(new Class[] {float.class}).newInstance(new Object[] {value}); + } catch (Exception e) { + System.out.println(e); + return null; + } + } + + protected DataType newNumber(Infinity inf) { + try { + return numClass.getConstructor(new Class[] {Infinity.class}).newInstance(new Object[] {inf}); + } catch (Exception e) { + System.out.println(e); + return null; + } + } + + public boolean isAssociative() { + return true; + } + + public boolean isCommutative() { + return true; + } + + public DataType star(DataType arg, Operation other) { + RationalNumber v1, v2, v3; + + v1 = (RationalNumber) star(arg, other, 1); + v2 = (RationalNumber) star(arg, other, 2); + v3 = (RationalNumber) star(arg, other, 3); + + // Constant value + if (v1.equals(v2) && v2.equals(v3)) + return v1; + else if (v1.toFloat() < v2.toFloat() && v2.toFloat() < v3.toFloat()) { + if (v1.toFloat() >= 0) + return newNumber(Infinity.POSITIVE_INFINITE); + else if (v1.toFloat() >= -1 && v1.toFloat() < 0 && v2.toFloat() < 0 && v3.toFloat() < 0) + return newNumber(0.0f); + else + throw new UnsupportedOperationException(); + } + else if (v1.toFloat() > v2.toFloat() && v2.toFloat() > v3.toFloat()) { + if (v1.toFloat() <= 0) + return newNumber(Infinity.NEGATIVE_INFINITE); + else if (v1.toFloat() <= 1 && v1.toFloat() > 0 && v2.toFloat() > 0 && v3.toFloat() > 0) + return newNumber(0.0f); + else + throw new UnsupportedOperationException(); + } + else + throw new UnsupportedOperationException(); + } + + protected DataType star(DataType arg, Operation other, int count) { + List ops1, ops2; + + ops1 = new ArrayList(); + ops2 = new ArrayList(); + + for (int i=0; i<=count; i++) { + ops1.add(other.op(ops2)); + ops2.add(arg); + } + + return op(ops1); + } +} diff --git a/src/org/jalgo/module/app/core/dataType/rationalNumber/package.html b/src/org/jalgo/module/app/core/dataType/rationalNumber/package.html new file mode 100644 index 0000000..d8dbcb1 --- /dev/null +++ b/src/org/jalgo/module/app/core/dataType/rationalNumber/package.html @@ -0,0 +1,10 @@ + + + + + + +The set of rational numbers and the appropriate operations. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/graph/CVS/Entries b/src/org/jalgo/module/app/core/graph/CVS/Entries new file mode 100644 index 0000000..2373e35 --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/CVS/Entries @@ -0,0 +1,4 @@ +/Edge.java/1.1/Wed Oct 29 18:05:25 2008// +/Graph.java/1.1/Wed Oct 29 18:05:25 2008// +/Node.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/core/graph/CVS/Repository b/src/org/jalgo/module/app/core/graph/CVS/Repository new file mode 100644 index 0000000..6221a03 --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/graph diff --git a/src/org/jalgo/module/app/core/graph/CVS/Root b/src/org/jalgo/module/app/core/graph/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/graph/Edge.java b/src/org/jalgo/module/app/core/graph/Edge.java new file mode 100644 index 0000000..1a2aaab --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/Edge.java @@ -0,0 +1,89 @@ +package org.jalgo.module.app.core.graph; + +import java.io.Serializable; + +import org.jalgo.module.app.core.dataType.DataType; + +/** + * Represents an edge of a graph. It has a start node, an end node and a weight. + * + */ +public class Edge implements Serializable { + + private static final long serialVersionUID = 7514261796341292879L; + private Node begin; + private Node end; + private DataType weight; + + /** + * Initialized the edge with start and end node. + * + * @param begin + * The start node. + * @param end + * The end node. + */ + public Edge(Node begin, Node end) { + this.begin = begin; + this.end = end; + this.weight = null; + } + + /** + * Returns the start node of the edge. + * + * @return the start node of the edge. + */ + public Node getBegin() { + return begin; + } + + /** + * Sets the edge to new start node. + * + * @param begin + * The start node + */ + public void setBegin(Node begin) { + this.begin = begin; + } + + /** + * Returns the end node of the edge. + * + * @return the end node of the edge. + */ + public Node getEnd() { + return end; + } + + /** + * Sets the edge to anew end node. + * + * @param end + * The end node. + */ + public void setEnd(Node end) { + this.end = end; + } + + /** + * Gets the current weight of the edge. + * + * @return The weight of the edge. This can be an arbitrary + * DataType, based on the used Semiring. + */ + public DataType getWeight() { + return weight; + } + + /** + * Sets the edge to a new weight. + * + * @param weight + * the new weight to set. + */ + public void setWeight(DataType weight) { + this.weight = weight; + } +} diff --git a/src/org/jalgo/module/app/core/graph/Graph.java b/src/org/jalgo/module/app/core/graph/Graph.java new file mode 100644 index 0000000..fcd8257 --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/Graph.java @@ -0,0 +1,327 @@ +package org.jalgo.module.app.core.graph; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.DataType; + +/** + * Represents the graph model. This consists of nodes (of type Node) + * and edges (of type Edge). + * + */ +public class Graph implements Serializable { + + private static final long serialVersionUID = 7342120321239695018L; + private Set nodes; + private Set edges; + + /** + * Creates an empty set for edges an one for nodes. + */ + public Graph() { + // FIXME: why in try-catch? + try { + nodes = new HashSet(); + } catch (RuntimeException e) { + e.printStackTrace(); + } + edges = new HashSet(); + } + + /** + * Returns the set of all nodes in this graph. + * + * @return the whole set of nodes. + */ + public Set getNodes() { + return nodes; + } + + /** + * Returns the Node with the given ID. + * + * @param id + * the ID of an existing node of the graph. + * @return The node with the given ID. + */ + public Node getNode(int id) { + for (Node n : nodes) { + if (n.getId() == id) + return n; + } + + return null; + } + + /** + * Generates a new node with the number of nodes as ID, adding it to the + * node list. + * + * @return the added node. + */ + public Node newNode() { + return newNode(true); + } + + /** + * Generates a new node with the number of nodes as ID, adding it to the + * node list, if add is true. + * + * @param add + * + * @return The added node. + */ + public Node newNode(boolean add) { + Node node = new Node(nodes.size()); + + if (add) { + nodes.add(node); + } + + return node; + } + + public int getBiggestID() { + return nodes.size() - 1; + } + + // private int getNextID() { + // int nextID = 0; + // for (Node node : nodes) { + // if (node.getId() >= nextID) { + // nextID = node.getId() + 1; + // } + // } + // return nextID; + // } + + /** + * Adds the given node to the set of nodes. + * + * @param node The node to add. + */ + public void addNode(Node node) { + nodes.add(node); + } + + /** + * Adds a node and adjust the node ids of the existing nodes. + * + * @param node + * The node to add after remove. + */ + public void addUndoNode(Node node) { + int id = node.getId(); + + for (Node graphNode : nodes) { + if (graphNode.getId() >= id) { + graphNode.setId(graphNode.getId() + 1); + } + } + + nodes.add(node); + } + + /** + * Generate a list of new nodes. Does not add these nodes to the graph. + * + * @param count + * The number of new created nodes. + * @return A list with new nodes. + */ + public List newNodes(int count) { + List newNodes; + + newNodes = new ArrayList(count); + for (int i = 0; i < count; i++) { + newNodes.add(newNode()); + } + + return newNodes; + } + + /** + * Removes the given node from the graph. + * + * @param node + * The node to delete. + */ + public void removeNode(Node node) { + if (node == null) { + throw new NullPointerException(); + } else if (!(nodes.contains(node))) { + throw new NoSuchElementException(); + } + + int id = node.getId(); + nodes.remove(node); + + // correct id of nodes + for (Node n : nodes) { + if (n.getId() > id) + n.setId(n.getId() - 1); + } + + // delete all edges on the removed node + for (Edge e : new LinkedList(edges)) { + if (e.getBegin() == node || e.getEnd() == node) { + edges.remove(e); + } + } + } + + /** + * Gets the set of alle edges in this graph. + * + * @return The whole set of edges. + */ + public Set getEdges() { + return edges; + } + + /** + * @param begin + * The ID of the start node. + * @param end + * The ID of the end node. + * @return the edge with the given start and end node. + */ + public Edge getEdge(int begin, int end) { + return getEdge(getNode(begin), getNode(end)); + } + + /** + * @param begin + * The start node. + * @param end + * The end node. + * @return the edge with the given start and end node. + */ + public Edge getEdge(Node begin, Node end) { + for (Edge e : edges) { + if (e.getBegin() == begin && e.getEnd() == end) + return e; + } + + return null; + } + + /** + * Adds a new edge to the graph, based on the IDs of start and end node. The + * weight is set to null. + * + * @param begin + * The ID of the start node. + * @param end + * The ID of the end node. + * @return The new edge. + */ + public Edge addEdge(int begin, int end) { + return addEdge(getNode(begin), getNode(end)); + } + + /** + * Adds a new edge to the graph with the given weight, based on the IDs of + * start and end node. + * + * @param begin + * The ID of the start node. + * @param end + * The ID of the end node. + * @param weight + * The weight of the new edge. + * @return The new edge. + */ + public Edge addEdge(int begin, int end, DataType weight) { + return addEdge(getNode(begin), getNode(end), weight); + } + + /** + * Adds a new edge to the graph, based on the given start and end node. The + * weight is set to null. + * + * @param begin + * The start node. + * @param end + * The end node. + * @return The new edge. + */ + public Edge addEdge(Node begin, Node end) { + return addEdge(begin, end, null); + } + + /** + * Adds a new edge to the graph with the given weight, based on the given + * start and end node. + * + * @param begin + * The start node. + * @param end + * The end node. + * @param weight + * The weight of the new edge. + * @return The new edge. + */ + public Edge addEdge(Node begin, Node end, DataType weight) { + return newEdge(begin, end, weight, true); + } + + /** + * Adds a new edge to the graph. + * + * @param edge + * the given edge. + */ + public void addEdge(Edge edge) { + edges.add(edge); + } + + /** + * Creates a new edge, and adds it to the graph at the same time, if + * add is true. + * + * @param begin + * the start node. + * @param end + * the end node. + * @param weight + * the weight of the edge + * @param add + * if true, add the edge to the graph. + * @return the created edge. + */ + public Edge newEdge(Node begin, Node end, DataType weight, boolean add) { + if (begin == null || end == null) { + throw new NullPointerException(); + } + if (begin == end) { + throw new IllegalArgumentException(); + } + if (getEdge(begin, end) != null) { + throw new IllegalArgumentException(); + } + + Edge edge = new Edge(begin, end); + edge.setWeight(weight); + if (add) + edges.add(edge); + + return edge; + } + + /** + * Removes the given edge from the graph. + * + * @param edge + * The edge to remove. + */ + public void removeEdge(Edge edge) { + edges.remove(edge); + } +} diff --git a/src/org/jalgo/module/app/core/graph/Node.java b/src/org/jalgo/module/app/core/graph/Node.java new file mode 100644 index 0000000..11ae4ea --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/Node.java @@ -0,0 +1,97 @@ +package org.jalgo.module.app.core.graph; + +import java.awt.geom.Point2D; +import java.io.Serializable; + +/** + * Represents a node which should be a part of a graph. The node has an ID which + * have to be unambiguous in the graph. The node knows its name and location. + */ +public class Node implements Serializable { + + private static final long serialVersionUID = 8145719979029192129L; + + /** + * The unambiguous identification of the node. + */ + private int id; + + /** + * The position in the paint area on the screen. + */ + private SerialPoint2D location; + + /** + * Initialized the node with the given ID. The Label is set by default on + * the string representation of the ID. + * + * @param id + * The ID of the new node. + */ + public Node(int id) { + this.id = id; + this.location = new SerialPoint2D(0, 0); + } + + /** + * Gets the ID of the node. + * + * @return The ID of the node. + */ + public int getId() { + return id; + } + + /** + * Sets the node to a new ID. + * + * @param id + * the new ID. + */ + public void setId(int id) { + this.id = id; + } + + /** + * Gets the location of the node + * + * @return the position of the node. + */ + public Point2D getLocation() { + return location.getPoint2D(); + } + + /** + * Puts the node in a new location. + * + * @param location + * the new location. + */ + public void setLocation(Point2D location) { + this.location = new SerialPoint2D(location); + } + + /* + * This private class is needed, because Point2d.Float is not serializable. + * (Sun Developer Network - Bug ID: 4263142) + * + */ + private class SerialPoint2D implements Serializable { + private static final long serialVersionUID = -3941806130927961539L; + double x, y; + + public SerialPoint2D(int x, int y) { + this.x = x; + this.y = y; + } + + public SerialPoint2D(Point2D point) { + x = point.getX(); + y = point.getY(); + } + + public Point2D getPoint2D() { + return new Point2D.Float((float) x, (float) y); + } + } +} diff --git a/src/org/jalgo/module/app/core/graph/package.html b/src/org/jalgo/module/app/core/graph/package.html new file mode 100644 index 0000000..2a3a8a7 --- /dev/null +++ b/src/org/jalgo/module/app/core/graph/package.html @@ -0,0 +1,10 @@ + + + + + + +The internal representation of the graph over which is calculated. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/package.html b/src/org/jalgo/module/app/core/package.html new file mode 100644 index 0000000..dd73a66 --- /dev/null +++ b/src/org/jalgo/module/app/core/package.html @@ -0,0 +1,10 @@ + + + + + + +The model, who does the internal calculation. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/step/AtomicStep.java b/src/org/jalgo/module/app/core/step/AtomicStep.java new file mode 100644 index 0000000..0c1989b --- /dev/null +++ b/src/org/jalgo/module/app/core/step/AtomicStep.java @@ -0,0 +1,140 @@ +package org.jalgo.module.app.core.step; + +import java.util.List; + +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.dataType.DataType; + +/** + * Represents a single, atomic step, where only one element in the matrix is + * processed (the element (u,v)). + * + */ +public class AtomicStep extends Step { + + private int u; + private int v; + private int k; + private DataType value; + private boolean changed; + private List nodes; + + @Override + public Matrix getAfterMatrix() { + Matrix matrix; + + matrix = getBeforeMatrix(); + if (changed) { + matrix = matrix.clone(); + injectChange(matrix); + } + + return matrix; + } + + /** + * @return the u + */ + public int getU() { + return u; + } + + /** + * @return the v + */ + public int getV() { + return v; + } + + /** + * @return the k + */ + public int getK() { + return k; + } + + /** + * Sets the parameters needed for the step. + * + * @param k + * the step k to set + * @param u + * the u-coordinate to set + * @param v + * the v-coordinate to set + */ + public void setKUV(int k, int u, int v) { + this.k = k; + + this.u = u; + this.v = v; + } + + /** + * @return the value + */ + public DataType getValue() { + return value; + } + + /** + * @param value + * the value to set + */ + public void setValue(DataType value) { + this.value = value; + } + + /** + * @return the nodes + */ + public List getNodes() { + return nodes; + } + + /** + * @param nodes + * the nodes to set + */ + public void setNodes(List nodes) { + this.nodes = nodes; + } + + /** + * Changes the given matrix by inserting the changed cell. + * + * @param matrix + * the matrix to modify + */ + public void injectChange(Matrix matrix) { + if (changed) { + matrix.setValueAt(u, v, value); + matrix.setNodesAt(u, v, nodes); + } + } + + /** + * @return the changed + */ + public boolean isChanged() { + return changed; + } + + /** + * @param changed + * the changed to set + */ + public void setChanged(boolean changed) { + this.changed = changed; + } + + public String toString() { + String str; + + str = "Step:{k/u/v = " + k + "/" + u + "/" + v + "; changed = " + + changed + "; value = " + value + "; nodes = " + nodes + "}\n"; + str += getAfterMatrix(); + + return str; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/step/CVS/Entries b/src/org/jalgo/module/app/core/step/CVS/Entries new file mode 100644 index 0000000..868da33 --- /dev/null +++ b/src/org/jalgo/module/app/core/step/CVS/Entries @@ -0,0 +1,5 @@ +/AtomicStep.java/1.1/Wed Oct 29 18:05:25 2008// +/GroupStep.java/1.1/Wed Oct 29 18:05:25 2008// +/RootStep.java/1.1/Wed Oct 29 18:05:25 2008// +/Step.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/core/step/CVS/Repository b/src/org/jalgo/module/app/core/step/CVS/Repository new file mode 100644 index 0000000..3e54abc --- /dev/null +++ b/src/org/jalgo/module/app/core/step/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/core/step diff --git a/src/org/jalgo/module/app/core/step/CVS/Root b/src/org/jalgo/module/app/core/step/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/core/step/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/core/step/GroupStep.java b/src/org/jalgo/module/app/core/step/GroupStep.java new file mode 100644 index 0000000..19283e7 --- /dev/null +++ b/src/org/jalgo/module/app/core/step/GroupStep.java @@ -0,0 +1,159 @@ +package org.jalgo.module.app.core.step; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.app.core.Matrix; + +/** + * Represents a big step, where all elements in a matrix are processed once, + * i.e. there are n^2 AtomicSteps between two + * GroupSteps (where n is the number of rows/columns of the + * matrix). A GroupStep holds all the AtomicSteps up to the next + * GroupStep. + * + */ +public class GroupStep extends Step { + + protected List steps; + private Matrix afterMatrix; + + public GroupStep() { + steps = new ArrayList(); + } + + @Override + public Matrix getAfterMatrix() { + return afterMatrix; + } + + /** + * Gets the matrix before the child Step. + * + * @param child + * The matrix to get the previous step to. + * @return the Matrix before the Step child. + */ + public Matrix getMatrixBeforeStep(Step child) { + Matrix matrix; + int index; + + index = steps.indexOf(child); + if (index == 0) + return parent.getMatrixBeforeStep(this); + else { + if (!(child instanceof AtomicStep)) + return getStepBeforeStep(child).getAfterMatrix(); + + // Flat implementation, line above would work as well + matrix = parent.getMatrixBeforeStep(this); + matrix = matrix.clone(); + + for (Step s : steps) { + ((AtomicStep) s).injectChange(matrix); + + if (s == child) + break; + } + + return matrix; + } + } + + /** + * Gets the Step before the + * child Step. + * + * @param child + * the step to get the previous step to. + * @return the step before the child step + */ + public Step getStepBeforeStep(Step child) { + int index; + + index = steps.indexOf(child); + if (index == 0) { + if (parent != null) + return parent.getStepBeforeStep(this); + else + return null; + } else { + return steps.get(index - 1); + } + } + + /** + * Gets the Step after the + * child Step. + * + * @param child + * the step to get the following step to. + * @return the step after the child step + */ + public Step getStepAfterStep(Step child) { + int index; + + index = steps.indexOf(child); + if (index == steps.size() - 1) { + if (parent != null) + return parent.getStepAfterStep(this); + else + return null; + } else { + return steps.get(index + 1); + } + } + + /** + * Gets a list of all the steps in this GroupStep. + * + * @return a list of all the steps in this GroupStep. + */ + public List getSteps() { + return steps; + } + + /** + * Sets the steps in this GroupStep. + * + * @param steps + */ + public void setSteps(List steps) { + this.steps = steps; + } + + /** + * Gets the step at the position index. + * + * @param index + * the position of the step + * @return the step at the position index + */ + public Step getStep(int index) { + return steps.get(index); + } + + /** + * Returns the numbers of steps in this GroupStep. + * + * @return the numbers of steps in this GroupStep. + */ + public int getStepCount() { + return steps.size(); + } + + /** + * Adds a step to this GroupStep. + * + * @param step + * the step to be added. + */ + public void addStep(Step step) { + this.steps.add(step); + step.setGroupStep(this); + } + + public void setAfterMatrix(Matrix afterMatrix) { + this.afterMatrix = afterMatrix; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/core/step/RootStep.java b/src/org/jalgo/module/app/core/step/RootStep.java new file mode 100644 index 0000000..3af6733 --- /dev/null +++ b/src/org/jalgo/module/app/core/step/RootStep.java @@ -0,0 +1,36 @@ +package org.jalgo.module.app.core.step; + +import org.jalgo.module.app.core.Matrix; + +/** + * Represents the very first step of the whole Calculation. The matrix before + * this step is the adjacency matrix. + * + */ +public class RootStep extends GroupStep { + + private Matrix beforeMatrix; + + public Matrix getBeforeMatrix() { + return beforeMatrix; + } + + /** + * Sets the matrix at the begin of the calculation (adjacency matrix). + * + * @param m + * the adjacency matrix + */ + public void setBeforeMatrix(Matrix m) { + beforeMatrix = m; + } + + @Override + public Matrix getMatrixBeforeStep(Step child) { + if (steps.indexOf(child) == 0) + return getBeforeMatrix(); + else + return super.getMatrixBeforeStep(child); + } + +} diff --git a/src/org/jalgo/module/app/core/step/Step.java b/src/org/jalgo/module/app/core/step/Step.java new file mode 100644 index 0000000..1c1e13d --- /dev/null +++ b/src/org/jalgo/module/app/core/step/Step.java @@ -0,0 +1,49 @@ +package org.jalgo.module.app.core.step; + +import org.jalgo.module.app.core.Matrix; + +/** + * Represents a Step in the calculation during the Aho-algorithm. A step can + * access the matrix before the calculation step and after the calculation step. + * It is also connected to its parent step. Therefore it is possible to navigate + * between the steps. + */ +public abstract class Step { + + protected GroupStep parent; + + /** + * Gets the parent GroupStep. + * + * @return parent GroupStep + */ + public GroupStep getGroupStep() { + return parent; + } + + /** + * Sets the parent GroupStep. + */ + public void setGroupStep(GroupStep aStep) { + parent = aStep; + } + + /** + * Returns the calculation matrix before performing the step. + * + * @return the matrix before the step. + */ + public Matrix getBeforeMatrix() { + if (parent != null) + return parent.getMatrixBeforeStep(this); + else + return null; + } + + /** + * Returns the calculation matrix after performing the step. + * + * @return the matrix after the step. + */ + public abstract Matrix getAfterMatrix(); +} diff --git a/src/org/jalgo/module/app/core/step/package.html b/src/org/jalgo/module/app/core/step/package.html new file mode 100644 index 0000000..2ecf221 --- /dev/null +++ b/src/org/jalgo/module/app/core/step/package.html @@ -0,0 +1,10 @@ + + + + + + +The steps of calculation, organized in a tree structure. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/coreTest/AllCalculationTests.java b/src/org/jalgo/module/app/coreTest/AllCalculationTests.java new file mode 100644 index 0000000..630c555 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/AllCalculationTests.java @@ -0,0 +1,18 @@ +package org.jalgo.module.app.coreTest; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + SimpleCalculationTest.class, + DijkstraComparisonTest.class, + AvailabilityProblemTest.class, + CapacityProblemTest.class, + FormalLanguageTest.class +}) +public class AllCalculationTests { + // the class remains completely empty, + // being used only as a holder for the above annotations + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/coreTest/AllDataTypeTests.java b/src/org/jalgo/module/app/coreTest/AllDataTypeTests.java new file mode 100644 index 0000000..49cf581 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/AllDataTypeTests.java @@ -0,0 +1,27 @@ +package org.jalgo.module.app.coreTest; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + AvailableDataTypesTest.class, + NaturalNumberTest.class, + NaturalAddTest.class, + NaturalMultiplyTest.class, + NaturalMaximumTest.class, + NaturalMinimumTest.class, + RationalNumberTest.class, + RationalOperationTest.class, + RationalStarOperationTest.class, + PercentageTypeTest.class, + PositiveRationalOperationTest.class, + BooleanTypeTest.class, + BooleanOperationsTest.class, + FormalLanguageTest.class +}) +public class AllDataTypeTests { + // the class remains completely empty, + // being used only as a holder for the above annotations + +} diff --git a/src/org/jalgo/module/app/coreTest/AllTests.java b/src/org/jalgo/module/app/coreTest/AllTests.java new file mode 100644 index 0000000..27d3a8a --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/AllTests.java @@ -0,0 +1,14 @@ +package org.jalgo.module.app.coreTest; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +@RunWith(Suite.class) +@Suite.SuiteClasses({ + AllDataTypeTests.class, + GraphTest.class, + AllCalculationTests.class +}) +public class AllTests { + +} diff --git a/src/org/jalgo/module/app/coreTest/AvailabilityProblemTest.java b/src/org/jalgo/module/app/coreTest/AvailabilityProblemTest.java new file mode 100644 index 0000000..e66de76 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/AvailabilityProblemTest.java @@ -0,0 +1,128 @@ +package org.jalgo.module.app.coreTest; + + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.AvailableSemiRings; +import org.jalgo.module.app.core.Calculation; +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.dataType.booleanType.BooleanType; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.core.step.Step; +import org.junit.Before; +import org.junit.Test; + +public class AvailabilityProblemTest { + RootStep step; + Graph graph; + List steps; + int size; + + @Before + public void setUp() throws Exception { + SemiRing ring; + Calculation calc; + + ring = AvailableSemiRings.getSemiRings().get(AvailableSemiRings.AVAILABILITY_PROBLEM_ID); + + graph = new Graph(); + + graph.newNodes(7); + + List nodeList; + nodeList = GraphTest.getOrderedNodeList(graph.getNodes()); + + assertEquals(7,nodeList.size()); + + graph.newEdge(nodeList.get(0), nodeList.get(1), new BooleanType(true),true); + graph.newEdge(nodeList.get(1), nodeList.get(2), new BooleanType(true),true); + graph.newEdge(nodeList.get(2), nodeList.get(3), new BooleanType(true),true); + graph.newEdge(nodeList.get(3), nodeList.get(4), new BooleanType(true),true); + graph.newEdge(nodeList.get(4), nodeList.get(5), new BooleanType(true),true); + graph.newEdge(nodeList.get(5), nodeList.get(6), new BooleanType(true),true); + graph.newEdge(nodeList.get(6), nodeList.get(1), new BooleanType(false),true); + graph.newEdge(nodeList.get(5), nodeList.get(2), new BooleanType(true),true); + graph.newEdge(nodeList.get(4), nodeList.get(2), new BooleanType(false),true); + graph.newEdge(nodeList.get(3), nodeList.get(1), new BooleanType(false),true); + + calc = new Calculation(); + calc.setSemiring(ring); + calc.setGraph(graph); + + step = (RootStep)calc.getRootStep(); + steps = step.getSteps(); + size = graph.getNodes().size(); + } + + @Test + public void checkBeforeMatrix() { + Matrix before; + + before = step.getBeforeMatrix(); + size = graph.getNodes().size(); + + // diagonal + for (int i=0; i viaNodes; + + before = step.getSteps().get(5).getAfterMatrix(); + size = graph.getNodes().size(); + viaNodes = new LinkedList(); + + for (int i = 0; i < size; i++) + // should return empty list + assertEquals(viaNodes,before.getNodesAt(i, i)); + + // path from node 0 to node 2 + viaNodes.add(1); + assertEquals(viaNodes,before.getNodesAt(0, 2)); + // path from node 0 to node 6 (max. length of a path in this graph) + viaNodes.add(2); + viaNodes.add(3); + viaNodes.add(4); + viaNodes.add(5); + assertEquals(viaNodes,before.getNodesAt(0, 6)); + viaNodes.clear(); + // path from node 5 to node 4 + viaNodes.add(2); + viaNodes.add(3); + assertEquals(viaNodes,before.getNodesAt(5, 4)); + + } +} diff --git a/src/org/jalgo/module/app/coreTest/AvailableDataTypesTest.java b/src/org/jalgo/module/app/coreTest/AvailableDataTypesTest.java new file mode 100644 index 0000000..334b942 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/AvailableDataTypesTest.java @@ -0,0 +1,31 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; + +import java.util.Set; + +import org.jalgo.module.app.core.dataType.AvailableDataTypes; +import org.jalgo.module.app.core.dataType.DataType; +import org.junit.Test; + +public class AvailableDataTypesTest { + /** check if there are any DataTypes available + */ + @Test + public void getDataTypes() { + assertNotNull(AvailableDataTypes.getDataTypes()); + assertNotSame(0,AvailableDataTypes.getDataTypes().size()); + } + + /** check if there's only one instance + */ + @Test + public void sameInstanceTest() { + Set> dataTypes1 = AvailableDataTypes.getDataTypes(); + Set> dataTypes2 = AvailableDataTypes.getDataTypes(); + + assertEquals(dataTypes1,dataTypes2); + } +} diff --git a/src/org/jalgo/module/app/coreTest/BooleanOperationsTest.java b/src/org/jalgo/module/app/coreTest/BooleanOperationsTest.java new file mode 100644 index 0000000..db8ec44 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/BooleanOperationsTest.java @@ -0,0 +1,69 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.booleanType.BooleanType; +import org.jalgo.module.app.core.dataType.booleanType.Conjunction; +import org.jalgo.module.app.core.dataType.booleanType.Disjunction; +import org.junit.Before; +import org.junit.Test; + +public class BooleanOperationsTest { + BooleanType bFalse,bTrue1,bTrue2; + Disjunction or; + Conjunction and; + + List list; + + @Before + public void setUp() throws Exception { + bFalse = new BooleanType(); + bTrue1 = new BooleanType(true); + bTrue2 = new BooleanType(true); + + Set ops; + + ops = BooleanType.getOperations(); + for (Operation op : ops) { + if (op instanceof Conjunction) + and = (Conjunction)op; + if (op instanceof Disjunction) + or = (Disjunction)op; + } + + list = new LinkedList(); + } + + @Test + public void twoVariables() { + assertEquals(new BooleanType(true),or.op(bFalse,bTrue1)); + assertEquals(new BooleanType(false),and.op(bFalse,bTrue1)); + assertEquals(new BooleanType(true),and.op(bTrue1, bTrue2)); + } + + @Test + public void listOfNumbers1() { + list.add(bFalse); + list.add(bTrue1); + list.add(bTrue2); + + assertEquals(new BooleanType(true),or.op(list)); + assertEquals(new BooleanType(false),and.op(list)); + } + + @Test + public void listOfNumbers2() { + for(int i = 0; i < 3; i++) { + list.add(bTrue1); + } + assertEquals(new BooleanType(true),or.op(list)); + assertEquals(new BooleanType(true),and.op(list)); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/BooleanTypeTest.java b/src/org/jalgo/module/app/coreTest/BooleanTypeTest.java new file mode 100644 index 0000000..9ec3d22 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/BooleanTypeTest.java @@ -0,0 +1,88 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; + +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.booleanType.BooleanType; +import org.jalgo.module.app.core.dataType.booleanType.Conjunction; +import org.jalgo.module.app.core.dataType.booleanType.Disjunction; +import org.junit.Before; +import org.junit.Test; + +public class BooleanTypeTest { + BooleanType bEmpty, bFalse, bTrue; + + @Before + public void setUp() throws Exception { + bEmpty = new BooleanType(); + bFalse = new BooleanType(false); + bTrue = new BooleanType(true); + } + + @Test + public void checkNumberOfOperations() { + assertNotNull(BooleanType.getOperations()); + assertNotSame(0,BooleanType.getOperations().size()); + assertNotSame(1,BooleanType.getOperations().size()); + } + + @Test + public void checkValue() { + assertFalse(bEmpty.toBoolean()); + assertFalse(bFalse.toBoolean()); + assertTrue(bTrue.toBoolean()); + } + + @Test + public void setFromBoolean() { + bEmpty.setFromBoolean(false); + assertFalse(bEmpty.toBoolean()); + bEmpty.setFromBoolean(true); + assertTrue(bEmpty.toBoolean()); + } + + @Test + public void setFromInt() { + bEmpty.setFromInt(0); + assertFalse(bEmpty.toBoolean()); + bEmpty.setFromInt(1); + assertTrue(bEmpty.toBoolean()); + } + + @Test + public void setFromString() { + bEmpty.setFromString("false"); + assertFalse(bEmpty.toBoolean()); + bEmpty.setFromString("1"); + assertTrue(bEmpty.toBoolean()); + } + + @Test + public void wrongStringInput() { + assertFalse(bEmpty.setFromString("aba")); + } + + @Test + public void setToType() { + bEmpty.setFromBoolean(false); + assertFalse(bEmpty.toBoolean()); + assertEquals(0,bEmpty.toInt()); + assertEquals("false",bEmpty.toString()); + } + + @Test + public void testSimpleOperation() { + for (Operation op : BooleanType.getOperations()) { + if (op instanceof Conjunction) { + assertEquals(new BooleanType(false),op.op(bFalse, bTrue)); + } else if (op instanceof Disjunction) { + assertEquals(new BooleanType(true),op.op(bFalse, bTrue)); + } + } + } + +} diff --git a/src/org/jalgo/module/app/coreTest/CVS/Entries b/src/org/jalgo/module/app/coreTest/CVS/Entries new file mode 100644 index 0000000..27ef4c2 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/CVS/Entries @@ -0,0 +1,23 @@ +/AllCalculationTests.java/1.1/Wed Oct 29 18:05:24 2008// +/AllDataTypeTests.java/1.1/Wed Oct 29 18:05:24 2008// +/AllTests.java/1.1/Wed Oct 29 18:05:24 2008// +/AvailabilityProblemTest.java/1.1/Wed Oct 29 18:05:24 2008// +/AvailableDataTypesTest.java/1.1/Wed Oct 29 18:05:24 2008// +/BooleanOperationsTest.java/1.1/Wed Oct 29 18:05:24 2008// +/BooleanTypeTest.java/1.1/Wed Oct 29 18:05:24 2008// +/CapacityProblemTest.java/1.1/Wed Oct 29 18:05:24 2008// +/DijkstraComparisonTest.java/1.1/Wed Oct 29 18:05:24 2008// +/FormalLanguageProblemTest.java/1.1/Wed Oct 29 18:05:24 2008// +/FormalLanguageTest.java/1.1/Wed Oct 29 18:05:24 2008// +/GraphTest.java/1.1/Wed Oct 29 18:05:24 2008// +/NaturalAddTest.java/1.1/Wed Oct 29 18:05:24 2008// +/NaturalMaximumTest.java/1.1/Wed Oct 29 18:05:24 2008// +/NaturalMinimumTest.java/1.1/Wed Oct 29 18:05:24 2008// +/NaturalMultiplyTest.java/1.1/Wed Oct 29 18:05:24 2008// +/NaturalNumberTest.java/1.1/Wed Oct 29 18:05:24 2008// +/PercentageTypeTest.java/1.1/Wed Oct 29 18:05:24 2008// +/PositiveRationalOperationTest.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalNumberTest.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalOperationTest.java/1.1/Wed Oct 29 18:05:24 2008// +/RationalStarOperationTest.java/1.1/Wed Oct 29 18:05:24 2008// +/SimpleCalculationTest.java/1.1/Wed Oct 29 18:05:24 2008// diff --git a/src/org/jalgo/module/app/coreTest/CVS/Repository b/src/org/jalgo/module/app/coreTest/CVS/Repository new file mode 100644 index 0000000..ef8977c --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/coreTest diff --git a/src/org/jalgo/module/app/coreTest/CVS/Root b/src/org/jalgo/module/app/coreTest/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/coreTest/CapacityProblemTest.java b/src/org/jalgo/module/app/coreTest/CapacityProblemTest.java new file mode 100644 index 0000000..e19e063 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/CapacityProblemTest.java @@ -0,0 +1,111 @@ +package org.jalgo.module.app.coreTest; + + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.jalgo.module.app.core.Calculation; +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.core.step.Step; +import org.junit.Before; +import org.junit.Test; + +public class CapacityProblemTest { + RootStep step; + Graph graph; + List steps; + int size; + PositiveRationalNumber inf; + + @Before + public void setUp() throws Exception { + SemiRing ring; + Class type; + Operation plus, dot; + Calculation calc; + inf = new PositiveRationalNumber(Infinity.POSITIVE_INFINITE); + + type = PositiveRationalNumber.class; + plus = null; + dot = null; + + for (Operation o : PositiveRationalNumber.getOperations()) { + if (o instanceof RationalMaximum) + plus = o; + if (o instanceof RationalMinimum) + dot = o; + } + + ring = new SemiRing(type, plus, dot); + graph = new Graph(); + + graph.newNodes(4); + + List list; + list = GraphTest.getOrderedNodeList(graph.getNodes()); + + graph.newEdge(list.get(0), list.get(2), new PositiveRationalNumber(30.5f),true); + graph.newEdge(list.get(1), list.get(0), new PositiveRationalNumber(20.5f),true); + graph.newEdge(list.get(1), list.get(3), new PositiveRationalNumber(30.5f),true); + graph.newEdge(list.get(2), list.get(1), new PositiveRationalNumber(10.5f),true); + graph.newEdge(list.get(3), list.get(0), new PositiveRationalNumber(25.5f),true); + + calc = new Calculation(); + calc.setSemiring(ring); + calc.setGraph(graph); + + step = (RootStep)calc.getRootStep(); + steps = step.getSteps(); + size = graph.getNodes().size(); + } + + @Test + public void checkStepMatrix1() { + Matrix m; + + // check after step 1 + m = steps.get(0).getAfterMatrix(); + + for (int i=0; i list; + + list = GraphTest.getOrderedNodeList(graph.getNodes()); + + graph.newEdge(list.get(0), list.get(1), new PositiveRationalNumber(2),true); + graph.newEdge(list.get(0), list.get(5), new PositiveRationalNumber(4),true); + graph.newEdge(list.get(0), list.get(6), new PositiveRationalNumber(12),true); + + graph.newEdge(list.get(1), list.get(2), new PositiveRationalNumber(10),true); + graph.newEdge(list.get(1), list.get(6), new PositiveRationalNumber(9),true); + + graph.newEdge(list.get(2), list.get(3), new PositiveRationalNumber(2),true); + + graph.newEdge(list.get(3), list.get(4), new PositiveRationalNumber(1),true); + + graph.newEdge(list.get(5), list.get(4), new PositiveRationalNumber(11),true); + graph.newEdge(list.get(5), list.get(7), new PositiveRationalNumber(2),true); + + graph.newEdge(list.get(6), list.get(7), new PositiveRationalNumber(15),true); + + graph.newEdge(list.get(7), list.get(4), new PositiveRationalNumber(9),true); + graph.newEdge(list.get(7), list.get(8), new PositiveRationalNumber(1),true); + + graph.newEdge(list.get(8), list.get(2), new PositiveRationalNumber(4),true); + graph.newEdge(list.get(8), list.get(3), new PositiveRationalNumber(7),true); + graph.newEdge(list.get(8), list.get(6), new PositiveRationalNumber(3),true); + + // Create calculation + calc = new Calculation(); + calc.setSemiring(ring); + calc.setGraph(graph); + + step = (RootStep)calc.getRootStep(); + result = step.getAfterMatrix(); + size = graph.getNodes().size(); + } + + @Test + public void checkDistances() { + assertEquals(new PositiveRationalNumber(0), result.getValueAt(0, 0)); + assertEquals(new PositiveRationalNumber(2), result.getValueAt(0, 1)); + assertEquals(new PositiveRationalNumber(11), result.getValueAt(0, 2)); + assertEquals(new PositiveRationalNumber(13), result.getValueAt(0, 3)); + assertEquals(new PositiveRationalNumber(14), result.getValueAt(0, 4)); + assertEquals(new PositiveRationalNumber(4), result.getValueAt(0, 5)); + assertEquals(new PositiveRationalNumber(10), result.getValueAt(0, 6)); + assertEquals(new PositiveRationalNumber(6), result.getValueAt(0, 7)); + assertEquals(new PositiveRationalNumber(7), result.getValueAt(0, 8)); + } + + @Test + public void checkNodes() { + List list; + + list = new ArrayList(); + assertEquals(list, result.getNodesAt(0, 0)); + assertEquals(list, result.getNodesAt(0, 1)); + assertEquals(list, result.getNodesAt(0, 5)); + + list.add(5); + assertEquals(list, result.getNodesAt(0, 7)); + + list.add(7); + assertEquals(list, result.getNodesAt(0, 8)); + + list.add(8); + assertEquals(list, result.getNodesAt(0, 2)); + assertEquals(list, result.getNodesAt(0, 6)); + + list.add(2); + assertEquals(list, result.getNodesAt(0, 3)); + + list.add(3); + assertEquals(list, result.getNodesAt(0, 4)); + } + + @Test + public void checkEmptyNodeLists() { + for (int i=0; i steps; + int size; + + + @Before + public void setUp() throws Exception { + SemiRing ring; + Calculation calc; + + ring = AvailableSemiRings.getSemiRings().get(AvailableSemiRings.PROCESS_PROBLEM_ID); + graph = new Graph(); + + graph.newNodes(4); + + List nodeList; + nodeList = GraphTest.getOrderedNodeList(graph.getNodes()); + + graph.newEdge(nodeList.get(1), nodeList.get(3), new FormalLanguage("a"),true); + graph.newEdge(nodeList.get(1), nodeList.get(0), new FormalLanguage("c"),true); + graph.newEdge(nodeList.get(0), nodeList.get(2), new FormalLanguage("a"),true); + graph.newEdge(nodeList.get(2), nodeList.get(1), new FormalLanguage("b"),true); + graph.newEdge(nodeList.get(3), nodeList.get(0), new FormalLanguage("b"),true); + + calc = new Calculation(); + calc.setSemiring(ring); + calc.setGraph(graph); + + step = (RootStep)calc.getRootStep(); + steps = step.getSteps(); + size = graph.getNodes().size(); + } + + @Test + public void checkBeforeMatrix() { + System.out.println(step.getBeforeMatrix()); + System.out.println(step.getStep(1).getAfterMatrix()); + System.out.println(step.getStep(2).getAfterMatrix()); + System.out.println(step.getStep(3).getAfterMatrix()); + System.out.println(step.getAfterMatrix()); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/FormalLanguageTest.java b/src/org/jalgo/module/app/coreTest/FormalLanguageTest.java new file mode 100644 index 0000000..b38830e --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/FormalLanguageTest.java @@ -0,0 +1,76 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.HashSet; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.formalLanguage.Concatenate; +import org.jalgo.module.app.core.dataType.formalLanguage.FormalLanguage; +import org.jalgo.module.app.core.dataType.formalLanguage.Union; +import org.junit.Ignore; +import org.junit.Test; + +public class FormalLanguageTest { + + @Test + public void testMake() { + new FormalLanguage("(c+(ca(bca+E)*bc))"); + } + + @Test + public void testToString() { + Union union = (Union) FormalLanguage.getOperationByID("union"); + Concatenate conc = (Concatenate) FormalLanguage.getOperationByID("concat"); + + try { + FormalLanguage language1 = new FormalLanguage("a"); + FormalLanguage language2 = new FormalLanguage("b"); + + FormalLanguage language3 = (FormalLanguage) union.op(language1, language2); + assertEquals("(a+b)", language3.toString()); + + FormalLanguage language4 = (FormalLanguage) conc.op(language3, language3); + + Set testSet = new HashSet(); + testSet.add("aa"); + testSet.add("ab"); + testSet.add("ba"); + testSet.add("bb"); + assertEquals("(a+b)(a+b)", language4.toString()); + + language3 = (FormalLanguage) union.star(language3, null); + //assertEquals("{(a|b)*}", language3.toString()); + } catch (IllegalArgumentException e) { + fail("Illegal argument"); + } + } + + @Test + public void testFormalLanguage() { + FormalLanguage language = new FormalLanguage(); + assertTrue("A new formal language has to be empty.", language.isEmpty()); + } + + @Test + public void testSimplify() { + FormalLanguage l1 = new FormalLanguage("((a|b)*)"); + FormalLanguage l2 = new FormalLanguage("((E|a|b)*)"); + FormalLanguage l3 = new FormalLanguage("((E)*)"); + FormalLanguage l4 = new FormalLanguage("(EE)"); + FormalLanguage l5 = new FormalLanguage("(EEEEE)"); + FormalLanguage l6 = new FormalLanguage("(E+(EE|(a|E*)*|baad)*+ baEbEd)"); + FormalLanguage l7 = new FormalLanguage("(a+g+d+(b|a)*+z+E)"); + FormalLanguage l8 = new FormalLanguage("(c(abc)*)"); + + assertEquals("((a|b)*)",l1.toString()); + assertEquals("((a|b)*)",l2.toString()); + assertEquals("(E)",l3.toString()); + assertEquals("(E)",l4.toString()); + assertEquals("(E)",l5.toString()); + assertEquals("((a*|baad)*+E+babd)",l6.toString()); + assertEquals("((a|b)*+E+a+d+g+z)",l7.toString()); + } +} diff --git a/src/org/jalgo/module/app/coreTest/GraphTest.java b/src/org/jalgo/module/app/coreTest/GraphTest.java new file mode 100644 index 0000000..54a500d --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/GraphTest.java @@ -0,0 +1,115 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.junit.Before; +import org.junit.Test; + +public class GraphTest { + Graph graph; + Node n1,n2,n3; + Edge e1,e2,e3,e4; + + public static List getOrderedNodeList(Set nodeSet) { + List nodeList; + nodeList = new ArrayList(); + + for (int i = 0; i < nodeSet.size(); i++) { + nodeList.add(null); + } + for (Node n : nodeSet) { + nodeList.set(n.getId(), n); + } + + return nodeList; + } + + @Before + public void setUp() { + graph = new Graph(); + n1 = graph.newNode(); + n2 = graph.newNode(); + n3 = graph.newNode(); + + e1 = graph.newEdge(n1, n2,null,true); + e2 = graph.newEdge(n2, n1,null,true); + e3 = graph.newEdge(n2, n3,null,true); + e4 = graph.newEdge(n1, n3,null,true); + } + + @Test + public void addNodes() { + assertEquals(0,n1.getId()); + assertEquals(2,n3.getId()); + + assertNotNull(n2.getLocation()); + } + + @Test(expected = NoSuchElementException.class) + public void deleteNodes() { + graph.removeNode(n2); + assertEquals(1,n3.getId()); + assertNotNull(n2); + graph.removeNode(n2); + n2 = graph.newNode(); + assertEquals(2,n2.getId()); + } + + @Test + public void testID() { + for(int i = 0; i < 10; i++) { + graph.newNode(); + } + checkNodeID(); + for (int i = 0; i < 5;i++) { + graph.removeNode(graph.getNode(11-i*2)); + } + checkNodeID(); + for(int i = 0; i < 7;i++) { + graph.newNode(); + } + checkNodeID(); + } + + @Test + public void checkNodeID() { + for (int i = 0; i < graph.getNodes().size(); i++) { + assertNotNull(graph.getNode(i)); + } + } + + @Test + public void addFaultyEdge() { + try { + graph.newEdge(n3, n3,null,true); + throw new RuntimeException(); + } catch (Exception e) { + assertTrue(e instanceof IllegalArgumentException); + } + + try { + graph.newEdge(n2, n3,null,true); + throw new RuntimeException(); + } catch (Exception e) { + assertTrue(e instanceof IllegalArgumentException); + } + } + + @Test + public void removeNodesAndCheckEdges() { + graph.removeNode(n1); + assertFalse(graph.getEdges().contains(e1)); + assertEquals(1,graph.getEdges().size()); + } +} diff --git a/src/org/jalgo/module/app/coreTest/NaturalAddTest.java b/src/org/jalgo/module/app/coreTest/NaturalAddTest.java new file mode 100644 index 0000000..e0e7b12 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/NaturalAddTest.java @@ -0,0 +1,76 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalAdd; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.junit.Before; +import org.junit.Test; + +public class NaturalAddTest { + NaturalAdd add; + NaturalNumber n1,n2,nZero; + // infinite + NaturalNumber inf; + List list; + + @Before + public void setUp() { + add = new NaturalAdd(); + n1 = new NaturalNumber(5); + n2 = new NaturalNumber(7); + nZero = new NaturalNumber(); + inf = new NaturalNumber(Infinity.POSITIVE_INFINITE); + + list = new LinkedList(); + } + + @Test + public void addTwoNumbers() { + assertEquals(new NaturalNumber(12),add.op(n1,n2)); + assertEquals(new NaturalNumber(12),add.op(n2,n1)); + + assertEquals(new NaturalNumber(5),add.op(n1,nZero)); + assertEquals(new NaturalNumber(7),add.op(nZero,n2)); + } + + @Test + public void addListOfNumbers1() { + list.add(n1); + list.add(n2); + list.add(nZero); + assertEquals(new NaturalNumber(12),add.op(list)); + } + + @Test + public void addListOfNumbers2() { + for (int i = 0; i < 3; i++) { + list.add(n1); + } + assertEquals(new NaturalNumber(15),add.op(list)); + } + + @Test + public void addNothing() { + assertEquals(new NaturalNumber(0),add.op(nZero, nZero)); + assertEquals(new NaturalNumber(0),add.op(list)); + } + + @Test + public void addInfinite() { + List l = new LinkedList(); + l.add(inf); + l.add(inf); + + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),add.op(inf,nZero)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),add.op(n1, inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),add.op(inf,inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),add.op(l)); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/NaturalMaximumTest.java b/src/org/jalgo/module/app/coreTest/NaturalMaximumTest.java new file mode 100644 index 0000000..4102a5f --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/NaturalMaximumTest.java @@ -0,0 +1,79 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalMaximum; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.junit.Before; +import org.junit.Test; + +public class NaturalMaximumTest { + NaturalMaximum max; + NaturalNumber n1,n2,nZero,nOne; + // infinite + NaturalNumber inf; + List list; + + @Before + public void setUp() { + max = new NaturalMaximum(); + n1 = new NaturalNumber(5); + n2 = new NaturalNumber(7); + nZero = new NaturalNumber(); + nOne = new NaturalNumber(1); + inf = new NaturalNumber(Infinity.POSITIVE_INFINITE); + + list = new LinkedList(); + } + + @Test + public void maxTwoNumbers() { + //test if commutative + assertEquals(new NaturalNumber(7),max.op(n1,n2)); + assertEquals(new NaturalNumber(7),max.op(n2,n1)); + + assertEquals(new NaturalNumber(5),max.op(n1,nZero)); + assertEquals(new NaturalNumber(7),max.op(nOne,n2)); + } + + @Test + public void maxListOfNumbers1() { + list.add(n1); + list.add(n2); + list.add(nOne); + assertEquals(new NaturalNumber(7),max.op(list)); + } + + @Test + public void maxListOfNumbers2() { + for (int i = 0; i < 3; i++) { + list.add(n1); + } + assertEquals(new NaturalNumber(5),max.op(list)); + } + + @Test + public void maxNothing() { + assertEquals(new NaturalNumber(0),max.op(nZero, nZero)); + assertEquals(new NaturalNumber(0),max.op(list)); + + assertEquals(new NaturalNumber(1),max.op(nOne,nOne)); + } + + @Test + public void maxInfinite() { + List l = new LinkedList(); + l.add(inf); + l.add(inf); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),max.op(inf,nZero)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),max.op(n1, inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),max.op(inf,inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),max.op(l)); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/NaturalMinimumTest.java b/src/org/jalgo/module/app/coreTest/NaturalMinimumTest.java new file mode 100644 index 0000000..8a3aa75 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/NaturalMinimumTest.java @@ -0,0 +1,79 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalMinimum; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.junit.Before; +import org.junit.Test; + +public class NaturalMinimumTest { + NaturalMinimum min; + NaturalNumber n1,n2,nZero,nOne; + // infinite + NaturalNumber inf; + List list; + + @Before + public void setUp() { + min = new NaturalMinimum(); + n1 = new NaturalNumber(5); + n2 = new NaturalNumber(7); + nZero = new NaturalNumber(); + nOne = new NaturalNumber(1); + inf = new NaturalNumber(Infinity.POSITIVE_INFINITE); + + list = new LinkedList(); + } + + @Test + public void minTwoNumbers() { + //test if commutative + assertEquals(new NaturalNumber(5),min.op(n1,n2)); + assertEquals(new NaturalNumber(5),min.op(n2,n1)); + + assertEquals(new NaturalNumber(0),min.op(n1,nZero)); + assertEquals(new NaturalNumber(1),min.op(nOne,n2)); + } + + @Test + public void minListOfNumbers1() { + list.add(n1); + list.add(n2); + list.add(nOne); + assertEquals(new NaturalNumber(1),min.op(list)); + } + + @Test + public void minListOfNumbers2() { + for (int i = 0; i < 3; i++) { + list.add(n1); + } + assertEquals(new NaturalNumber(5),min.op(list)); + } + + @Test + public void minNothing() { + assertEquals(new NaturalNumber(0),min.op(nZero, nZero)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),min.op(list)); + + assertEquals(new NaturalNumber(1),min.op(nOne,nOne)); + } + + @Test + public void minInfinite() { + List l = new LinkedList(); + l.add(inf); + l.add(inf); + assertEquals(new NaturalNumber(0),min.op(inf,nZero)); + assertEquals(new NaturalNumber(5),min.op(n1, inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),min.op(inf,inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),min.op(l)); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/NaturalMultiplyTest.java b/src/org/jalgo/module/app/coreTest/NaturalMultiplyTest.java new file mode 100644 index 0000000..40d850a --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/NaturalMultiplyTest.java @@ -0,0 +1,79 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalMultiply; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.junit.Before; +import org.junit.Test; + +public class NaturalMultiplyTest { + NaturalMultiply mult; + NaturalNumber n1,n2,nZero,nOne; + // infinite + NaturalNumber inf; + List list; + + @Before + public void setUp() { + mult = new NaturalMultiply(); + n1 = new NaturalNumber(5); + n2 = new NaturalNumber(7); + nZero = new NaturalNumber(); + nOne = new NaturalNumber(1); + inf = new NaturalNumber(Infinity.POSITIVE_INFINITE); + + list = new LinkedList(); + } + + @Test + public void multiplyTwoNumbers() { + //test if commutative + assertEquals(new NaturalNumber(35),mult.op(n1,n2)); + assertEquals(new NaturalNumber(35),mult.op(n2,n1)); + + assertEquals(new NaturalNumber(0),mult.op(n1,nZero)); + assertEquals(new NaturalNumber(7),mult.op(nOne,n2)); + } + + @Test + public void multiplyListOfNumbers1() { + list.add(n1); + list.add(n2); + list.add(nOne); + assertEquals(new NaturalNumber(35),mult.op(list)); + } + + @Test + public void multiplyListOfNumbers2() { + for (int i = 0; i < 3; i++) { + list.add(n1); + } + assertEquals(new NaturalNumber(125),mult.op(list)); + } + + @Test + public void multiplyNothing() { + assertEquals(new NaturalNumber(0),mult.op(nZero, nZero)); + assertEquals(new NaturalNumber(1),mult.op(list)); + + assertEquals(new NaturalNumber(1),mult.op(nOne,nOne)); + } + + @Test + public void multiplyInfinite() { + List l = new LinkedList(); + l.add(inf); + l.add(inf); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),mult.op(inf,nZero)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),mult.op(n1, inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),mult.op(inf,inf)); + assertEquals(new NaturalNumber(Infinity.POSITIVE_INFINITE),mult.op(l)); + } + +} diff --git a/src/org/jalgo/module/app/coreTest/NaturalNumberTest.java b/src/org/jalgo/module/app/coreTest/NaturalNumberTest.java new file mode 100644 index 0000000..03c01b8 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/NaturalNumberTest.java @@ -0,0 +1,129 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.naturalNumber.NaturalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalNumber; +import org.junit.Before; +import org.junit.Test; + +public class NaturalNumberTest { + NaturalNumber nEmpty,nZero,nStandard,nNegative,nInfinity; + + @Before + public void setUp() { + nEmpty = new NaturalNumber(); + nZero = new NaturalNumber(0); + nStandard = new NaturalNumber(7); + nNegative = new NaturalNumber(); + nInfinity = new NaturalNumber(Infinity.POSITIVE_INFINITE); + } + + /** + * Check if the data type has at least 2 Operations. + */ + @Test + public void checkNumberOfOperations() { + assertNotNull(NaturalNumber.getOperations()); + assertNotSame(0,NaturalNumber.getOperations().size()); + assertNotSame(1,NaturalNumber.getOperations().size()); + } + + @Test + public void checkIntPositiveNumber() { + assertEquals(0,nEmpty.toInt()); + assertEquals(0,nZero.toInt()); + assertEquals(7,nStandard.toInt()); + assertEquals(Integer.MAX_VALUE,nInfinity.toInt()); + } + + @Test(expected = IllegalArgumentException.class) + public void createNegativeNumber() { + new NaturalNumber(-7); + } + + @Test + public void setNegativeNumber() { + assertFalse(nNegative.setFromInt(-7)); + assertFalse(nNegative.setFromFloat(-7)); + assertFalse(nNegative.setFromString("-7")); + assertFalse(nNegative.setFromNumeric(new RationalNumber(-7.7f))); + } + + @Test + public void setFromFloat() { + nEmpty.setFromFloat(1.0f); + assertEquals(1,nEmpty.toInt()); + nEmpty.setFromFloat(0.1f); + assertEquals(0,nEmpty.toInt()); + nEmpty.setFromFloat(1.9f); + assertEquals(1,nEmpty.toInt()); + } + + @Test + public void setFromInt() { + nEmpty.setFromInt(1); + assertEquals(1,nEmpty.toInt()); + nEmpty.setFromInt(0); + assertEquals(0,nEmpty.toInt()); + } + + @Test + public void setFromNumericNumber() { + nEmpty.setFromNumeric(new RationalNumber(1.1f)); + assertEquals(1,nEmpty.toInt()); + nEmpty.setFromNumeric(new RationalNumber()); + assertEquals(0,nEmpty.toInt()); + nEmpty.setFromNumeric(new RationalNumber(1.9f)); + assertEquals(1,nEmpty.toInt()); + } + + @Test + public void setFromString() { + nEmpty.setFromString("3"); + assertEquals(3,nEmpty.toInt()); + } + + @Test + public void setWrongStringInput1() { + assertFalse(nEmpty.setFromString("aba")); + + } + + @Test + public void setWrongStringInput2() { + assertFalse(nEmpty.setFromString("-2")); + } + + @Test + public void setWrongStringInput3() { + assertFalse(nEmpty.setFromString("2.3")); + } + + + @Test + public void setToTypes() { + nEmpty.setFromInt(3); + assertEquals(3,nEmpty.toInt()); + assertEquals(3.0f,nEmpty.toFloat()); + assertEquals("3",nEmpty.toString()); + } + + @Test + public void addNumbers() { + nEmpty.setFromInt(2); + nZero.setFromInt(3); + for (Operation op : NaturalNumber.getOperations()) { + if (op instanceof org.jalgo.module.app.core.dataType.naturalNumber.NaturalAdd) { + assertEquals(new NaturalNumber(5),op.op(nEmpty, nZero)); + } else if (op instanceof org.jalgo.module.app.core.dataType.naturalNumber.NaturalMultiply) { + assertEquals(new NaturalNumber(6),op.op(nEmpty, nZero)); + } + } + } +} diff --git a/src/org/jalgo/module/app/coreTest/PercentageTypeTest.java b/src/org/jalgo/module/app/coreTest/PercentageTypeTest.java new file mode 100644 index 0000000..92fbb45 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/PercentageTypeTest.java @@ -0,0 +1,144 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.rationalNumber.PercentageType; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalAdd; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMultiply; +import org.junit.Before; +import org.junit.Test; + +public class PercentageTypeTest { + PercentageType rEmpty,rZero,rOne,r5,r2,rNegative; + // infinite + PercentageType pinf, ninf; + RationalAdd add; + RationalMultiply mult; + RationalMinimum min; + RationalMaximum max; + + List list1,list2; + + @Before + public void setUp() { + add = (RationalAdd) PercentageType.getOperationByID("add"); + mult = (RationalMultiply) PercentageType.getOperationByID("mult"); + min = (RationalMinimum) PercentageType.getOperationByID("min"); + max = (RationalMaximum) PercentageType.getOperationByID("max"); + + rEmpty = new PercentageType(); + rZero = new PercentageType(0); + rOne = new PercentageType(1.0f); + pinf = new PercentageType(Infinity.POSITIVE_INFINITE); + ninf = new PercentageType(Infinity.NEGATIVE_INFINITE); + rNegative = new PercentageType(); + r5 = new PercentageType(0.5f); + r2 = new PercentageType(0.25f); + list1 = new LinkedList(); + list2 = new LinkedList(); + + } + + @Test(expected = IllegalArgumentException.class) + public void checkInvalidNumbers() { + rNegative = new PercentageType(1.2f); + } + + @Test + public void checkClosure() { + assertTrue((add.op(rEmpty, rEmpty).getClass() == PercentageType.class)); + assertTrue((mult.op(rEmpty, rEmpty).getClass() == PercentageType.class)); + assertTrue((min.op(rEmpty, rEmpty).getClass() == PercentageType.class)); + assertTrue((max.op(rEmpty, rEmpty).getClass() == PercentageType.class)); + assertTrue((rEmpty.clone().getClass() == PercentageType.class)); + } + + @Test + public void twoNumbers() { + assertEquals(new PercentageType(0.75f),add.op(r5,r2)); + assertEquals(new PercentageType(0.75f),add.op(r2,r5)); + assertEquals(new PercentageType(0.0f),add.op(rEmpty, rZero)); + + assertEquals(new PercentageType(0.125f),mult.op(r5,r2)); + assertEquals(new PercentageType(0.125f),mult.op(r2,r5)); + assertEquals(new PercentageType(0.0f),mult.op(rEmpty, rZero)); + + assertEquals(new PercentageType(0.25f),min.op(r5,r2)); + assertEquals(new PercentageType(0),min.op(rZero,r5)); + assertEquals(new PercentageType(0.0f),min.op(rEmpty, rZero)); + + assertEquals(new PercentageType(0.5f),max.op(r5,r2)); + assertEquals(new PercentageType(0.25f),max.op(r2,rZero)); + assertEquals(new PercentageType(0.0f),max.op(rEmpty, rZero)); + } + + @Test + public void listOfNumbers1() { + list1.add(r5); + list1.add(r2); + list1.add(rZero); + + list2.add(r5); + list2.add(r2); + list2.add(r2); + + assertEquals(new PercentageType(0.75f),add.op(list1)); + assertEquals(new PercentageType(1.0f),add.op(list2)); + + assertEquals(new PercentageType(0.0f),mult.op(list1)); + assertEquals(new PercentageType(0.03125f),mult.op(list2)); + + assertEquals(new PercentageType(0.0f),min.op(list1)); + assertEquals(new PercentageType(0.25f),min.op(list2)); + + assertEquals(new PercentageType(0.5f),max.op(list1)); + assertEquals(new PercentageType(0.5f),max.op(list2)); + } + + @Test + public void listOfNumbers2() { + for (int i = 0; i < 3; i++) { + list1.add(new PercentageType(0.25f)); + } + assertEquals(new PercentageType(0.75f),add.op(list1)); + + assertEquals(new PercentageType(0.015625f),mult.op(list1)); + + assertEquals(new PercentageType(0.25f),min.op(list1)); + + assertEquals(new PercentageType(0.25f),max.op(list1)); + } + + @Test + public void testNeutralElement() { + assertEquals(new PercentageType(0),add.op(rZero,rZero)); + assertEquals(new PercentageType(0),add.op(list1)); + + assertEquals(new PercentageType(1),mult.op(rOne,rOne)); + assertEquals(new PercentageType(1),mult.op(list1)); + + assertEquals(new PercentageType(Infinity.POSITIVE_INFINITE),min.op(pinf,pinf)); + assertEquals(new PercentageType(Infinity.POSITIVE_INFINITE),min.op(list1)); + + assertEquals(new PercentageType(Infinity.NEGATIVE_INFINITE),max.op(ninf,ninf)); + assertEquals(new PercentageType(Infinity.NEGATIVE_INFINITE),max.op(list1)); + } + + @Test + public void testNegativeInfinite() { + assertEquals(new PercentageType(Infinity.NEGATIVE_INFINITE), new PercentageType(0f)); + } + + @Test + public void testPositiveInfinite() { + assertEquals(new PercentageType(Infinity.POSITIVE_INFINITE), new PercentageType(1f)); + } +} diff --git a/src/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.java b/src/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.java new file mode 100644 index 0000000..2cebd46 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/PositiveRationalOperationTest.java @@ -0,0 +1,180 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalAdd; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMultiply; +import org.junit.Before; +import org.junit.Test; + + +public class PositiveRationalOperationTest { + PositiveRationalNumber rEmpty,rZero,rOne,r5,r7,rNegative; + // infinite + PositiveRationalNumber pinf, ninf; + RationalAdd add; + RationalMultiply mult; + RationalMinimum min; + RationalMaximum max; + + List list1,list2; + + @Before + public void setUp() { + Set ops; + + ops = PositiveRationalNumber.getOperations(); + for (Operation op : ops) { + if (op instanceof RationalAdd) + add = (RationalAdd)op; + if (op instanceof RationalMultiply) + mult = (RationalMultiply)op; + if (op instanceof RationalMinimum) + min = (RationalMinimum)op; + if (op instanceof RationalMaximum) + max = (RationalMaximum)op; + } + + rEmpty = new PositiveRationalNumber(); + rZero = new PositiveRationalNumber(0); + rOne = new PositiveRationalNumber(1.0f); + pinf = new PositiveRationalNumber(Infinity.POSITIVE_INFINITE); + ninf = new PositiveRationalNumber(Infinity.NEGATIVE_INFINITE); + r5 = new PositiveRationalNumber(5.2f); + r7 = new PositiveRationalNumber(7.2f); + rNegative = new PositiveRationalNumber(); + + list1 = new LinkedList(); + list2 = new LinkedList(); + + } + + @Test + public void checkClosure() { + assertTrue((add.op(rEmpty, rEmpty).getClass() == PositiveRationalNumber.class)); + assertTrue((mult.op(rEmpty, rEmpty).getClass() == PositiveRationalNumber.class)); + assertTrue((min.op(rEmpty, rEmpty).getClass() == PositiveRationalNumber.class)); + assertTrue((max.op(rEmpty, rEmpty).getClass() == PositiveRationalNumber.class)); + assertTrue((rEmpty.clone().getClass() == PositiveRationalNumber.class)); + } + + @Test + public void checkInvalidNumbers() { + assertFalse(rNegative.setFromFloat(-2.2f)); + } + @Test + public void twoNumbers() { + assertEquals(new PositiveRationalNumber(12.4f),add.op(r5,r7)); + assertEquals(new PositiveRationalNumber(12.4f),add.op(r7,r5)); + assertEquals(new PositiveRationalNumber(0.0f),add.op(rEmpty, rZero)); + + assertEquals(new PositiveRationalNumber(37.44f),mult.op(r5,r7)); + assertEquals(new PositiveRationalNumber(37.44f),mult.op(r7,r5)); + assertEquals(new PositiveRationalNumber(0.0f),mult.op(rEmpty, rZero)); + + assertEquals(new PositiveRationalNumber(5.2f),min.op(r5,r7)); + assertEquals(new PositiveRationalNumber(0),min.op(rZero,r5)); + assertEquals(new PositiveRationalNumber(0.0f),min.op(rEmpty, rZero)); + + assertEquals(new PositiveRationalNumber(7.2f),max.op(r5,r7)); + assertEquals(new PositiveRationalNumber(7.2f),max.op(r7,rZero)); + assertEquals(new PositiveRationalNumber(0.0f),max.op(rEmpty, rZero)); + } + + @Test + public void listOfNumbers1() { + list1.add(r5); + list1.add(r7); + list1.add(rZero); + + list2.add(r5); + list2.add(r7); + list2.add(rOne); + + assertEquals(new PositiveRationalNumber(12.4f),add.op(list1)); + assertEquals(new PositiveRationalNumber(13.4f),add.op(list2)); + + assertEquals(new PositiveRationalNumber(0.0f),mult.op(list1)); + assertEquals(new PositiveRationalNumber(37.44f),mult.op(list2)); + + assertEquals(new PositiveRationalNumber(0.0f),min.op(list1)); + assertEquals(new PositiveRationalNumber(1.0f),min.op(list2)); + + assertEquals(new PositiveRationalNumber(7.2f),max.op(list1)); + assertEquals(new PositiveRationalNumber(7.2f),max.op(list2)); + } + + @Test + public void listOfNumbers2() { + for (int i = 0; i < 3; i++) { + list1.add(new PositiveRationalNumber(5.125f)); + } + assertEquals(new PositiveRationalNumber(15.375f),add.op(list1)); + + assertEquals(new PositiveRationalNumber(134.611328125f),mult.op(list1)); + + assertEquals(new PositiveRationalNumber(5.125f),min.op(list1)); + + assertEquals(new PositiveRationalNumber(5.125f),max.op(list1)); + } + + @Test + public void testNeutralElement() { + assertEquals(new PositiveRationalNumber(0),add.op(rZero,rZero)); + assertEquals(new PositiveRationalNumber(0),add.op(list1)); + + assertEquals(new PositiveRationalNumber(1),mult.op(rOne,rOne)); + assertEquals(new PositiveRationalNumber(1),mult.op(list1)); + + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),min.op(pinf,pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),min.op(list1)); + + assertEquals(new PositiveRationalNumber(Infinity.NEGATIVE_INFINITE),max.op(ninf,ninf)); + assertEquals(new PositiveRationalNumber(Infinity.NEGATIVE_INFINITE),max.op(list1)); + } + + @Test + public void testNegativeInfinite() { + assertEquals(new PositiveRationalNumber(Infinity.NEGATIVE_INFINITE), new PositiveRationalNumber(0f)); + } + + @Test + public void testPositiveInfinite() { + List l = new LinkedList(); + l.add(pinf); + l.add(pinf); + l.add(pinf); + + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),add.op(pinf,rZero)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),add.op(rOne, pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),add.op(pinf,pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),add.op(l)); + + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),mult.op(pinf,rZero)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),mult.op(rOne, pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),mult.op(pinf,pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),mult.op(l)); + + assertEquals(new PositiveRationalNumber(0),min.op(pinf,rZero)); + assertEquals(new PositiveRationalNumber(1),min.op(rOne, pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),min.op(pinf,pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),min.op(l)); + + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),max.op(pinf,rZero)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),max.op(rOne, pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),max.op(pinf,pinf)); + assertEquals(new PositiveRationalNumber(Infinity.POSITIVE_INFINITE),max.op(l)); + } +} diff --git a/src/org/jalgo/module/app/coreTest/RationalNumberTest.java b/src/org/jalgo/module/app/coreTest/RationalNumberTest.java new file mode 100644 index 0000000..a4042a2 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/RationalNumberTest.java @@ -0,0 +1,125 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalAdd; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMultiply; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalNumber; +import org.junit.Before; +import org.junit.Test; + +public class RationalNumberTest { + RationalNumber rEmpty,rZero,rStandard,rNegative,rInfinity; + + @Before + public void setUp() { + rEmpty = new RationalNumber(); + rZero = new RationalNumber(0); + rStandard = new RationalNumber(7.2f); + rNegative = new RationalNumber(); + rInfinity = new RationalNumber(Infinity.POSITIVE_INFINITE); + } + + /** + * Check if the data type has at least 2 Operations. + */ + @Test + public void checkNumberOfOperations() { + assertNotNull(RationalNumber.getOperations()); + assertNotSame(0,RationalNumber.getOperations().size()); + assertNotSame(1,RationalNumber.getOperations().size()); + } + + @Test + public void checkIntPositiveNumber() { + assertEquals(0,rEmpty.toInt()); + assertEquals(0,rZero.toInt()); + assertEquals(7,rStandard.toInt()); + } + + @Test + public void createNegativeNumber() { + assertTrue(rNegative.setFromInt(-7)); + assertTrue(rNegative.setFromFloat(-7)); + assertTrue(rNegative.setFromString("-7")); + assertTrue(rNegative.setFromNumeric(new RationalNumber(-7.7f))); + } + + @Test + public void setFromFloat() { + rEmpty.setFromFloat(1.0f); + assertEquals(1.0f,rEmpty.toFloat()); + rEmpty.setFromFloat(0.1f); + assertEquals(0.1f,rEmpty.toFloat()); + rEmpty.setFromFloat(1.9f); + assertEquals(1.9f,rEmpty.toFloat()); + } + + @Test + public void setFromInt() { + rEmpty.setFromInt(1); + assertEquals(1.0f,rEmpty.toFloat()); + rEmpty.setFromInt(0); + assertEquals(0.0f,rEmpty.toFloat()); + } + + @Test + public void setFromNumericNumber() { + rEmpty.setFromNumeric(new RationalNumber(1.1f)); + assertEquals(1,rEmpty.toInt()); + rEmpty.setFromNumeric(new RationalNumber()); + assertEquals(0,rEmpty.toInt()); + rEmpty.setFromNumeric(new RationalNumber(1.9f)); + assertEquals(1,rEmpty.toInt()); + } + + @Test + public void setFromString() { + rEmpty.setFromString("3"); + assertEquals(3.0f,rEmpty.toFloat()); + } + + @Test + public void setWrongStringInput1() { + assertFalse(rEmpty.setFromString("aba")); + } + + @Test + public void setWrongStringInput2() { + assertFalse(rEmpty.setFromString("2.3ts")); + } + + + @Test + public void setToTypes() { + rEmpty.setFromFloat(3.4f); + assertEquals(3,rEmpty.toInt()); + assertEquals(3.4f,rEmpty.toFloat()); + assertEquals("3.4",rEmpty.toString()); + } + + @Test + public void addNumbers() { + rEmpty.setFromFloat(2.5f); + rZero.setFromFloat(3.5f); + for (Operation op : RationalNumber.getOperations()) { + if (op instanceof RationalAdd) { + assertEquals(new RationalNumber(6.0f),op.op(rEmpty, rZero)); + } else if (op instanceof RationalMultiply) { + assertEquals(new RationalNumber(8.75f),op.op(rEmpty, rZero)); + } else if (op instanceof RationalMinimum) { + assertEquals(new RationalNumber(2.5f),op.op(rEmpty, rZero)); + } else if (op instanceof RationalMaximum) { + assertEquals(new RationalNumber(3.5f),op.op(rEmpty, rZero)); + } + } + } +} diff --git a/src/org/jalgo/module/app/coreTest/RationalOperationTest.java b/src/org/jalgo/module/app/coreTest/RationalOperationTest.java new file mode 100644 index 0000000..a2f31a6 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/RationalOperationTest.java @@ -0,0 +1,186 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalAdd; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMultiply; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalNumber; +import org.junit.Before; +import org.junit.Test; + +public class RationalOperationTest { + RationalNumber rEmpty,rZero,rOne,r5,r7,rNegative; + // infinite + RationalNumber pinf, ninf; + RationalAdd add; + RationalMultiply mult; + RationalMinimum min; + RationalMaximum max; + + List list1, list2; + + @Before + public void setUp() { + add = (RationalAdd) RationalNumber.getOperationByID("add"); + mult = (RationalMultiply) RationalNumber.getOperationByID("mult"); + min = (RationalMinimum) RationalNumber.getOperationByID("min"); + max = (RationalMaximum) RationalNumber.getOperationByID("max"); + + rEmpty = new RationalNumber(); + rZero = new RationalNumber(0); + rOne = new RationalNumber(1.0f); + pinf = new RationalNumber(Infinity.POSITIVE_INFINITE); + ninf = new RationalNumber(Infinity.NEGATIVE_INFINITE); + r5 = new RationalNumber(5.2f); + r7 = new RationalNumber(7.2f); + rNegative = new RationalNumber(); + + list1 = new LinkedList(); + list2 = new LinkedList(); + + } + + @Test + public void checkClosure() { + assertTrue((add.op(rEmpty, rEmpty).getClass() == RationalNumber.class)); + assertTrue((mult.op(rEmpty, rEmpty).getClass() == RationalNumber.class)); + assertTrue((min.op(rEmpty, rEmpty).getClass() == RationalNumber.class)); + assertTrue((max.op(rEmpty, rEmpty).getClass() == RationalNumber.class)); + assertTrue((rEmpty.clone().getClass() == RationalNumber.class)); + } + + @Test + public void twoNumbers() { + assertEquals(new RationalNumber(12.4f),add.op(r5,r7)); + assertEquals(new RationalNumber(12.4f),add.op(r7,r5)); + assertEquals(new RationalNumber(0.0f),add.op(rEmpty, rZero)); + + assertEquals(new RationalNumber(37.44f),mult.op(r5,r7)); + assertEquals(new RationalNumber(37.44f),mult.op(r7,r5)); + assertEquals(new RationalNumber(0.0f),mult.op(rEmpty, rZero)); + + assertEquals(new RationalNumber(5.2f),min.op(r5,r7)); + assertEquals(new RationalNumber(0),min.op(rZero,r5)); + assertEquals(new RationalNumber(0.0f),min.op(rEmpty, rZero)); + + assertEquals(new RationalNumber(7.2f),max.op(r5,r7)); + assertEquals(new RationalNumber(7.2f),max.op(r7,rZero)); + assertEquals(new RationalNumber(0.0f),max.op(rEmpty, rZero)); + } + + @Test + public void listOfNumbers1() { + list1.add(r5); + list1.add(r7); + list1.add(rZero); + + list2.add(r5); + list2.add(r7); + list2.add(rOne); + + assertEquals(new RationalNumber(12.4f),add.op(list1)); + assertEquals(new RationalNumber(13.4f),add.op(list2)); + + assertEquals(new RationalNumber(0.0f),mult.op(list1)); + assertEquals(new RationalNumber(37.44f),mult.op(list2)); + + assertEquals(new RationalNumber(0.0f),min.op(list1)); + assertEquals(new RationalNumber(1.0f),min.op(list2)); + + assertEquals(new RationalNumber(7.2f),max.op(list1)); + assertEquals(new RationalNumber(7.2f),max.op(list2)); + } + + @Test + public void listOfNumbers2() { + for (int i = 0; i < 3; i++) { + list1.add(new RationalNumber(5.125f)); + } + assertEquals(new RationalNumber(15.375f),add.op(list1)); + + assertEquals(new RationalNumber(134.611328125f),mult.op(list1)); + + assertEquals(new RationalNumber(5.125f),min.op(list1)); + + assertEquals(new RationalNumber(5.125f),max.op(list1)); + } + + @Test + public void testNeutralElement() { + assertEquals(new RationalNumber(0),add.op(rZero,rZero)); + assertEquals(new RationalNumber(0),add.op(list1)); + + assertEquals(new RationalNumber(1),mult.op(rOne,rOne)); + assertEquals(new RationalNumber(1),mult.op(list1)); + + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),min.op(pinf,pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),min.op(list1)); + + assertEquals(new RationalNumber(Infinity.NEGATIVE_INFINITE),max.op(ninf,ninf)); + assertEquals(new RationalNumber(Infinity.NEGATIVE_INFINITE),max.op(list1)); + } + + @Test + public void testNegativeInfinite() { + List l = new LinkedList(); + l.add(ninf); + l.add(ninf); + l.add(ninf); + + assertEquals("-∞ + 0", new RationalNumber(Infinity.NEGATIVE_INFINITE),add.op(ninf,rZero)); + assertEquals("1 + -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),add.op(rOne, ninf)); + assertEquals("-∞ + -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),add.op(ninf,ninf)); + assertEquals("+{-∞, -∞, -∞}", new RationalNumber(Infinity.NEGATIVE_INFINITE),add.op(l)); + + assertEquals("-∞ * 0", new RationalNumber(Infinity.NEGATIVE_INFINITE),mult.op(ninf,rZero)); + assertEquals("1 * -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),mult.op(rOne, ninf)); + assertEquals("-∞ * -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),mult.op(ninf,ninf)); + assertEquals("*{-∞, -∞, -∞}", new RationalNumber(Infinity.NEGATIVE_INFINITE),mult.op(l)); + + assertEquals("min -∞ 0", new RationalNumber(Infinity.NEGATIVE_INFINITE),min.op(ninf,rZero)); + assertEquals("min 1 -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),min.op(rOne, ninf)); + assertEquals("min -∞ -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),min.op(ninf,ninf)); + assertEquals("min{-∞, -∞, -∞}", new RationalNumber(Infinity.NEGATIVE_INFINITE),min.op(l)); + + assertEquals("max -∞ 0", new RationalNumber(0),max.op(ninf,rZero)); + assertEquals("max 1 -∞", new RationalNumber(1),max.op(rOne, ninf)); + assertEquals("max -∞ -∞", new RationalNumber(Infinity.NEGATIVE_INFINITE),max.op(ninf,ninf)); + assertEquals("max{-∞, -∞, -∞}", new RationalNumber(Infinity.NEGATIVE_INFINITE),max.op(l)); + } + + @Test + public void testPositiveInfinite() { + List l = new LinkedList(); + l.add(pinf); + l.add(pinf); + l.add(pinf); + + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),add.op(pinf,rZero)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),add.op(rOne, pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),add.op(pinf,pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),add.op(l)); + + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),mult.op(pinf,rZero)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),mult.op(rOne, pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),mult.op(pinf,pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),mult.op(l)); + + assertEquals(new RationalNumber(0),min.op(pinf,rZero)); + assertEquals(new RationalNumber(1),min.op(rOne, pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),min.op(pinf,pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),min.op(l)); + + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),max.op(pinf,rZero)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),max.op(rOne, pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),max.op(pinf,pinf)); + assertEquals(new RationalNumber(Infinity.POSITIVE_INFINITE),max.op(l)); + } +} diff --git a/src/org/jalgo/module/app/coreTest/RationalStarOperationTest.java b/src/org/jalgo/module/app/coreTest/RationalStarOperationTest.java new file mode 100644 index 0000000..0bd32d0 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/RationalStarOperationTest.java @@ -0,0 +1,202 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.Operation; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalAdd; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMaximum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMinimum; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalMultiply; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalNumber; +import org.jalgo.module.app.core.dataType.rationalNumber.RationalOperation; +import org.junit.Before; +import org.junit.Test; + +public class RationalStarOperationTest { + RationalNumber rZero, rOne, rNInf, rPInf; + RationalOperation add, mult, min, max; + List rItems; + + @Before + public void setUp() { + Set ops; + + ops = RationalNumber.getOperations(); + for (Operation op : ops) { + if (op instanceof RationalAdd) + add = (RationalAdd) op; + if (op instanceof RationalMultiply) + mult = (RationalMultiply) op; + if (op instanceof RationalMinimum) + min = (RationalMinimum) op; + if (op instanceof RationalMaximum) + max = (RationalMaximum) op; + } + + rItems = new ArrayList(); + // Regular numbers + rItems.add(new RationalNumber(16.92f)); + rItems.add(new RationalNumber(39.55f)); + rItems.add(new RationalNumber(37.47f)); + rItems.add(new RationalNumber(123.23f)); + rItems.add(new RationalNumber(-16.92f)); + rItems.add(new RationalNumber(-39.55f)); + rItems.add(new RationalNumber(-37.47f)); + rItems.add(new RationalNumber(-123.23f)); + + // Small numbers close to or lesser than 1 + rItems.add(new RationalNumber(1.01f)); + rItems.add(new RationalNumber(0.23f)); + rItems.add(new RationalNumber(0.01f)); + rItems.add(new RationalNumber(0.99f)); + rItems.add(new RationalNumber(-1.01f)); + rItems.add(new RationalNumber(-0.23f)); + rItems.add(new RationalNumber(-0.01f)); + rItems.add(new RationalNumber(-0.99f)); + + // Standard numbers + rItems.add(new RationalNumber(0.0f)); + rItems.add(new RationalNumber(1.0f)); + rItems.add(new RationalNumber(2.0f)); + rItems.add(new RationalNumber(-1.0f)); + rItems.add(new RationalNumber(-2.0f)); + + // Fixed values + rZero = new RationalNumber(0f); + rOne = new RationalNumber(1f); + rNInf = new RationalNumber(Infinity.NEGATIVE_INFINITE); + rPInf = new RationalNumber(Infinity.POSITIVE_INFINITE); + } + + @Test + public void starWithAdd() { + for (RationalNumber item : rItems) { + assertEquals("+min "+item, rPInf, add.star(item, min)); + assertEquals("+max "+item, rNInf, add.star(item, max)); + + if (item.toFloat() > 0) { + assertEquals("++ "+item, rPInf, add.star(item, add)); + assertEquals("+* "+item, rPInf, add.star(item, mult)); + } + else if (item.toFloat() == 0) { + assertEquals("++ "+item, rZero, add.star(item, add)); + assertEquals("+* "+item, rOne, add.star(item, mult)); + } + else { // (item.toFloat() < -0) + assertEquals("++ "+item, rNInf, add.star(item, add)); + + try { + assertEquals("+* "+item, null, add.star(item, mult)); + } + catch (UnsupportedOperationException e) {} + } + } + + assertEquals("++ "+rPInf, rPInf, add.star(rPInf, add)); + assertEquals("+* "+rPInf, rPInf, add.star(rPInf, mult)); + assertEquals("+min "+rPInf, rPInf, add.star(rPInf, min)); + + assertEquals("++ "+rNInf, rNInf, add.star(rNInf, add)); + assertEquals("+max "+rNInf, rNInf, add.star(rNInf, max)); + } + + @Test + public void starWithMult() { + for (RationalNumber item : rItems) { + assertEquals("*min "+item, rPInf, mult.star(item, min)); + assertEquals("*max "+item, rNInf, mult.star(item, max)); + assertEquals("*+ "+item, rZero, mult.star(item, add)); + + if (item.toFloat() > 1) { + assertEquals("** "+item, rPInf, mult.star(item, mult)); + } + else if (item.toFloat() == 1) { + assertEquals("** "+item, rOne, mult.star(item, mult)); + } + else if (item.toFloat() > 0) { + assertEquals("** "+item, rZero, mult.star(item, mult)); + } + else if (item.toFloat() == 0) { + assertEquals("** "+item, rZero, mult.star(item, mult)); + } + else { + try { + assertEquals("** "+item, null, mult.star(item, mult)); + } + catch (UnsupportedOperationException e) {} + } + } + } + + @Test + public void starWithMin() { + for (RationalNumber item : rItems) { + assertEquals("min min "+item, item, min.star(item, min)); + assertEquals("min max "+item, rNInf, min.star(item, max)); + + if (item.toFloat() >= 1) { + assertEquals("min+ "+item, rZero, min.star(item, add)); + assertEquals("min* "+item, rOne, min.star(item, mult)); + } + else if (item.toFloat() > 0) { + assertEquals("min+ "+item, rZero, min.star(item, add)); + assertEquals("min* "+item, rZero, min.star(item, mult)); + } + else if (item.toFloat() == 0) { + assertEquals("min+ "+item, rZero, min.star(item, add)); + assertEquals("min* "+item, rZero, min.star(item, mult)); + } + else if (item.toFloat() >= -1) { + assertEquals("min+ "+item, rNInf, min.star(item, add)); + assertEquals("min* "+item, item, min.star(item, mult)); + } + else { + assertEquals("min+ "+item, rNInf, min.star(item, add)); + + try { + assertEquals("min* "+item, null, min.star(item, mult)); + } + catch (UnsupportedOperationException e) {} + } + } + + } + + @Test + public void starWithMax() { + for (RationalNumber item : rItems) { + assertEquals("max min "+item, rPInf, max.star(item, min)); + assertEquals("max max "+item, item, max.star(item, max)); + + if (item.toFloat() > 1) { + assertEquals("max+ "+item, rPInf, max.star(item, add)); + assertEquals("max* "+item, rPInf, max.star(item, mult)); + } + else if (item.toFloat() > 0) { + assertEquals("max+ "+item, rPInf, max.star(item, add)); + assertEquals("max* "+item, rOne, max.star(item, mult)); + } + else if (item.toFloat() == 0) { + assertEquals("max+ "+item, rZero, max.star(item, add)); + assertEquals("max* "+item, rOne, max.star(item, mult)); + } + else if (item.toFloat() >= -1) { + assertEquals("max+ "+item, rZero, max.star(item, add)); + assertEquals("max* "+item, rOne, max.star(item, mult)); + } + else { + assertEquals("max+ "+item, rZero, max.star(item, add)); + + try { + assertEquals("max* "+item, null, max.star(item, mult)); + } + catch (UnsupportedOperationException e) {} + } + } + } +} diff --git a/src/org/jalgo/module/app/coreTest/SimpleCalculationTest.java b/src/org/jalgo/module/app/coreTest/SimpleCalculationTest.java new file mode 100644 index 0000000..6058e67 --- /dev/null +++ b/src/org/jalgo/module/app/coreTest/SimpleCalculationTest.java @@ -0,0 +1,215 @@ +package org.jalgo.module.app.coreTest; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.jalgo.module.app.core.AvailableSemiRings; +import org.jalgo.module.app.core.Calculation; +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.SemiRing; +import org.jalgo.module.app.core.dataType.Infinity; +import org.jalgo.module.app.core.dataType.rationalNumber.PositiveRationalNumber; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.core.step.Step; +import org.junit.Before; +import org.junit.Test; + +public class SimpleCalculationTest { + RootStep step; + Graph graph; + + PositiveRationalNumber inf; + List steps; + int size; + + @Before + public void setUp() { + SemiRing ring; + Calculation calc; + + ring = AvailableSemiRings.getSemiRings().get(AvailableSemiRings.SHORTEST_PATH_PROBLEM_ID); + + graph = new Graph(); + + // Build Graph + graph.newNodes(4); + + List nodeList; + nodeList = GraphTest.getOrderedNodeList(graph.getNodes()); + + assertEquals(4,nodeList.size()); + + graph.newEdge(nodeList.get(0), nodeList.get(2), new PositiveRationalNumber(5),true); + graph.newEdge(nodeList.get(1), nodeList.get(0), new PositiveRationalNumber(8),true); + graph.newEdge(nodeList.get(1), nodeList.get(3), new PositiveRationalNumber(3),true); + graph.newEdge(nodeList.get(2), nodeList.get(1), new PositiveRationalNumber(2),true); + graph.newEdge(nodeList.get(3), nodeList.get(0), new PositiveRationalNumber(2),true); + + // Create calculation + calc = new Calculation(); + calc.setSemiring(ring); + calc.setGraph(graph); + + step = (RootStep)calc.getRootStep(); + steps = step.getSteps(); + size = graph.getNodes().size(); + inf = new PositiveRationalNumber(Infinity.POSITIVE_INFINITE); + } + + @Test + public void checkBeforeMatrix() { + Matrix before; + + before = step.getBeforeMatrix(); + size = graph.getNodes().size(); + + for (int i=0; i + + + + + +The jAlgo-Modul for the algorithmic path problem. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/res.properties b/src/org/jalgo/module/app/res.properties new file mode 100644 index 0000000..95a2a4d --- /dev/null +++ b/src/org/jalgo/module/app/res.properties @@ -0,0 +1,29 @@ +Module_logo=/images/logo.gif +icon_editMode_s=/images/edit_button_s.gif +icon_editMode=/images/edit_button.gif +icon_runMode_s=/images/go_button_s.gif +icon_runMode=/images/go_button.gif +icon_nodeEdit=/images/edit_nodes.gif +icon_edgeEdit=/images/edit_edges.gif +icon_addEdit=/images/plus_button.gif +icon_deleteEdit=/images/minus_button.gif +icon_modifyEdit=/images/modifie_button.gif +icon_animateStart=/images/start_task.gif +icon_animatePause=/images/suspend.gif +icon_StepForward=/images/step_forward.gif +icon_StepBackward=/images/step_backward.gif +icon_GroupStepForward=/images/groupstep_forward.gif +icon_GroupStepBackward=/images/groupstep_backward.gif +graph_component_editmode=/images/graph_component_editmode.gif +graph_component_runmode=/images/graph_component_runmode.gif +helpSet_name=/help/jhelp/app_help.hs +formula_component=/images/formula_component.gif +matrix1_component=/images/matrix1_component.gif +matrix2_component=/images/matrix2_component.gif +matrix_preview=/images/matrix_preview.gif +icon_undoEdit=/images/undo.gif +icon_redoEdit=/images/redo.gif +parenthesis_arc=/images/parenthesis-arc.gif +parenthesis_edge=/images/parenthesis-edge.gif +zoom=/images/zoom.gif +icon_beamerMode=/images/beamermode_button.gif \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/CVS/Entries b/src/org/jalgo/module/app/view/CVS/Entries new file mode 100644 index 0000000..cf835cd --- /dev/null +++ b/src/org/jalgo/module/app/view/CVS/Entries @@ -0,0 +1,5 @@ +/InterfaceConstants.java/1.1/Wed Oct 29 18:05:26 2008// +/SemiringComponent.java/1.1/Wed Oct 29 18:05:26 2008// +D/graph//// +/package.html/1.1/Wed Oct 29 18:05:26 2008// +D/run//// diff --git a/src/org/jalgo/module/app/view/CVS/Repository b/src/org/jalgo/module/app/view/CVS/Repository new file mode 100644 index 0000000..daf9266 --- /dev/null +++ b/src/org/jalgo/module/app/view/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/view diff --git a/src/org/jalgo/module/app/view/CVS/Root b/src/org/jalgo/module/app/view/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/view/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/view/InterfaceConstants.java b/src/org/jalgo/module/app/view/InterfaceConstants.java new file mode 100644 index 0000000..7b38d33 --- /dev/null +++ b/src/org/jalgo/module/app/view/InterfaceConstants.java @@ -0,0 +1,579 @@ +package org.jalgo.module.app.view; + +import java.awt.Color; +import java.awt.Font; + +import org.jalgo.module.app.view.graph.HighlightState; + +/** + * This class holds all of the constants (colors, font sizes and other sizes) + * needed to adjust the view of the module interface. These constants should + * only be used by the components in the view. + * + */ +public class InterfaceConstants { + + private static Color defaultRed() { + return new Color(186, 58, 55); + } + + private static Color defaultGreen() { + return new Color(62, 136, 62); + } + + private static Color defaultBlue() { + return new Color(56, 111, 159); + } + + /** + * Gets the border color for the node in the respective highlighting state + * (no highlighting, selected, current, pre_path and post_path highlighting) + * + * @see HighlightState + * @param state + * the HighLightState for which the border color + * is needed + * @return the color for the given HighLightState + */ + public static Color borderColorForHighlightState(HighlightState state) { + switch (state) { + case NONE: + return Color.BLACK; + + case SELECTED: + case CURRENT: + return defaultRed(); // Red + + case PRE_PATH: + return defaultGreen(); // Green + + case POST_PATH: + return defaultBlue(); // Blue + } + + return null; + } + + /** + * Gets the fill color for the node in the respective highlighting state (no + * highlighting, selected, current, pre_path and post_path highlighting) + * + * @see HighlightState + * @param state + * the HighLightState for which the fill color is + * needed + * @return the color for the given HighLightState + */ + public static Color fillColorForHighlightStateNode(HighlightState state) { + switch (state) { + case NONE: + return Color.WHITE; + + case SELECTED: + case CURRENT: + return defaultRed(); // Red + + case PRE_PATH: + return defaultGreen(); // Green + + case POST_PATH: + return defaultBlue(); // Blue + } + + return null; + } + + /** + * Gets the fill color for the edge in the respective highlighting state (no + * highlighting, selected, current, pre_path and post_path highlighting) + * + * @see HighlightState + * @param state + * the HighLightState for which the fill color is + * needed + * @return the color for the given HighLightState + */ + public static Color fillColorForHighlightStateEdge(HighlightState state) { + switch (state) { + case NONE: + return Color.WHITE; + + case SELECTED: + case CURRENT: + return defaultRed(); // Red + + case PRE_PATH: + return Color.WHITE; + + case POST_PATH: + return Color.WHITE; + } + + return null; + } + + /** + * Gets the text color for the node in the respective highlighting state (no + * highlighting, selected, current, pre_path and post_path highlighting) + * + * @see HighlightState + * @param state + * the HighLightState for which the text color is + * needed + * @return the color for the given HighLightState + */ + public static Color textColorForHighlightStateNode(HighlightState state) { + switch (state) { + case NONE: + return Color.BLACK; + + default: + return Color.WHITE; + } + } + + /** + * Gets the text color for the edge weight in the respective highlighting + * state (no highlighting, selected, current, pre_path and post_path + * highlighting) + * + * @see HighlightState + * @param state + * the HighLightState for which the text color is + * needed + * @return the color for the given HighLightState + */ + public static Color textColorForHighlightStateEdge(HighlightState state) { + switch (state) { + case NONE: + return Color.BLACK; + + case SELECTED: + case CURRENT: + return Color.WHITE; + + case PRE_PATH: + return defaultGreen(); // Green + + case POST_PATH: + return defaultBlue(); // Blue + + default: + return Color.WHITE; + } + } + + /** + * Gets the text color for a matrix element in the respective highlighting + * state (no highlighting, selected, current, pre_path and post_path + * highlighting). + * + * @see HighlightState + * @param state + * the HighLightState for which the text color is + * needed + * @return the color for the given HighLightState + */ + public static Color matrixForegroundColorForHighlightState(HighlightState state) { + if (state == HighlightState.NONE) + return Color.BLACK; + + return Color.WHITE; + } + + /** + * Gets the background color for the matrix element based in the + * HighlightState. It is used in the left matrix of the + * MatrixComponent during the AlgorithmMode. + * + * @see HighlightState + * + * @param state + * the HighlightState of the matrix element + * @return the color for the given HighlightState. If + * HighLightState is set to NONE, + * return + */ + public static Color matrixBackgroundColorForHighlightState(HighlightState state) { + if (state == HighlightState.NONE) + return Color.WHITE; + + return borderColorForHighlightState(state); + } + + /** + * Gets the font color for the matrix element if this element has already + * been processed by the Aho-Algorithm. It is used in the right matrix of + * the MatrixComponent during the AlgorithmMode. + * + * @return the color for the matrix element if this element has already been + * processed by the Aho-Algorithm. + */ + public static Color changedMatrixEntryForegroundColor() { + return Color.BLACK; + } + + /** + * Gets the font color for the matrix element if this element has not been + * processed by the Aho-Algorithm. It is used in the right matrix of the + * MatrixComponent during the AlgorithmMode. + * + * @return the color for the matrix element if this element has not been + * processed by the Aho-Algorithm. + */ + public static Color unchangedMatrixEntryForegroundColor() { + return Color.GRAY; + } + + /** + * Gets the font color for the matrix element if this element is currently + * being processed by the Aho-Algorithm. It is used in the right matrix of + * the MatrixComponent during the AlgorithmMode. + * + * @return the color for the matrix element if this element is currently + * being processed by the Aho-Algorithm. + */ + public static Color currentMatrixEntryForegroundColor() { + return Color.WHITE; + } + + /** + * Gets the background color for the matrix element if this element has + * already been process by the Aho-Algorithm. It is used in the right matrix + * of the MatrixComponent during the + * AlgorithmMode. + * + * @return the color for the matrix element if this element has already + * being processed by the Aho-Algorithm. + */ + public static Color changedMatrixEntryBackgroundColor() { + return Color.WHITE; + } + + /** + * Gets the background color for the matrix element if this element has not + * been process by the Aho-Algorithm. It is used in the right matrix of the + * MatrixComponent during the AlgorithmMode. + * + * @return the color for the matrix element if this element has not been + * processed by the Aho-Algorithm. + */ + public static Color unchangedMatrixEntryBackgroundColor() { + return Color.WHITE; + } + + /** + * Gets the background color for the matrix element if this element is + * currently being process by the Aho-Algorithm. It is used in the right + * matrix of the MatrixComponent during the + * AlgorithmMode. + * + * @return the color for the matrix element if this element is currently + * being processed by the Aho-Algorithm. + */ + public static Color currentMatrixEntryBackgroundColor() { + return Color.BLACK; + } + + public static float getNodeDiameter(boolean beamerMode) { + if (beamerMode) + return 36.0f; + else + return 32.0f; + } + + public static float getNodeBorderWidth(boolean beamerMode) { + if (beamerMode) + return 4.0f; + else + return 3.0f; + } + + public static float getEdgeWidth(boolean beamerMode) { + if (beamerMode) + return 5.0f; + else + return 4.0f; + } + + public static float getEdgeWeightBorder(boolean beamerMode) { + if (beamerMode) + return 6.0f; + else + return 5.0f; + } + + public static float getEdgeArrowWidth(boolean beamerMode) { + if (beamerMode) + return 14.0f; + else + return 12.0f; + } + + public static float getEdgeArrowLength(boolean beamerMode) { + if (beamerMode) + return 16.0f; + else + return 14.0f; + } + + public static float getDoubleEdgeDistance(boolean beamerMode) { + return 50.0f; + } + + public static Font getGraphNodeFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 24); + else + return new Font("Default", Font.BOLD, 20); + } + + public static Font getGraphWeightFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 24); + else + return new Font("Default", Font.BOLD, 20); + } + + public static Font getMatrixFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 20); + else + return new Font("Default", Font.BOLD, 10); + } + + /** + * Gets the minimum font size for a matrix element. No matter how small the + * matrix is scaled, the font size will not be under this value. + * + * @param beamerMode + * true if beamerMode is enabled, + * false otherwise + * @return the minimum font size + */ + public static int getMatrixMinimumFontSize(boolean beamerMode) { + if (beamerMode) + return 24; + else + return 8; + } + + /** + * Gets the maximum font size for a matrix element. No matter how big the + * matrix is scaled, the font size will not be under this value. + * + * @param beamerMode + * true if beamerMode is enabled, + * false otherwise + * @return the maximum font size + */ + public static int getMatrixMaximumFontSize(boolean beamerMode) { + if (beamerMode) + return 35; + else + return 20; + } + + /** + * Gets the matrix color for the adjacency matrix used in the + * MatrixPreviewComponent. + * + * @return the matrix (font) color. + */ + public static Color getMatrixColor() { + return Color.BLACK; + } + + /** + * Gets the color for any wrong input. + * + * @return A red color. + */ + public static Color wrongInputColor() { + return Color.RED; + } + + /** + * Gets the fill color for the HighlightBox in GraphTextComponent. + * If an edge is selected in GraphComponent, the corresponding tuple will be + * filled in this color. + * + * @return The highlight color. + */ + public static Color textViewEdgeFillColor() { + return new Color(255, 212, 43); + } + + /** + * Gets the line color for the HighlightBox in + * GraphTextComponent. If an edge is selected in + * GraphComponent, the corresponding tuple's box will have + * an outer line of this color. + * + * @return The highlight border color. + */ + public static Color textViewEdgeLineColor() { + return new Color(42, 17, 0); + } + + /** + * Gets the font used for the edge list in GraphTextComponent. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return the font. + */ + public static Font GraphTextComponentFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 20); + else + return new Font("Default", Font.PLAIN, 16); + } + + /** + * Gets the font color for the formula in FormulaComponent. + * + * @return the font color for the formula in FormulaComponent. + */ + public static Color formulaForegroundColor() { + return Color.BLACK; + } + + /** + * Gets the background color for the formula in + * FormulaComponent. + * + * @return the background color for the formula in + * FormulaComponent. + */ + public static Color formulaBackgroundColor() { + return Color.WHITE; + } + + /** + * Gets the font for every string in the FormulaComponent + * that is painted "normally", i.e. it is neither super/subscripted nor + * bold. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A plain font. + */ + public static Font formulaNormalFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.PLAIN, 22); + else + return new Font("Default", Font.PLAIN, 14); + } + + /** + * Gets the font for every string in the FormulaComponent + * that is painted bold. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A bold font. + */ + public static Font formulaBoldFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 22); + else + return new Font("Default", Font.BOLD, 14); + } + + /** + * Gets the font for every string in the FormulaComponent + * that is painted in superscript or subscript (used for D_G^{k}. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A italic font. + */ + public static Font formulaSmallFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.ITALIC, 16); + else + return new Font("Default", Font.ITALIC, 10); + + } + + /** + * Gets the font for every string in the FormulaWindow that + * is painted "normally", i.e. it is neither super/subscripted nor bold. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A plain font. + */ + public static Font formulaWindowNormalFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.PLAIN, 26); + else + return new Font("Default", Font.PLAIN, 18); + + } + + /** + * Gets the font for every string in the FormulaWindow that + * is bold. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A bold font. + */ + public static Font formulaWindowBoldFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.BOLD, 26); + else + return new Font("Default", Font.BOLD, 18); + } + + /** + * Gets the font for every string in the FormulaWindow that + * is painted in superscript or subscript (used for D_G^{k}. + * + * @param beamerMode + * true if the beamerMode is enabled, + * false otherwise. + * @return A italic font. + */ + public static Font formulaWindowSmallFont(boolean beamerMode) { + if (beamerMode) + return new Font("Default", Font.ITALIC, 22); + else + return new Font("Default", Font.ITALIC, 14); + } + + /** + * Gets the horizontal gap between two matrices in the + * MatrixComponent. + * + * @return the horizontal gap between two matrices in the + * MatrixComponent. + */ + public static int matrixHgap() { + return 10; + } + + /** + * Gets the vertical gap between two matrices in the + * MatrixComponent. + * + * @return the vertical gap between two matrices in the + * MatrixComponent. + */ + public static int matrixVgap() { + return 10; + } + + public static int parenthesisHgap() { + return 20; + } + +} diff --git a/src/org/jalgo/module/app/view/SemiringComponent.java b/src/org/jalgo/module/app/view/SemiringComponent.java new file mode 100644 index 0000000..dbc42b1 --- /dev/null +++ b/src/org/jalgo/module/app/view/SemiringComponent.java @@ -0,0 +1,335 @@ +package org.jalgo.module.app.view; + +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; +import java.util.Map; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.SemiringController; +import org.jalgo.module.app.core.AvailableSemiRings; +import org.jalgo.module.app.core.SemiRing; + +/** + * This component is used for displaying a) the semiring selection at the start + * of the module and b) the selected semiring during the graph editing and + * algorithm mode. The component is displayed in the right panel at the top. The + * Display mode depends on the enum SemiringDisplay. + * + */ +public class SemiringComponent extends JPanel { + + private static final long serialVersionUID = -1301296968702660788L; + + private SemiringController semiringController; + + private Map semirings; + private String[] semiringNameList; + + private JPanel editPanel; + private BorderLayout editLayout; + private JComboBox semiringBox; + private JButton okayButton; + private JLabel text; + + private Font normalFont, smallFont, boldFont; + + private boolean beamerMode; + + /** + * This enum is used for setting the displayMode of the semiring display. + * + */ + private enum SemiringDisplay { + TEMPLATE_SELECTION, DISPLAY + } + + private SemiringDisplay displayMode; + + /** + * Instantiates the SemiRingComponent. This component is used for displaying + * a) the semiring selection at the start of the module and b) the selected + * semiring during the graph editing and algorithm mode. The component is + * displayed in the right panel at the top. The Display mode depends on the + * enum SemiringDisplay. + * + * @param controller + * the controller, through which access to the model is possible. + */ + public SemiringComponent(SemiringController controller) { + + semiringController = controller; + setAlignmentX(Component.LEFT_ALIGNMENT); + + beamerMode = false; + + setDisplayMode(SemiringDisplay.TEMPLATE_SELECTION); + } + + /** + * Initializes the dropdown box with a alphabetical sorted list of all + * Semirings. + */ + private void initSemiringDropDown() { + semirings = AvailableSemiRings.getSemiRings(); + semiringNameList = new String[semirings.size()]; + + int i = 0; + for (SemiRing s : semirings.values()) { + semiringNameList[i] = s.getName(); + i++; + } + Arrays.sort(semiringNameList); + semiringBox = new JComboBox(semiringNameList); + } + + private void initEditPanel() { + initSemiringDropDown(); + + editLayout = new BorderLayout(); + + + + text = new JLabel(Messages.getString("app", "SemiringComponent.Text")); + editPanel = new JPanel(editLayout); + editPanel.setLayout(editLayout); + + okayButton = new JButton(Messages.getString( + "app", "SemiringComponent.OK")); //$NON-NLS-1$ //$NON-NLS-2$ + + editLayout.setVgap(7); + editLayout.setHgap(20); + editPanel.add(semiringBox, BorderLayout.CENTER); + editPanel.add(okayButton, BorderLayout.EAST); + editPanel.add(text, BorderLayout.NORTH); + okayButton.addActionListener(new OkayButtonListener()); + } + + private void initViewPanel() { + Dimension panelDimension = new Dimension(this.getWidth(), + (int) (InterfaceConstants.formulaNormalFont(beamerMode) + .getSize() * 4.5f)); + + this.setMinimumSize(panelDimension); + this.setPreferredSize(panelDimension); + this.setMaximumSize(panelDimension); + + normalFont = InterfaceConstants.formulaNormalFont(beamerMode); + smallFont = InterfaceConstants.formulaSmallFont(beamerMode); + boldFont = InterfaceConstants.formulaBoldFont(beamerMode); + + repaint(); + revalidate(); + } + + private int paintString(String string, Graphics2D graphics, Font font, + int offsetX, int offsetY) { + graphics.setFont(font); + + graphics.drawString(string, offsetX, offsetY); + return offsetX + + (int) graphics.getFontMetrics(font).getStringBounds(string, + graphics).getWidth(); + } + + private int paintStringNormal(String string, Graphics2D graphics, + int offsetX, int offsetY) { + return paintString(string, graphics, normalFont, offsetX, offsetY); + } + + private int paintStringBold(String string, Graphics2D graphics, + int offsetX, int offsetY) { + return paintString(string, graphics, boldFont, offsetX, offsetY); + } + + private int paintStringSmall(String string, Graphics2D graphics, + int offsetX, int offsetY) { + return paintString(string, graphics, smallFont, offsetX, offsetY); + } + + private void paintSemiringDefinition(Graphics2D graphics, + SemiRing semiring, int offsetX, int offsetY, int lineHeight) { + int lowerOffset, upperOffset; + + String[] symbolicRepresentation; + String plusOperator, dotOperator, plusNeutral, dotNeutral; + + symbolicRepresentation = semiring.getTypeRepresentation(); + plusOperator = semiring.getPlusOperation().getSymbolicRepresentation(); + dotOperator = semiring.getDotOperation().getSymbolicRepresentation(); + plusNeutral = semiring.getPlusOperation().getNeutralElementDescription(); + dotNeutral = semiring.getDotOperation().getNeutralElementDescription(); + + // ( + offsetX = paintStringNormal("(", graphics, offsetX, offsetY); + + // Paint symbolic representation of type + offsetX = paintStringBold(symbolicRepresentation[0], graphics, offsetX, + offsetY); + lowerOffset = paintStringSmall(symbolicRepresentation[1], graphics, + offsetX, offsetY - lineHeight / 4); + upperOffset = paintStringSmall(symbolicRepresentation[2], graphics, + offsetX, offsetY + lineHeight / 4); + + offsetX = Math.max(lowerOffset, upperOffset); + offsetX = paintStringNormal(", ", graphics, offsetX, offsetY); + + // Paint operators + offsetX = paintStringBold(plusOperator, graphics, offsetX, offsetY); + offsetX = paintStringNormal(", ", graphics, offsetX, offsetY); + + offsetX = paintStringBold(dotOperator, graphics, offsetX, offsetY); + offsetX = paintStringNormal(", ", graphics, offsetX, offsetY); + + // Paint neutrals elements + offsetX = paintStringBold(plusNeutral, graphics, offsetX, offsetY); + offsetX = paintStringNormal(", ", graphics, offsetX, offsetY); + + offsetX = paintStringBold(dotNeutral, graphics, offsetX, offsetY); + + // ) + offsetX = paintStringNormal(")", graphics, offsetX, offsetY); + } + + private void paintView(Graphics2D graphics) { + int fontHeight, lineHeight, offsetX, offsetY; + SemiRing semiring; + + semiring = semiringController.getSemiRing(); + + // Draw background + graphics.setColor(this.getBackground()); + graphics.fill(new Rectangle(this.getSize())); + + // Initialize painting + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + graphics.setStroke(new BasicStroke(1)); + + fontHeight = (int) graphics.getFontMetrics(normalFont).getStringBounds( + "D", graphics).getHeight(); + lineHeight = (int) (fontHeight * 1.5); + offsetX = lineHeight / 2; + offsetY = 0; + + graphics.setFont(normalFont); + + // Paint name of Semiring + offsetY += lineHeight; + graphics.drawString(semiring.getName(), offsetX, offsetY); + + // Paint description of Semiring + /* + * offsetY += lineHeight; graphics.drawString(semiring.getDescription(), + * offsetX, offsetY); + */ + + // Paint formal definition of Semiring + offsetY += lineHeight; + paintSemiringDefinition(graphics, semiring, offsetX, offsetY, + lineHeight); + } + + public void paint(Graphics graphics) { + Graphics2D g; + + g = (Graphics2D) graphics; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + if (displayMode == SemiringDisplay.TEMPLATE_SELECTION) + super.paint(graphics); + else + this.paintView(g); + } + + /** + * Gets the current DisplayMode of the Semiring (either TEMPLATE_SELECTION + * or DISPLAY). + * + * @return the mode. + */ + public SemiringDisplay getDisplayMode() { + return displayMode; + } + + /** + * Sets the current DisplayMode of the Semiring to either TEMPLATE_SELECTION + * or DISPLAY. + * + * @param mode + */ + public void setDisplayMode(SemiringDisplay mode) { + this.displayMode = mode; + + switch (this.displayMode) { + case TEMPLATE_SELECTION: + if (editPanel == null) + initEditPanel(); + + add(editPanel); + break; + + case DISPLAY: + initViewPanel(); + + if (editPanel != null) + remove(editPanel); + + break; + } + } + + /** + * @return the Semiring depending on selection in drop-down box. + */ + public SemiRing getSelectedSemiring() { + String semiringName = semiringNameList[semiringBox.getSelectedIndex()]; + + for (SemiRing s : semirings.values()) { + if (s.getName().equals(semiringName)) { + return s; + } + } + + return null; + } + + public void updateDisplay(SemiRing semiring) { + if (semiring != null) { + setDisplayMode(SemiringDisplay.DISPLAY); + + repaint(); + } else { + setDisplayMode(SemiringDisplay.TEMPLATE_SELECTION); + } + } + + public void updateBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + this.boldFont = InterfaceConstants.formulaBoldFont(beamerMode); + this.normalFont = InterfaceConstants.formulaNormalFont(beamerMode); + this.smallFont = InterfaceConstants.formulaSmallFont(beamerMode); + initViewPanel(); + } + + class OkayButtonListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + semiringController.setSemiRing(getSelectedSemiring()); + } + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/graph/BoxingHighlightPainter.java b/src/org/jalgo/module/app/view/graph/BoxingHighlightPainter.java new file mode 100644 index 0000000..e9ee412 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/BoxingHighlightPainter.java @@ -0,0 +1,25 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.Color; +import java.awt.Shape; +import java.awt.geom.RoundRectangle2D; + +public class BoxingHighlightPainter extends ShapeHighlightPainter { + + public BoxingHighlightPainter(Color lineColor, Color fillColor) { + this.lineColor = Color.WHITE; //lineColor; + this.fillColor = fillColor; + this.hasBorder = true; + this.hasFilling = true; + this.strokeWidth = 2; + } + + protected Shape calculateShape(int x, int y, int length, int height, int fontSize) { + RoundRectangle2D box; + + box = new RoundRectangle2D.Float((float)x, (float)y, (float)length, (float)height, 8f, 8f); + + return box; + } + +} diff --git a/src/org/jalgo/module/app/view/graph/CVS/Entries b/src/org/jalgo/module/app/view/graph/CVS/Entries new file mode 100644 index 0000000..822cff2 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/CVS/Entries @@ -0,0 +1,13 @@ +/BoxingHighlightPainter.java/1.1/Wed Oct 29 18:05:24 2008// +/EdgeElement.java/1.1/Wed Oct 29 18:05:24 2008// +/EditToolbar.java/1.1/Wed Oct 29 18:05:24 2008// +/GraphComponent.java/1.1/Wed Oct 29 18:05:24 2008// +/GraphElement.java/1.1/Wed Oct 29 18:05:24 2008// +/GraphTextComponent.java/1.1/Wed Oct 29 18:05:24 2008// +/HighlightState.java/1.1/Wed Oct 29 18:05:24 2008// +/ModeSwitchComponent.java/1.1/Wed Oct 29 18:05:24 2008// +/NewEdgeElement.java/1.1/Wed Oct 29 18:05:24 2008// +/NodeElement.java/1.1/Wed Oct 29 18:05:24 2008// +/ShapeHighlightPainter.java/1.1/Wed Oct 29 18:05:24 2008// +/UnderliningHighlightPainter.java/1.1/Wed Oct 29 18:05:24 2008// +/package.html/1.1/Wed Oct 29 18:05:24 2008// diff --git a/src/org/jalgo/module/app/view/graph/CVS/Repository b/src/org/jalgo/module/app/view/graph/CVS/Repository new file mode 100644 index 0000000..eeb8f47 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/view/graph diff --git a/src/org/jalgo/module/app/view/graph/CVS/Root b/src/org/jalgo/module/app/view/graph/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/view/graph/EdgeElement.java b/src/org/jalgo/module/app/view/graph/EdgeElement.java new file mode 100644 index 0000000..07a82af --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/EdgeElement.java @@ -0,0 +1,551 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.BasicStroke; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.font.FontRenderContext; +import java.awt.font.LineMetrics; +import java.awt.geom.AffineTransform; +import java.awt.geom.Ellipse2D; +import java.awt.geom.GeneralPath; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Highlighter.HighlightPainter; + +import org.jalgo.module.app.controller.GraphActionListener.EditMode; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.view.InterfaceConstants; + +/** + * The graphical representation of an edge in the user interface. This class + * wraps an object from type Edge. + */ +public class EdgeElement extends GraphElement { + + private static final long serialVersionUID = -4469336801616982360L; + private Edge edge; + private EdgeShape shape; + + // attributes for the WeightEditing + private JTextField input; + private HighlightPainter mistakePainter; + private Object currentHighlight; + private FontRenderContext renderContext; + + private boolean isWeightEditing; + private DataType oldweight; + + private static boolean beamerMode; + + @SuppressWarnings("serial") + public class EdgeTextField extends JTextField { + } + + public EdgeElement(Edge edge) { + this.edge = edge; + + beamerMode = false; + + highlightState = HighlightState.NONE; + renderContext = new FontRenderContext(new AffineTransform(), true, false); + isWeightEditing = false; + + input = new EdgeTextField(); + input.setVisible(false); + } + + @Override + public boolean contains(Point2D point) { + return (shape.arrow.contains(point) || shape.labelShape.contains(point) || shape.lineShape + .contains(point)); + } + + @Override + public void paint(Graphics2D g) { + calculateShape(); + if (shape == null) + return; + + // Draw line & arrow + g.setColor(InterfaceConstants + .borderColorForHighlightState(highlightState)); + g.setStroke(new BasicStroke(InterfaceConstants.getEdgeWidth(beamerMode))); + + g.fill(shape.lineShape); + + g.fill(shape.arrow); + + + // Draw weight box + if (!isWeightEditing) { + g.setColor(InterfaceConstants + .fillColorForHighlightStateEdge(highlightState)); + g.fill(shape.labelShape); + + // Draw weight + Font font; + + font = InterfaceConstants.getGraphWeightFont(beamerMode); + g.setColor(InterfaceConstants + .textColorForHighlightStateEdge(highlightState)); + g.setFont(font); + + g.drawString(getEdgeWeight(), + (float) (shape.labelBounds.getCenterX() - shape.labelSize + .getWidth() / 2), (float) (shape.labelBounds + .getCenterY() + - shape.metrics.getHeight() / 2 + shape.metrics + .getAscent())); + } + } + + private class EdgeShape { + public Point2D beginPoint, endPoint; + public Rectangle2D labelSize, labelBounds; + public LineMetrics metrics; + public GeneralPath arrow, lineShape; + public Shape labelShape; + } + + private void calculateShape() { + Point2D beginPoint, midPoint, endPoint; + boolean hasInverse; + + // Get necessary data + beginPoint = new Point2D.Float(); + endPoint = new Point2D.Float(); + + beginPoint.setLocation(getBeginNodePoint()); + endPoint.setLocation(getEndNodePoint()); + + if (getBeginNode() != null && getEndNode() != null) + hasInverse = (getComponent().getGraphActionListener().getGraph() + .getEdge(getEndNode(), getBeginNode()) != null); + else + hasInverse = false; + + // Calculate mid point + AffineTransform rotation; + Point2D offsetPoint; + float distance; + double dx, dy; + + midPoint = new Point2D.Float(); + midPoint.setLocation((beginPoint.getX() + endPoint.getX()) / 2, + (beginPoint.getY() + endPoint.getY()) / 2); + + // get delta + dx = endPoint.getX() - beginPoint.getX(); + dy = endPoint.getY() - beginPoint.getY(); + + // offset point if it has an inverse + if (hasInverse) { + distance = InterfaceConstants.getDoubleEdgeDistance(beamerMode) / 2; + offsetPoint = rotateVerticalDistance(getRotation(dx, dy), distance); + midPoint.setLocation(midPoint.getX() + offsetPoint.getX(), midPoint + .getY() + + offsetPoint.getY()); + } + + // Fix begin point + double x, y; + float nodeRadius; + + nodeRadius = getBeginNodeRadius(); + + dx = midPoint.getX() - beginPoint.getX(); + dy = midPoint.getY() - beginPoint.getY(); + + x = dx * nodeRadius / Math.sqrt(dx * dx + dy * dy); + y = dy * nodeRadius / Math.sqrt(dx * dx + dy * dy); + + beginPoint = new Point2D.Float((float) (beginPoint.getX() + x), + (float) (beginPoint.getY() + y)); + + // Fix end point + dx = endPoint.getX() - midPoint.getX(); + dy = endPoint.getY() - midPoint.getY(); + + nodeRadius = getEndNodeRadius(); + nodeRadius += InterfaceConstants.getEdgeArrowLength(beamerMode); + x = dx * nodeRadius / Math.sqrt(dx * dx + dy * dy); + y = dy * nodeRadius / Math.sqrt(dx * dx + dy * dy); + + endPoint = new Point2D.Float((float) (endPoint.getX() - x), + (float) (endPoint.getY() - y)); + + // Create arrow + AffineTransform move; + GeneralPath arrow; + + rotation = getRotation(dx, dy); + arrow = getArrowShape(); + arrow.transform(rotation); + + move = new AffineTransform(); + move.translate(endPoint.getX(), endPoint.getY()); + arrow.transform(move); + + // Create line shape + float xOffset[], yOffset[]; + GeneralPath lineShape; + + xOffset = new float[3]; + yOffset = new float[3]; + + distance = InterfaceConstants.getEdgeWidth(beamerMode) / 2; + + rotation = getRotation(midPoint.getX() - beginPoint.getX(), midPoint + .getY() + - beginPoint.getY()); + offsetPoint = rotateVerticalDistance(rotation, distance); + xOffset[0] = (float) offsetPoint.getX(); + yOffset[0] = (float) offsetPoint.getY(); + + rotation = getRotation(endPoint.getX() - beginPoint.getX(), endPoint + .getY() + - beginPoint.getY()); + offsetPoint = rotateVerticalDistance(rotation, distance); + xOffset[1] = (float) offsetPoint.getX(); + yOffset[1] = (float) offsetPoint.getY(); + + rotation = getRotation(endPoint.getX() - midPoint.getX(), endPoint + .getY() + - midPoint.getY()); + offsetPoint = rotateVerticalDistance(rotation, distance); + xOffset[2] = (float) offsetPoint.getX(); + yOffset[2] = (float) offsetPoint.getY(); + + lineShape = new GeneralPath(); + + lineShape.moveTo((float) beginPoint.getX() - xOffset[0], + (float) beginPoint.getY() - yOffset[0]); + lineShape.curveTo((float) midPoint.getX() - xOffset[1], + (float) midPoint.getY() - yOffset[1], (float) midPoint.getX() + - xOffset[1], (float) midPoint.getY() - yOffset[1], + (float) endPoint.getX() - xOffset[2], (float) endPoint.getY() + - yOffset[2]); + + lineShape.lineTo((float) endPoint.getX() + xOffset[2], (float) endPoint + .getY() + + yOffset[2]); + lineShape.curveTo((float) midPoint.getX() + xOffset[1], + (float) midPoint.getY() + yOffset[1], (float) midPoint.getX() + + xOffset[1], (float) midPoint.getY() + yOffset[1], + (float) beginPoint.getX() + xOffset[0], (float) beginPoint + .getY() + + yOffset[0]); + + lineShape.closePath(); + + // Get label attributes + Rectangle2D labelSize, labelBounds; + LineMetrics metrics; + float labelBorder; + Shape labelShape; + String label; + Font font; + + if (!isWeightEditing) + label = getEdgeWeight(); + else if (input.getText() != null) + label = input.getText(); + else + label = ""; + + font = InterfaceConstants.getGraphWeightFont(beamerMode); + labelBorder = InterfaceConstants.getEdgeWeightBorder(beamerMode); + + labelSize = font.getStringBounds(label, renderContext); + metrics = font.getLineMetrics(label, renderContext); + + // Add border to label size + labelBounds = (Rectangle2D) labelSize.clone(); + labelBounds.setFrame(labelBounds.getX() - labelBorder, labelBounds + .getY() + - labelBorder, labelBounds.getWidth() + 2 * labelBorder, + labelBounds.getHeight() + 2 * labelBorder); + + // Calculate position + x = midPoint.getX(); + y = midPoint.getY(); + + labelBounds.setFrame(x - labelBounds.getWidth() / 2, y + - labelBounds.getHeight() / 2, labelBounds.getWidth(), + labelBounds.getHeight()); + + // Adjust weight box + if (highlightState != HighlightState.CURRENT) { + Ellipse2D ellipse; + + ellipse = new Ellipse2D.Float(); + ellipse.setFrame(labelBounds); + + labelShape = ellipse; + } + else{ + labelShape = labelBounds; + } + + // Create Shape object + shape = new EdgeShape(); + + shape.arrow = arrow; + shape.beginPoint = beginPoint; + shape.endPoint = endPoint; + shape.labelSize = labelSize; + shape.labelBounds = labelBounds; + shape.metrics = metrics; + shape.labelShape = labelShape; + shape.lineShape = lineShape; + + } + + protected float getBeginNodeRadius() { + return (InterfaceConstants.getNodeDiameter(beamerMode) + InterfaceConstants + .getNodeBorderWidth(beamerMode) / 2) / 2; + } + + protected float getEndNodeRadius() { + return (InterfaceConstants.getNodeDiameter(beamerMode) + InterfaceConstants + .getNodeBorderWidth(beamerMode) / 2) / 2; + } + + protected Node getBeginNode() { + return edge.getBegin(); + } + + protected Node getEndNode() { + return edge.getEnd(); + } + + protected Point2D getBeginNodePoint() { + return component.getScaledLocation(getBeginNode().getLocation()); + } + + protected Point2D getEndNodePoint() { + return component.getScaledLocation(getEndNode().getLocation()); + } + + protected String getEdgeWeight() { + return edge.getWeight().toString(); + } + + private static AffineTransform getRotation(double dx, double dy) { + AffineTransform rotation; + + rotation = new AffineTransform(); + if (dx >= 0) + rotation.rotate(Math.atan(dy / dx)); + else + rotation.rotate(Math.atan(dy / dx) + Math.PI); + + return rotation; + } + + private static Point2D rotateVerticalDistance(AffineTransform rotation, + double distance) { + GeneralPath offset; + + offset = new GeneralPath(); + offset.moveTo(0, (float) distance); + + offset.transform(rotation); + + return offset.getCurrentPoint(); + } + + private static GeneralPath getArrowShape() { + GeneralPath arrow; + + arrow = new GeneralPath(); + arrow.moveTo(InterfaceConstants.getEdgeArrowLength(beamerMode), 0); + arrow.lineTo(0, -InterfaceConstants.getEdgeArrowWidth(beamerMode) / 2); + arrow.lineTo(0, InterfaceConstants.getEdgeArrowWidth(beamerMode) / 2); + arrow.closePath(); + + return arrow; + } + + public Edge getEdge() { + return edge; + } + + public void setEdge(Edge edge) { + this.edge = edge; + } + + public void beginWeightEditing() { + + isWeightEditing = true; + oldweight = edge.getWeight(); + + input.setVisible(true); + input.setText(edge.getWeight().toString()); + input.setBounds(shape.labelBounds.getBounds()); + + input.setFont(InterfaceConstants.getGraphWeightFont(beamerMode)); + input.setAlignmentX(0.5f); + input.setAlignmentY(0.5f); + input.setSelectionStart(0); + input.setSelectionEnd(input.getText().length()); + input.setHighlighter(new DefaultHighlighter()); + + component.add(input); + component.validate(); + + input.validate(); + input.grabFocus(); + + input.addActionListener(new InputActionListener()); + input.getDocument().addDocumentListener(new CurrentDocumentListener()); + input.addFocusListener(new TextFieldFocusListener()); + + mistakePainter = new UnderliningHighlightPainter( + InterfaceConstants.wrongInputColor()); + currentHighlight = null; + + repaint(); + + // getInputMethodRequests() + +// component.setIgnoreEvents(true); + } + + public void endWeightEditing() { + isWeightEditing = false; + input.setVisible(false); + + component.update(); +// component.setIgnoreEvents(false); + } + + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_DELETE + || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { + component.getGraphActionListener().removeEdge(edge); + } + } + + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + beginWeightEditing(); + super.mouseClicked(e); + } else { + if(component.getGraphActionListener().getEditMode() == EditMode.EDITING_WEIGHT) + beginWeightEditing(); + super.mouseClicked(e); + } + } + + private class CurrentDocumentListener implements DocumentListener { + + private void updateCheck() { + String weightText; + DataType weight; + weightText = input.getText(); + weight = null; + int width, height, x, y; + + // Update input field size + calculateShape(); + + Rectangle inputsize = shape.labelBounds.getBounds(); + width = (int) (inputsize.getWidth()); + height = (int) inputsize.getHeight(); + x = (int) inputsize.getX(); + y = (int )inputsize.getY(); + + inputsize.setBounds(x, y, width, height); + input.setBounds(inputsize); + input.setHorizontalAlignment(JTextField.CENTER); + + repaint(); + + // Test for wrong inputs + try { + weight = component.getGraphActionListener().getDataType() + .newInstance(); + } catch (InstantiationException e1) { + return; + } catch (IllegalAccessException e2) { + return; + } + + + + if (currentHighlight != null) { + input.getHighlighter().removeHighlight(currentHighlight); + currentHighlight = null; + } + + if (weight.setFromString(weightText)) { + component.getGraphActionListener().alterEdgeWeight(edge, weight); + } + else { + component.getGraphActionListener().alterEdgeWeight(edge, oldweight); + try { + currentHighlight = input.getHighlighter().addHighlight(0, + weightText.length(), mistakePainter); + } catch (BadLocationException e1) { + } + } + } + + public void changedUpdate(DocumentEvent event) { + updateCheck(); + } + + public void insertUpdate(DocumentEvent event) { + updateCheck(); + } + + public void removeUpdate(DocumentEvent event) { + updateCheck(); + } + + } + + private class InputActionListener implements ActionListener { + + public void actionPerformed(ActionEvent ae) { + endWeightEditing(); + } + + } + + private class TextFieldFocusListener implements FocusListener { + + public void focusGained(FocusEvent event) { + + } + + public void focusLost(FocusEvent event) { + if (!(event.getOppositeComponent() instanceof EditToolbar.JSpecialCharButton)) + if (event.getSource() == input) + endWeightEditing(); + } + + } + + public void updateBeamerMode(boolean beamerMode) { + EdgeElement.beamerMode = beamerMode; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/graph/EditToolbar.java b/src/org/jalgo/module/app/view/graph/EditToolbar.java new file mode 100644 index 0000000..0c14b50 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/EditToolbar.java @@ -0,0 +1,333 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.ButtonGroup; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JToggleButton; +import javax.swing.text.JTextComponent; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.GraphActionListener; +import org.jalgo.module.app.controller.GraphController; +import org.jalgo.module.app.controller.GraphObserver; +import org.jalgo.module.app.controller.GraphActionListener.EditMode; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; + +public class EditToolbar extends JPanel implements GraphObserver { + + private static final long serialVersionUID = -8480050495295128178L; + + private GraphActionListener graphActionListener; + private GraphController graphCtrl; + + private ButtonGroup modeGroup; + private JToggleButton nodeEdit, edgeEdit; + private JButton addButton, deleteButton, modifyButton, undoButton, + redoButton; + private JPanel spacer_mode, spacer_undo, spacer_char; + + private List specialCharButtons; + + private boolean enabled; + + @SuppressWarnings("unused") + private String[] specialChars; + + public class JSpecialCharButton extends JButton { + + private static final long serialVersionUID = 4161178148628990677L; + + } + + public EditToolbar(GraphController graphCtrl) { + this.graphCtrl = graphCtrl; + graphCtrl.addGraphObserver(this); + + specialCharButtons = new ArrayList(); + + nodeEdit = new JToggleButton(); + edgeEdit = new JToggleButton(); + addButton = new JButton(); + deleteButton = new JButton(); + modifyButton = new JButton(); + undoButton = new JButton(); + redoButton = new JButton(); + + // Setup Buttons + nodeEdit.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_nodeEdit"))); //$NON-NLS-1$ + edgeEdit.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_edgeEdit"))); //$NON-NLS-1$ + addButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_addEdit"))); //$NON-NLS-1$ + deleteButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_deleteEdit"))); //$NON-NLS-1$ + modifyButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_modifyEdit"))); //$NON-NLS-1$ + undoButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_undoEdit"))); //$NON-NLS-1$ + redoButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_redoEdit"))); //$NON-NLS-1$ + + nodeEdit.setToolTipText(Messages.getString("app","EditToolbar.nodeEdit")); //$NON-NLS-1$ //$NON-NLS-2$ + edgeEdit.setToolTipText(Messages.getString("app","EditToolbar.edgeEdit")); //$NON-NLS-1$ //$NON-NLS-2$ + addButton.setToolTipText(Messages.getString("app","EditToolbar.addButton")); //$NON-NLS-1$ //$NON-NLS-2$ + deleteButton.setToolTipText(Messages.getString("app","EditToolbar.deleteButton")); //$NON-NLS-1$ //$NON-NLS-2$ + modifyButton.setToolTipText(Messages.getString("app","EditToolbar.modifyButton")); //$NON-NLS-1$ //$NON-NLS-2$ + undoButton.setToolTipText(Messages.getString("app","EditToolbar.undoButton")); //$NON-NLS-1$ //$NON-NLS-2$ + redoButton.setToolTipText(Messages.getString("app","EditToolbar.redoButton")); //$NON-NLS-1$ //$NON-NLS-2$ + + undoButton.setName("undoButton"); //$NON-NLS-1$ + redoButton.setName("redoButton"); //$NON-NLS-1$ + + nodeEdit.addActionListener(new nodeModeListener()); + edgeEdit.addActionListener(new edgeModeListener()); + addButton.addActionListener(new addButtonListener()); + deleteButton.addActionListener(new deleteButtonListener()); + modifyButton.addActionListener(new modifyButtonListener()); + undoButton.addActionListener(new undoButtonListener()); + redoButton.addActionListener(new redoButtonListener()); + + // Setup Button Group + modeGroup = new ButtonGroup(); + modeGroup.add(nodeEdit); + modeGroup.add(edgeEdit); + nodeEdit.setSelected(true); + + spacer_mode = new JPanel(); + spacer_mode.setSize(60, 0); + + spacer_undo = new JPanel(); + spacer_undo.setSize(60, 0); + + // Setup Tool Bar + this.add(nodeEdit); + this.add(edgeEdit); + this.add(spacer_mode); + this.add(addButton); + this.add(deleteButton); + this.add(modifyButton); + this.add(spacer_undo); + this.add(undoButton); + this.add(redoButton); + // this.setBorder(border); + + modifyButton.setVisible(false); + + } + + public void setSpecialCharButtons(String[] specialChars) { + this.specialChars = specialChars; + + if (specialChars != null) { + spacer_char = new JPanel(); + spacer_char.setSize(60, 0); + this.add(spacer_char); + + for (int i = 0; i < specialChars.length; i ++) { + JButton spButton; + SpecialCharButtonListener listener; + + spButton = new JSpecialCharButton(); + listener = new SpecialCharButtonListener(); + + spButton.setText(specialChars[i]); + spButton.setToolTipText(Messages.getString("app","EditToolbar.specialCharButton")+": "+specialChars[i]); + + spButton.addActionListener(listener); + spButton.addFocusListener(listener); + + specialCharButtons.add(spButton); + this.add(spButton); + } + } + } + + public void setEnabled(boolean state, boolean undo, boolean redo) { + this.enabled = state; + + nodeEdit.setEnabled(state); + edgeEdit.setEnabled(state); + addButton.setEnabled(state); + + if (graphCtrl.getSelectedEdge() != null || graphCtrl.getSelectedNode() != null) + deleteButton.setEnabled(state); + else + deleteButton.setEnabled(false); + modifyButton.setEnabled(state); + undoButton.setEnabled(undo); + redoButton.setEnabled(redo); + if (specialCharButtons != null) + for (JButton spButton : specialCharButtons) { + if (graphCtrl.getSelectedEdge() != null) + spButton.setEnabled(state); + else + spButton.setEnabled(false); + } + } + + public void updateButtons() { + if (graphCtrl.getSelectedEdge() != null || graphCtrl.getSelectedNode() != null) + deleteButton.setEnabled(enabled); + else + deleteButton.setEnabled(false); + } + + + public void setUndoState() { + undoButton.setEnabled(getGraphActionListener().getUndoManager() + .isUndoable()); + redoButton.setEnabled(getGraphActionListener().getUndoManager() + .isRedoable()); + } + + public void setGraphActionListener(GraphActionListener listener) { + graphActionListener = listener; + } + + public GraphActionListener getGraphActionListener() { + return graphActionListener; + } + + class nodeModeListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + modifyButton.setSelected(false); + graphActionListener.setEditMode(EditMode.EDITING_NODES); + } + } + + class edgeModeListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + modifyButton.setSelected(false); + graphActionListener.setEditMode(EditMode.EDITING_EDGES); + } + } + + class addButtonListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + if (graphActionListener.getEditMode() == EditMode.EDITING_NODES) + graphActionListener.addNode(); + } + } + + class deleteButtonListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + if (graphActionListener.getSelectedEdge() != null) + graphActionListener.removeEdge(graphActionListener + .getSelectedEdge()); + else if (graphActionListener.getSelectedNode() != null) + graphActionListener.removeNode(graphActionListener + .getSelectedNode()); + } + } + + class modifyButtonListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + graphActionListener.setEditMode(EditMode.EDITING_WEIGHT); + modifyButton.setSelected(true); + } + } + + class undoButtonListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + getGraphActionListener().getUndoManager().undo(); + undoButton.setEnabled(getGraphActionListener().getUndoManager() + .isUndoable()); + redoButton.setEnabled(getGraphActionListener().getUndoManager() + .isRedoable()); + } + } + + class redoButtonListener implements ActionListener { + + public void actionPerformed(ActionEvent arg0) { + getGraphActionListener().getUndoManager().redo(); + undoButton.setEnabled(getGraphActionListener().getUndoManager() + .isUndoable()); + redoButton.setEnabled(getGraphActionListener().getUndoManager() + .isRedoable()); + } + } + + class SpecialCharButtonListener implements ActionListener, FocusListener { + private JTextComponent other; + + public void actionPerformed(ActionEvent arg0) { + JButton button; + char label; + + if ((other == null) && !(other instanceof JTextComponent)) + return; + + button = (JButton)arg0.getSource(); + label = button.getText().charAt(0); + + other.dispatchEvent(new KeyEvent(other, KeyEvent.KEY_PRESSED, 0, 0,KeyEvent.VK_UNDEFINED, label)); + other.dispatchEvent(new KeyEvent(other, KeyEvent.KEY_RELEASED, 0, 0,KeyEvent.VK_UNDEFINED, label)); + other.dispatchEvent(new KeyEvent(other, KeyEvent.KEY_TYPED, 0, 0,KeyEvent.VK_UNDEFINED, label)); + + other.requestFocus(); + } + + public void focusGained(FocusEvent event) { + if (!(event.getOppositeComponent() instanceof JTextComponent)) + other = null; + else + other = (JTextComponent)event.getOppositeComponent(); + } + + public void focusLost(FocusEvent event) { + other = null; + } + + } + + public void edgeAdded(Graph graph, Edge edge) { + } + + public void edgeAltered(Graph graph, Edge edge) { + } + + public void edgeRemoved(Graph graph, Edge edge) { + } + + public void graphSelectionChanged() { + if (graphCtrl.getSelectedEdge() == null && graphCtrl.getSelectedNode() == null) { + deleteButton.setEnabled(false); + } else { + deleteButton.setEnabled(true); + } + + if (graphCtrl.getSelectedEdge() == null || graphCtrl.getGraphTextComponentFocusState()) { + for (JButton spButton : specialCharButtons) + spButton.setEnabled(false); + } else { + for (JButton spButton : specialCharButtons) + spButton.setEnabled(true); + } + } + + public void graphUpdated() { + } + + public void nodeAdded(Graph graph, Node node) { + } + + public void nodeAltered(Graph graph, Node node) { + } + + public void nodeRemoved(Graph graph, Node node) { + } + +} diff --git a/src/org/jalgo/module/app/view/graph/GraphComponent.java b/src/org/jalgo/module/app/view/graph/GraphComponent.java new file mode 100644 index 0000000..b7eb44a --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/GraphComponent.java @@ -0,0 +1,649 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Toolkit; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.swing.JComponent; +import javax.swing.JPanel; + +import org.jalgo.module.app.controller.GraphActionListener; +import org.jalgo.module.app.controller.GraphController; +import org.jalgo.module.app.controller.GraphObserver; +import org.jalgo.module.app.controller.GraphActionListener.EditMode; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.view.InterfaceConstants; +import org.jalgo.module.app.view.run.StepHighlighting; + +public class GraphComponent extends JPanel implements StepHighlighting, + GraphObserver, MouseListener, MouseMotionListener, KeyListener, FocusListener { + + private static final long serialVersionUID = -1899916065578097190L; + + private Set nodeElements; + private Set edgeElements; + private GraphElement focussedElement; + + private GraphActionListener graphActionListener; + private GraphController graphCtrl; + + private boolean isDragging; + private boolean ignoreClick; + private boolean ignoreNextClick; + + private boolean isDynamicScaling; + + private AtomicStep highlightedStep; + + private boolean beamerMode; + + private class ScalingInformation { + float offsX, offsY; + float scaleWidth, scaleHeight; + } + + public GraphComponent(GraphController graphCtrl) { + nodeElements = new HashSet(); + edgeElements = new HashSet(); + focussedElement = null; + ignoreNextClick = false; + isDynamicScaling = false; + beamerMode = false; + + this.graphCtrl = graphCtrl; + + initInterface(); + + } + + /** + * Creates all relevant Interface thing + */ + private void initInterface() { + JPanel testPanel = new JPanel(); + + this.setBackground(Color.WHITE); + this.setLayout(new BorderLayout()); + this.add(testPanel, BorderLayout.CENTER); + + testPanel.setLayout(new BorderLayout()); + testPanel.setBackground(Color.WHITE); + + this.addMouseListener(this); + this.addMouseMotionListener(this); + this.addKeyListener(this); + this.addFocusListener(this); + + this.setFocusable(true); + this.setLayout(null); + } + + /** + * Initializes the element lists from the initial graph + */ + private void initElements() { + Graph graph; + + graph = graphActionListener.getGraph(); + + if (graph != null) { + + for (Edge edge : graph.getEdges()) + edgeAdded(graph, edge); + for (Node node : graph.getNodes()) + nodeAdded(graph, node); + } + + graphUpdated(); + } + + /** + * Triggers the component to redraw + */ + public void update() { + repaint(); + revalidate(); + } + + @Override + public void paint(Graphics graphics) { + Graphics2D g; + + // Setup + g = (Graphics2D) graphics; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + // Draw background + g.setColor(Color.WHITE); + g.fill(this.getBounds()); + + // Draw edges + for (EdgeElement edge : edgeElements) + edge.paint(g); + if (focussedElement instanceof NewEdgeElement) + focussedElement.paint(g); + + // Draw nodes + for (NodeElement node : nodeElements) + node.paint(g); + + paintChildren(g); + } + + private void setFocussedElementInternal(GraphElement element) { + if (highlightedStep != null) + throw new UnsupportedOperationException(); + + // Change internal selection + if (focussedElement != null) + focussedElement.setHighlightState(HighlightState.NONE); + + focussedElement = element; + + if (focussedElement != null) + focussedElement.setHighlightState(HighlightState.CURRENT); + } + + public void setFocussedElement(GraphElement element) { + setFocussedElementInternal(element); + + if (focussedElement == null + || focussedElement instanceof NewEdgeElement) { + graphActionListener.setSelectedEdge(null); + } else if (focussedElement instanceof EdgeElement) + graphActionListener.setSelectedEdge(((EdgeElement) focussedElement) + .getEdge()); + else + graphActionListener.setSelectedNode(((NodeElement) focussedElement) + .getNode()); + } + + + private ScalingInformation getStaticScaleFactors() { + ScalingInformation scales = new ScalingInformation(); + + scales.offsX = 0; + scales.offsY = 0; + scales.scaleWidth = this.getWidth() / 1000f; + scales.scaleHeight = this.getHeight() / 1000f; + + return scales; + } + + private ScalingInformation getDynamicScaleFactors() { + float minX, minY, maxX, maxY; + float curHeight, curWidth; + float spaceX, spaceY; + + ScalingInformation scales = new ScalingInformation(); + + if (graphActionListener.getGraph().getNodes().size() == 0) + return getStaticScaleFactors(); + + curHeight = (float)this.getHeight(); + curWidth = (float)this.getWidth(); + + maxX = 0; + maxY = 0; + minX = 1000; + minY = 1000; + + for (Node node : graphActionListener.getGraph().getNodes() ) { + if (minX > node.getLocation().getX()) + minX = (float)node.getLocation().getX(); + + if (minY > node.getLocation().getY()) + minY = (float)node.getLocation().getY(); + + if (maxX < node.getLocation().getX()) + maxX = (float)node.getLocation().getX(); + + if (maxY < node.getLocation().getY()) + maxY = (float)node.getLocation().getY(); + } + + spaceX = InterfaceConstants.getNodeDiameter(beamerMode) / (curWidth / 1000f); + spaceY = InterfaceConstants.getNodeDiameter(beamerMode) / (curHeight / 1000f); + + scales.scaleWidth = curWidth / (maxX + 2 * spaceX - minX); + scales.scaleHeight = curHeight / (maxY + 2 * spaceY - minY); + + scales.offsX = minX * scales.scaleWidth - InterfaceConstants.getNodeDiameter(beamerMode); + scales.offsY = minY * scales.scaleHeight - InterfaceConstants.getNodeDiameter(beamerMode); + + + return scales; + } + + public boolean isDynamicScaling() { + return isDynamicScaling; + } + + public void setDynamicScaling(boolean state) { + isDynamicScaling = state; + } + + public Point2D getScaledLocation(Point2D location) { + ScalingInformation scales; + + if (isDynamicScaling) + scales = getDynamicScaleFactors(); + else + scales = getStaticScaleFactors(); + + return new Point2D.Float(((float)location.getX() * scales.scaleWidth) - scales.offsX, + ((float)location.getY() * scales.scaleHeight) - scales.offsY + ); + } + + public Point2D getCoreLocation(Point2D location) { + ScalingInformation scales; + + if (isDynamicScaling) + scales = getDynamicScaleFactors(); + else + scales = getStaticScaleFactors(); + + return new Point2D.Float(((float)location.getX() / scales.scaleWidth) + scales.offsX, + ((float)location.getY() / scales.scaleHeight) + scales.offsY + ); + } + + /** + * + */ + public GraphElement getFocussedElement() { + return focussedElement; + } + + public void updateBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + for(EdgeElement e : edgeElements){ + e.updateBeamerMode(beamerMode); + } + for(NodeElement n : nodeElements){ + n.updateBeamerMode(beamerMode); + } + repaint(); + revalidate(); + } + + private void setHighlightedStep(AtomicStep step) { + // Remove any selection + if (focussedElement != null) + setFocussedElement(null); + + // Erase current highlighting + if (highlightedStep != null) { + for (EdgeElement edge : edgeElements) + edge.setHighlightState(HighlightState.NONE); + for (NodeElement node : nodeElements) + node.setHighlightState(HighlightState.NONE); + } + + highlightedStep = step; + + if (highlightedStep != null) { + List nodes; + HighlightState st; + int k, n, n2; + + k = highlightedStep.getK(); + nodes = new ArrayList(highlightedStep.getNodes()); + nodes.add(0, highlightedStep.getU()); + nodes.add(highlightedStep.getV()); + + st = HighlightState.PRE_PATH; + for (int i = 0; i < nodes.size(); i++) { + NodeElement elem; + + n = nodes.get(i); + + elem = null; + for (NodeElement e : nodeElements) { + if (e.getNode().getId() == n) { + elem = e; + break; + } + } + + if (elem == null) + continue; + + if (n == k) { + elem.setHighlightState(HighlightState.CURRENT); + st = HighlightState.POST_PATH; + } else { + elem.setHighlightState(st); + } + } + + st = HighlightState.PRE_PATH; + for (int i = 0; i < nodes.size() - 1; i++) { + EdgeElement elem; + + n = nodes.get(i); + n2 = nodes.get(i + 1); + + if (n == n2) + continue; + + elem = null; + for (EdgeElement e : edgeElements) { + if (e.getEdge().getBegin().getId() == n + && e.getEdge().getEnd().getId() == n2) { + elem = e; + break; + } + } + + if (n == k) + st = HighlightState.POST_PATH; + if (elem != null) + elem.setHighlightState(st); + } + } + + update(); + } + + public void setGraphActionListener(GraphActionListener listener) { + graphActionListener = listener; + graphActionListener.addGraphObserver(this); + + initElements(); + update(); + } + + public GraphActionListener getGraphActionListener() { + return graphActionListener; + } + + /** + * @return the nodeElements + */ + public Set getNodeElements() { + return nodeElements; + } + + /** + * @return the edgeElements + */ + public Set getEdgeElements() { + return edgeElements; + } + + public void nodeAdded(Graph graph, Node node) { + NodeElement n; + + n = new NodeElement(node); + n.setComponent(this); + n.updateBeamerMode(beamerMode); + + nodeElements.add(n); + + setFocussedElement(n); + + } + + public void nodeAltered(Graph graph, Node node) { + update(); + } + + public void nodeRemoved(Graph graph, Node node) { + NodeElement del; + + del = null; + for (NodeElement elem : nodeElements) { + if (elem.getNode() == node) { + del = elem; + break; + } + } + + if (del != null) + nodeElements.remove(del); + if (del == focussedElement) { + setFocussedElement(null); + } + } + + public void edgeAdded(Graph graph, Edge edge) { + EdgeElement e; + + e = new EdgeElement(edge); + e.setComponent(this); + e.updateBeamerMode(beamerMode); + + edgeElements.add(e); + update(); + } + + public void edgeAltered(Graph graph, Edge edge) { + // Nothing to do, just redraw + } + + public void edgeRemoved(Graph graph, Edge edge) { + EdgeElement del; + + del = null; + for (EdgeElement elem : edgeElements) { + if (elem.getEdge() == edge) { + del = elem; + break; + } + } + + if (del != null) + edgeElements.remove(del); + if (del == focussedElement) + setFocussedElement(null); + } + + public void graphUpdated() { + update(); + } + + public void graphSelectionChanged() { + update(); + + for (EdgeElement e : edgeElements) { + if (e.getEdge().equals(graphActionListener.getSelectedEdge())) + setFocussedElementInternal(e); + } + } + + public void enterHighlightMode(RootStep rootStep) { + setHighlightedStep(null); + } + + public void leaveHighlightMode() { + setHighlightedStep(null); + } + + public void highlightLastStep(RootStep step) { + setHighlightedStep(null); + } + + public void highlightFirstStep(RootStep step) { + setHighlightedStep(null); + } + + public void highlightAtomicStep(AtomicStep step, boolean isForward) { + setHighlightedStep(step); + } + + public void highlightGroupStep(GroupStep step, boolean isForward) { + setHighlightedStep(null); + } + + public void setIgnoreEvents(boolean yorn) { + ignoreClick = yorn; + } + + public void mousePressed(MouseEvent event) { + Point2D point; + + // Set the focus + grabFocus(); + + // Only while editing + if ( graphActionListener.getEditMode() == EditMode.NONE + || ignoreClick + ) + return; + + // Track the click + point = event.getPoint(); + + for (NodeElement node : nodeElements) { + if (node.contains(point)) { + node.mouseClicked(event); + return; + } + } + + for (EdgeElement edge : edgeElements) { + if (edge.contains(point)) { + edge.mouseClicked(event); + return; + } + } + + setFocussedElement(null); + } + + public void mouseReleased(MouseEvent event) { + if (graphActionListener.getEditMode() == EditMode.NONE || ignoreClick) + return; + + if ( ((event.getX() >= this.getWidth()) || (event.getY() >= this.getHeight())) + || ((event.getX() <= 0) || (event.getY() <= 0)) + ) + { + isDragging = false; + + if (focussedElement instanceof NewEdgeElement) + setFocussedElement(null); + + return; + } + + if (isDragging) { + isDragging = false; + + if (focussedElement != null) + focussedElement.mouseReleased(event); + + return; + } + + if (ignoreNextClick) { + ignoreNextClick = false; + return; + } + + if (getFocussedElement() == null && graphActionListener != null + && graphActionListener.getEditMode() == EditMode.EDITING_NODES) { + graphActionListener.addNode(getCoreLocation(event.getPoint())); + } + } + + public void mouseDragged(MouseEvent event) { + Point2D point; + + if (graphActionListener.getEditMode() == EditMode.NONE || ignoreClick) + return; + + if ( ((event.getX() >= this.getWidth()) || (event.getY() >= this.getHeight())) + || ((event.getX() <= 0) || (event.getY() <= 0)) + ) + return; + + point = event.getPoint(); + + if (graphActionListener.getEditMode() == EditMode.EDITING_EDGES + && !isDragging && point != null) { + for (NodeElement n : nodeElements) { + if (n.contains(point)) { + NewEdgeElement newEdge; + + newEdge = new NewEdgeElement(n.getNode(), event.getPoint()); + newEdge.setComponent(this); + + setFocussedElement(newEdge); + isDragging = true; + } + } + + return; + } + + if (focussedElement != null + && (isDragging || focussedElement.contains(point)) && point != null) { + + focussedElement.mouseDragged(event); + isDragging = true; + } + } + + public void keyReleased(KeyEvent event) { + if (graphActionListener.getEditMode() == EditMode.NONE) + return; + + if (focussedElement != null) { + focussedElement.keyReleased(event); + } + } + + public void mouseClicked(MouseEvent event) { + } + + public void mouseEntered(MouseEvent event) { + } + + public void mouseExited(MouseEvent event) { + } + + public void mouseMoved(MouseEvent event) { + } + + public void keyPressed(KeyEvent e) { + } + + public void keyTyped(KeyEvent event) { + } + + public void focusGained(FocusEvent event) { + if ( (event.getOppositeComponent() instanceof EdgeElement.EdgeTextField) + && (graphActionListener.getEditMode() == EditMode.EDITING_NODES) + ) + ignoreNextClick = true; + } + + public void focusLost(FocusEvent event) { + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/graph/GraphElement.java b/src/org/jalgo/module/app/view/graph/GraphElement.java new file mode 100644 index 0000000..5378ae7 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/GraphElement.java @@ -0,0 +1,73 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.geom.Point2D; + +import javax.swing.JComponent; + +/** + * The graphical representation of an arbitrary element in the user interface. + * This class is the superclass of NodeElement and EdgeElement. + */ +public abstract class GraphElement extends JComponent implements KeyListener, MouseListener, + MouseMotionListener { + + protected GraphComponent component; + protected HighlightState highlightState; + + public abstract void paint(Graphics2D g); + + public abstract boolean contains(Point2D point); + + public HighlightState getHighlightState() { + return highlightState; + } + + public void setHighlightState(HighlightState s) { + highlightState = s; + } + + public GraphComponent getComponent() { + return component; + } + + public void setComponent(GraphComponent component) { + this.component = component; + } + + public void keyPressed(KeyEvent e) { + } + + public void keyReleased(KeyEvent e) { + } + + public void keyTyped(KeyEvent e) { + } + + public void mouseClicked(MouseEvent e) { + component.setFocussedElement(this); + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseReleased(MouseEvent e) { + } + + public void mouseDragged(MouseEvent e) { + } + + public void mouseMoved(MouseEvent e) { + } +} diff --git a/src/org/jalgo/module/app/view/graph/GraphTextComponent.java b/src/org/jalgo/module/app/view/graph/GraphTextComponent.java new file mode 100644 index 0000000..dd8b1fc --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/GraphTextComponent.java @@ -0,0 +1,892 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.util.*; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Highlighter; +import javax.swing.text.Highlighter.HighlightPainter; + +import org.jalgo.module.app.controller.GraphActionListener; +import org.jalgo.module.app.controller.GraphController; +import org.jalgo.module.app.controller.GraphObserver; +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.view.InterfaceConstants; + +public class GraphTextComponent extends JPanel implements GraphObserver { + private Graph graph; + private GraphActionListener graphActionListener; + + private List mistakeHighlights; + private List selectionHighlights; + private Map> actionMap; + + private List currentEdgeDescriptors; + private GraphController graphCtrl; + + private boolean beamerMode; + + private boolean isEditing; + + private class EdgeDescriptor { + public DataType weight; + public int start, end; + + public ParsedTuple parserInput; + + public EdgeDescriptor(int start, int end, DataType weight) { + this.weight = weight; + this.start = start; + this.end = end; + } + + public EdgeDescriptor(int start, int end, DataType weight, ParsedTuple parserInput) { + this(start, end, weight); + this.parserInput = parserInput; + } + + public boolean equals(Object o) { + if ((o != null) && (o instanceof EdgeDescriptor)) { + EdgeDescriptor edge = (EdgeDescriptor)o; + + return ( (this.start == edge.start) + && (this.end == edge.end) + ); + } + + return false; + } + } + + private class ParsedTuple { + public boolean isMistake; + public boolean seemsValid; + + public int startPos, endPos; + + public ParsedTuple() { + isMistake = true; + seemsValid = false; + startPos = 0; + endPos = 0; + } + + public ParsedTuple(int startPos, int endPos) { + isMistake = false; + seemsValid = true; + this.startPos = startPos; + this.endPos = endPos; + } + } + + private enum UpdateOperation { + NEW_EDGE, + ALTER_WEIGHT, + KEEP_EDGE, + DELETE_EDGE + } + + /** + * + */ + private static final long serialVersionUID = 3641739084413985176L; + + private JTextArea textArea; + + private Highlighter highlighter; + private Highlighter.HighlightPainter mistakePainter; + private Highlighter.HighlightPainter selectionPainter; + + + public GraphTextComponent(GraphController graphCtrl) { + mistakeHighlights = new ArrayList(); + selectionHighlights = new ArrayList(); + currentEdgeDescriptors = new ArrayList(); + this.graphCtrl = graphCtrl; + + beamerMode = false; + + this.setLayout(new GridLayout(1,1)); + + highlighter = new DefaultHighlighter(); + mistakePainter = new UnderliningHighlightPainter(InterfaceConstants.wrongInputColor()); + selectionPainter = new BoxingHighlightPainter(InterfaceConstants.textViewEdgeLineColor(), InterfaceConstants.textViewEdgeFillColor()); + + textArea = new JTextArea(); + JScrollPane scrollpane = new JScrollPane(textArea); + + textArea.setHighlighter(highlighter); + textArea.setMargin(new Insets(3,3,3,3)); + textArea.getDocument().addDocumentListener(new TextAreaListener()); + textArea.addKeyListener(new TextAreaListener()); + + textArea.addCaretListener(new TextAreaListener()); + + textArea.setLineWrap(true); + textArea.setWrapStyleWord(true); + textArea.setFont(InterfaceConstants.GraphTextComponentFont(beamerMode)); + + this.add(scrollpane); + + isEditing = false; + + } + + public GraphActionListener getGraphActionListener() { + return graphActionListener; + } + + public void setGraphActionListener(GraphActionListener action_listener) { + graphActionListener = action_listener; + graphActionListener.addGraphObserver(this); + + graph = graphActionListener.getGraph(); + + initEdgeList(); + } + + public void setTextAreaFont(){ + textArea.setFont(InterfaceConstants.GraphTextComponentFont(beamerMode)); + repaint(); + revalidate(); + } + + /** + * + */ + private String edgeToString(Edge edge) + { + String weight, start, end; + + weight = edge.getWeight().toString(); + start = Integer.toString(edge.getBegin().getId() + 1); + end = Integer.toString(edge.getEnd().getId() + 1); + + return "("+start+","+weight+","+end+")"; + } + + /** + * + */ + private EdgeDescriptor stringToEdge(String input) + { + int start, end; + DataType weight; + String[] split_input; + + // Initial parsing + input = input.replaceAll("\\s", ""); + + if (!input.startsWith("(") || !input.endsWith(")")) + return null; + + input = input.substring(1, input.length() - 1); + split_input = input.split(","); + + if (split_input.length != 3) + return null; + + // Create new instance of DataType + try { + weight = this.graphActionListener.getDataType().newInstance(); + } catch (InstantiationException e) { + e.printStackTrace(); + /* FIXME */ + return null; + } catch (IllegalAccessException e) { + e.printStackTrace(); + + /* FIXME */ + return null; + } + + // Set and test values + try { + start = Integer.parseInt(split_input[0].trim()); + end = Integer.parseInt(split_input[2].trim()); + } catch (NumberFormatException e) { + return null; + } + + // Invalid node number + if ((start == 0) || (end == 0)) + return null; + + // Syntax error in start / end values + if ( (!Integer.toString(start).equals(split_input[0].trim())) + || (!Integer.toString(end).equals(split_input[2].trim())) + ) + { + return null; + } + + // Reflexive edges are not allowed + if (start == end) + return null; + + // Illegal weight + if (weight.setFromString(split_input[1].trim()) == false) { + return null; + } + + return new EdgeDescriptor(start - 1, end - 1, weight); + } + + /** + * + * + */ + private Edge getEdge(EdgeDescriptor descriptor) { + + for (Edge edge : graph.getEdges() ) { + if ( edge.getBegin().getId() == descriptor.start + && edge.getEnd().getId() == descriptor.end + ) + { + return edge; + } + } + + return null; + } + + /** + * + * + */ + private void determineAction(EdgeDescriptor descriptor) { + List operationList; + Edge edge; + + edge = graph.getEdge(descriptor.start, descriptor.end); + + if (edge == null) { + + operationList = actionMap.get(UpdateOperation.NEW_EDGE); + operationList.add(descriptor); + } + else { + if (edge.getWeight().equals(descriptor.weight)) { + operationList = actionMap.get(UpdateOperation.KEEP_EDGE); + operationList.add(descriptor); + } + else { + operationList = actionMap.get(UpdateOperation.ALTER_WEIGHT); + operationList.add(descriptor); + } + } + } + + /** + * + */ + private void calculateUnrequiredEdges() { + List operationList; + + for (Edge edge : graph.getEdges()) { + EdgeDescriptor edgeDescriptor = new EdgeDescriptor(edge.getBegin().getId(), edge.getEnd().getId(), null); + + if ( !actionMap.get(UpdateOperation.KEEP_EDGE).contains(edgeDescriptor) + && !actionMap.get(UpdateOperation.ALTER_WEIGHT).contains(edgeDescriptor) + ) + { + operationList = actionMap.get(UpdateOperation.DELETE_EDGE); + operationList.add(edgeDescriptor); + } + } + } + + /** + * + * @return + */ + private void createActionMap() { + actionMap = new HashMap(); + + actionMap.put(UpdateOperation.NEW_EDGE, new ArrayList()); + actionMap.put(UpdateOperation.KEEP_EDGE, new ArrayList()); + actionMap.put(UpdateOperation.ALTER_WEIGHT, new ArrayList()); + actionMap.put(UpdateOperation.DELETE_EDGE, new ArrayList()); + } + + private void addEdge(EdgeDescriptor descriptor) { + while (graph.getNode(descriptor.start) == null) { + graphActionListener.addNode(); + } + + while (graph.getNode(descriptor.end) == null) { + graphActionListener.addNode(); + } + + graphActionListener.addEdge(graph.getNode(descriptor.start), graph.getNode(descriptor.end)); + graphActionListener.alterEdgeWeight(graph.getEdge(descriptor.start, descriptor.end), descriptor.weight); + } + + private void deleteEdge(EdgeDescriptor descriptor) { + graphActionListener.removeEdge(graph.getEdge(descriptor.start, descriptor.end)); + } + + private void alterEdge(EdgeDescriptor descriptor) { + graphActionListener.alterEdgeWeight(graph.getEdge(descriptor.start, descriptor.end), descriptor.weight); + } + + /** + * + */ + private void processActions() { + List operationList; + + graphActionListener.beginEditing(); + + // Delete unneeded edges + operationList = actionMap.get(UpdateOperation.DELETE_EDGE); + for (EdgeDescriptor edge : operationList) { + deleteEdge(edge); + } + + // Create new edges + operationList = actionMap.get(UpdateOperation.NEW_EDGE); + for (EdgeDescriptor edge : operationList) { + addEdge(edge); + } + + // Alter weight + operationList = actionMap.get(UpdateOperation.ALTER_WEIGHT); + for (EdgeDescriptor edge : operationList) { + alterEdge(edge); + } + + graphActionListener.endEditing(); + } + + /** + * + * + */ + private List calculateInvalidEdges() { + SortedSet nodeIds, faultyIds; + List operationList, faultyEdges; + + int lastId, delta; + + faultyEdges = new ArrayList(); + + faultyIds = new TreeSet(); + nodeIds = new TreeSet(); + + // Collect all node IDs + for (UpdateOperation operation : UpdateOperation.values()) { + if (operation == UpdateOperation.DELETE_EDGE) + continue; + + operationList = actionMap.get(operation); + for (EdgeDescriptor edge : operationList) { + nodeIds.add(new Integer(edge.start)); + nodeIds.add(new Integer(edge.end)); + } + } + + if (nodeIds.isEmpty()) + return faultyEdges; + + // Compute holes between node IDs and collect faulty node IDs + lastId = nodeIds.first() + 1; + delta = 0; + + for (int nodeId : nodeIds) { + delta += nodeId - lastId - 1; + + if (delta >= 10) + faultyIds.add(new Integer(nodeId)); + } + + // Determine faulty edges + for (UpdateOperation operation : UpdateOperation.values()) { + if (operation == UpdateOperation.DELETE_EDGE) + continue; + + operationList = actionMap.get(operation); + for (EdgeDescriptor edge : operationList) { + if ( faultyIds.contains(new Integer(edge.start)) + || faultyIds.contains(new Integer(edge.end)) + ) + { + faultyEdges.add(edge); + } + } + } + + return faultyEdges; + } + + + + /** + * + * + */ + private ParsedTuple findNextEdgeString(String list, int start) { + ParsedTuple parsedTuple; + int nestedParenthesis, firstOpeningParenthesis, lastClosingParenthesis, lastAccepted; + int pos; + + nestedParenthesis = 0; + firstOpeningParenthesis = -1; + lastClosingParenthesis = -1; + + parsedTuple = new ParsedTuple(); + parsedTuple.startPos = start; + parsedTuple.endPos = start; + parsedTuple.isMistake = true; + parsedTuple.seemsValid = false; + + for (pos = start; pos < list.length(); pos ++) { + parsedTuple.endPos = pos; + + // Ignore all white space charracters + if ( list.charAt(pos) == ' ' + || list.charAt(pos) == '\t' + || list.charAt(pos) == '\n' + || list.charAt(pos) == '\r' + ) + continue; + + if (list.charAt(pos) == '(') { + + // Found first parenthesis + if (nestedParenthesis == 0) { + + // Missing "," + if (firstOpeningParenthesis != -1) { + parsedTuple.startPos = lastClosingParenthesis; + + return parsedTuple; + } + + firstOpeningParenthesis = pos; + parsedTuple.startPos = firstOpeningParenthesis; + } + + nestedParenthesis ++; + } + + // Found end of tuple + if (list.charAt(pos) == ')') { + nestedParenthesis --; + + if (nestedParenthesis == 0) { + lastClosingParenthesis = pos; + } + + // There are more parenthesis closing than opening + if (nestedParenthesis < 0) + return parsedTuple; + else + continue; + } + + // Ignore all characters inside a tuple + if (nestedParenthesis > 0) + continue; + + // Found end of tuple + if ( (list.charAt(pos) == ',') + && (nestedParenthesis == 0) + ) + { + parsedTuple.isMistake = false; + parsedTuple.seemsValid = true; + return parsedTuple; + } + + + // Invalid character outside a parenthesis, try to find next "(" + if (lastClosingParenthesis == -1) + parsedTuple.startPos = start; + else + parsedTuple.startPos = lastClosingParenthesis; + + for (parsedTuple.endPos += 1; parsedTuple.endPos < list.length(); parsedTuple.endPos ++) { + if (list.charAt(parsedTuple.endPos) == '(') + break; + } + + return parsedTuple; + } + + parsedTuple.endPos = pos; + + // Input is only valid, if all parenthesis are closing + if (nestedParenthesis == 0) { + parsedTuple.seemsValid = true; + parsedTuple.isMistake = false; + } + + return parsedTuple; + } + + /** + * + */ + private void highlightText(ParsedTuple parserOutput, HighlightPainter painter, List highlightList) { + int startPos = parserOutput.startPos; + int endPos = parserOutput.endPos; + + try { + highlightList.add(highlighter.addHighlight(startPos, endPos, painter)); + } + catch (BadLocationException e) { + return; + } + } + + private void highlightMistake(ParsedTuple parserOutput) { + highlightText(parserOutput, mistakePainter, mistakeHighlights); + } + + private void highlightSelection(ParsedTuple parserOutput) { + highlightText(parserOutput, selectionPainter, selectionHighlights); + } + + + /** + * + * + */ + private void parseEdgeList() { + String edgeStringList; + List faultyEdges; + + createActionMap(); + + // Remove existing highlights of mistakes + for (Object highlight : mistakeHighlights) + highlighter.removeHighlight(highlight); + + mistakeHighlights.clear(); + + currentEdgeDescriptors.clear(); + edgeStringList = this.textArea.getText(); + + for (int pos = 0; pos < edgeStringList.length(); ) { + ParsedTuple parserOutput; + EdgeDescriptor descriptor; + + // Parse edge list + parserOutput = findNextEdgeString(edgeStringList, pos); + descriptor = null; + + if (!parserOutput.isMistake && parserOutput.seemsValid) { + descriptor = stringToEdge(edgeStringList.substring(parserOutput.startPos, parserOutput.endPos)); + + if (descriptor != null) { + if (currentEdgeDescriptors.contains(descriptor)) { + parserOutput.isMistake = true; + } + else { + currentEdgeDescriptors.add(descriptor); + descriptor.parserInput = parserOutput; + } + } + } + + // Markup mistakes + if ((parserOutput.isMistake == true) || (descriptor == null && parserOutput.seemsValid)) { + highlightMistake(parserOutput); + } + else if (descriptor != null) + { + determineAction(descriptor); + } + + pos = parserOutput.endPos + 1; + } + + faultyEdges = calculateInvalidEdges(); + + if (faultyEdges.size() > 0) { + for (EdgeDescriptor edge : faultyEdges) { + highlightMistake(edge.parserInput); + } + } + + if (mistakeHighlights.size() == 0) { + calculateUnrequiredEdges(); + processActions(); + } + + } + + private void updateOutput(String output) { + int caretPosition; + + if (isEditing) + return; + + isEditing = true; + + if (output.endsWith(", ")) + output = output.substring(0, output.length() - 2); + + // Update text and restore caret position + caretPosition = textArea.getCaretPosition(); + textArea.setText(output); + + if (caretPosition < 0) + caretPosition = 0; + if (caretPosition > output.length()) + caretPosition = output.length(); + + textArea.setCaretPosition(caretPosition); + + updateSelection(); + + isEditing = false; + } + + private void updateEdgeDescriptors(int startPos, int update) { + for (EdgeDescriptor descriptor : currentEdgeDescriptors) { + if (descriptor.parserInput.startPos > startPos) { + descriptor.parserInput.startPos += update; + descriptor.parserInput.endPos += update; + } + } + } + + public void nodeAdded(Graph graph, Node node) { + + } + + public void nodeAltered(Graph graph, Node node) { + } + + public void nodeRemoved(Graph graph, Node node) { + } + + public void edgeAdded(Graph graph, Edge edge) { + String output; + EdgeDescriptor descriptor; + ParsedTuple parsedTuple; + String edgeString; + + if (getSimilarEdgeDescriptor(edge) != null) + return; + + edgeString = edgeToString(edge); + output = textArea.getText(); + + if (currentEdgeDescriptors.size() > 0) + output += ", "; + + // Create a new edge descriptor + parsedTuple = new ParsedTuple(output.length(), output.length() + edgeString.length()); + + descriptor = new EdgeDescriptor(edge.getBegin().getId(), + edge.getEnd().getId(), + edge.getWeight(), + parsedTuple + ); + + output += edgeString; + + currentEdgeDescriptors.add(descriptor); + updateOutput(output); + } + + public void edgeAltered(Graph graph, Edge edge) { + String newOutput, output; + int oldLength; + EdgeDescriptor descriptor; + int updateOffset; + String edgeString; + + edgeString = edgeToString(edge); + descriptor = getSimilarEdgeDescriptor(edge); + + oldLength = descriptor.weight.toString().length(); + + output = textArea.getText(); + + // Update, if old descriptor has changes + descriptor.weight = edge.getWeight(); + + newOutput = output.substring(0, descriptor.parserInput.startPos); + newOutput += edgeString; + newOutput += output.substring(descriptor.parserInput.endPos); + + updateOffset = descriptor.weight.toString().length() - oldLength; + + descriptor.parserInput.endPos = descriptor.parserInput.startPos + edgeString.length(); + + updateEdgeDescriptors(descriptor.parserInput.startPos, updateOffset); + updateOutput(newOutput); + } + + public void edgeRemoved(Graph graph, Edge edge) { + String newOutput, output; + EdgeDescriptor descriptor; + int updateOffset; + int commaOffset; + + updateOffset = 0; + + output = textArea.getText(); + descriptor = getSimilarEdgeDescriptor(edge); + if (descriptor == null) + return; + + if (currentEdgeDescriptors.lastIndexOf(descriptor) == currentEdgeDescriptors.size() - 1) + commaOffset = 0; + else + commaOffset = 2; + + newOutput = output.substring(0, descriptor.parserInput.startPos + updateOffset); + newOutput += output.substring(descriptor.parserInput.endPos + updateOffset + commaOffset); + + updateOffset -= descriptor.parserInput.endPos - descriptor.parserInput.startPos + commaOffset; + + currentEdgeDescriptors.remove(descriptor); + + updateEdgeDescriptors(descriptor.parserInput.startPos, updateOffset); + updateOutput(newOutput); + } + + private void updateSelection() { + Edge graphEdge; + + // Remove old selections + for (Object o : selectionHighlights) + highlighter.removeHighlight(o); + + // Detect new + graphEdge = graphActionListener.getSelectedEdge(); + if (graphEdge == null) + return; + + for (EdgeDescriptor localEdge : currentEdgeDescriptors) { + if ( (localEdge.start == graphEdge.getBegin().getId()) + && (localEdge.end == graphEdge.getEnd().getId()) + ) + { + highlightSelection(localEdge.parserInput); + return; + } + } + } + + private EdgeDescriptor getSimilarEdgeDescriptor(Edge edge) { + for (EdgeDescriptor descriptor : currentEdgeDescriptors) { + if ( (descriptor.start == edge.getBegin().getId()) + && (descriptor.end == edge.getEnd().getId()) + ) + { + return descriptor; + } + } + + return null; + } + + public void graphUpdated() { + + } + + private void initEdgeList() { + for (Edge edge : graph.getEdges()) { + this.edgeAdded(graph, edge); + } + } + + public void graphSelectionChanged() { + updateSelection(); + } + + private class TextAreaListener implements DocumentListener, CaretListener, KeyListener { + public void changedUpdate(DocumentEvent event) { + if (isEditing) + return; + + isEditing = true; + parseEdgeList(); + isEditing = false; + + updateSelection(); + } + + public void insertUpdate(DocumentEvent event) { + changedUpdate(event); + } + + public void removeUpdate(DocumentEvent event) { + changedUpdate(event); + } + + public void caretUpdate(CaretEvent event) { + int position = event.getDot(); + + if (!textArea.hasFocus()) + return; + + if (currentEdgeDescriptors == null) + return; + + for (EdgeDescriptor edge : currentEdgeDescriptors) { + ParsedTuple parsed = edge.parserInput; + + if ((parsed.startPos <= position) && (parsed.endPos >= position)) { + Edge graphEdge = graph.getEdge(edge.start, edge.end); + + if (graphEdge != null) { + graphActionListener.setSelectedEdge(graphEdge); + } + } + } + } + + public void keyPressed(KeyEvent event) { + if (event.getKeyChar() == '\n') + event.consume(); + + return; + } + + public void keyReleased(KeyEvent event) { + if (event.getKeyChar() == '\n') + event.consume(); + + } + + public void keyTyped(KeyEvent event) { + if (event.getKeyChar() == '\n') + event.consume(); + } + + } + + public void nodeAltered(Graph graph, NodeElement node) { + + } + + public void nodeAlteredPosition(Graph graph, Node node) { + } + + public void updateBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + setTextAreaFont(); + } + +} diff --git a/src/org/jalgo/module/app/view/graph/HighlightState.java b/src/org/jalgo/module/app/view/graph/HighlightState.java new file mode 100644 index 0000000..5f06bb0 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/HighlightState.java @@ -0,0 +1,9 @@ +package org.jalgo.module.app.view.graph; + +public enum HighlightState { + NONE, + SELECTED, + CURRENT, + PRE_PATH, + POST_PATH +} diff --git a/src/org/jalgo/module/app/view/graph/ModeSwitchComponent.java b/src/org/jalgo/module/app/view/graph/ModeSwitchComponent.java new file mode 100644 index 0000000..21a6a44 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/ModeSwitchComponent.java @@ -0,0 +1,218 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.GraphActionListener; +import org.jalgo.module.app.controller.GraphObserver; +import org.jalgo.module.app.controller.InterfaceMode; +import org.jalgo.module.app.controller.MainController; +import org.jalgo.module.app.core.graph.Edge; +import org.jalgo.module.app.core.graph.Graph; +import org.jalgo.module.app.core.graph.Node; + +/** + * Displays the two Buttons to toggle between Graph Editing and Algorithm Mode. + * + */ +public class ModeSwitchComponent extends JPanel implements GraphObserver { + private static final long serialVersionUID = 3586672679853106515L; + private ButtonGroup modeGroup; + private JToggleButton editToggle, runToggle, beamerToggle; + private MainController mainCtrl; + private GraphActionListener graphActionListener; + + private JMenu menu; + private JCheckBoxMenuItem beamerModeMenu; + + /** + * Initializes the toggler between the two modes (edit mode and algorithm mode). + * + */ + public ModeSwitchComponent(MainController mainCtrl, JMenu menu) { + + this.mainCtrl = mainCtrl; + + // Setup control menu + beamerModeMenu = new JCheckBoxMenuItem(Messages.getString("app", "ModeSwitchComponent.beamerToggle"), + new ImageIcon(Messages.getResourceURL("app","icon_beamerMode")), + false + ); + beamerModeMenu.addActionListener(new BeamerToggleListener()); + + menu.add(beamerModeMenu); + + // Button Group: edit / run + editToggle = new JToggleButton(); + runToggle = new JToggleButton(); + + modeGroup = new ButtonGroup(); + modeGroup.add(editToggle); + modeGroup.add(runToggle); + editToggle.setSelected(true); + + editToggle.setIcon(new ImageIcon(Messages.getResourceURL("app","icon_editMode"))); //$NON-NLS-1$ //$NON-NLS-1$ + editToggle.setToolTipText(Messages.getString("app", "ModeSwitchComponent.editToggleToolTip")); //$NON-NLS-1$ //$NON-NLS-2$ + editToggle.setText(Messages.getString("app", "ModeSwitchComponent.editToggle")); //$NON-NLS-1$ //$NON-NLS-2$ + + runToggle.setIcon(new ImageIcon(Messages.getResourceURL("app", "icon_runMode"))); //$NON-NLS-1$ //$NON-NLS-1$ + runToggle.setToolTipText(Messages.getString("app", "ModeSwitchComponent.runToggleToolTip")); //$NON-NLS-1$ //$NON-NLS-2$ + runToggle.setText(Messages.getString("app", "ModeSwitchComponent.runToggle")); //$NON-NLS-1$ //$NON-NLS-2$ + + if (mainCtrl.getGraphController() == null + || mainCtrl.getGraphController().getGraph() == null + || mainCtrl.getGraphController().getGraph().getEdges() + .isEmpty()) + runToggle.setEnabled(false); + + editToggle.addActionListener(new EditToggleListener()); + runToggle.addActionListener(new RunToggleListener()); + + // Beamer Toggle + beamerToggle = new JToggleButton(); + beamerToggle.setIcon(new ImageIcon(Messages.getResourceURL("app","icon_beamerMode"))); + beamerToggle.setToolTipText(Messages.getString("app", "ModeSwitchComponent.beamerToggle")); //$NON-NLS-1$ + beamerToggle.setText(Messages.getString("app", "ModeSwitchComponent.beamerToggle")); //$NON-NLS-1$ + + beamerToggle.addActionListener(new BeamerToggleListener()); + + // Layouting + this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); + this.setAlignmentX(LEFT_ALIGNMENT); + + this.add(Box.createRigidArea(new Dimension(5,0))); + this.add(editToggle); + this.add(Box.createRigidArea(new Dimension(5,0))); + this.add(runToggle); + + this.add(Box.createHorizontalGlue()); + this.add(beamerToggle); + this.add(Box.createRigidArea(new Dimension(5,0))); + } + + /** + * Enables the editToolbar, so that it's invisible in the + * User Interface. The use of this method depends on the + * currentDisplaymode. + * + * @param state + * true if enabled, false if + * disabled. + */ + public void setToolbarEnabled(boolean state) { + editToggle.setEnabled(state); + if (mainCtrl.getGraphController() == null + || mainCtrl.getGraphController().getGraph() == null + || mainCtrl.getGraphController().getGraph().getEdges() + .isEmpty()) { + runToggle.setEnabled(false); + } else { + runToggle.setEnabled(state); + } + beamerToggle.setEnabled(state); + } + + /** + * Enables the modeButton from this Mode, where the user currently works. + * @param currentDisplayMode + * @see InterfaceMode + * @param noGraphElement + * true sets runToggle disable + * false sets runToggle enable + */ + public void setCurrentModeButtonEnable(InterfaceMode currentDisplayMode, boolean noGraphElement){ + + if(currentDisplayMode==InterfaceMode.GRAPH_EDITING){ + editToggle.setEnabled(false); + } + else if(currentDisplayMode==InterfaceMode.GRAPH_EDITING&&noGraphElement){ + runToggle.setEnabled(false); + } + else if(currentDisplayMode==InterfaceMode.GRAPH_EDITING&&!noGraphElement){ + runToggle.setEnabled(true); + } + else if(currentDisplayMode==InterfaceMode.ALGORITHM_DISPLAY){ + runToggle.setEnabled(false); + editToggle.setEnabled(true); + } + } + + /** + * ActionListener for the ToggleButton to reach the Graph-Editing-Mode. + */ + class EditToggleListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + mainCtrl.getInterfaceController().setEditLayout(); + } + + } + + class BeamerToggleListener implements ActionListener { + public void actionPerformed(ActionEvent event) { + AbstractButton source = (AbstractButton)event.getSource(); + + if (source.isSelected()) { + mainCtrl.getInterfaceController().setBeamerLayout(true); + beamerModeMenu.setSelected(true); + beamerToggle.setSelected(true); + } + else { + mainCtrl.getInterfaceController().setBeamerLayout(false); + beamerModeMenu.setSelected(false); + beamerToggle.setSelected(false); + } + } + + } + + /** + * ActionListener for the ToggleButton to reach the Algorithm-Process-Mode. + */ + private class RunToggleListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + mainCtrl.getInterfaceController().setAlgorithmLayout(); + + } + } + + public void edgeAdded(Graph graph, Edge edge) { + runToggle.setEnabled(true); + } + + public void edgeAltered(Graph graph, Edge edge) { + + } + + public void edgeRemoved(Graph graph, Edge edge) { + if (mainCtrl.getGraphController().getGraph().getEdges().isEmpty()) + runToggle.setEnabled(false); + } + + public void graphSelectionChanged() { + } + + public void graphUpdated() { + } + + public void nodeAdded(Graph graph, Node node) { + } + + public void nodeAltered(Graph graph, Node node) { + } + + public void nodeRemoved(Graph graph, Node node) { + } + + public void setGraphActionListener(GraphActionListener listener) { + graphActionListener = listener; + graphActionListener.addGraphObserver(this); + } + + public GraphActionListener getGraphActionListener() { + return graphActionListener; + } +} diff --git a/src/org/jalgo/module/app/view/graph/NewEdgeElement.java b/src/org/jalgo/module/app/view/graph/NewEdgeElement.java new file mode 100644 index 0000000..21d6142 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/NewEdgeElement.java @@ -0,0 +1,117 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionListener; +import java.awt.geom.Point2D; + +import org.jalgo.module.app.core.dataType.DataType; +import org.jalgo.module.app.core.graph.Node; + +/** + * This is for creating new Edges + */ +public class NewEdgeElement extends EdgeElement { + + private static final long serialVersionUID = 4184948572353232611L; + private Node beginNode; + private Node endNode; + + private Point2D endPoint; + private DataType weight; + + public NewEdgeElement(Node node, Point2D point) { + super(null); + + beginNode = node; + endPoint = point; + } + + /** + * @return the endPoint + */ + public Point2D getEndPoint() { + return endPoint; + } + + /** + * @param endPoint + * the endPoint to set + */ + public void setEndPoint(Point2D endPoint) { + this.endPoint = endPoint; + } + + public void mouseDragged(MouseEvent event) { + setEndPoint(event.getPoint()); + + if (component == null) + return; + + // Search for a matching end node + endNode = null; + + for (NodeElement n : component.getNodeElements()) { + if (n.nodeContains(event.getPoint()) + && component.getGraphActionListener().getGraph().getEdge( + beginNode, n.getNode()) == null + && n.getNode() != beginNode) { + endNode = n.getNode(); + break; + } + } + + // Redraw + component.update(); + } + + public void mouseReleased(MouseEvent event) { + if (component == null) + return; + + if (endNode == null) + component.setFocussedElement(null); + else { + component.getGraphActionListener().addEdge(beginNode, endNode); + component.setFocussedElement(null); + // TODO Implement add edge + } + } + + protected float getEndNodeRadius() { + if (endNode == null) + return 0f; + else + return super.getEndNodeRadius(); + } + + protected Node getBeginNode() { + return beginNode; + } + + protected Node getEndNode() { + return endNode; + } + + protected Point2D getEndNodePoint() { + if (endNode == null) + return getEndPoint(); + else + return component.getScaledLocation(endNode.getLocation()); + } + + protected String getEdgeWeight() { + if (weight == null && component != null) { + try { + weight = component.getGraphActionListener().getDataType() + .newInstance(); + } catch (InstantiationException e) { + } catch (IllegalAccessException e) { + } + } + + if (weight != null) + return weight.toString(); + else + return ""; + } +} diff --git a/src/org/jalgo/module/app/view/graph/NodeElement.java b/src/org/jalgo/module/app/view/graph/NodeElement.java new file mode 100644 index 0000000..9f4027a --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/NodeElement.java @@ -0,0 +1,174 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.BasicStroke; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Stroke; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.awt.font.LineMetrics; +import java.awt.geom.Dimension2D; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +import org.jalgo.module.app.core.graph.Node; +import org.jalgo.module.app.view.InterfaceConstants; + +/** + * The graphical representation of a node in the user interface. This class + * wraps an object from type Node. + */ +public class NodeElement extends GraphElement { + + private static final long serialVersionUID = 1938758344902933851L; + + private Node node; + private Ellipse2D ellipse; + private Stroke stroke; + private String label; + + private static boolean beamerMode; + + + public NodeElement(Node node) { + this.node = node; + + beamerMode = false; + highlightState = HighlightState.NONE; + } + + @Override + public boolean contains(Point2D point) { + return getShape().contains(point); + } + + /* + * the mouseDragged method in NewEdgeElement doesn't find the contains + * method. So I use this. + */ + public boolean nodeContains(Point2D point) { + return getShape().contains(point); + } + + @Override + public void paint(Graphics2D g) { + + ellipse = getShape(); + + // Draw content + g.setColor(InterfaceConstants + .fillColorForHighlightStateNode(highlightState)); + g.fill(ellipse); + + // Draw border + stroke = new BasicStroke(InterfaceConstants.getNodeBorderWidth(beamerMode)); + g.setStroke(stroke); + g.setColor(InterfaceConstants + .borderColorForHighlightState(highlightState)); + g.draw(ellipse); + + // Draw label + Rectangle2D labelSize; + LineMetrics metrics; + Font font; + + label = Integer.toString(node.getId() + 1); + + font = InterfaceConstants.getGraphNodeFont(beamerMode); + labelSize = font.getStringBounds(label, g.getFontRenderContext()); + metrics = font.getLineMetrics(label, g.getFontRenderContext()); + + g.setColor(InterfaceConstants + .textColorForHighlightStateNode(highlightState)); + g.setFont(font); + + g.drawString(label, (float) (ellipse.getCenterX() - labelSize + .getWidth() / 2), (float) (ellipse.getCenterY() + - metrics.getHeight() / 2 + metrics.getAscent())); + } + + private Ellipse2D getShape() { + Dimension2D dimension; + Ellipse2D ellipse; + Point2D location; + + ellipse = new Ellipse2D.Float(); + location = new Point2D.Float(); + + location = component.getScaledLocation(node.getLocation()); + + dimension = new Dimension((int) InterfaceConstants.getNodeDiameter(beamerMode), + (int) InterfaceConstants.getNodeDiameter(beamerMode)); + + location.setLocation(location.getX() - dimension.getWidth() / 2, + location.getY() - dimension.getHeight() / 2); + ellipse.setFrame(location, dimension); + + return ellipse; + } + + public Node getNode() { + return node; + } + + public void setNode(Node node) { + this.node = node; + } + + public void updateBeamerMode(boolean beamerMode) { + NodeElement.beamerMode = beamerMode; + } + + public void mouseDragged(MouseEvent event) { + component.setIgnoreEvents(true); + + /*if(event.getPoint().x <= component.getWidth() - 20 + && event.getPoint().y <= component.getHeight() - 20 + &&event.getPoint().y >= component.getLocation().y + 20 + &&event.getPoint().x >= component.getLocation().x + 20)*/ + component.getGraphActionListener().alterNodePosition(node, + component.getCoreLocation(event.getPoint()) + ); + + component.setIgnoreEvents(false); + } + + public void keyReleased(KeyEvent e) { + component.setIgnoreEvents(true); + + if (e.getKeyCode() == KeyEvent.VK_DELETE + || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { + component.getGraphActionListener().removeNode(node); + } + + component.setIgnoreEvents(false); + } + + /* (non-Javadoc) + * @see org.jalgo.module.app.view.graph.GraphElement#mouseClicked(java.awt.event.MouseEvent) + */ + @Override + public void mouseClicked(MouseEvent e) { + super.mouseClicked(e); + //Memorize node position for undo concerns. + component.getGraphActionListener().setPreviousPosition(component.getCoreLocation(e.getPoint())); + } + + /* (non-Javadoc) + * @see org.jalgo.module.app.view.graph.GraphElement#mouseReleased(java.awt.event.MouseEvent) + */ + @Override + public void mouseReleased(MouseEvent e) { + //Realize that the movement of a node has ended. + component.getGraphActionListener().setFinalNodePosition(node, component.getCoreLocation(e.getPoint())); + + + + + } + + + +} diff --git a/src/org/jalgo/module/app/view/graph/ShapeHighlightPainter.java b/src/org/jalgo/module/app/view/graph/ShapeHighlightPainter.java new file mode 100644 index 0000000..130222f --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/ShapeHighlightPainter.java @@ -0,0 +1,62 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Shape; + +import javax.swing.text.BadLocationException; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; + +abstract class ShapeHighlightPainter implements Highlighter.HighlightPainter { + + protected Color lineColor, fillColor; + protected boolean hasBorder, hasFilling; + protected int strokeWidth; + + protected abstract Shape calculateShape(int x, int y, int length, int height, int fontSize); + + public void paint(Graphics output, int startOffset, int endOffset, Shape bounds, JTextComponent component) { + Rectangle startRect, endRect; + Shape shape; + Graphics2D g; + + g = (Graphics2D)output; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON + ); + + // Paint underline + try { + startRect = component.modelToView(startOffset); + endRect = component.modelToView(endOffset); + } + catch (BadLocationException e) { + return; + } + + shape = calculateShape((int)startRect.getX(), + (int)startRect.getY(), + (int)(endRect.getX() + endRect.getWidth() - startRect.getX()), + (int)(endRect.getHeight()), + component.getFont().getSize() + ); + + g.setStroke(new BasicStroke(strokeWidth)); + + if (hasBorder) { + g.setColor(lineColor); + g.draw(shape); + } + + if (hasFilling) { + g.setColor(fillColor); + g.fill(shape); + } + } + +} diff --git a/src/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.java b/src/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.java new file mode 100644 index 0000000..b2414f5 --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/UnderliningHighlightPainter.java @@ -0,0 +1,43 @@ +package org.jalgo.module.app.view.graph; + +import java.awt.Color; +import java.awt.Shape; +import java.awt.geom.GeneralPath; + + +public class UnderliningHighlightPainter extends ShapeHighlightPainter { + + public UnderliningHighlightPainter(Color lineColor) { + this.lineColor = lineColor; + this.hasBorder = true; + this.hasFilling = false; + this.strokeWidth = 1; + } + + protected Shape calculateShape(int x, int y, int length, int height, int fontSize) { + GeneralPath underline; + int step, wave; + + step = fontSize / 6; + wave = fontSize / 8; + y += wave + fontSize; + + underline = new GeneralPath(); + + underline.moveTo(x, y); + + for (int i = 0; i < length / step; i ++, x += step) { + int sign; + + if ((i % 2) == 0) + sign = -1; + else + sign = 1; + + underline.quadTo(x + wave, y + (wave * sign), x + step, y); + } + + return underline; + } + + } \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/graph/package.html b/src/org/jalgo/module/app/view/graph/package.html new file mode 100644 index 0000000..c004fee --- /dev/null +++ b/src/org/jalgo/module/app/view/graph/package.html @@ -0,0 +1,10 @@ + + + + + + +The left hand side of the interface. The illustration of the graph. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/package.html b/src/org/jalgo/module/app/view/package.html new file mode 100644 index 0000000..4fb3c91 --- /dev/null +++ b/src/org/jalgo/module/app/view/package.html @@ -0,0 +1,10 @@ + + + + + + +The interface of the program. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/run/CVS/Entries b/src/org/jalgo/module/app/view/run/CVS/Entries new file mode 100644 index 0000000..e5ab4b3 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/CVS/Entries @@ -0,0 +1,9 @@ +/ControlToolbar.java/1.1/Wed Oct 29 18:05:25 2008// +/FormulaComponent.java/1.1/Wed Oct 29 18:05:25 2008// +/FormulaDisplay.java/1.1/Wed Oct 29 18:05:25 2008// +/FormulaWindow.java/1.1/Wed Oct 29 18:05:25 2008// +/MatrixComponent.java/1.1/Wed Oct 29 18:05:25 2008// +/MatrixDisplay.java/1.1/Wed Oct 29 18:05:25 2008// +/MatrixPreviewComponent.java/1.1/Wed Oct 29 18:05:25 2008// +/StepHighlighting.java/1.1/Wed Oct 29 18:05:25 2008// +/package.html/1.1/Wed Oct 29 18:05:25 2008// diff --git a/src/org/jalgo/module/app/view/run/CVS/Repository b/src/org/jalgo/module/app/view/run/CVS/Repository new file mode 100644 index 0000000..05f6b01 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/app/view/run diff --git a/src/org/jalgo/module/app/view/run/CVS/Root b/src/org/jalgo/module/app/view/run/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/app/view/run/ControlToolbar.java b/src/org/jalgo/module/app/view/run/ControlToolbar.java new file mode 100644 index 0000000..996f7e6 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/ControlToolbar.java @@ -0,0 +1,175 @@ +package org.jalgo.module.app.view.run; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JMenu; +import javax.swing.JPanel; +import javax.swing.JToggleButton; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.AlgorithmController; + +/** + * Displays the toolbar on the lower end of the algorithm panel. + */ +public class ControlToolbar extends JPanel { + private static final long serialVersionUID = 24047077533400298L; + + private AlgorithmController algorithmController; + + private JButton fastBackwardButton, backwardButton, forwardButton, + fastForwardButton; + private JToggleButton animateButton; + private JPanel animateSpacer; + + public enum ControlButtons { + FastBackwardButton, BackwardButton, ForwardButton, FastForwardButton, AnimateButton + } + + /** + * Instantiates the toolbar on the lower end of the algorithm panel. + */ + public ControlToolbar(AlgorithmController algoCtrl) { + algorithmController = algoCtrl; + + fastBackwardButton = new JButton(); + backwardButton = new JButton(); + forwardButton = new JButton(); + fastForwardButton = new JButton(); + animateButton = new JToggleButton(); + + // Setup Buttons + fastBackwardButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_GroupStepBackward"))); //$NON-NLS-1$ + backwardButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_StepBackward"))); //$NON-NLS-1$ + forwardButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_StepForward"))); //$NON-NLS-1$ + fastForwardButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_GroupStepForward"))); //$NON-NLS-1$ + animateButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_animateStart"))); //$NON-NLS-1$ + + fastBackwardButton.setToolTipText(Messages.getString("app", "ControlToolbar.FastBackward")); //$NON-NLS-1$ //$NON-NLS-2$ + backwardButton.setToolTipText(Messages.getString("app", "ControlToolbar.Backward")); //$NON-NLS-1$ //$NON-NLS-2$ + forwardButton.setToolTipText(Messages.getString("app", "ControlToolbar.Forward")); //$NON-NLS-1$ //$NON-NLS-2$ + fastForwardButton.setToolTipText(Messages.getString("app", "ControlToolbar.FastForward")); //$NON-NLS-1$ //$NON-NLS-2$ + animateButton.setToolTipText(Messages.getString("app", "ControlToolbar.Animate")); //$NON-NLS-1$ //$NON-NLS-2$ + + fastBackwardButton.addActionListener(new fastBackwardListener()); + backwardButton.addActionListener(new backwardListener()); + forwardButton.addActionListener(new forwardListener()); + fastForwardButton.addActionListener(new fastForwardListener()); + animateButton.addActionListener(new animateListener()); + + // Setup Tool Bar + animateSpacer = new JPanel(); + animateSpacer.setSize(60, 0); + + this.add(fastBackwardButton); + this.add(backwardButton); + this.add(forwardButton); + this.add(fastForwardButton); + this.add(animateSpacer); + this.add(animateButton); + } + + /** + * Enables/Disables all buttons based on the parameter state. + * + * @param state + * true to enable all Buttons in this toolbar. + */ + public void setEnabled(boolean state) { + fastBackwardButton.setEnabled(state); + backwardButton.setEnabled(state); + forwardButton.setEnabled(state); + fastForwardButton.setEnabled(state); + animateButton.setEnabled(state); + } + + /** + * Toggles the state of the animation button between animate(play) and pause + * + * @param animate + * if true, set the animation button to play, + * otherwise set it to pause + */ + public void toggleAnimationState(boolean animate) { + if (animate) { + animateButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_animateStart"))); //$NON-NLS-1$ + animateButton.setSelected(false); + } else { + animateButton.setIcon(new ImageIcon(Messages.getResourceURL("app", //$NON-NLS-1$ + "icon_animatePause"))); //$NON-NLS-1$ + animateButton.setSelected(true); + } + } + + /** + * Enables/disables the control toolbar buttons according to state. + * @param button the button to be changed. + * @param state if true, enable button, otherwise disable it (gray it out). + */ + public void setButtonState(ControlButtons button, boolean state) { + switch (button) { + case FastBackwardButton: + fastBackwardButton.setEnabled(state); + break; + + case BackwardButton: + backwardButton.setEnabled(state); + break; + + case ForwardButton: + forwardButton.setEnabled(state); + break; + + case FastForwardButton: + fastForwardButton.setEnabled(state); + break; + + case AnimateButton: + animateButton.setEnabled(state); + } + } + + class fastBackwardListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + algorithmController.previousGroupStep(); + } + } + + class backwardListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + algorithmController.previousStep(); + } + } + + class forwardListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + algorithmController.nextStep(); + } + } + + class fastForwardListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + algorithmController.nextGroupStep(); + } + } + + class animateListener implements ActionListener { + public void actionPerformed(ActionEvent arg0) { + if (animateButton.isSelected()) { + algorithmController.startAnimation(); + } else { + algorithmController.pauseAnimation(); + } + } + } +} diff --git a/src/org/jalgo/module/app/view/run/FormulaComponent.java b/src/org/jalgo/module/app/view/run/FormulaComponent.java new file mode 100644 index 0000000..1786c53 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/FormulaComponent.java @@ -0,0 +1,202 @@ +package org.jalgo.module.app.view.run; + + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; + +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.AlgorithmController; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.view.InterfaceConstants; + +/** + * Displays the recursive formula (using variables and its current values and + * the result) incl. highlighting on the algorithm panel during the algorithm + * mode. + */ +public class FormulaComponent extends JPanel implements StepHighlighting,MouseListener { + + private static final long serialVersionUID = -5258259352683364934L; + + private AlgorithmController algoCtrl; + + private FormulaDisplay formulaDisplay; + private JPanel enlargePanel; + private Dimension panelDimension; + private Cursor handCursor, defaultCursor; + + private boolean beamerMode; + + /** + * Displays the recursive formula (using variables and its current values and + * the result) incl. highlighting on the algorithm panel during the algorithm + * mode. + */ + public FormulaComponent(AlgorithmController algoCtrl) { + this.algoCtrl = algoCtrl; + algoCtrl.addStepHighlighting(this); + + this.beamerMode = false; + + setLayout(null); + + formulaDisplay = new FormulaDisplay(InterfaceConstants.formulaNormalFont(beamerMode), + InterfaceConstants.formulaBoldFont(beamerMode), + InterfaceConstants.formulaSmallFont(beamerMode)); + enlargePanel = new JPanel(); + enlargePanel.setBackground(Color.white); + enlargePanel.setToolTipText(Messages.getString("app","FormulaComponent.enlargePanel")); //$NON-NLS-1$ //$NON-NLS-2$ + JLabel magnifier; + magnifier = new JLabel(new ImageIcon(Messages.getResourceURL("app", "zoom"))); //$NON-NLS-1$ //$NON-NLS-2$ + magnifier.setBounds(0, 0, 16, 16); + enlargePanel.add(magnifier); + + panelDimension = new Dimension(100, InterfaceConstants.formulaNormalFont(beamerMode).getSize() * 8); + + this.setMinimumSize(panelDimension); + this.setPreferredSize(panelDimension); + this.setMaximumSize(panelDimension); + + this.add(formulaDisplay); + this.add(enlargePanel); + + this.setComponentZOrder(formulaDisplay, 1); + this.setComponentZOrder(enlargePanel, 0); + + this.addComponentListener(new FormulaComponentListener()); + this.setBackground(InterfaceConstants.formulaBackgroundColor()); + this.setOpaque(true); + + enlargePanel.addMouseListener(this); + handCursor = new Cursor(Cursor.HAND_CURSOR); + defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); + } + + /** + * Sets the current operators. + * + * @param addOperator + * the multiplicative operator in its symbolic representation. + * @param addInfix + * if true, the add operator must be printed + * infix, otherwise prefix. + * @param multOperator + * the multiplicative operator in its symbolic representation. + * @param multInfix + * if true, the multiply operator must be printed + * infix, otherwise prefix. + */ + public void setOperators(String addOperator, boolean addInfix, String multOperator, boolean multInfix) { + formulaDisplay.setOperators(addOperator, addInfix, multOperator, multInfix); + } + + public void updateBeamerMode(boolean beamerMode){ + this.beamerMode = beamerMode; + formulaDisplay.updateBeamerMode(beamerMode); + panelDimension = new Dimension(100, InterfaceConstants.formulaNormalFont(beamerMode).getSize() * 8); + this.setMinimumSize(panelDimension); + this.setPreferredSize(panelDimension); + this.setMaximumSize(panelDimension); + + } + + public void enterHighlightMode(RootStep rootStep) { + formulaDisplay.setNoPainting(true); + + repaint(); + revalidate(); + } + + public void leaveHighlightMode() { + formulaDisplay.setNoPainting(true); + + repaint(); + revalidate(); + } + + public void highlightAtomicStep(AtomicStep step, boolean isForward) { + formulaDisplay.setNoPainting(false); + + formulaDisplay.setParameterDescription(step); + + repaint(); + revalidate(); + } + + public void highlightGroupStep(GroupStep step, boolean isForward) { + formulaDisplay.setNoPainting(true); + + repaint(); + revalidate(); + } + + public void highlightLastStep(RootStep step) { + formulaDisplay.setNoPainting(true); + + repaint(); + revalidate(); + } + + public void highlightFirstStep(RootStep step) { + formulaDisplay.setNoPainting(true); + + repaint(); + revalidate(); + } + + public void mouseClicked(MouseEvent e) { + } + + public void mouseEntered(MouseEvent e) { + this.setCursor(handCursor); + } + + public void mouseExited(MouseEvent e) { + this.setCursor(defaultCursor); + } + + public void mousePressed(MouseEvent e) { + algoCtrl.initFormulaWindow(); + } + + public void mouseReleased(MouseEvent e) { + } + + /** + * Used to resize a formula. + */ + private class FormulaComponentListener implements ComponentListener { + + public void componentHidden(ComponentEvent arg0) { + } + + public void componentMoved(ComponentEvent arg0) { + componentResized(arg0); + } + + public void componentResized(ComponentEvent arg0) { + formulaDisplay.setBounds(0, 0, getWidth() - 20, getHeight()); + enlargePanel.setBounds(getWidth() - 20, getHeight() - 25, 20, 20); + + repaint(); + revalidate(); + } + + public void componentShown(ComponentEvent arg0) { + componentResized(arg0); + + } + + } + +} diff --git a/src/org/jalgo/module/app/view/run/FormulaDisplay.java b/src/org/jalgo/module/app/view/run/FormulaDisplay.java new file mode 100644 index 0000000..0daee6c --- /dev/null +++ b/src/org/jalgo/module/app/view/run/FormulaDisplay.java @@ -0,0 +1,601 @@ +package org.jalgo.module.app.view.run; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; + +import javax.swing.JPanel; + +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.view.InterfaceConstants; +import org.jalgo.module.app.view.graph.HighlightState; + +/** + * Displays the formula of the current step. It is used for + * FormulaComponent and FormulaWindow. + * + */ +public class FormulaDisplay extends JPanel { + + private static final long serialVersionUID = 679622426179670735L; + private Graphics2D graphics; + private Font normalFont, boldFont, smallFont; + + private OperatorDescription currentOperators; + private ParameterDescription currentParameters; + + private Metrics globalMetrics; + + private boolean beamerMode; + + private boolean noPainting; + + /** + * Describes the two Operators used in a SemiRing. + */ + private class OperatorDescription { + public String multOperator; + public boolean multInfix; + + public String addOperator; + public boolean addInfix; + + /** + * Describes the two operators used in a SemiRing. + * + * @param addOperator + * the multiplicative operator in its symbolic + * representation. + * @param addInfix + * if true, the add operator must be printed + * infix, otherwise prefix. + * @param multOperator + * the multiplicative operator in its symbolic + * representation. + * @param multInfix + * if true, the multiply operator must be + * printed infix, otherwise prefix. + */ + public OperatorDescription(String addOperator, boolean addInfix, String multOperator, boolean multInfix) { + this.addOperator = addOperator; + this.addInfix = addInfix; + this.multOperator = multOperator; + this.multInfix = multInfix; + } + } + + private class ParameterDescription { + public int u, k, v; + public String[] values; + + public ParameterDescription(AtomicStep step) { + this.u = step.getU() + 1; + this.k = step.getK() + 1; + this.v = step.getV() + 1; + this.values = new String[5]; + + this.values[0] = step.getGroupStep().getBeforeMatrix().getValueAt(u-1, v-1).toString(); + this.values[1] = step.getGroupStep().getBeforeMatrix().getValueAt(u-1, k-1).toString(); + this.values[2] = step.getGroupStep().getBeforeMatrix().getValueAt(k-1, k-1).toString(); + this.values[3] = step.getGroupStep().getBeforeMatrix().getValueAt(k-1, v-1).toString(); + this.values[4] = step.getValue().toString(); + } + } + + /** + * Represents a container for font properties (font and line height) and for + * the offset in the x and y direction (used for the points to paint the + * next element to). + * + */ + private class Metrics { + public int offsetX, offsetY, fontHeight, lineHeight; + } + + /** + * An extension of Metrics used for painting multiply lines + * of a formula at once. + * + */ + private class MultiLineMetrics extends Metrics { + public int upperX, upperY; + public int lowerX, lowerY; + } + + /** + * Displays the recursive formula (using variables and its current values + * and the result) including highlighting on the algorithm panel during the + * algorithm mode. + */ + public FormulaDisplay(Font normalFont, Font boldFont, Font smallFont) { + noPainting = true; + this.beamerMode = false; + + this.normalFont = normalFont; + this.boldFont = boldFont; + this.smallFont = smallFont; + + // FIXME: Static calculation + Dimension panelDimension = new Dimension(normalFont.getSize() * 6, 100); + + this.setMinimumSize(panelDimension); + this.setPreferredSize(panelDimension); + this.setMaximumSize(panelDimension); + + globalMetrics = new Metrics(); + + this.setOpaque(true); + this.setBackground(InterfaceConstants.formulaBackgroundColor()); + } + + public void setFont(Font normalFont, Font boldFont, Font smallFont) { + this.normalFont = normalFont; + this.boldFont = boldFont; + this.smallFont = smallFont; + } + + /** + * Sets the current operators. + * + * @param addOperator + * the multiplicative operator in its symbolic representation. + * @param addInfix + * if true, the add operator must be printed + * infix, otherwise prefix. + * @param multOperator + * the multiplicative operator in its symbolic representation. + * @param multInfix + * if true, the multiply operator must be printed + * infix, otherwise prefix. + */ + public void setOperators(String addOperator, boolean addInfix, String multOperator, boolean multInfix) { + currentOperators = new OperatorDescription(addOperator, addInfix, multOperator, multInfix); + } + + /** + * Sets the ParamterDescription used for painting the formula + * of the step. + * + * @param step + * the Step to be painted in a formula representation. + */ + public void setParameterDescription(AtomicStep step) { + currentParameters = new ParameterDescription(step); + + repaint(); + revalidate(); + } + + /** + * Draws a string to the given coordinates. + * + * @param string + * the given String + * @param font + * the Font used for this string. + * @param offsetX + * the x-coordinate + * @param offsetY + * the y-coordinate + * @return the new offSetX (points to the coordinates at the + * end of the string) + */ + private int paintString(String string, Font font, int offsetX, int offsetY) { + graphics.setFont(font); + + graphics.drawString(string, offsetX, offsetY); + return offsetX + (int)graphics.getFontMetrics(font).getStringBounds(string, graphics).getWidth(); + } + + /** + * Same as paintString, but using the "normal" font defined + * in InterfaceConstants.formulaNormalFont(). + * + * @param string + * the given String + * @param offsetX + * the x-coordinate + * @param offsetY + * the y-coordinate + * @return the new offSetX (points to the coordinates at the + * end of the string) + */ + private int paintStringNormal(String string, int offsetX, int offsetY) { + return paintString(string, normalFont, offsetX, offsetY); + } + + /** + * Same as paintString, but using the "bold" font defined + * in InterfaceConstants.formulaBoldFont(). + * + * @param string + * the given String + * @param offsetX + * the x-coordinate + * @param offsetY + * the y-coordinate + * @return the new offSetX (points to the coordinates at the + * end of the string) + */ + private int paintStringBold(String string, int offsetX, int offsetY) { + return paintString(string, boldFont, offsetX, offsetY); + } + + /** + * Same as paintString, but using the "small" font defined + * in InterfaceConstants.formulaSmallFont(). + * + * @param string + * the given String + * @param offsetX + * the x-coordinate + * @param offsetY + * the y-coordinate + * @return the new offSetX (points to the coordinates at the + * end of the string) + */ + private int paintStringSmall(String string, int offsetX, int offsetY) { + return paintString(string, smallFont, offsetX, offsetY); + } + + /** + * Paints $D_G^{(superscript)} (a,b)$ (LaTeX Math style) + * + * @param metrics + * the used metrics for the string + * @param superscript + * @param a + * @param b + * @return the new x offset + */ + private int paintDistanceSymbol(Metrics metrics, int superscript, int a, int b) { + // Paint "D" + graphics.setFont(normalFont); + metrics.offsetX = paintStringNormal("D", metrics.offsetX, metrics.offsetY); + + // Paint (k) and G + int offsetSuperscript = paintStringSmall("("+superscript+")", metrics.offsetX, metrics.offsetY - metrics.fontHeight/2); + int offsetSubscript = paintStringSmall("G", metrics.offsetX, metrics.offsetY + metrics.fontHeight/4); + + // Paint (u,v) + metrics.offsetX = Math.max(offsetSuperscript, offsetSubscript); + + graphics.setFont(normalFont); + + metrics.offsetX = paintStringNormal( "("+a+","+b+")", metrics.offsetX, metrics.offsetY); + + return metrics.offsetX; + } + + /** + * Paints the infix operator (e.g. +) + * + * @param metrics + * the font metrics used for this operator + * @param operator + * the given operator + * @return the new x offset + */ + private int paintInfixOperator(MultiLineMetrics metrics, String operator) { + // Paint Operator + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + paintStringBold(" "+operator+" ", metrics.offsetX, metrics.upperY); + metrics.offsetX = paintStringBold(" "+operator+" ", metrics.offsetX, metrics.lowerY); + + return metrics.offsetX; + } + + /** + * Paints a whole element of the formula (the variable and the value in the + * line below), e.g. (D_{G}^{(superscript)} (a,b))* + * + * @param metrics + * the used font metrics + * @param superscript + * @param a + * @param b + * @param value + * the calculated value for this element + * @param hasStar + * true, if D_{G}.. has a star at its end + * @param hasComma + * true, if D_{G}.. has a comma at its end + * @return + */ + private int paintFormulaElement(MultiLineMetrics metrics, int superscript, int a, int b, String value, boolean hasStar, boolean hasComma) { + String prefix; + + Color formulaElementColor; + + formulaElementColor = graphics.getColor(); + + if (hasStar) { + // set Color to black + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + + paintStringNormal("(", metrics.offsetX, metrics.upperY); + metrics.offsetX = paintStringNormal("(", metrics.offsetX, metrics.lowerY); + + // reset Color + graphics.setColor(formulaElementColor); + } + + // Paint Element + metrics.upperX = metrics.offsetX; + metrics.lowerX = metrics.offsetX; + + metrics.upperX = paintDistanceSymbol(metrics, superscript, a, b); + metrics.lowerX = paintStringNormal(value, metrics.lowerX, metrics.lowerY); + + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + + if (hasStar) { + metrics.upperX = paintStringNormal(")*", metrics.upperX, metrics.upperY); + metrics.lowerX = paintStringNormal(")*", metrics.lowerX, metrics.lowerY); + } + + if (hasComma) + prefix = ", "; + else + prefix = " "; + + metrics.upperX = paintStringNormal(prefix, metrics.upperX, metrics.upperY); + metrics.lowerX = paintStringNormal(prefix, metrics.lowerX, metrics.lowerY); + + // Update metrics + metrics.offsetX = Math.max(metrics.lowerX, metrics.upperX); + + + return metrics.offsetX; + } + + /** + * Paints the inner formula, which is the one after the add operator. + * + * @param metrics + * the used font metrics + * @param operators + * the multiplicative operator + * @param parameter + * the used parameters (u,k,v) in the inner formula + * @return the new x offset + */ + private int paintInnerFormula(MultiLineMetrics metrics, OperatorDescription operators, ParameterDescription parameter) { + String openingParenthesis, closingParenthesis; + + if (operators.multInfix) { + // ( + openingParenthesis = "( "; + closingParenthesis = ") "; + } + else + { + // Prefix ( ) + openingParenthesis = " "+operators.multOperator+" {"; + closingParenthesis = "} "; + } + + // ( or prefix operator + paintStringNormal(openingParenthesis, metrics.offsetX, metrics.upperY); + metrics.offsetX = paintStringNormal(openingParenthesis, metrics.offsetX, metrics.lowerY); + + // (u,k) + graphics.setColor(InterfaceConstants.borderColorForHighlightState(HighlightState.PRE_PATH)); + metrics.offsetX = paintFormulaElement(metrics, + parameter.k-1, + parameter.u, + parameter.k, + parameter.values[1], + false, + !operators.multInfix + ); + + // Infix Operator + if (operators.multInfix) { + metrics.offsetX = paintInfixOperator(metrics, operators.multOperator); + } + + // (k,k) * + graphics.setColor(InterfaceConstants.borderColorForHighlightState(HighlightState.SELECTED)); + metrics.offsetX = paintFormulaElement(metrics, + parameter.k-1, + parameter.k, + parameter.k, + parameter.values[2], + true, + !operators.multInfix + ); + + // Infix Operator + if (operators.multInfix) { + metrics.offsetX = paintInfixOperator(metrics, operators.multOperator); + } + + // (k,v) + graphics.setColor(InterfaceConstants.borderColorForHighlightState(HighlightState.POST_PATH)); + metrics.offsetX = paintFormulaElement(metrics, + parameter.k-1, + parameter.k, + parameter.v, + parameter.values[3], + false, + false + ); + + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + + // ) or } + paintStringNormal(closingParenthesis, metrics.offsetX, metrics.upperY); + metrics.offsetX = paintStringNormal(closingParenthesis, metrics.offsetX, metrics.lowerY); + + return metrics.offsetX; + } + + /** + * Paints the whole formula (outer and inner formula). + * + * @param metrics + * the used font metrics. + * @param operators + * the used operators (+,*) + * @param parameter + * the used parameters (u,k,v) + * @return the new x offset + */ + private int paintFormula(Metrics metrics, OperatorDescription operators, ParameterDescription parameter) { + MultiLineMetrics mlMetrics = new MultiLineMetrics(); + + // Calculate multiline metrics + mlMetrics.offsetX = metrics.offsetX; + mlMetrics.offsetY = metrics.offsetY; + mlMetrics.fontHeight = metrics.fontHeight; + mlMetrics.lineHeight = metrics.lineHeight; + + mlMetrics.upperY = mlMetrics.offsetY; + mlMetrics.lowerY = mlMetrics.offsetY + mlMetrics.lineHeight; + + mlMetrics.upperX = mlMetrics.offsetX; + mlMetrics.lowerX = mlMetrics.offsetX; + + // "=" or "= OPERATOR {" + if (operators.addInfix) { + paintStringBold("= ", mlMetrics.offsetX, mlMetrics.upperY); + mlMetrics.offsetX = paintStringBold("= ", mlMetrics.offsetX, mlMetrics.lowerY); + } + else { + paintStringBold("= "+operators.addOperator+"{ ", mlMetrics.offsetX, mlMetrics.upperY); + mlMetrics.offsetX = paintStringBold("= "+operators.addOperator+"{ ", mlMetrics.offsetX, mlMetrics.lowerY); + } + + // (u,v) + mlMetrics.offsetX = paintFormulaElement(mlMetrics, + parameter.k-1, + parameter.u, + parameter.v, + parameter.values[0], + false, + !operators.addInfix + ); + + // Infix Operator + if (operators.addInfix) { + mlMetrics.offsetX = paintInfixOperator(mlMetrics, operators.addOperator); + } + + mlMetrics.offsetX = paintInnerFormula(mlMetrics, operators, parameter); + + // } + paintStringBold(" }", mlMetrics.offsetX, mlMetrics.upperY); + mlMetrics.offsetX = paintStringBold(" }", mlMetrics.offsetX, mlMetrics.lowerY); + + return mlMetrics.offsetX; + } + + + /** + * Paints the formula component. + */ + public void paint(Graphics output) { + Metrics metrics; + + // Setup + + if (output == null) + return; + + graphics = (Graphics2D) output; + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + // Draw background + graphics.setColor(InterfaceConstants.formulaBackgroundColor()); + graphics.setStroke(new BasicStroke(1)); + + graphics.fill(new Rectangle(this.getSize())); + + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + graphics.setStroke(new BasicStroke(1)); + + // Calculate metrics + metrics = new Metrics(); + + metrics.fontHeight = (int)graphics.getFontMetrics(normalFont).getStringBounds("D", graphics).getHeight(); + metrics.offsetX = metrics.fontHeight / 2; + metrics.offsetY = metrics.fontHeight + metrics.fontHeight / 2; + metrics.lineHeight = (int)(metrics.fontHeight * 1.5); + + // First line + paintDistanceSymbol(metrics, + currentParameters.k, + currentParameters.u, + currentParameters.v + ); + metrics.offsetX = metrics.fontHeight / 2; + + // Second + Third line + metrics.offsetY += metrics.lineHeight; + globalMetrics.offsetX = paintFormula(metrics, currentOperators, currentParameters); + + // Last line + metrics.offsetY += metrics.lineHeight * 2; + paintStringBold("= "+currentParameters.values[4], metrics.offsetX, metrics.offsetY); + + globalMetrics.offsetY = metrics.offsetY + metrics.lineHeight * 2; + } + + /** + * @return the X coordinate from the last String painted. + */ + public int getOffsetX() { + return globalMetrics.offsetX; + } + + /** + * @return the Y coordinate from the last String painted. + */ + public int getOffsetY() { + return globalMetrics.offsetY; + } + + /** + * @return true, if there should be no painting at this + * point (e.g. when the current Step is a + * GroupStep). + */ + public boolean isNoPainting() { + repaint(); + revalidate(); + + return noPainting; + } + + public void updateBeamerMode(boolean beamerMode){ + this.beamerMode = beamerMode; + this.boldFont = InterfaceConstants.formulaBoldFont(beamerMode); + this.normalFont = InterfaceConstants.formulaNormalFont(beamerMode); + this.smallFont = InterfaceConstants.formulaSmallFont(beamerMode); + repaint(); + revalidate(); + } + + /** + * Sets the boolean variable noPainting. + * + * @param noPainting + * true if the current Step should + * not be painted. + */ + public void setNoPainting(boolean noPainting) { + this.noPainting = noPainting; + + this.setVisible(!noPainting); + + repaint(); + revalidate(); + } +} diff --git a/src/org/jalgo/module/app/view/run/FormulaWindow.java b/src/org/jalgo/module/app/view/run/FormulaWindow.java new file mode 100644 index 0000000..9ea9eb7 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/FormulaWindow.java @@ -0,0 +1,214 @@ +package org.jalgo.module.app.view.run; + +import java.awt.GraphicsConfiguration; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.awt.image.BufferedImage; + +import javax.swing.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.app.controller.AlgorithmController; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; +import org.jalgo.module.app.view.InterfaceConstants; + +/** + * Displays an enlarged version (with increased font sizes) of the + * FormulaComponent in an extra window. + */ +public class FormulaWindow extends JFrame implements StepHighlighting, ComponentListener, WindowListener { + private static final long serialVersionUID = 7712663723144407282L; + + private AlgorithmController algoCtrl; + private FormulaDisplay formulaDisplay; + private Point lowerLeftCorner; + private boolean modifiedPosition; + + private boolean beamerMode; + + /** + * Displays an enlarged version (with increased font sizes) of the + * FormulaComponent in an extra window. + */ + public FormulaWindow(AlgorithmController algoCtrl, GraphicsConfiguration display, Point lowerLeftCorner, boolean beamerMode) { + super(display); + + this.setTitle(Messages.getString("app", "FormulaWindow.Title")); //$NON-NLS-1$ //$NON-NLS-2$" + this.setIconImage(Toolkit.getDefaultToolkit().getImage(Messages.getResourceURL("app", //$NON-NLS-1$ + "Module_logo"))); + + this.lowerLeftCorner = lowerLeftCorner; + modifiedPosition = false; + + this.beamerMode = beamerMode; + this.algoCtrl = algoCtrl; + + algoCtrl.addStepHighlighting(this); + + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + setAlwaysOnTop(true); + setResizable(false); + + formulaDisplay = new FormulaDisplay(InterfaceConstants.formulaWindowNormalFont(this.beamerMode), + InterfaceConstants.formulaWindowBoldFont(this.beamerMode), + InterfaceConstants.formulaWindowSmallFont(this.beamerMode)); + + this.add(formulaDisplay); + + this.getContentPane().setBackground(InterfaceConstants.formulaBackgroundColor()); + + addComponentListener(this); + } + + /** + * Sets the operators needed to display the formula. + * + * @param addOperator + * the String representation of the add operator. + * @param addInfix + * true, if the add operator is written infix. + * @param multOperator + * the String representation of the multiply operator. + * @param multInfix + * true, if the multiply operator is written infix. + */ + public void setOperators(String addOperator, boolean addInfix, String multOperator, boolean multInfix) { + formulaDisplay.setOperators(addOperator, addInfix, multOperator, multInfix); + } + + /** + * Repaints the formula for the given step. + * + * @param step + * the step to paint the formula for. + */ + public void repaintFormula(AtomicStep step) { + int newX,newY; + BufferedImage tempImage; + + if (step != null) + formulaDisplay.setParameterDescription(step); + + formulaDisplay.revalidate(); + this.update(this.getGraphics()); + this.repaint(); + + // Calculate size + tempImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB); + formulaDisplay.paint( tempImage.getGraphics() ); + + newX = formulaDisplay.getOffsetX(); + newY = formulaDisplay.getOffsetY(); + this.setSize(newX + 10,newY - 20); + + if (!modifiedPosition) { + this.setLocation(lowerLeftCorner.x, lowerLeftCorner.y - newY + 20); + } + } + + public void updateBeamerMode(boolean beamerMode){ + //FIXME resize depending on beamerMode + int newX,newY; + + this.beamerMode = beamerMode; + newX = formulaDisplay.getOffsetX(); + newY = formulaDisplay.getOffsetY(); + this.setSize(newX + 10,newY - 20); + + formulaDisplay.setFont(InterfaceConstants.formulaWindowNormalFont(this.beamerMode), + InterfaceConstants.formulaWindowBoldFont(this.beamerMode), + InterfaceConstants.formulaWindowSmallFont(this.beamerMode)); + + formulaDisplay.repaint(); + formulaDisplay.revalidate(); + } + + public void enterHighlightMode(RootStep rootStep) { + } + + public void leaveHighlightMode() { + dispose(); + } + + public void highlightAtomicStep(AtomicStep step, boolean isForward) { + formulaDisplay.setNoPainting(false); + repaintFormula(step); + } + + public void highlightGroupStep(GroupStep step, boolean isForward) { + formulaDisplay.setNoPainting(true); + repaintFormula((AtomicStep)step.getStep(0)); + + formulaDisplay.repaint(); + formulaDisplay.revalidate(); + } + + public void highlightLastStep(RootStep step) { + formulaDisplay.setNoPainting(true); + repaintFormula((AtomicStep)((GroupStep)step.getStep(0)).getStep(0)); + + formulaDisplay.repaint(); + formulaDisplay.revalidate(); + } + + public void highlightFirstStep(RootStep step) { + formulaDisplay.setNoPainting(true); + repaintFormula((AtomicStep)((GroupStep)step.getStep(0)).getStep(0)); + + formulaDisplay.repaint(); + formulaDisplay.revalidate(); + } + + public void componentHidden(ComponentEvent arg0) { + } + + public void componentMoved(ComponentEvent arg0) { + modifiedPosition = true; + } + + public void componentResized(ComponentEvent arg0) { + } + + public void componentShown(ComponentEvent arg0) { + } + + public void windowActivated(WindowEvent e) { + // TODO Auto-generated method stub + + } + + public void windowClosed(WindowEvent e) { + algoCtrl.formulaWindowClosed(); + } + + public void windowClosing(WindowEvent e) { + // TODO Auto-generated method stub + + } + + public void windowDeactivated(WindowEvent e) { + // TODO Auto-generated method stub + + } + + public void windowDeiconified(WindowEvent e) { + // TODO Auto-generated method stub + + } + + public void windowIconified(WindowEvent e) { + // TODO Auto-generated method stub + + } + + public void windowOpened(WindowEvent e) { + // TODO Auto-generated method stub + + } +} diff --git a/src/org/jalgo/module/app/view/run/MatrixComponent.java b/src/org/jalgo/module/app/view/run/MatrixComponent.java new file mode 100644 index 0000000..b6509da --- /dev/null +++ b/src/org/jalgo/module/app/view/run/MatrixComponent.java @@ -0,0 +1,1119 @@ +package org.jalgo.module.app.view.run; + +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.core.step.*; +import org.jalgo.module.app.view.InterfaceConstants; +import java.awt.Color; +import java.awt.Font; +import java.awt.Rectangle; +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import org.jalgo.module.app.controller.AlgorithmController; +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; + +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.util.ArrayList; +import java.util.List; +import java.util.TimerTask; +import java.util.Timer; + +/** + * Displays and updates the two matrices (the matrix from the last group step + * including path highlighting and the current matrix with highlighting of + * processed and unprocessed elements) during the algorithm mode in the + * algorithm panel. + */ +public class MatrixComponent extends JPanel implements StepHighlighting { + + private static final long serialVersionUID = -1480166238292888483L; + + private MatrixDisplay leftDisplay, rightDisplay, tempDisplay, probeDisplay; + private MatrixMoveAnimator animator; + private Step currentStep; + private boolean isVisible; + private ViewMode viewMode; + + private RootStep rootStep; + private Font forcedFont; + + private boolean beamerMode; + + private enum ViewMode { + StartView, GroupStepView, AtomicStepView, EndView + } + + public MatrixComponent(AlgorithmController algoCtrl) { + algoCtrl.addStepHighlighting(this); + + this.beamerMode = false; + + this.setBackground(InterfaceConstants.formulaBackgroundColor()); + + leftDisplay = new MatrixDisplay(true); + rightDisplay = new MatrixDisplay(true); + tempDisplay = new MatrixDisplay(true); + probeDisplay = new MatrixDisplay(true); + + leftDisplay.setBounds(calculateLeftOuterPosition(),0,1,1); + rightDisplay.setBounds(calculateRightOuterPosition(),0,1,1); + tempDisplay.setBounds(calculateRightOuterPosition(),0,1,1); + probeDisplay.setBounds(calculateRightOuterPosition(),0,1,1); + + currentStep = null; + + this.setLayout(null); + + this.add(leftDisplay); + this.add(rightDisplay); + this.add(tempDisplay); + + forcedFont = InterfaceConstants.getMatrixFont(beamerMode); + + // Set separation line + setBorder(BorderFactory.createMatteBorder(-1, -1, 1, -1, + Color.LIGHT_GRAY)); + setBackground(Color.WHITE); + + isVisible = false; + + setOpaque(true); // Needed for ubuntulooks GUI decorator + addComponentListener(new MatrixComponentListener()); + + setDoubleBuffered(true); + } + + /** + * Toggles whether the matrix component is visible or not. + * + */ + public void setVisible(boolean state) { + isVisible = state; + } + + public void updateBeamerMode(boolean beamerMode){ + this.beamerMode = beamerMode; + leftDisplay.updateBeamerMode(beamerMode); + rightDisplay.updateBeamerMode(beamerMode); + tempDisplay.updateBeamerMode(beamerMode); + probeDisplay.updateBeamerMode(beamerMode); + forcedFont = InterfaceConstants.getMatrixFont(beamerMode); + repaint(); + revalidate(); + } + + /** + * Calculates the height of a matrix. + * + * @return + */ + private int calculateMatrixHeight() { + return calculateDualMatrixWidth(); + } + + private int calculateMatrixPositionTop() { + if (calculateMatrixHeight() > getHeight()) + return 0; + else + return getHeight() / 2 - calculateMatrixHeight() / 2; + } + + private int calculateMatrixDisplayHeight() { + return getHeight() - calculateMatrixPositionTop() - 10; + } + + /** + * Calculates the width of a matrix if two matrices are shown. + * @return + */ + private int calculateDualMatrixWidth() { + return Math.min(getWidth()/2 - (1 * InterfaceConstants.matrixHgap()), getHeight() - 1*InterfaceConstants.matrixVgap()); + } + + /** + * Calculates the position of the left matrix if two matrices are shown. + * + * @return + */ + private int calculateDualMatrixPositionLeft() { + return (getWidth() / 4) - (calculateDualMatrixWidth() / 2) + InterfaceConstants.matrixHgap() / 2; + } + + /** + * Calculates the position of the right matrix if two matrices are shown. + * + * @return + */ + private int calculateDualMatrixPositionRight() { + return (getWidth() * 3/4) - (calculateDualMatrixWidth() / 2) - (InterfaceConstants.matrixHgap() / 2); + } + + /** + * Calculates the width of a single matrix. + * + * @return + */ + + private int calculateSingleMatrixWidth() { + return calculateDualMatrixWidth(); + } + + /** + * Calculates the position of a single matrix centered to the screen. + * + * @return + */ + + private int calculateSingleMatrixPosition() { + return getWidth() / 2 - calculateSingleMatrixWidth() / 2; + } + + /** + * Calculates the position of a matrix moved outside of the left side of the window. + * + * @return + */ + private int calculateRightOuterPosition() { + return getWidth() + 10; + } + + /** + * Calculates the position of a matrix moved outside of the right side of the window. + * + * @return + */ + private int calculateLeftOuterPosition() { + return - calculateDualMatrixWidth(); + } + + /** + * Sets the position, width and the font of a matrix display. + * + * @return + */ + private void arrangeView(MatrixDisplay display, int x) + { + Rectangle rect = display.getBounds(); + + rect.x = x; + rect.y = calculateMatrixPositionTop(); + + rect.width = calculateDualMatrixWidth(); + rect.height = calculateMatrixDisplayHeight(); + + display.scaleTo(rect.width, rect.height); + display.setBounds(rect); + display.setFontForced(forcedFont); + } + + /** + * Arranges the left and the right matrix display that + * the left display is shown centered and the right matrix + * is placed on the right outer position. + * + */ + private void arrangeSingleViewLeft() { + arrangeView(leftDisplay, calculateSingleMatrixPosition()); + arrangeView(rightDisplay, calculateRightOuterPosition()); + } + + /** + * Arranges the left and the right matrix display that + * the right display is shown centered and the left matrix + * is placed on the left outer position. + * + */ + private void arrangeSingleViewRight() { + arrangeView(leftDisplay, calculateLeftOuterPosition()); + arrangeView(rightDisplay, calculateSingleMatrixPosition()); + + } + + /** + * Arranges the left and the right matrix display that + * the both displays are shown on their usual positions. + * + */ + private void arrangeDualView() { + arrangeView(leftDisplay, calculateDualMatrixPositionLeft()); + arrangeView(rightDisplay, calculateDualMatrixPositionRight()); + } + + /** + * Prepares any matrix display to show the content of a given + * matrix. + * + * @param component + * The affected matrix display + * @param matrix + * The content to show + */ + private void singleView(MatrixDisplay component, Matrix matrix) { + int matrixWidth, matrixHeight; + + matrixHeight = calculateMatrixHeight(); + matrixWidth = calculateSingleMatrixWidth(); + + component.setBounds((int)component.getBounds().getX(), (int)component.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + + //component.setFontForced(null); + component.setFontForced(forcedFont); + + component.updateMatrix(matrix); + + this.repaint(); + this.revalidate(); + } + + /** + * Prepares the left matrix display to shown the content of the given matrix. + * + * @param matrix + */ + private void singleViewLeft(Matrix matrix) { + singleView(leftDisplay, matrix); + } + + /** + * Prepares the right matrix display to shown the content of the given matrix. + * + * @param matrix + */ + private void singleViewRight(Matrix matrix) { + singleView(rightDisplay, matrix); + } + + /** + * Prepares the left and right matrix to show the content of the matrix "left" + * and "right. + * + * @param left + * @param right + */ + private void dualView(Matrix left, Matrix right) { + int matrixWidth, matrixHeight; + + matrixHeight = calculateMatrixHeight(); + matrixWidth = calculateDualMatrixWidth(); + + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + + leftDisplay.setBounds((int)leftDisplay.getBounds().getX(), (int)leftDisplay.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + rightDisplay.setBounds((int)rightDisplay.getBounds().getX(), (int)rightDisplay.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + + leftDisplay.setFontForced(null); + rightDisplay.setFontForced(null); + + leftDisplay.updateMatrix(left); + rightDisplay.updateMatrix(right); + + leftDisplay.setFontForced(forcedFont); + rightDisplay.setFontForced(forcedFont); + + leftDisplay.updateMatrix(left); + rightDisplay.updateMatrix(right); + + this.repaint(); + this.revalidate(); + } + + /** + * Prepares the left, the right and the temporary matrix to show + * the content of the given matrices. + * + * @param left + * @param right + * @param temp + */ + private void trippleView(Matrix left, Matrix right, Matrix temp) { + int matrixWidth, matrixHeight; + + matrixHeight = calculateMatrixHeight(); + matrixWidth = calculateDualMatrixWidth(); + + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + leftDisplay.setBounds((int)leftDisplay.getBounds().getX(), (int)leftDisplay.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + rightDisplay.setBounds((int)rightDisplay.getBounds().getX(), (int)rightDisplay.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + tempDisplay.setBounds((int)tempDisplay.getBounds().getX(), (int)tempDisplay.getBounds().getY(), matrixWidth, calculateMatrixDisplayHeight()); + + leftDisplay.setFontForced(null); + rightDisplay.setFontForced(null); + tempDisplay.setFontForced(null); + + leftDisplay.updateMatrix(left); + rightDisplay.updateMatrix(right); + tempDisplay.updateMatrix(temp); + + leftDisplay.setFontForced(forcedFont); + rightDisplay.setFontForced(forcedFont); + tempDisplay.setFontForced(forcedFont); + + leftDisplay.updateMatrix(left); + rightDisplay.updateMatrix(right); + tempDisplay.updateMatrix(temp); + + this.repaint(); + this.revalidate(); + } + + /** + * Cancels a running animation. + * + */ + private void cancelAnimations() { + if ((animator != null) && (!animator.isCanceled())) { + animator.cancelAnimation(); + } + } + + /** + * Animates the switch from any step to the first step. + * + * @param changer + */ + private void animateBackToStart(MatrixChanger changer) { + leftDisplay.removePathHighlighting(); + + animator = new MatrixMoveAnimator(changer); + animator.addAnimator(leftDisplay, 1, calculateSingleMatrixPosition()); + animator.addAnimator(rightDisplay, 1, calculateRightOuterPosition()); + + animator.startAnimation(); + } + + /** + * Animates the switch from the first step to the first + * group or atomic step. + * + * @param changer + */ + private void animateStartToStep(MatrixChanger changer) { + animator = new MatrixMoveAnimator(changer); + + animator.addAnimator(leftDisplay, -1, calculateDualMatrixPositionLeft()); + animator.addAnimator(rightDisplay, -1, calculateDualMatrixPositionRight()); + + animator.startAnimation(); + } + + /** + * Animates the switch to the last step. + * + * @param changer + */ + private void animateReachedEnd(MatrixChanger changer) { + animator = new MatrixMoveAnimator(changer); + + animator.addAnimator(leftDisplay, -1, calculateLeftOuterPosition()); + animator.addAnimator(rightDisplay, -1, calculateSingleMatrixPosition()); + + animator.startAnimation(); + } + + /** + * Animates the switch from the last step to a group step or an atomic step. + * + * @param changer + */ + private void animateEndToStep(MatrixChanger changer) { + animator = new MatrixMoveAnimator(changer); + + animator.addAnimator(leftDisplay, 1, calculateDualMatrixPositionLeft()); + animator.addAnimator(rightDisplay, 1, calculateDualMatrixPositionRight()); + + animator.startAnimation(); + } + + /** + * Animates the switch to the next group step from a group step or atomic step. + * + * @param changer + */ + private void animateGroupStepNext(MatrixChanger changer) { + animator = new MatrixMoveAnimator(changer); + + animator.addAnimator(leftDisplay, -1, calculateLeftOuterPosition()); + animator.addAnimator(rightDisplay,-1, calculateDualMatrixPositionLeft()); + animator.addAnimator(tempDisplay, -1, calculateDualMatrixPositionRight()); + + animator.startAnimation(); + } + + /** + * Animates the switch to the previous group step from a group step or atomic step. + * + * @param changer + */ + private void animateGroupStepPrev(MatrixChanger changer) { + animator = new MatrixMoveAnimator(changer); + + animator.addAnimator(leftDisplay, 1, calculateDualMatrixPositionRight()); + animator.addAnimator(rightDisplay, 1, calculateRightOuterPosition()); + animator.addAnimator(tempDisplay, 1, calculateDualMatrixPositionLeft()); + + animator.startAnimation(); + } + + /** + * Probes the best font for a matrix displayes in "matrix". + * + * @param matrix + * @return + */ + private Font probeFont(Matrix matrix) { + Font font; + + probeDisplay.scaleTo(calculateDualMatrixWidth(), calculateDualMatrixWidth()); + probeDisplay.setFontForced(null); + probeDisplay.updateMatrix(rootStep.getAfterMatrix()); + + font = probeDisplay.getCurrentFont(); + + if (font == null) + font = InterfaceConstants.getMatrixFont(beamerMode); + else + font = new Font(font.getName(), font.getStyle(), font.getSize()); + + return font; + } + + /** + * Probes the best font for the whole algorithm by testing the ideal font for + * the initial or the final matrix. + */ + private void probeForcedFont() { + Font start, end; + + if (rootStep == null) { + forcedFont = InterfaceConstants.getMatrixFont(beamerMode); + return; + } + + start = probeFont(rootStep.getBeforeMatrix()); + end = probeFont(rootStep.getAfterMatrix()); + + if (start.getSize() > end.getSize()) { + forcedFont = end; + } + else { + forcedFont = start; + } + } + + /** + * Entering the algorithm mode. + */ + public void enterHighlightMode(RootStep step) { + rootStep = step; + + arrangeSingleViewLeft(); + + probeForcedFont(); + } + + /** + * Leaving the algorithm mode. + */ + public void leaveHighlightMode() { + rootStep = null; + } + + public void highlightFirstStep(RootStep step) { + MatrixChanger changer; + ViewMode oldMode; + + if (!isVisible) + return; + + cancelAnimations(); + oldMode = viewMode; + changer = new StartChanger(); + changer.setStep(step); + + + if ((oldMode == ViewMode.GroupStepView) || (oldMode == ViewMode.AtomicStepView)) { + animateBackToStart(changer); + } + else { + changer.show(); + } + } + + public void highlightLastStep(RootStep step) { + MatrixChanger changer; + ViewMode oldMode; + + if (!isVisible) + return; + + cancelAnimations(); + oldMode = viewMode; + changer = new EndChanger(); + changer.setStep(step); + + if ((oldMode == ViewMode.GroupStepView) || (oldMode == ViewMode.AtomicStepView)) { + animateReachedEnd(changer); + } + else { + changer.show(); + } + } + + public void highlightAtomicStep(AtomicStep step, boolean isForward) { + MatrixChanger changer; + ViewMode oldMode; + boolean needUpdate; + + if (!isVisible) + return; + + cancelAnimations(); + + oldMode = viewMode; + needUpdate = (oldMode == ViewMode.StartView) || (oldMode == ViewMode.EndView) || (oldMode == ViewMode.GroupStepView) || (!isForward); + + changer = new AtomicStepChanger(needUpdate, isForward); + changer.setStep(step); + + if (oldMode == ViewMode.StartView) + animateStartToStep(changer); + else if (oldMode == ViewMode.EndView) + animateEndToStep(changer); + else { + // Reverse switch from group step to atomic step + if ( (isForward == false) + && (currentStep instanceof GroupStep) + ) + { + changer = new PrevGroupStepToAtomicChanger(); + changer.setStep(step); + + animateGroupStepPrev(changer); + } + else { + changer.show(); + } + } + } + + public void highlightGroupStep(GroupStep step, boolean isForward) { + MatrixChanger changer; + ViewMode oldMode = viewMode; + + if (!isVisible) + return; + + cancelAnimations(); + + if (isForward) + changer = new NextGroupStepChanger(); + else + changer = new PrevGroupStepChanger(); + + changer.setStep(step); + + if (oldMode == ViewMode.StartView) + animateStartToStep(changer); + else if (oldMode == ViewMode.EndView) + animateEndToStep(changer); + else if (isForward) + animateGroupStepNext(changer); + else { + // Reverse switch from atomic step to group step + if (currentStep instanceof AtomicStep) { + changer.show(); + } + else + animateGroupStepPrev(changer); + } + } + + /** + * Used to split up the display operations during an animation. + * + * + */ + private abstract class MatrixChanger { + /** + * Sets the step which will be shown after the animation. + * + * @param step + */ + public abstract void setStep(Step step); + + /** + * Processes all actions needed before the start of the animation. + * (Like placing the matrix display to the start positions of + * the animation or loading the right content). + * + * This function is usually called by the Animator object. + */ + public abstract void preAnimation(); + + /** + * Processes all actions needed to finish the animation + * (Like placing the matrix display to the final position after + * the animation and setting the correct highlights and matrix name) + * + * This function is usually called by the Animator object. + */ + public abstract void postAnimation(); + + /** + * Executes the pre- and post operations of the animation. This + * is needed if an action should be executed without any animation. + */ + public void show() { + preAnimation(); + postAnimation(); + } + } + + /** + * Used to setup the display of any group step. + * + */ + private abstract class GroupMatrixChanger extends MatrixChanger { + protected GroupStep step; + + public void setStep(Step step) { + this.step = (GroupStep)step; + } + } + + /** + * Used to setup the switching to an atomic step. + * + */ + private abstract class AtomicMatrixChanger extends MatrixChanger { + protected AtomicStep step; + + public void setStep(Step step) { + this.step = (AtomicStep)step; + } + } + + /** + * Used to show the switching to any group step + * + */ + private class GenericGroupStepChanger extends GroupMatrixChanger { + public void preAnimation() { + leftDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK() - 1); + rightDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK()); + } + + public void postAnimation() { + arrangeDualView(); + + leftDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK()); + rightDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK() + 1); + + currentStep = step; + viewMode = ViewMode.GroupStepView; + } + } + + /** + * Used to show a group step without switching. + * + */ + private class GroupStepChanger extends GenericGroupStepChanger { + } + + /** + * Used to setup the switching to the initial matrix. + * + */ + private class StartChanger extends GroupMatrixChanger { + public void preAnimation() { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(false); + singleViewLeft(step.getBeforeMatrix()); + + leftDisplay.setMatrixName(true, 0); + } + + public void postAnimation() { + arrangeSingleViewLeft(); + leftDisplay.setMatrixName(false, 0); + + currentStep = step; + viewMode = ViewMode.StartView; + } + } + + /** + * Used to setup the switching to the final matrix. + * + */ + private class EndChanger extends GroupMatrixChanger { + public void preAnimation() { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(false); + dualView(step.getBeforeMatrix(), step.getAfterMatrix()); + } + + public void postAnimation() { + arrangeSingleViewRight(); + leftDisplay.setMatrixName(false, 0); + rightDisplay.removeChangeHighlighting(); + + currentStep = step; + viewMode = ViewMode.EndView; + } + } + + /** + * Used to setup the switching to a next group step. + * + */ + private class NextGroupStepChanger extends GenericGroupStepChanger { + public void preAnimation() { + if (viewMode == ViewMode.EndView) { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + dualView(step.getBeforeMatrix(), step.getBeforeMatrix()); + } + else + { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + arrangeView(tempDisplay, calculateRightOuterPosition()); + trippleView(step.getBeforeMatrix(), step.getBeforeMatrix(), step.getBeforeMatrix()); + tempDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK() + 1); + } + + super.preAnimation(); + } + + public void postAnimation() { + if (viewMode != ViewMode.EndView) { + MatrixDisplay buffer; + + buffer = leftDisplay; + leftDisplay = rightDisplay; + rightDisplay = tempDisplay; + tempDisplay = buffer; + + tempDisplay.setVisible(false); + } + + super.postAnimation(); + } + } + + /** + * Used to setup the switching to a previous group step. + * + */ + private class PrevGroupStepChanger extends GenericGroupStepChanger { + public void preAnimation() { + if (viewMode == ViewMode.StartView) { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + dualView(step.getBeforeMatrix(), step.getBeforeMatrix()); + } + else + { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + arrangeView(tempDisplay, calculateLeftOuterPosition()); + trippleView(step.getBeforeMatrix(), step.getBeforeMatrix(), step.getBeforeMatrix()); + tempDisplay.setMatrixName(true, ((AtomicStep)step.getStep(0)).getK()); + } + + super.preAnimation(); + } + + public void postAnimation() { + if (viewMode != ViewMode.EndView) { + MatrixDisplay buffer; + + buffer = rightDisplay; + rightDisplay = leftDisplay; + leftDisplay = tempDisplay; + tempDisplay = buffer; + + tempDisplay.setVisible(false); + } + + super.postAnimation(); + } + } + + /** + * Used to setup an atomic step. + * + */ + private class AtomicStepChanger extends AtomicMatrixChanger { + private boolean needUpdate; + private boolean isForward; + + public AtomicStepChanger() { + this.needUpdate = true; + } + + public AtomicStepChanger(boolean needUpdate, boolean isForward) { + this.needUpdate = needUpdate; + this.isForward = isForward; + } + + public void preAnimation() { + if (needUpdate) + dualView(step.getGroupStep().getBeforeMatrix(), step.getAfterMatrix()); + else if ( (isForward && !(step.getGroupStep().getBeforeMatrix().getValueAt(step.getU(), step.getV()).equals(step.getAfterMatrix().getValueAt(step.getU(), step.getV())))) + || (!isForward && (step.getGroupStep().getBeforeMatrix().getValueAt(step.getU(), step.getV()).equals(step.getAfterMatrix().getValueAt(step.getU(), step.getV())))) + ) + { + rightDisplay.updateMatrix(step.getBeforeMatrix()); + rightDisplay.repaint(); + rightDisplay.revalidate(); + } + + + leftDisplay.setMatrixName(true, step.getK()); + rightDisplay.setMatrixName(true, step.getK() + 1); + } + + public void postAnimation() { + arrangeDualView(); + + leftDisplay.setPathHighlighting(step.getU(), step.getK(), step.getV()); + rightDisplay.setChangeHighlighting(step.getU(), step.getV()); + + currentStep = step; + viewMode = ViewMode.AtomicStepView; + } + } + + private class PrevGroupStepToAtomicChanger extends AtomicStepChanger { + public void preAnimation() { + leftDisplay.setVisible(true); + rightDisplay.setVisible(true); + tempDisplay.setVisible(true); + + arrangeView(tempDisplay, calculateLeftOuterPosition()); + trippleView(step.getGroupStep().getAfterMatrix(), step.getGroupStep().getAfterMatrix(), step.getGroupStep().getBeforeMatrix()); + tempDisplay.setMatrixName(true, step.getK()); + } + + public void postAnimation() { + AtomicStepChanger changer; + MatrixDisplay buffer; + + buffer = rightDisplay; + rightDisplay = leftDisplay; + leftDisplay = tempDisplay; + tempDisplay = buffer; + + tempDisplay.setVisible(false); + + super.postAnimation(); + } + } + + /** + * Used for generic animation tasks. + * + */ + private abstract class Animator extends TimerTask { + private Timer localTimer; + private boolean canceled; + private MatrixChanger changer; + + /** + * Initializes an animation object. + * + * @param changer + * A MatrixChanger object which contains callback + * functions which should be called before and after + * the animation. + * + */ + public Animator(MatrixChanger changer) { + this.changer = changer; + this.canceled = false; + } + + public boolean isCanceled() { + return this.canceled; + } + + public void startAnimation() { + changer.preAnimation(); + + localTimer = new Timer(); + + localTimer.schedule(this, 0, 4); + } + + public void cancelAnimation() { + if (canceled) + return; + + localTimer.cancel(); + localTimer.purge(); + + canceled = true; + + if (changer != null) + changer.postAnimation(); + } + } + + private class MatrixMoveAnimator extends Animator { + private List tasks; + + private class AnimationTask { + MatrixDisplay display; + float step; + int dest; + + public AnimationTask(MatrixDisplay display, float step, int dest) { + this.display = display; + this.step = step; + this.dest = dest; + } + } + + private float calculateAnimationStep() { + return getWidth() / 100; + } + + public MatrixMoveAnimator(MatrixChanger changer) { + super(changer); + + tasks = new ArrayList(); + } + + /** + * Adds an animation task to the animator. + * + * @param component + * The component which should be animated + * + * @param step + * The step which should be shown after the animation + * + * @param destX + * The destination coordinates of the animation + * + */ + public void addAnimator(MatrixDisplay component, float step, int destX) + { + tasks.add(new AnimationTask(component, step, destX)); + } + + /** + * Executes all move actions of one particular animation task. + * + * @param task + * @return + */ + private boolean moveTask(AnimationTask task) { + Rectangle rect = task.display.getBounds(); + float step; + + step = task.step * calculateAnimationStep(); + + if ( ((rect.x + step >= task.dest) && (task.step > 0)) + || ((rect.x + step <= task.dest) && (task.step < 0)) + ) + return true; + + rect.x += step; + + task.display.setBounds(rect); + + return false; + } + + /** + * Does one animation step of all animation tasks. + * + */ + @Override + public void run() { + boolean allTerminated = true; + + for (AnimationTask task : tasks) { + allTerminated &= moveTask(task); + } + + if (allTerminated) + cancelAnimation(); + + repaint(); + revalidate(); + } + } + + private class MatrixComponentListener implements ComponentListener { + + public void componentHidden(ComponentEvent arg0) { + componentResized(arg0); + } + + public void componentMoved(ComponentEvent arg0) { + componentResized(arg0); + } + + public void componentResized(ComponentEvent event) { + if (!isVisible) + return; + + probeForcedFont(); + + switch (viewMode) { + case StartView : + arrangeSingleViewLeft(); + + break; + + case EndView : + arrangeSingleViewRight(); + + break; + + case GroupStepView : + arrangeDualView(); + + break; + + case AtomicStepView : + arrangeDualView(); + + break; + + } + + leftDisplay.redrawCurrentMatrix(); + rightDisplay.redrawCurrentMatrix(); + tempDisplay.redrawCurrentMatrix(); + + repaint(); + revalidate(); + } + + public void componentShown(ComponentEvent arg0) { + componentResized(arg0); + } + } +} diff --git a/src/org/jalgo/module/app/view/run/MatrixDisplay.java b/src/org/jalgo/module/app/view/run/MatrixDisplay.java new file mode 100644 index 0000000..c5b3c5f --- /dev/null +++ b/src/org/jalgo/module/app/view/run/MatrixDisplay.java @@ -0,0 +1,972 @@ +package org.jalgo.module.app.view.run; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.font.FontRenderContext; +import java.awt.geom.AffineTransform; +import java.awt.geom.GeneralPath; +import java.awt.geom.Rectangle2D; +import java.awt.geom.RoundRectangle2D; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.module.app.core.Matrix; +import org.jalgo.module.app.view.InterfaceConstants; +import org.jalgo.module.app.view.graph.HighlightState; + +public class MatrixDisplay extends JPanel { + + private static final long serialVersionUID = 5100649092337883024L; + + private GridBagLayout matrixLayout; + + private JPanel matrixPanel; + + private ParenthesisDisplay openingParenthesis; + private ParenthesisDisplay closingParenthesis; + + private MatrixLabel[][] labels; + private int matrixSize; + + private boolean isOpaque; + + private int highlightedStart, highlightedInner, highlightedEnd; + + private int scaleHeight, scaleWidth; + + private Font defaultFont; + private Font currentFont; + private Graphics2D matrixGraphics; + private FontRenderContext renderContext; + + private Matrix currentMatrix; + private int[][] cellStates; + private int[] colSizes; + private int totalFreeSpace; + + private MatrixNamePanel matrixNamePanel; + + private boolean fontForced; + + private boolean beamerMode; + + private class CellDescriptor implements Comparable { + public int row, col, cellWidth; + + public CellDescriptor(int col, int row, int cellWidth) { + this.row = row; + this.col = col; + this.cellWidth = cellWidth; + } + + public int compareTo(CellDescriptor o) { + CellDescriptor other; + + if ((o == null) || (!(o instanceof CellDescriptor))) + throw new IllegalArgumentException(); + + other = (CellDescriptor)o; + + return cellWidth - other.cellWidth; + } + } + + /** + * A panel to display a n x n Matrix (incl. parenthesis). Elements of a + * matrix can be highlighted (change in font style or in background color), + * if needed. + * + * @param isOpaque + * if true, set background non-transparent; if + * false, set background transparent. + */ + public MatrixDisplay(boolean isOpaque) { + this.beamerMode = false; + + GridBagConstraints constr = new GridBagConstraints(); + + matrixLayout = new GridBagLayout(); + + highlightedStart = -1; + highlightedInner = -1; + highlightedEnd = -1; + + renderContext = new FontRenderContext(new AffineTransform(), true, false); + + openingParenthesis = new ParenthesisDisplay(true); + closingParenthesis = new ParenthesisDisplay(false); + + matrixPanel = new JPanel(); + matrixPanel.setLayout(matrixLayout); + + matrixNamePanel = new MatrixNamePanel(); + + this.setLayout(new GridBagLayout()); + + constr.gridy = 0; + constr.gridheight = 1; + constr.gridwidth = 1; + constr.fill = GridBagConstraints.REMAINDER; + constr.ipady = InterfaceConstants.matrixVgap(); + constr.ipadx = 0; //InterfaceConstants.matrixHgap(); + + constr.gridx = 0; + this.add(openingParenthesis, constr); + + constr.gridx = 1; + constr.fill = GridBagConstraints.CENTER; + this.add(matrixPanel, constr); + + constr.gridx = 2; + constr.fill = GridBagConstraints.REMAINDER; + this.add(closingParenthesis, constr); + + constr.gridx = 1; + constr.gridy = 1; + constr.fill = GridBagConstraints.CENTER; + this.add(matrixNamePanel, constr); + + this.isOpaque = isOpaque; + + if (isOpaque) { + this.setBackground(InterfaceConstants.formulaBackgroundColor()); + + matrixPanel.setBackground(InterfaceConstants.formulaBackgroundColor()); + openingParenthesis.setBackground(InterfaceConstants.formulaBackgroundColor()); + closingParenthesis.setBackground(InterfaceConstants.formulaBackgroundColor()); + } + + } + + /** + * Forces the matrix to display a certain font + * + * @param font + */ + public void setFontForced(Font font) { + if ((font == null) || (matrixGraphics == null)) + fontForced = false; + else { + fontForced = true; + currentFont = font; + } + } + + /** + * Returns the font currently used by the matrix + * + */ + public Font getCurrentFont() { + return currentFont; + } + + /** + * Sets the labeling of the matrix + * + * @param isDistance + * True, if matrix is a distance matrix (paints a DG instead of a AG) + * @param k + * The index of the distance matrix + * + */ + public void setMatrixName(boolean isDistance, int k) { + matrixNamePanel.setMatrixName(isDistance, k); + } + + /** + * Hides the labeling of the matrix + */ + public void hideMatrixName() { + matrixNamePanel.hideMatrixName(); + } + + /** + * Toggles the beamer mode. + * + * @param beamerMode + */ + public void updateBeamerMode(boolean beamerMode){ + this.beamerMode = beamerMode; + prepareGraphics(); + repaint(); + revalidate(); + } + + /* + * Perpares the graphics context and the display font of + * the current matrix. + */ + private void prepareGraphics() { + matrixGraphics = (Graphics2D)this.getGraphics(); + + defaultFont = InterfaceConstants.getMatrixFont(beamerMode); + + if (!fontForced) { + currentFont = InterfaceConstants.getMatrixFont(beamerMode); + } + } + + /** + * Defines the maximum bounds of a matrix + * + * @param width + * @param height + */ + public void scaleTo(int width, int height) { + scaleWidth = width; + scaleHeight = height - (InterfaceConstants.formulaNormalFont(beamerMode).getSize() * 2); + } + + private Rectangle2D getCellMetrics(int col, int row, Matrix matrix, Font font) { + return font.getStringBounds(matrix.getValueAt(row, col).toString(), renderContext); + } + + /** + * Calculates the average width of a column of + * a given matrix according to the given scaleWidth. + * of the display widget. The horizontal gap of each + * column will be subtracted of the average width. + * + * @param matrix + * The given matrix. + * + */ + private int getAverageColWidth(Font font) { + int matrixWidth, avgWidth, minimumFontWidth, minimumColWidth; + + matrixWidth = scaleWidth - (2 * InterfaceConstants.matrixHgap()); + avgWidth = (matrixWidth / matrixSize) - (1 * InterfaceConstants.matrixHgap()); + minimumFontWidth = (int)font.getStringBounds("...", renderContext).getWidth(); + minimumColWidth = InterfaceConstants.matrixHgap() + minimumFontWidth; + + // At least a row has to contain the text "..." + if (avgWidth < minimumColWidth) + avgWidth = 0; //minimumColWidth; + + return avgWidth; + } + + /** + * Returns the height of the matrix if using a default font. + * + */ + private int getMatrixHeight() { + return (InterfaceConstants.getMatrixFont(beamerMode).getSize() * matrixSize) + + (InterfaceConstants.matrixVgap() * (matrixSize + 2)) + ; + } + + /** + * Calculates the size of each column in the matrix based on the current font. + * If a label is too big for a column, it will be shortened to "..." + * + * The function will store the information about all shortened fields to + * the private member "cellStates" and the size of each column to "colSizes". + * The remaining space in the current matrix will be stored to "totalFreeSpace". + * + */ + private int calculateDeactivatedFields() { + ArrayList tooLongList; + int avgColWidth; + int freeSpace[]; + int elipseWidth; + int countDeactivated; + + // Prepare data structures + countDeactivated = 0; + tooLongList = new ArrayList(); + + // Try to find a usable font size + avgColWidth = 0; + + while (avgColWidth == 0) { + avgColWidth = getAverageColWidth(currentFont); + + if (currentFont.getSize() - 1 < InterfaceConstants.getMatrixMinimumFontSize(beamerMode)) + break; + + if (avgColWidth == 0) { + currentFont = new Font(defaultFont.getName(), defaultFont.getStyle(), currentFont.getSize() - 1); + } + } + + + elipseWidth = (int)currentFont.getStringBounds("...", renderContext).getWidth(); + + cellStates = new int[matrixSize][matrixSize]; + colSizes = new int[matrixSize]; + freeSpace = new int[matrixSize]; + + // Initialize + Arrays.fill(colSizes, avgColWidth); + Arrays.fill(freeSpace, avgColWidth); + + totalFreeSpace = avgColWidth * matrixSize; + + for (int row = 0; row < matrixSize; row ++) { + if (avgColWidth > 0) + Arrays.fill(cellStates[row], 0); + else + Arrays.fill(cellStates[row], -1); + } + + if (avgColWidth == 0) + return matrixSize * matrixSize; + + // Remove elements which are too long + for (int col = 0; col < matrixSize; col ++) { + int biggest = elipseWidth; + + for (int row = 0; row < matrixSize; row ++) { + int cellMetrics = (int)getCellMetrics(col, row, currentMatrix, currentFont).getWidth(); + + if (cellMetrics >= colSizes[col]) { + // Element too long, disable and remember it... + CellDescriptor descriptor; + + cellStates[col][row] = -1; + + descriptor = new CellDescriptor(col, row, cellMetrics); + + tooLongList.add(descriptor); + + cellMetrics = elipseWidth; + + countDeactivated ++; + } + + // Element fits (now) into column, just set free space + if (cellMetrics >= biggest) { + biggest = cellMetrics; + } + } + + colSizes[col] = biggest; + totalFreeSpace -= biggest; + } + + Collections.sort(tooLongList); + + // Re-enable deactivated fields, if possible + for (CellDescriptor cell : tooLongList) { + int need; + + need = cell.cellWidth - colSizes[cell.col]; + + if (need <= 0) { + cellStates[cell.col][cell.row] = 0; + countDeactivated --; + } else if (need <= totalFreeSpace) { + totalFreeSpace -= need; + cellStates[cell.col][cell.row] = 0; + colSizes[cell.col] += need; + countDeactivated --; + } + } + + return countDeactivated; + } + + /** + * Calculates the size of the font based on the scaling width + * of the matrix. It also determines whether a field is shown or not + * by calling calculateDeactivatedFields() + * + */ + private void calculateColumnSizes() { + float scaleFactor; + int deactivatedFields, tmpFields, tmpSize; + + // Is there a forced font size? + if (fontForced == true) { + calculateDeactivatedFields(); + return; + } + + // Scale matrix font to fit the window + scaleFactor = (scaleHeight / getMatrixHeight()); + + if (scaleFactor < 1) + scaleFactor = 1; + + if ((defaultFont.getSize() * scaleFactor) > InterfaceConstants.getMatrixMaximumFontSize(beamerMode)) + scaleFactor = InterfaceConstants.getMatrixMaximumFontSize(beamerMode) / defaultFont.getSize(); + + currentFont = new Font(defaultFont.getName(), defaultFont.getStyle(), (int)(defaultFont.getSize() /* * scaleFactor */)); + + deactivatedFields = calculateDeactivatedFields(); + tmpFields = deactivatedFields; + + // Scale down unless we have minimized the count of deactivated fields + while( (deactivatedFields > 0) + && (currentFont.getSize() > InterfaceConstants.getMatrixFont(beamerMode).getSize()) + ) + { + currentFont = new Font(defaultFont.getName(), defaultFont.getStyle(), currentFont.getSize() - 1); + + deactivatedFields = calculateDeactivatedFields(); + } + + // It is still bad after decreasing the font size + /*if (tmpFields == deactivatedFields) + return;*/ + + // To maximize font width, scale up unless the count of deactivated fields doesn't increase + tmpFields = 10000; + tmpSize = currentFont.getSize() - 1; + + while((tmpFields > deactivatedFields) && (currentFont.getSize() < InterfaceConstants.getMatrixMaximumFontSize(beamerMode)) && (tmpSize < currentFont.getSize())) { + tmpSize = currentFont.getSize(); + + currentFont = new Font(defaultFont.getName(), defaultFont.getStyle(), currentFont.getSize() + 1); + + deactivatedFields = calculateDeactivatedFields(); + } + + // Recalculate font + currentFont = new Font(defaultFont.getName(), defaultFont.getStyle(), tmpSize); + + deactivatedFields = calculateDeactivatedFields(); + } + + public void redrawCurrentMatrix() { + GridBagConstraints constr = new GridBagConstraints(); + boolean keepLabels = true; + + if ((scaleWidth == 0) || (currentMatrix == null) || (currentMatrix.getSize() < 2)) { + openingParenthesis.setVisible(false); + closingParenthesis.setVisible(false); + + return; + } + + prepareGraphics(); + + matrixPanel.removeAll(); + + if (matrixSize != currentMatrix.getSize()) { + keepLabels = false; + + matrixSize = currentMatrix.getSize(); + labels = new MatrixLabel[matrixSize][matrixSize]; + } + + openingParenthesis.setVisible(true); + closingParenthesis.setVisible(true); + + calculateColumnSizes(); + + for (int row = 0; row < currentMatrix.getSize(); row++) { + for (int col = 0; col < currentMatrix.getSize(); col++) { + String value; + MatrixLabel l; + + value = currentMatrix.getValueAt(row, col).toString(); + if (!keepLabels) { + l = new MatrixLabel(); + labels[row][col] = l; + } + else { + l = labels[row][col]; + } + + l.setHorizontalAlignment(JLabel.CENTER); + l.setVerticalAlignment(JLabel.CENTER); + l.setFont(currentFont); + l.setForeground(InterfaceConstants.getMatrixColor()); + setLabelColorByState(row, col, HighlightState.NONE); + l.setOpaque(isOpaque); + + l.setToolTipText(value); + + if (cellStates[col][row] == -1) + l.setText("..."); + else + l.setText(value); + + constr.gridx = col; + constr.gridy = row; + constr.gridheight = 1; + constr.gridwidth = 1; + constr.fill = GridBagConstraints.REMAINDER; + constr.ipady = InterfaceConstants.matrixVgap(); + constr.ipadx = InterfaceConstants.matrixHgap(); + + matrixPanel.add(l, constr); + + Graphics2D g = (Graphics2D) l.getGraphics(); + if (g != null) + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + } + } + + Dimension matrixLayoutDimension = matrixLayout + .minimumLayoutSize(matrixPanel); + Dimension parenthesisDimension = new Dimension(11, + (int) matrixLayoutDimension.getHeight() + 5); + + openingParenthesis.setMinimumSize(parenthesisDimension); + openingParenthesis.setPreferredSize(parenthesisDimension); + openingParenthesis.setMaximumSize(parenthesisDimension); + + closingParenthesis.setMinimumSize(parenthesisDimension); + closingParenthesis.setPreferredSize(parenthesisDimension); + closingParenthesis.setMaximumSize(parenthesisDimension); + + matrixPanel.setMinimumSize(matrixLayoutDimension); + matrixPanel.setPreferredSize(matrixLayoutDimension); + matrixPanel.setMaximumSize(matrixLayoutDimension); + } + + /** + * Updates every element of the matrix, including its highlighting and its + * opaque state and renders it into the panel. + * + * @param matrix + * the given matrix + */ + public void updateMatrix(Matrix matrix) { + if ((scaleWidth == 0) || (matrix == null) || (matrix.getSize() < 2)) { + openingParenthesis.setVisible(false); + closingParenthesis.setVisible(false); + + return; + } + + currentMatrix = matrix; + redrawCurrentMatrix(); + } + + /** + * Sets the color of a matrix element to the color given by its state. + * + * @param x + * the column + * @param y + * the row + * @param state + * the state the element is currently in. + */ + private void setLabelColorByState(int row, int col, HighlightState state) { + labels[row][col].setBackground(InterfaceConstants.matrixBackgroundColorForHighlightState(state)); + labels[row][col].setForeground(InterfaceConstants.matrixForegroundColorForHighlightState(state)); + } + + /** + * Removes the highlighting of the start element, inner element and the end + * element of the path. + */ + public void removePathHighlighting() { + if ((highlightedStart == -1) || (highlightedEnd == -1) || (highlightedInner == -1)) { + return; + } + + setLabelColorByState(highlightedStart, highlightedInner, HighlightState.NONE); + setLabelColorByState(highlightedInner, highlightedInner, HighlightState.NONE); + setLabelColorByState(highlightedInner, highlightedEnd, HighlightState.NONE); + } + + /** + * Sets the highlighting of the matrix elements according to their + * HighlightState in the following painting order:
      + * 1. (start,inner)
      + * 2. (inner,end)
      + * 3. (inner, inner) (the topmost coloring)
      + * + * @param start + * the start coordinate + * @param inner + * the inner coordinate + * @param end + * the end coordinate + */ + public void setPathHighlighting(int start, int inner, int end) { + + removePathHighlighting(); + + if ( (start > matrixSize) || (end > matrixSize) || (inner > matrixSize) + || (start < 0) || (end < 0) || (inner < 0) + ) + { + throw new IllegalArgumentException(); + } + + highlightedStart = start; + highlightedInner = inner; + highlightedEnd = end; + + setLabelColorByState(highlightedStart, highlightedInner, HighlightState.PRE_PATH); + setLabelColorByState(highlightedInner, highlightedEnd, HighlightState.POST_PATH); + + // Enforce the color of the current element + setLabelColorByState(highlightedInner, highlightedInner, HighlightState.CURRENT); + } + + /** + * Removes the highlighting of all labels in the matrix + */ + public void removeChangeHighlighting() { + for (int row = 0; row < matrixSize; row ++) { + for (int col = 0; col < matrixSize; col ++) { + labels[col][row].setBackground(InterfaceConstants.matrixBackgroundColorForHighlightState(HighlightState.NONE)); + labels[col][row].setForeground(InterfaceConstants.matrixForegroundColorForHighlightState(HighlightState.NONE)); + } + } + + } + + /** + * Sets the matrix coloring for a whole matrix. All elements up to (endRow,endCol) + * are already processed, the (endRow,endCol) is the + * current element and the ones after it still need to be processed (and are + * therefore unchanged) in the algorithm. + * + * @param endRow + * the row of the current element + * @param endCol + * the column of the current element + */ + public void setChangeHighlighting(int endRow, int endCol) { + for (int row = 0; row < matrixSize; row ++) { + for (int col = 0; col < matrixSize; col ++) { + if ((row > endRow) || ((row == endRow) && (col > endCol))) { + labels[row][col].setBackground(InterfaceConstants.unchangedMatrixEntryBackgroundColor()); + labels[row][col].setForeground(InterfaceConstants.unchangedMatrixEntryForegroundColor()); + } + else if (row == endRow && col == endCol) { + labels[row][col].setBackground(InterfaceConstants.currentMatrixEntryBackgroundColor()); + labels[row][col].setForeground(InterfaceConstants.currentMatrixEntryForegroundColor()); + } + else { + labels[row][col].setBackground(InterfaceConstants.changedMatrixEntryBackgroundColor()); + labels[row][col].setForeground(InterfaceConstants.changedMatrixEntryForegroundColor()); + } + } + } + } + + /** + * A panel for displaying a parenthesis which can either be on the left or + * on the right side of a matrix. + */ + private class ParenthesisDisplay extends JPanel { + + private static final long serialVersionUID = -8294840496607673029L; + + private boolean isOpeningParenthesis; + + public ParenthesisDisplay(boolean isOpeningParenthesis) { + this.isOpeningParenthesis = isOpeningParenthesis; + } + + private GeneralPath createArc(float height) { + GeneralPath arc = new GeneralPath(); + float arcScale, leftOuter, leftInner; + + if (height < 60) { + arcScale = (height / 2) / 30.f; + leftOuter = 10 - 7 * arcScale; + leftInner = 11 - 6 * arcScale; + } else { + arcScale = 1; + leftOuter = 0; + leftInner = 2; + } + + // Outer Shape + arc.moveTo(10, 0); + arc.curveTo(leftOuter, 10 * arcScale, leftOuter, 30 * arcScale, + leftOuter, 40 * arcScale); + arc.lineTo(leftOuter, height - 40 * arcScale); + arc.curveTo(leftOuter, height - 30 * arcScale, leftOuter, height + - 10 * arcScale, 10, height); + + arc.lineTo(11, height); + arc.curveTo(leftInner, height - 10 * arcScale, leftInner, height + - 30 * arcScale, leftInner, height - 40 * arcScale); + arc.lineTo(leftInner, 40 * arcScale); + arc.curveTo(leftInner, 30 * arcScale, leftInner, 10 * arcScale, 11, + 0); + + arc.closePath(); + + return arc; + } + + public void paint(Graphics output) { + Graphics2D g; + GeneralPath path; + AffineTransform trans; + + // Setup + g = (Graphics2D) output; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + // Draw background + g.setColor(this.getBackground()); + g.fill(this.getBounds()); + + // + g.setColor(Color.BLACK); + g.setStroke(new BasicStroke(10)); + + path = createArc(this.getHeight()); + + if (isOpeningParenthesis) { + trans = AffineTransform.getScaleInstance(1, 1); + trans.translate(0, 0); + } else { + trans = AffineTransform.getScaleInstance(-1, 1); + trans.translate(-this.getWidth(), 0); + } + + path.transform(trans); + + g.fill(path); + + } + } + + /** + * A single element of a matrix as a JLabel. + */ + private class MatrixLabel extends JLabel { + private static final long serialVersionUID = 1456853217007624321L; + public boolean isOpaque; + public Color backgroundColor; + + public MatrixLabel() { + super(); + + super.setOpaque(false); + + isOpaque = false; + backgroundColor = super.getBackground(); + } + + /** + * Returns whether the matrix label paints its own background or not. + * + * @return + */ + public boolean getOpaque() { + return isOpaque; + } + + /** + * Toggles whether the matrix label paints its own background or not. + * + * @param opaque + */ + public void setOpaque(boolean opaque) { + this.isOpaque = opaque; + } + + public Color getBackground() { + return backgroundColor; + } + + public void setBackground(Color color) { + if (color == null) + setOpaque(false); + + backgroundColor = color; + } + + public void paint(Graphics graphics) { + Graphics2D graph; + RoundRectangle2D box; + float width, height; + + graph = (Graphics2D)graphics; + graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON + ); + + if (isOpaque) { + width = (float)getBounds().getWidth(); + height = (float)getBounds().getHeight(); + + box = new RoundRectangle2D.Float(0, + 0, + width , + height , + 8f, + 8f + ); + + // Draw background + graph.setColor(this.getBackground()); + graph.fill(box); + } + + super.paint(graphics); + } + } + + private class MatrixNamePanel extends JPanel { + /** + * + */ + private static final long serialVersionUID = 1L; + private boolean isDistance, doPainting; + private int currentMatrix; + private Font normalFont, smallFont; + private FontMetrics normalMetrics, smallMetrics; + private Graphics2D graphics; + private FontRenderContext renderContext; + + public MatrixNamePanel() { + super(); + + normalFont = InterfaceConstants.formulaWindowNormalFont(beamerMode); + smallFont = InterfaceConstants.formulaWindowSmallFont(beamerMode); + + renderContext = new FontRenderContext(new AffineTransform(), true, false); + } + + private void defineSize() { + Dimension dimension = new Dimension(normalFont.getSize() * 3, calculateHeight()); + + this.setMinimumSize(dimension); + this.setPreferredSize(dimension); + this.setMaximumSize(dimension); + } + + public void setMatrixName(boolean isDistance, int k) { + this.isDistance = isDistance; + this.doPainting = true; + currentMatrix = k; + + defineSize(); + } + + public void hideMatrixName() { + this.doPainting = false; + + defineSize(); + } + + private int paintString(String string, Font font, int offsetX, int offsetY) { + graphics.setFont(font); + + graphics.drawString(string, offsetX, offsetY); + return offsetX + (int)graphics.getFontMetrics(font).getStringBounds(string, graphics).getWidth(); + } + + private int paintStringNormal(String string, int offsetX, int offsetY) { + return paintString(string, normalFont, offsetX, offsetY); + } + + private int paintStringSmall(String string, int offsetX, int offsetY) { + return paintString(string, smallFont, offsetX, offsetY); + } + + /** + * Paints $D_G^{(superscript)} $ (LaTeX Math style) + * + * @param metrics + * the used metrics for the string + * @param superscript + * @return the new x offset + */ + private int paintDistanceSymbol(String symbol, int superscript) { + int fontHeight, offsetX, offsetY; + int superscriptOffset, subscriptOffset; + + fontHeight = normalFont.getSize(); + + // Paint "D" + offsetY = fontHeight; + offsetX = getWidth()/2 - calculateWidth() /2; + + graphics.setFont(normalFont); + offsetX = paintStringNormal(symbol, offsetX, offsetY + fontHeight/2); + + superscriptOffset = 0; + + if (superscript > -1) { + // Paint (k) + superscriptOffset = paintStringSmall("("+superscript+")", offsetX, offsetY); + } + + // Paint G + subscriptOffset = paintStringSmall("G", offsetX, offsetY + fontHeight); + + return offsetX + Math.max(subscriptOffset, superscriptOffset); + } + + private int calculateHeight() { + return (normalFont.getSize() * 2) + smallFont.getSize(); + } + + private int calculateWidth() { + int superscriptWidth; + String symbol; + + if ((normalMetrics == null) || (smallMetrics == null)) + return 0; + + if (isDistance) { + symbol = "D"; + superscriptWidth = (int)smallFont.getStringBounds("("+currentMatrix+")", renderContext).getWidth(); + } + else { + symbol = "A"; + superscriptWidth = 0; + } + + return (int)normalFont.getStringBounds(symbol, renderContext).getWidth() + + Math.max( + superscriptWidth, + (int)smallFont.getStringBounds("G", renderContext).getWidth() + ); + } + + public void paint(Graphics g) { + // Setup + this.graphics = (Graphics2D)g; + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + super.paint(g); + + if (isOpaque) { + // Draw background + graphics.setColor(InterfaceConstants.formulaBackgroundColor()); + graphics.fill(new Rectangle(this.getSize())); + } + + if (!doPainting) + return; + + normalFont = InterfaceConstants.formulaWindowNormalFont(beamerMode); + smallFont = InterfaceConstants.formulaWindowSmallFont(beamerMode); + + normalMetrics = graphics.getFontMetrics(normalFont); + smallMetrics = graphics.getFontMetrics(smallFont); + + graphics.setColor(InterfaceConstants.formulaForegroundColor()); + graphics.setStroke(new BasicStroke(1)); + + if (isDistance) + paintDistanceSymbol("D", currentMatrix); + else + paintDistanceSymbol("A", -1); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/app/view/run/MatrixPreviewComponent.java b/src/org/jalgo/module/app/view/run/MatrixPreviewComponent.java new file mode 100644 index 0000000..7de3518 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/MatrixPreviewComponent.java @@ -0,0 +1,97 @@ +package org.jalgo.module.app.view.run; + +import java.awt.Dimension; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JPanel; + +import org.jalgo.module.app.controller.*; +import org.jalgo.module.app.core.graph.*; + +/** + * Displays the adjacency matrix during the Graph Editing mode. + * + */ +public class MatrixPreviewComponent extends JPanel implements GraphObserver { + + private static final long serialVersionUID = -8497615664297725862L; + private GraphController controller; + + private MatrixDisplay display; + private boolean beamerMode; + + public MatrixPreviewComponent(GraphController controller) { + display = new MatrixDisplay(false); + + this.controller = controller; + controller.addGraphObserver(this); + + display.addComponentListener(new MatrixComponentListener()); + + display.hideMatrixName(); + + this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + this.add(Box.createRigidArea(new Dimension(10,10))); + this.add(display); + this.add(Box.createRigidArea(new Dimension(10,10))); + } + + public void nodeAdded(Graph graph, Node node) { + } + + public void nodeAltered(Graph graph, Node node) { + } + + public void nodeRemoved(Graph graph, Node node) { + } + + public void edgeAdded(Graph graph, Edge edge) { + } + + public void edgeAltered(Graph graph, Edge edge) { + } + + public void edgeRemoved(Graph graph, Edge edge) { + } + + public void graphUpdated() { + display.updateMatrix(controller.getInitialMatrix()); + display.repaint(); + display.revalidate(); + } + + public void updateBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + display.updateBeamerMode(beamerMode); + repaint(); + revalidate(); + } + + public void graphSelectionChanged() { + } + + private class MatrixComponentListener implements ComponentListener { + + public void componentHidden(ComponentEvent arg0) { + componentResized(arg0); + } + + public void componentMoved(ComponentEvent arg0) { + componentResized(arg0); + } + + public void componentResized(ComponentEvent event) { + if (display.getHeight() != display.getWidth()) { + display.scaleTo(getWidth(), getWidth()); + graphUpdated(); + } + } + + public void componentShown(ComponentEvent arg0) { + componentResized(arg0); + } + } +} diff --git a/src/org/jalgo/module/app/view/run/StepHighlighting.java b/src/org/jalgo/module/app/view/run/StepHighlighting.java new file mode 100644 index 0000000..5cf37a4 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/StepHighlighting.java @@ -0,0 +1,62 @@ +package org.jalgo.module.app.view.run; + +import org.jalgo.module.app.core.step.AtomicStep; +import org.jalgo.module.app.core.step.GroupStep; +import org.jalgo.module.app.core.step.RootStep; + +/** + * An interface used for notifying the matrices and the formula (in the + * algorithm panel) upon changing the Step. + * + */ +public interface StepHighlighting { + + /** + * Notifies components about entering the algorithm view + * + * @param rootStep + * the root step of the calculation process + */ + public void enterHighlightMode(RootStep rootStep); + + /** + * Notifies components about leaving the view + */ + public void leaveHighlightMode(); + + /** + * Notifies components (step observers) upon the first step. + * + * @param step + * the current GroupStep. + */ + public void highlightFirstStep(RootStep step); + + /** + * Notifies components (step observers) upon the last step. + * + * @param step + * the current GroupStep. + */ + public void highlightLastStep(RootStep step); + + /** + * Notifies components (step observers) upon group step change. + * + * @param step + * the current GroupStep. + * isForward + * the next step was selected + */ + public void highlightGroupStep(GroupStep step, boolean isForward); + + /** + * Notifies components (step observers) upon atomic step change. + * + * @param step + * the current AtomicStep. + * isForward + * the next step was selected + */ + public void highlightAtomicStep(AtomicStep step, boolean isForward); +} diff --git a/src/org/jalgo/module/app/view/run/package.html b/src/org/jalgo/module/app/view/run/package.html new file mode 100644 index 0000000..edb0056 --- /dev/null +++ b/src/org/jalgo/module/app/view/run/package.html @@ -0,0 +1,10 @@ + + + + + + +The right hand side of the interface. The illustration of the matrixes and the calculation steps. + + + \ No newline at end of file diff --git a/src/org/jalgo/module/avl/.cvsignore b/src/org/jalgo/module/avl/.cvsignore new file mode 100644 index 0000000..650b404 --- /dev/null +++ b/src/org/jalgo/module/avl/.cvsignore @@ -0,0 +1 @@ +GUISim.java diff --git a/src/org/jalgo/module/avl/CVS/Entries b/src/org/jalgo/module/avl/CVS/Entries new file mode 100644 index 0000000..63d9a7b --- /dev/null +++ b/src/org/jalgo/module/avl/CVS/Entries @@ -0,0 +1,12 @@ +/.cvsignore/1.1/Thu Jun 23 10:08:27 2005// +/Constants.java/1.4/Thu Jan 31 20:15:06 2008// +/Controller.java/1.8/Thu Jan 31 20:15:06 2008// +/ModuleConnector.java/1.10/Thu Jan 31 20:15:06 2008// +/ModuleInfo.java/1.7/Thu Jan 31 20:15:03 2008// +/NoActionException.java/1.6/Thu Jan 31 20:15:06 2008// +D/algorithm//// +D/datastructure//// +/de.properties/1.3/Tue Feb 19 00:14:07 2008// +/en.properties/1.2/Sat Mar 4 13:36:06 2006/-kk/ +D/gui//// +/res.properties/1.3/Sun Mar 12 16:05:31 2006// diff --git a/src/org/jalgo/module/avl/CVS/Repository b/src/org/jalgo/module/avl/CVS/Repository new file mode 100644 index 0000000..7e86e2e --- /dev/null +++ b/src/org/jalgo/module/avl/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl diff --git a/src/org/jalgo/module/avl/CVS/Root b/src/org/jalgo/module/avl/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/Constants.java b/src/org/jalgo/module/avl/Constants.java new file mode 100644 index 0000000..5d3a0e3 --- /dev/null +++ b/src/org/jalgo/module/avl/Constants.java @@ -0,0 +1,52 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.05.2005 */ +package org.jalgo.module.avl; + +/** + * The interface Constants is a collection of several constant + * values used in the core implementation of the AVL module. + * + * @author Ulrike Fischer, Alexander Claus + */ +public interface Constants { + + /*----------------------------valid key range----------------------------*/ + /** The minimum integer value a key can have. */ + public static final int MIN_KEY = 1; + /** The maximum integer value a key can have. */ + public static final int MAX_KEY = 99; + + /*------------------------------return codes-----------------------------*/ + public static final int FOUND = 1; + public static final int WORKING = 2; + public static final int NOTFOUND = 4; + public static final int LEFT = 8; + public static final int RIGHT = 16; + public static final int DONE = 32; + public static final int ROTATE = 64; + public static final int ROOT = 128; + public static final int LASTUNDO = 256; + public static final int DOUBLEROTATE = 512; +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/Controller.java b/src/org/jalgo/module/avl/Controller.java new file mode 100644 index 0000000..6a8ff18 --- /dev/null +++ b/src/org/jalgo/module/avl/Controller.java @@ -0,0 +1,440 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 26.04.2005 + * + */ +package org.jalgo.module.avl; + +import java.util.LinkedList; +import java.util.Queue; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.algorithm.AVLTest; +import org.jalgo.module.avl.algorithm.CommandFactory; +import org.jalgo.module.avl.algorithm.CreateRandomTree; +import org.jalgo.module.avl.algorithm.Insert; +import org.jalgo.module.avl.algorithm.InsertAVL; +import org.jalgo.module.avl.algorithm.MacroCommand; +import org.jalgo.module.avl.algorithm.Remove; +import org.jalgo.module.avl.algorithm.RemoveAVL; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Matthias Schmidt + * + * The class Controller is an important connection between the + * GUI an the working algorithms.
      + * It provides several functions like: to start a new algorithm, to check if the + * working algorithm is ready and to get the results of the active algorithm. + */ +public class Controller +implements Constants { + + private SearchTree tree; + private boolean avlMode = false; + private MacroCommand currentCommand = null; + private WorkNode workingNode = null; + private Queue logDescriptions; + + /** + * Constructs the Controller instance for the current AVL + * module instance.
      + * Initializes the WorkingNode for the algorithms.
      + * Initializes the list of logdescriptions shown in the logbook at the GUI. + * + * @param st the datastructure for the algorithm + */ + public Controller(SearchTree st) { + tree = st; + workingNode = new WorkNode(0, null); + workingNode.setVisualizationStatus(Visualizable.INVISIBLE); + + logDescriptions = new LinkedList(); + } + + /** + * Sets the AVL mode + * + * @param avl true to enable the AVL mode, false + * to disable it. + */ + public void setAVLMode(boolean avl) { + avlMode = avl; + } + + /** + * Retrieves the status of the AVL mode + * + * @return true if the AVL mode is enabled + */ + public boolean isAVLMode() { + return avlMode; + } + + /** + * @return The section of the current command.
      + * If there is no current command "noCommand" is returned. + */ + public String getSection() { + if (currentCommand == null || !currentCommand.hasNext()) return null; + return (String)currentCommand.getResults().get(1); + } + + /** + * Retrieves the Node with which the algorithms work. + * + * @return The WorkNode of the active algorithm. + */ + public WorkNode getWorkNode() { + return workingNode; + } + + /** + * Starts a new Search algorithm. + * + * @param key the key of the Node that is searched in the + * tree + */ + public void startSearch(int key) { + workingNode = new WorkNode(key, tree.getRoot()); + currentCommand = CommandFactory.createSearch(workingNode); + putLogDescription((String)currentCommand.getResult(0)); + } + + /** + * Starts a new Insert algorithm.
      + * If the AVL mode is enabled the insertation keeps the avl character. + * + * @param key the key of the Node that shall be inserted. + */ + public void startInsert(int key) { + workingNode = new WorkNode(key, tree.getRoot()); + if (avlMode) currentCommand = CommandFactory.createInsertAVL( + workingNode, tree); + else currentCommand = CommandFactory.createInsert(workingNode, tree); + putLogDescription((String)currentCommand.getResult(0)); + } + + /** + * Starts a new Remove algorithm. If the AVL mode is enabled the removal + * keeps the avl character. + * + * @param key the key of the Node the shall be removed. + */ + public void startRemove(int key) { + workingNode = new WorkNode(key, tree.getRoot()); + if (avlMode) currentCommand = CommandFactory.createRemoveAvl( + workingNode, tree); + else currentCommand = CommandFactory.createRemove(workingNode, tree); + putLogDescription((String)currentCommand.getResult(0)); + } + + /** + * Starts an algorithm that creates a random tree.
      + * If the AVL mode is enabled the new tree has the avl character. + * + * @param nodeNumber number of Nodes for the random tree + */ + public void createRandomTree(int nodeNumber) { + workingNode = new WorkNode(0, tree.getRoot()); + workingNode.setVisualizationStatus(Visualizable.INVISIBLE); + currentCommand = CommandFactory.createCreateRandomTree(nodeNumber, + tree, workingNode, avlMode); + putLogDescription((String)currentCommand.getResult(0)); + } + + /** + * Starts an AVLTest algorithm and performs it once. + */ + public void startAVLTest() { + currentCommand = CommandFactory.createAVLTest(tree); + currentCommand.perform(); + putLogDescription((String)currentCommand.getResult(0)); + } + + /** + * Checks the status of the current command. + * + * @return false if the current command has no next step or + * if there is no current command. + */ + public boolean algorithmHasNextStep() { + boolean next = false; + if (currentCommand != null) next = currentCommand.hasNext(); + return next; + } + + /** + * Checks the status of the current command. + * + * @return false if the current command has no previous step + * or if there is no current command. + */ + public boolean algorithmHasPreviousStep() { + boolean previous = false; + if (currentCommand != null) previous = currentCommand.hasPrevious(); + return previous; + } + + /** + * Tries to perform one step forward in the active algorithm. + * + * @throws NoActionException if there is no active algorithm or if it's + * impossible to calculate a new step in the active algorithm + */ + public void perform() + throws NoActionException { + try { + currentCommand.perform(); + // section = (String) currentCommand.getResults().get(0); + putLogDescription((String)currentCommand.getResult(0)); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + catch (IndexOutOfBoundsException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_next_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Tries to perform one undo-Step in the active algorithm. + * + * @throws NoActionException if there is no active algorithm or if it's + * impossible to calculate a previous step in the active + * algorithm + */ + public void undo() + throws NoActionException { + try { + currentCommand.hasNext(); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + try { + currentCommand.undo(); + // section = (String) currentCommand.getResults().get(0); + putLogDescription((String)currentCommand.getResult(0)); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_prev_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Tries to perform one BIG step in the active algorithm. + * + * @throws NoActionException if there is no active algorithm or if it's + * impossible to calculate a new step in the active algorithm + */ + public void performBlockStep() + throws NoActionException { + try { + currentCommand.performBlockStep(); + // section = (String) currentCommand.getResults().get(0); + putLogDescription((String)currentCommand.getResult(0)); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + catch (IndexOutOfBoundsException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_next_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Tries to perform one BIG step backwards in the active algorithm. + * + * @throws NoActionException if there is no active algorithm or if it's + * impossible to calculate a previous step in the active + * algorithm + */ + public void undoBlockStep() + throws NoActionException { + try { + currentCommand.hasNext(); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + try { + currentCommand.undoBlockStep(); + // section = (String) currentCommand.getResults().get(0); + putLogDescription((String)currentCommand.getResult(0)); + } + catch (NullPointerException e) { + throw new NoActionException(Messages.getString( + "avl", "Controller.No_prev_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Terminates the active algorithm with the last stable status. + * + * @throws NoActionException if something goes wrong with the Termination. + */ + public void abort() + throws NoActionException { + if (currentCommand == null) throw new NoActionException( + Messages.getString( + "avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + + if (currentCommand.hasNext()) putLogDescription(getAlgoName() + + Messages.getString("avl", "Controller.aborted")); //$NON-NLS-1$ //$NON-NLS-2$ + currentCommand.abort(); + + if (tree.getRoot() != null) tree.getRoot().setVisualizationStatus( + Visualizable.NORMAL); + workingNode.setVisualizationStatus(Visualizable.INVISIBLE); + Node next; + if ((next = workingNode.getNextToMe()) != null) + next.setVisualizationStatus(Visualizable.NORMAL); + currentCommand = null; + } + + /** + * Terminates the active algorithm by getting it to the end. + * + * @throws NoActionException if something goes wrong with the Termination. + */ + public void finish() + throws NoActionException { + if (currentCommand == null) throw new NoActionException( + Messages.getString("avl", "Controller.No_alg_exception")); //$NON-NLS-1$ //$NON-NLS-2$ + + currentCommand.finish(); + putLogDescription(getAlgoName() + Messages.getString( + "avl", "Controller.finished")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns the Result of the AVL-Test + * + * @return false as Boolean if the tree has no + * avl character.
      + * null is returned if the active algorithm is no + * AVLTest. + */ + public Boolean getAVLTestResult() { + if (currentCommand instanceof AVLTest) + return (Boolean)currentCommand.getResult(2); + return null; + } + + /** + * Inserts the given String in the queue of log descriptions. + * These descriptions can be results of algorithms or events caused by the + * GUI. + * + * @param logDesc a log description of the last action + */ + public void putLogDescription(String logDesc) { + logDescriptions.offer(logDesc); + } + + /** + * Retrieves the log description of the last action as String. + * If this method is called, the string is removed from the description + * queue. This guarantees that no action is mentioned more than once in log. + * + * @return the log description of the last action + */ + public String getLogDescription() { + return logDescriptions.poll(); + } + + /** + * Retrieves all accumulated log descriptions in entrance order. + * + * @return a Queue of log descriptions. + */ + public Queue getLogDescriptions() { + Queue retVal = new LinkedList(logDescriptions); + logDescriptions.clear(); + return retVal; + } + + /** + * Returns a String which is shown in a short Message at the + * end of an algorithm. + * + * @return the result of the active algorithm.
      + * 0 is returned if there is no working algorithm or an + * AVLTest is working. + */ + public String getResult() { + if (currentCommand != null && !(currentCommand instanceof AVLTest)) { + int result = (Integer)currentCommand.getResult(2); + switch (result) { + case FOUND: + if (currentCommand instanceof Insert + || currentCommand instanceof InsertAVL) + return Messages.getString( + "avl", "Controller.Key_exists"); //$NON-NLS-1$ //$NON-NLS-2$ + return Messages.getString("avl", "Key_found"); //$NON-NLS-1$ //$NON-NLS-2$ + case DONE: + if (currentCommand instanceof Insert + || currentCommand instanceof InsertAVL) + return Messages.getString( + "avl", "Node_inserted"); //$NON-NLS-1$ //$NON-NLS-2$ + if (currentCommand instanceof CreateRandomTree) + return getAlgoName() + Messages.getString( + "avl", "Controller.Successful"); //$NON-NLS-1$ //$NON-NLS-2$ + if (currentCommand instanceof Remove + || currentCommand instanceof RemoveAVL) + return Messages.getString( + "avl", "Node_removed"); //$NON-NLS-1$ //$NON-NLS-2$ + case NOTFOUND: + return Messages.getString( + "avl", "Controller.Key_not_found"); //$NON-NLS-1$ //$NON-NLS-2$ + default: + return Messages.getString( + "avl", "Controller.Log_exception"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + return Messages.getString("avl", "Controller.No_alg_exception"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns a String better known as the algorithm name. + * + * @return the name of the current active MacroCommand + */ + public String getAlgoName() { + if (currentCommand != null) return currentCommand.getName(); + return "nocommand"; //$NON-NLS-1$ + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/ModuleConnector.java b/src/org/jalgo/module/avl/ModuleConnector.java new file mode 100644 index 0000000..9bc75f2 --- /dev/null +++ b/src/org/jalgo/module/avl/ModuleConnector.java @@ -0,0 +1,164 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.04.2005 */ +package org.jalgo.module.avl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.GUIController; + +/** + * This class provides the bridge between the main program and the current + * instance of the AVL module. It handles the references of several objects and + * provides some methods used in the main program. + * + * @author Alexander Claus + */ +public class ModuleConnector +extends AbstractModuleConnector { + + private SearchTree tree; + private Controller controller; + private GUIController gui; + + /** + * Initializes the ModuleConnector instance for the AVL module. + * Instances of the module specific SearchTree, + * Controller and GUIController are created + * here. + * + * @see AbstractModuleConnector#init() + */ + public void init() { + tree = new SearchTree(); + controller = new Controller(tree); + gui = new GUIController(this, controller, tree); + } + + /** + * The "program code" of the AVL module. Currently there is only the welcome + * screen displayed. + * + * @see org.jalgo.main.AbstractModuleConnector#run() + */ + public void run() { + gui.installWelcomeScreen(); + } + + /** + * This method is invoked, when module or program are intended to be closed. + * If there are no changes to save, it returns true, otherwise the user is + * asked for saving his work. + * + * @return true, if module is ready to be closed, + * false otherwise + */ + public boolean close() { + // if some dialogs are open, close this first + if (gui.isDialogOpen()) return false; + + // ensure, that tree is in consistent state + if (controller.algorithmHasNextStep()) try { + controller.abort(); + gui.algorithmAborted(); + } + catch (NoActionException ex) { + // no exception handling here, module is being closed + } + + return true; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + @SuppressWarnings("unchecked") + public void setDataFromFile(ByteArrayInputStream data) { + try { + ObjectInputStream in = new ObjectInputStream(data); + boolean avlMode = in.readBoolean(); + gui.setAVLMode(avlMode, avlMode); + tree.importLevelOrder((List)in.readObject()); + gui.installStandardLayout(); + } + catch (IOException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "avl", "ModuleConnector.No_valid_AVL_file")); //$NON-NLS-1$ //$NON-NLS-2$ + } + catch (ClassNotFoundException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "avl", "ModuleConnector.Loading_error") + //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator") + //$NON-NLS-1$ + Messages.getString("avl", "ModuleConnector.File_damaged")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Here the data for serializing the SearchTree is formatted. + * First there is a boolean value serialized, indicating, if the tree is an + * AVL-tree. Secondly the integer keys of the Nodes are + * serialized in a levelordered linked list. + * + * @see org.jalgo.main.AbstractModuleConnector#getDataForFile() + */ + public ByteArrayOutputStream getDataForFile() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeBoolean(controller.isAVLMode()); + List nodes = tree.exportLevelOrder(); + List keys = new LinkedList(); + for (Node node : nodes) + keys.add(node.getKey()); + objOut.writeObject(keys); + objOut.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + return out; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#print() + */ + public void print() { + // printing is currently not supported + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/ModuleInfo.java b/src/org/jalgo/module/avl/ModuleInfo.java new file mode 100644 index 0000000..4bf44b5 --- /dev/null +++ b/src/org/jalgo/module/avl/ModuleInfo.java @@ -0,0 +1,120 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.04.2005 */ +package org.jalgo.module.avl; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * This class represents some information about the AVL module. + * + * @author Alexander Claus + */ +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getName() + */ + public String getName() { + return Messages.getString("avl", "Module_name"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getVersion() + */ + public String getVersion() { + return Messages.getString("avl", "Module_version"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getAuthor() + */ + public String getAuthor() { + return Messages.getString("avl", "Module_authors"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getDescription() + */ + public String getDescription() { + return Messages.getString("avl", "Module_description_1") + //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator") + //$NON-NLS-1$ + Messages.getString("avl", "Module_description_2"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getLogo() + */ + public URL getLogoURL() { + return Messages.getResourceURL("avl", "Module_logo"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getLicense() + */ + public String getLicense() { + return Messages.getString("avl", "Module_license"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("avl","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/NoActionException.java b/src/org/jalgo/module/avl/NoActionException.java new file mode 100644 index 0000000..8f1216f --- /dev/null +++ b/src/org/jalgo/module/avl/NoActionException.java @@ -0,0 +1,47 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 18.05.2005 + */ +package org.jalgo.module.avl; + +/** + * @author Matthias Schmidt + * + * The class NoActionException is thrown if something is wrong + * with the connection between the GUI and the algorithm.
      + */ +public class NoActionException +extends Exception { + + private static final long serialVersionUID = 2348851116967125246L; + + public NoActionException() { + // empty constructor + } + + public NoActionException(String error) { + super(error); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/AVLTest.java b/src/org/jalgo/module/avl/algorithm/AVLTest.java new file mode 100644 index 0000000..dab53cc --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/AVLTest.java @@ -0,0 +1,115 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.*; +import java.util.*; + +/** + * @author Ulrike Fischer + * + * The class AVLTest checks if the current search tree has the + * AVL characteristic. + */ + +public class AVLTest +extends MacroCommand { + + private SearchTree tree; + private boolean result = true; + private Set nodes; + + /** + * @param st the searchtree + */ + public AVLTest(SearchTree st) { + tree = st; + name = Messages.getString("avl", "Alg_name.AVL_test"); //$NON-NLS-1$ //$NON-NLS-2$ + nodes = new HashSet(); + } + + /** + * returns true, if the tree is an AVLTree + */ + @SuppressWarnings("unchecked") + public void perform() { + results.clear(); + if (currentPosition == 0) { + SearchTree.calculateBalances((AVLNode)tree.getRoot()); + test((AVLNode)tree.getRoot()); + results.add(0, Messages.getString("avl", "Alg_name.AVL_test")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, ""); //$NON-NLS-1$ + results.add(2, result); + currentPosition++; + } + else { + for (Node n : nodes) + n.setVisualizationStatus(Visualizable.NORMAL); + results.add(0, ""); //$NON-NLS-1$ + results.add(1, ""); //$NON-NLS-1$ + } + currentPosition++; + } + + private void test(AVLNode n) { + if (n == null) return; + if (n.getBalance() >= 2 || n.getBalance() <= -2) { + n.setVisualizationStatus(Visualizable.FOCUSED + & Visualizable.LINE_NORMAL | Visualizable.BALANCE); + nodes.add(n); + result = false; + } + test((AVLNode)n.getLeftChild()); + test((AVLNode)n.getRightChild()); + } + + /** + * This method has no effect. + */ + public void abort() { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void undo() { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void performBlockStep() { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void undoBlockStep() { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/CVS/Entries b/src/org/jalgo/module/avl/algorithm/CVS/Entries new file mode 100644 index 0000000..4ce68cb --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CVS/Entries @@ -0,0 +1,24 @@ +/AVLTest.java/1.4/Thu Jan 31 20:15:09 2008// +/CalcBalance.java/1.4/Thu Jan 31 20:15:09 2008// +/CalcHeight.java/1.4/Thu Jan 31 20:15:09 2008// +/Command.java/1.4/Thu Jan 31 20:15:09 2008// +/CommandFactory.java/1.4/Thu Jan 31 20:15:09 2008// +/CompareKey.java/1.5/Thu Jan 31 20:15:09 2008// +/CreateNode.java/1.5/Thu Jan 31 20:15:09 2008// +/CreateRandomTree.java/1.7/Thu Jan 31 20:15:09 2008// +/FindSuccessor.java/1.5/Thu Jan 31 20:15:09 2008// +/FindSuccessorStart.java/1.5/Thu Jan 31 20:15:09 2008// +/FindSuccessorStep.java/1.5/Thu Jan 31 20:15:09 2008// +/Insert.java/1.6/Thu Jan 31 20:15:09 2008// +/InsertAVL.java/1.5/Thu Jan 31 20:15:09 2008// +/MacroCommand.java/1.5/Thu Jan 31 20:15:09 2008// +/NoOperation.java/1.5/Thu Jan 31 20:15:09 2008// +/Remove.java/1.6/Thu Jan 31 20:15:09 2008// +/RemoveAVL.java/1.5/Thu Jan 31 20:15:09 2008// +/RemoveNode.java/1.5/Thu Jan 31 20:15:09 2008// +/RotateLeft.java/1.5/Thu Jan 31 20:15:09 2008// +/RotateRight.java/1.5/Thu Jan 31 20:15:09 2008// +/Search.java/1.5/Thu Jan 31 20:15:09 2008// +/SearchAlg.java/1.5/Thu Jan 31 20:15:09 2008// +/Traverse.java/1.5/Thu Jan 31 20:15:09 2008// +/UpdateBalance.java/1.5/Thu Jan 31 20:15:09 2008// diff --git a/src/org/jalgo/module/avl/algorithm/CVS/Repository b/src/org/jalgo/module/avl/algorithm/CVS/Repository new file mode 100644 index 0000000..8ea3a69 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/algorithm diff --git a/src/org/jalgo/module/avl/algorithm/CVS/Root b/src/org/jalgo/module/avl/algorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/algorithm/CalcBalance.java b/src/org/jalgo/module/avl/algorithm/CalcBalance.java new file mode 100644 index 0000000..3d99d3e --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CalcBalance.java @@ -0,0 +1,100 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Ulrike Fischer + * + * The class CalcBalance calculates the balance of a node. + */ + +public class CalcBalance +extends Command { + + private WorkNode wn; + private AVLNode n; + private int oldBalance; + private String oldsection; + + /** + * @param wn reference to the position in the tree + */ + @SuppressWarnings("unchecked") + public CalcBalance(WorkNode wn) { + super(); + this.wn = wn; + results.add(0, "log"); //$NON-NLS-1$ + results.add(1, "2"); //$NON-NLS-1$ + } + + /** + * Takes the nextToMe node from the WorkNode and calculates + * the balance of this node. + */ + @SuppressWarnings("unchecked") + public void perform() { + oldsection = (String)results.get(1); + results.clear(); + + int rightheight = 0, leftheight = 0; + n = (AVLNode)wn.getNextToMe(); + if (n.getRightChild() != null) + rightheight = n.getRightChild().getHeight(); + if (n.getLeftChild() != null) leftheight = n.getLeftChild().getHeight(); + int balance = rightheight - leftheight; + oldBalance = n.getBalance(); + n.setBalance(balance); + n.setVisualizationStatus(Visualizable.BALANCE | Visualizable.NORMAL); + results.add(0, "log"); //$NON-NLS-1$ + if (oldBalance > balance) { + results.add(1, "3a"); //$NON-NLS-1$ + results.add(2, balance); + } + else if (oldBalance < balance) { + results.add(1, "3b"); //$NON-NLS-1$ + results.add(2, balance); + + } + else { + results.add(1, "2"); //$NON-NLS-1$ + results.add(2, balance); + } + } + + /** + * Changes the balance to the one before perform. + */ + @SuppressWarnings("unchecked") + public void undo() { + n.setBalance(oldBalance); + wn.setNextToMe(n); + n.setVisualizationStatus(Visualizable.NORMAL); + results.add("log"); //$NON-NLS-1$ + results.add(oldsection); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/CalcHeight.java b/src/org/jalgo/module/avl/algorithm/CalcHeight.java new file mode 100644 index 0000000..196a687 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CalcHeight.java @@ -0,0 +1,66 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.module.avl.datastructure.*; + +/** + * @author Ulrike Fischer + * + * The class CalcHeight calculates the height of one node. + */ +public class CalcHeight +extends Command { + + private Node startNode; + + /** + * @param n the node where the height is calculated + */ + public CalcHeight(Node n) { + super(); + startNode = n; + } + + /** + * Calculates the height. + */ + public void perform() { + calc(startNode); + } + + private int calc(Node node) { + if (node == null) return 0; + node.setHeight(1 + Math.max(calc(node.getLeftChild()), + calc(node.getRightChild()))); + return node.getHeight(); + } + + /** + * This method has no effect. + */ + public void undo() { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/Command.java b/src/org/jalgo/module/avl/algorithm/Command.java new file mode 100644 index 0000000..1f00b7a --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/Command.java @@ -0,0 +1,91 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import java.util.*; + +/** + * Part of the design pattern "Command/Action/Transaction" (class Command of the + * pattern). the abstract methods perform and undo + * make possible to do/undo operations stepwise (implemented in the inherited + * classes). the other methods are necessary to communicate between different + * command objects, e.g. to set parameters and get the results of a command. + * + * @author Ulrike Fischer + */ + +public abstract class Command { + + protected List results; + protected List parameters; + + /** + * Constructs a Command.
      + * Initializes the result and the parameters list. + */ + public Command() { + results = new LinkedList(); + parameters = new LinkedList(); + } + + /** + * This methode need to be specifed by the concrete command. + */ + public abstract void perform(); + + /** + * This methode need to be specifed by the concrete command. + */ + public abstract void undo(); + + /** + * Sets the parameters of the Command. + * + * @param p List of parameters. + */ + @SuppressWarnings("unchecked") + public void setParameters(List p) { + parameters = new LinkedList(p); + } + + /** + * Retrieves the whole result list of the Command + * + * @return List list of results. + */ + public List getResults() { + return results; + } + + /** + * Retrieves the entry of the result list from the given index. + * + * @param index position of the wanted result + * @return Object the result + */ + public Object getResult(int index) { + if (index < results.size()) return results.get(index); + return null; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/CommandFactory.java b/src/org/jalgo/module/avl/algorithm/CommandFactory.java new file mode 100644 index 0000000..615f565 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CommandFactory.java @@ -0,0 +1,243 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.module.avl.datastructure.*; + +/** + * @author Matthias Schmidt, Ulrike Fischer, Jean Christoph Jung + * + * The class CommandFactory has the function to create new + * algorithm objects and to give them initial parameters. + */ + +public class CommandFactory { + + /** + * Creates a CompareKey object. + * + * @param wn the WorkNode for the calculations. + * @return CompareKey the new instance. + */ + public static CompareKey createCompareKey(WorkNode wn) { + return new CompareKey(wn); + } + + /** + * Creates a CreateNode object. + * + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return CreateNode the new instance + */ + public static CreateNode createCreateNode(WorkNode wn, SearchTree tree) { + return new CreateNode(wn, tree); + } + + /** + * Creates a Search object. + * + * @param wn the WorkNode for the calculations. + * @return Search the new instance + */ + public static Search createSearch(WorkNode wn) { + return new Search(wn); + } + + /** + * Creates an Insert object. + * + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return Insert the new instance + */ + public static Insert createInsert(WorkNode wn, SearchTree tree) { + return new Insert(wn, tree); + } + + /** + * Creates an InsertAVL object. + * + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return InsertAVL the new instance + */ + public static InsertAVL createInsertAVL(WorkNode wn, SearchTree tree) { + return new InsertAVL(wn, tree); + } + + /** + * Creates a CalcBalance object. + * + * @param wn the WorkNode for the calculations. + * @return CalcBalance the new instance + */ + public static CalcBalance createCalcBalance(WorkNode wn) { + return new CalcBalance(wn); + } + + /** + * Creates an UpdateBalance object. + * + * @param wn the WorkNode for the calculations. + * @return UpdateBalance the new instance + */ + public static UpdateBalance createUpdateBalance(WorkNode wn) { + return new UpdateBalance(wn); + } + + /** + * Creates a RotateLeft object. + * + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return RotateLeft the new instance + */ + public static RotateLeft createRotateLeft(WorkNode wn, SearchTree tree) { + return new RotateLeft(tree, wn); + } + + /** + * Creates a RotateRight object. + * + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return RotateRight the new instance + */ + public static RotateRight createRotateRight(WorkNode wn, SearchTree tree) { + return new RotateRight(tree, wn); + } + + /** + * Creates a CreateRandomTree object. + * + * @param number the final tree has this number of nodes. + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @param avl if true the final tree has the avl character. + * @return CreateRandomTree the new instance + */ + public static CreateRandomTree createCreateRandomTree(int number, + SearchTree tree, WorkNode wn, boolean avl) { + return new CreateRandomTree(number, tree, wn, avl); + } + + /** + * Creates a CalcHeight object. + * + * @param n the height for this Node in a tree is calculated. + * @return CalcHeight the new instance. + */ + public static CalcHeight createCalcHeight(Node n) { + return new CalcHeight(n); + } + + /** + * Creates an AVLTest object. + * @param tree the datastructure for the calculations. + * @return AVLTest the new instance. + */ + public static AVLTest createAVLTest(SearchTree tree) { + return new AVLTest(tree); + } + + /** + * Creates a NoOperation object. The NoOperation needs no + * parameters. + * + * @return NoOperation the new instance. + */ + public static NoOperation createNoOperation() { + return new NoOperation(); + } + + /** + * Creates a RemoveNode object. + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @param nodeToRemove this Node will be removed from the tree. + * @return RemoveNode the new instance. + */ + public static RemoveNode createRemoveNode(WorkNode wn, SearchTree tree, + Node nodeToRemove) { + return new RemoveNode(wn, tree, nodeToRemove); + + } + + /** + * Creates a Remove object. + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return Remove the new instance. + */ + public static Remove createRemove(WorkNode wn, SearchTree tree) { + return new Remove(wn, tree); + } + + /** + * Creates a RemoveAVL object. + * @param wn the WorkNode for the calculations. + * @param tree the datastructure for the calculations. + * @return RemoveAVL the new instance. + */ + public static RemoveAVL createRemoveAvl(WorkNode wn, SearchTree tree) { + return new RemoveAVL(wn, tree); + } + + /** + * Creates a FindSuccessor object. + * @param wn the WorkNode for the calculations. + * @return FindSuccessor the new instance. + */ + public static FindSuccessor createFindSuccessor(WorkNode wn) { + return new FindSuccessor(wn); + } + + /** + * Creates a FindSuccessorStep object. + * @param wn the WorkNode for the calculations. + * @return FindSuccessorStep the new instance. + */ + public static FindSuccessorStep createFindSuccessorStep(WorkNode wn) { + return new FindSuccessorStep(wn); + } + + /** + * Creates a FindSuccessorStart object. + * @param wn the WorkNode for the calculations. + * @return FindSuccessorStart the new instance. + */ + public static FindSuccessorStart createFindSuccessorStart(WorkNode wn) { + return new FindSuccessorStart(wn); + } + + /** + * Creates a SearchAlg object. + * @param wn the WorkNode for the calculations. + * @return Command the new instance. + */ + public static Command createSearchAlg(WorkNode wn) { + return new SearchAlg(wn); + } +} diff --git a/src/org/jalgo/module/avl/algorithm/CompareKey.java b/src/org/jalgo/module/avl/algorithm/CompareKey.java new file mode 100644 index 0000000..11147ea --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CompareKey.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.module.avl.datastructure.*; + +/** + * @author Ulrike Fischer + * + * The class CompareKey compares two keys with eacher other. + */ +public class CompareKey +extends Command { + + private WorkNode wn; + + /** + * @param wn reference to the position in the tree, holds the new key + */ + public CompareKey(WorkNode wn) { + super(); + this.wn = wn; + } + + /** + * Gets the WorkNode and compares its key with the key of the nextToMe + * + * node, returns 0 if the keys are the same, -1 if the key of the WorkNode + * is smaller and 1 otherwise. + */ + @SuppressWarnings("unchecked") + public void perform() { + + Integer worknodekey = wn.getKey(); + Integer nexttomekey = wn.getNextToMe().getKey(); + + results.add(worknodekey.compareTo(nexttomekey)); + } + + /** + * method is empty, undo not necessary + */ + public void undo() { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/CreateNode.java b/src/org/jalgo/module/avl/algorithm/CreateNode.java new file mode 100644 index 0000000..cc5b9cc --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CreateNode.java @@ -0,0 +1,107 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.*; + +/** + * This class provides the creation of a new node. The node is inserted into the + * searchtree at the place, specified by the worknode and the parameterlist. + * + * @author Jean Christoph Jung + */ +public class CreateNode +extends Command { + + private WorkNode wn; + private SearchTree tree; + + /** + * @param w reference to the position in the tree, holds the new key too. + * @param st the searchtree the new node is inserted in. + */ + public CreateNode(WorkNode w, SearchTree st) { + super(); + wn = w; + tree = st; + } + + /** + * This method creates a new node and inserts it into the searchtree. + */ + @Override + public void perform() { + if (wn.getNextToMe() == null) { + AVLNode node = new AVLNode(wn.getKey()); + tree.setRoot(node); + wn.setNextToMe(node); + } + else { + AVLNode parent = (AVLNode)wn.getNextToMe(); + AVLNode node = new AVLNode(wn.getKey(), parent); + int child = ((Integer)parameters.get(0)).intValue(); + if (child == Constants.LEFT) { + parent.setLeftChild(node); + } + else { + parent.setRightChild(node); + } + wn.setNextToMe(node); + } + } + + /** + * This method deletes the node, which was created by the + * perform-method the behaviour is undefined, if perform has + * not been called yet; otherwise undo recovers the state + * before calling perform + */ + @Override + public void undo() { + if (wn.getNextToMe() == tree.getRoot()) { + wn.setNextToMe(null); + tree.setRoot(null); + wn.setVisualizationStatus(Visualizable.NORMAL); + } + else { + AVLNode parent = (AVLNode)wn.getNextToMe().getParent(); + wn.setNextToMe(parent); + int child = ((Integer)parameters.get(0)).intValue(); + if (child == Constants.LEFT) { + parent.setLeftChild(null); + wn.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.LEFT_ARROW); + } + else { + parent.setRightChild(null); + wn.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.RIGHT_ARROW); + } + } + + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/CreateRandomTree.java b/src/org/jalgo/module/avl/algorithm/CreateRandomTree.java new file mode 100644 index 0000000..a28df55 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/CreateRandomTree.java @@ -0,0 +1,252 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + * + * Created on 22.04.2005 + */ +package org.jalgo.module.avl.algorithm; + +import java.util.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.*; +import org.jalgo.module.avl.datastructure.*; + +/** + * @author Matthias Schmidt + * + * The class CreateRandomTree creates a random binary tree with a + * given number of notes. There is the posibility to create an avl tree as well. + */ +public class CreateRandomTree +extends MacroCommand +implements Constants { + + int finalNodeNumber; + Random rand; + List keyList; + private SearchTree tree; + private WorkNode wn; + private boolean avl; + + /** + * Constructs the CreateRandomTree instance for the current + * tree generation.
      + * Initializes the name of the working algorithm which is dependent on the + * avl mode. Initializes the command list with the first + * Insert or InsertAVL object. + * + * @param nodes number of nodes the SearchTree will have + * @param st SearchTree which ought to be builded. + * @param wn WorkNode which is always use by the + * MacroCommands + */ + @SuppressWarnings("unchecked") + public CreateRandomTree(int nodes, SearchTree st, WorkNode wn, boolean avl) { + super(); + if (avl) name = Messages.getString("avl", "Alg_name.Create_AVL_tree"); //$NON-NLS-1$ //$NON-NLS-2$ + else name = Messages.getString("avl", "Alg_name.Create_tree"); //$NON-NLS-1$ //$NON-NLS-2$ + tree = st; + this.wn = wn; + this.avl = avl; + if (nodes > 0) { + rand = new Random(); + finalNodeNumber = nodes; + keyList = new ArrayList(); + + int firstKey = rand.nextInt(MAX_KEY) + MIN_KEY; + changeWorkNode(firstKey); + if (avl) commands.add(0, CommandFactory.createInsertAVL(wn, tree)); + else commands.add(0, CommandFactory.createInsert(wn, tree)); + commands.add(1, CommandFactory.createNoOperation()); + keyList.add(0, firstKey); + + results.add(0, getName() + + Messages.getString("avl", "CreateRandomTree.With") + //$NON-NLS-1$ //$NON-NLS-2$ + finalNodeNumber + + Messages.getString("avl", "CreateRandomTree.Nodes")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "1"); //$NON-NLS-1$ + results.add(2, WORKING); + } + else { + results.add(0, Messages.getString( + "avl", "CreateRandomTree.Tree_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, " "); //$NON-NLS-1$ + results.add(2, DONE); + + } + } + + // Changes the work node. + private void changeWorkNode(int key) { + wn.setKey(key); + wn.setNextToMe(tree.getRoot()); + wn.setVisualizationStatus(Visualizable.NORMAL); + } + + // Stores the log description and the section from a command. + @SuppressWarnings("unchecked") + private void storeLogAndSectionFrom(Command c) { + results.clear(); + results.add(c.getResult(0)); + results.add(c.getResult(1)); + results.add(c.getResult(2)); + } + + /** + * Calculates one step.
      + * The result list gets WORKING at the index 2 if the final number of + * Nodes is not reached, DONE if the SearchTree + * is completed + */ + @SuppressWarnings("unchecked") + public void perform() { + Command c = commands.get(currentPosition); + if (c instanceof NoOperation) { + // Test: Ready? + if (keyList.size() >= finalNodeNumber) { + if (avl) results.set(0, Messages.getString( + "avl", "CreateRandomTree.AVL_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + else results.set(0, Messages.getString( + "avl", "CreateRandomTree.Tree_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + currentPosition++; + return; + } + int newkey = 0; + while (keyList.contains(newkey = rand.nextInt(MAX_KEY) + MIN_KEY)) { + /* search new key*/ } + keyList.add(newkey); + changeWorkNode(newkey); + if (avl) commands.set(0, CommandFactory.createInsertAVL(wn, tree)); + else commands.set(0, CommandFactory.createInsert(wn, tree)); + currentPosition = 0; + storeLogAndSectionFrom(c); + } + else { + MacroCommand m = (MacroCommand)c; + if (m.hasNext()) { + m.perform(); + storeLogAndSectionFrom(m); + if (!m.hasNext()) currentPosition++; + } + } + } + + /** + * Calculates one block step.
      + * The result list gets WORKING at the index 2 if the final number of + * Nodes is not reached, DONE if the SearchTree + * is completed + */ + @SuppressWarnings("unchecked") + public void performBlockStep() { + Command c = commands.get(currentPosition); + if (c instanceof NoOperation) { + if (keyList.size() >= finalNodeNumber) { + if (avl) results.set(0, Messages.getString( + "avl", "CreateRandomTree.AVL_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + else results.set(0, Messages.getString( + "avl", "CreateRandomTree.Tree_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + + currentPosition++; + return; + } + int newkey = 0; + while (keyList.contains(newkey = rand.nextInt(MAX_KEY) + MIN_KEY)) { + /* search new key*/ } + keyList.add(newkey); + changeWorkNode(newkey); + if (avl) commands.set(0, CommandFactory.createInsertAVL(wn, tree)); + else commands.set(0, CommandFactory.createInsert(wn, tree)); + currentPosition = 0; + } + else { + MacroCommand m = (MacroCommand)c; + while (m.hasNext()) { + m.perform(); + storeLogAndSectionFrom(m); + if (!m.hasNext()) currentPosition++; + } + if (keyList.size() >= finalNodeNumber) { + currentPosition = 2; + return; + } + } + } + + /** + * Calculates one undo. + */ + public void undo() { + if (!hasPrevious()) return; + + MacroCommand mc = (MacroCommand)commands.get(0); + mc.undo(); + storeLogAndSectionFrom(mc); + currentPosition = 0; + } + + /** + * Calculates one block undo. + */ + public void undoBlockStep() { + if (!hasPrevious()) return; + + currentPosition = 0; + MacroCommand mc = (MacroCommand)commands.get(0); + while (mc.hasPrevious()) + mc.undo(); + storeLogAndSectionFrom(mc); + } + + /** + * Terminates the tree generation. After that, the tree has it's current + * number of nodes. + */ + @SuppressWarnings("unchecked") + public void abort() { + if (!this.hasPrevious()) return; + Command com = commands.get(currentPosition); + if (com instanceof NoOperation) { + currentPosition++; + } + if (currentPosition < commands.size()) { + if (avl) { + InsertAVL ins = (InsertAVL)commands.get(currentPosition); + while (ins.hasPrevious()) + ins.undo(); + } + else { + Insert ins = (Insert)commands.get(currentPosition); + while (ins.hasPrevious()) + ins.undo(); + } + } + commands = commands.subList(0, currentPosition); + keyList = keyList.subList(0, currentPosition / 2); + finalNodeNumber = keyList.size(); + results.clear(); + results.add(Messages.getString( + "avl", "CreateRandomTree.Tree_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(" "); //$NON-NLS-1$ + results.add(DONE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/FindSuccessor.java b/src/org/jalgo/module/avl/algorithm/FindSuccessor.java new file mode 100644 index 0000000..1ec3f8d --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/FindSuccessor.java @@ -0,0 +1,114 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * + */ +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Jean Christoph Jung + * + * This Command searches the searchtree for the key, that is next in size to the + * key next to the worknode. It uses the classes + */ +public class FindSuccessor +extends MacroCommand +implements Constants { + + private WorkNode wn; + + /** + * @param wn the worknode indicates the position in the tree, where the + * search is started + */ + @SuppressWarnings("unchecked") + public FindSuccessor(WorkNode wn) { + super(); + this.wn = wn; + results.add(0, ""); //$NON-NLS-1$ + results.add(1, "absatz"); //$NON-NLS-1$ + results.add(2, WORKING); + commands.add(CommandFactory.createFindSuccessorStart(wn)); + } + + /** + * runs stepwise through the tree. first step (=first call) goes to the + * right child of the node next to the worknode the next steps (calls) are + * going to the left child until there is no left child + * + * @see org.jalgo.module.avl.algorithm.Command#perform() + */ + @SuppressWarnings("unchecked") + @Override + public void perform() { + Command c = commands.get(currentPosition); + c.perform(); + results = c.getResults(); + int stepresult = (Integer)results.get(2); + if (stepresult == WORKING) + commands.add(CommandFactory.createFindSuccessorStep(wn)); + if (stepresult == FOUND) + results.set(0, Messages.getString("avl", "Successor_found")); //$NON-NLS-1$ //$NON-NLS-2$ + currentPosition++; + } + + /** + * @see org.jalgo.module.avl.algorithm.Command#undo() + * + * recovers the state before the last called perform, i.e. + * goes to the parent of the current node + */ + @Override + public void undo() { + if (currentPosition > 0) currentPosition--; + else return; + + Command c = commands.get(currentPosition); + c.undo(); + + if (commands.size() > currentPosition + 1) + commands.remove(currentPosition + 1); + + results = c.getResults(); + } + + /** + * recovers the state before calling perform the first time, + * i.e. undoes all steps, that have been performed by this class it also + * clears the commands list apart from the first element. + */ + @Override + public void undoBlockStep() { + while (currentPosition > 0) { + currentPosition--; + Command c = commands.get(currentPosition); + c.undo(); + commands.remove(currentPosition); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/FindSuccessorStart.java b/src/org/jalgo/module/avl/algorithm/FindSuccessorStart.java new file mode 100644 index 0000000..abe3414 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/FindSuccessorStart.java @@ -0,0 +1,92 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * + */ +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Jean Christoph Jung + * + * FindNextInSizeStart is the first step in searching the key + * that is next in size to the key that will be removed. + */ +public class FindSuccessorStart +extends Command +implements Constants { + + private WorkNode wn; + + /** + * @param wn the worknode indicates the position in the tree, where the + * search is started + */ + @SuppressWarnings("unchecked") + public FindSuccessorStart(WorkNode wn) { + this.wn = wn; + results.add(0, ""); //$NON-NLS-1$ + results.add(1, "absatz"); //$NON-NLS-1$ + results.add(2, WORKING); + } + + /** + * perform moves the worknode to the right child of the + * current node next to the worknode, and changes the visualisations of both + * the old and new node next to the worknode + */ + @SuppressWarnings("unchecked") + @Override + public void perform() { + Node n = wn.getNextToMe(); + n = n.getRightChild(); + wn.setNextToMe(n); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + n.setVisualizationStatus(Visualizable.FOCUSED + | Visualizable.LINE_NORMAL); + if (wn.getNextToMe().getLeftChild() == null) results.set(2, FOUND); + results.set(0, Messages.getString( + "avl", "FindSuccessorStart.Step_to_right")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * undo moves the worknode to the parent of the current node + * next to the worknode, and changes the visualisations of both the old and + * new node next to the worknode + */ + @SuppressWarnings("unchecked") + @Override + public void undo() { + Node n = wn.getNextToMe(); + n.setVisualizationStatus(Visualizable.NORMAL); + n = n.getParent(); + wn.setNextToMe(n); + results.set(2, WORKING); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/FindSuccessorStep.java b/src/org/jalgo/module/avl/algorithm/FindSuccessorStep.java new file mode 100644 index 0000000..d78d767 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/FindSuccessorStep.java @@ -0,0 +1,94 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * + */ +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Jean Christoph Jung + * + * FindSuccessorStep is one step in the search for the symmetric + * order successor to the key that will be removed. + */ +public class FindSuccessorStep +extends Command +implements Constants { + + private WorkNode wn; + + /** + * @param wn the worknode indicates the position in the tree + */ + @SuppressWarnings("unchecked") + public FindSuccessorStep(WorkNode wn) { + this.wn = wn; + results.add(0, ""); //$NON-NLS-1$ + results.add(1, "absatz"); //$NON-NLS-1$ + results.add(2, WORKING); + } + + /** + * perform moves the worknode to the left child (if exists) + * of the current node next to the worknode, and changes the visualisations + * of both the old and new node next to the worknode + */ + @SuppressWarnings("unchecked") + @Override + public void perform() { + Node n = wn.getNextToMe(); + n.setVisualizationStatus(Visualizable.NORMAL); + n = n.getLeftChild(); + n.setVisualizationStatus(Visualizable.FOCUSED + | Visualizable.LINE_NORMAL); + wn.setNextToMe(n); + if (n.getLeftChild() != null) results.set(2, WORKING); + else results.set(2, FOUND); + results.set(0, Messages.getString( + "avl", "FindSuccessor.Step_to_left")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * undo moves the worknode to the parent of the current node + * next to the worknode, and changes the visualisations of both the old and + * new node next to the worknode + */ + @SuppressWarnings("unchecked") + @Override + public void undo() { + Node n = wn.getNextToMe(); + n.setVisualizationStatus(Visualizable.NORMAL); + n = n.getParent(); + n.setVisualizationStatus(Visualizable.FOCUSED + | Visualizable.LINE_NORMAL); + wn.setNextToMe(n); + results.set(2, WORKING); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/Insert.java b/src/org/jalgo/module/avl/algorithm/Insert.java new file mode 100644 index 0000000..8bb80fd --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/Insert.java @@ -0,0 +1,193 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.*; +import org.jalgo.module.avl.Constants; +import java.util.*; + +/** + * Realizes the insertion of a key into a given searchtree by holding the + * searchtree property + * + * @author Jean Christoph Jung + */ +public class Insert +extends MacroCommand +implements Constants { + + private WorkNode wn; + private SearchTree tree; + + /** + * @param w Reference to the the current Node; the key of the worknode is + * the key that will be inserted into the serchtree st. + * @param st the tree, the algorithm is working on. + */ + @SuppressWarnings("unchecked") + public Insert(WorkNode w, SearchTree st) { + super(); + name = Messages.getString("avl", "Alg_name.Insert"); //$NON-NLS-1$ //$NON-NLS-2$ + wn = w; + tree = st; + if (wn.getNextToMe() != null) { // Tree not empty + results.add(0, new String(Messages.getString( + "avl", "Alg_name.Insert") + //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("avl", "_of") + wn.getKey() + //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("avl", "Started"))); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert1"); //$NON-NLS-1$ + commands.add(CommandFactory.createSearch(w)); + } + else { // Tree empty, search not necessary + results.add(0, new String(Messages.getString( + "avl", "Alg_name.Insert") + //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("avl", "_of") + //$NON-NLS-1$ //$NON-NLS-2$ + wn.getKey() + + Messages.getString("avl", "Started"))); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert2"); //$NON-NLS-1$ + commands.add(CommandFactory.createCreateNode(wn, tree)); + } + results.add(2, WORKING); + } + + /** + * perform does one step in the insertion of a new node. + * writes into the resultlist: DONE, if Insert is finished, WORKING if not + * finished, FOUND if key already exists + */ + @SuppressWarnings("unchecked") + public void perform() { + Command c = commands.get(currentPosition); + c.setParameters(parameters); + c.perform(); + results.clear(); + List r = c.getResults(); + if (c instanceof Search) { + int searchresult = (Integer)r.get(2); + switch (searchresult) { + case FOUND: + currentPosition++; + results.add(0, r.get(0) + Messages.getString( + "avl", "Insert.Key_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert1"); //$NON-NLS-1$ + results.add(2, FOUND); + break; + case WORKING: + results.add(0, r.get(0)); + results.add(1, "insert1"); //$NON-NLS-1$ + results.add(2, WORKING); + break; + case NOTFOUND: + Integer child = (Integer)r.get(3); + if (child == LEFT) { + results.add(0, r.get(0) + Messages.getString( + "avl", "Insert_left")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert2"); //$NON-NLS-1$ + wn.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.LEFT_ARROW); + } + else { + results.add(0, r.get(0) + Messages.getString( + "avl", "Insert_right")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert2"); //$NON-NLS-1$ + wn.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.RIGHT_ARROW); + } + currentPosition++; + if (commands.size() < 2) commands.add( + 1, CommandFactory.createCreateNode(wn, tree)); + parameters.add(0, child); + results.add(2, WORKING); + break; + default: + results.add(2, WORKING); + break; + } + } + if (c instanceof CreateNode) { + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + + results.add(0, Messages.getString( + "avl", "Insert_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "insert2"); //$NON-NLS-1$ + results.add(2, DONE); + currentPosition++; + wn.setVisualizationStatus(Visualizable.INVISIBLE); + } + } + + /** + * First blockstep: the search Second blockstep: insert of the new node + */ + @SuppressWarnings("unchecked") + public void performBlockStep() { + if (!hasNext()) return; + Command c = commands.get(currentPosition); + results.clear(); + results.add("Absatznummer"); //$NON-NLS-1$ + if (c instanceof Search) while (((Search)c).hasNext()) perform(); + else perform(); + } + + /** + * recovers the state before the last call of perform + */ + @SuppressWarnings("unchecked") + public void undo() { + results.clear(); + results.add(0, Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + if (commands.size() <= currentPosition) currentPosition--; + else if (currentPosition == 1) currentPosition--; + + Command c = commands.get(currentPosition); + + if (c instanceof Search) { + results.add(1, "insert1"); //$NON-NLS-1$ + if (((Search)c).hasPrevious()) { + c.undo(); + results.add(2, DONE); + } + else results.add(2, DONE); + } + if (c instanceof CreateNode) { + c.undo(); + results.add(1, "insert2"); //$NON-NLS-1$ + results.add(2, DONE); + } + } + + /** + * First blockstep: the search Second blockstep: insert of the new node + */ + public void undoBlockStep() { + if ((commands.size() <= currentPosition) || (currentPosition == 1)) + currentPosition--; + + Command c = commands.get(currentPosition); + if (c instanceof Search) while (((Search)c).hasPrevious()) undo(); + else undo(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/InsertAVL.java b/src/org/jalgo/module/avl/algorithm/InsertAVL.java new file mode 100644 index 0000000..fe21188 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/InsertAVL.java @@ -0,0 +1,345 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import java.util.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.*; +import org.jalgo.module.avl.*; + +/** + * @author Ulrike Fischer + * + * The class InsertAVL realizes the insert of a node in an AVL + * tree. It uses the classes Insert to find the position and + * insert the key. It then uses the classes UpdateBalance, + * RotateLeft or RotateRight to restore the AVL + * characteristic. + */ +public class InsertAVL +extends MacroCommand +implements Constants { + + private WorkNode wn; + private SearchTree tree; + private List updatebalancelist; + private int help = 1; + private int balanceperformed = 0; + private String oldsection; + + /** + * @param w reference to the position in the tree, holds the new key + * @param st the searchtree the new node is inserted in + */ + @SuppressWarnings("unchecked") + public InsertAVL(WorkNode w, SearchTree st) { + super(); + name = Messages.getString("avl", "Alg_name.Insert_AVL"); //$NON-NLS-1$ //$NON-NLS-2$ + wn = w; + tree = st; + commands.add(CommandFactory.createInsert(w, tree)); + results.add(0, name + + Messages.getString("avl", "_of") + //$NON-NLS-1$ //$NON-NLS-2$ + wn.getKey() + + Messages.getString("avl", "Started")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "avlinsert1"); //$NON-NLS-1$ + results.add(2, WORKING); + } + + /** + * Inserts the key and restores the AVL characteristic. + */ + @SuppressWarnings("unchecked") + public void perform() { + Command c = commands.get(currentPosition); + c.perform(); + results.clear(); + List resultlist = c.getResults(); + + if (c instanceof Insert) { + int insertresult = ((Integer)resultlist.get(2)).intValue(); + switch (insertresult) { + case DONE: { + currentPosition++; + if (currentPosition == commands.size()) commands.add( + CommandFactory.createUpdateBalance(wn)); + results.add(0, Messages.getString("avl", "Node_inserted")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "avlinsert2"); //$NON-NLS-1$ + break; + } + case FOUND: { + currentPosition++; + results.add(0, resultlist.get(0)); + results.add(1, "avlinsert1"); //$NON-NLS-1$ + results.add(2, FOUND); + break; + // key already there, AVLInsert is finished + } + case WORKING: + results.add(0, resultlist.get(0)); + results.add(1, "avl" + resultlist.get(1)); //$NON-NLS-1$ + break; + } + } + + else if (c instanceof UpdateBalance) { + balanceperformed = 1; + int balanceresult = (Integer)resultlist.get(2); + updatebalancelist = resultlist; + oldsection = "avlinsert" + resultlist.get(1); //$NON-NLS-1$ + if (balanceresult == DONE || balanceresult == ROOT) { + results.add(0, resultlist.get(0) + + Messages.getString("avl", "Tree_balanced")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "avlinsert" + resultlist.get(1)); //$NON-NLS-1$ + results.add(2, DONE); + currentPosition++; + setBalancesNormal((AVLNode)wn.getNextToMe()); + // AVL-Insert is finished + } + + else if (balanceresult == ROTATE) { + results.add(0, resultlist.get(0)); + results.add(1, oldsection); + currentPosition++; + int direction = (Integer)resultlist.get(3); + if (direction == LEFT) { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + } + + else if (balanceresult == DOUBLEROTATE) { + currentPosition++; + AVLNode n = (AVLNode)resultlist.get(4); + wn.setNextToMe(n); + int direction = (Integer)resultlist.get(3); + if (direction == LEFT) { + results.add(0, resultlist.get(0)); + results.add(1, oldsection); + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + results.add(0, resultlist.get(0)); + results.add(1, oldsection); + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + help = 0; + } + + else { + results.add(0, resultlist.get(0)); + results.add(1, "avlinsert" + resultlist.get(1)); //$NON-NLS-1$ + } + } + + else if (c instanceof RotateLeft || c instanceof RotateRight) { + setBalancesNormal((AVLNode)wn.getNextToMe()); + currentPosition++; + int balanceresult = (Integer)updatebalancelist.get(2); + results.add(0, resultlist.get(0)); + results.add(1, oldsection); + results.add(2, DONE); + if (balanceresult == DOUBLEROTATE && help == 0) { + wn.setNextToMe((AVLNode)updatebalancelist.get(6)); + if (((Integer)updatebalancelist.get(5)) == LEFT) { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + help = 1; + } + else results.set(0, resultlist.get(0) + Messages.getString( + "avl", "Tree_balanced")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * This method recovers the state before calling perform. + */ + @SuppressWarnings("unchecked") + public void undo() { + results.clear(); + if (commands.size() <= currentPosition) currentPosition--; + // Checks if there are RotationObjects which haven't been performed yet + else if (currentPosition == 2 || currentPosition == 3) currentPosition--; + + Command c = commands.get(currentPosition); + + results.add(0, Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + + if (c instanceof UpdateBalance) { + + // UpdateBalance is in the Command-List but there was no perform yet + if (balanceperformed == 0) { + currentPosition--; + Command c2 = commands.get(currentPosition); + c2.undo(); + results.add(1, "avlinsert2"); //$NON-NLS-1$ + return; + } + + c.undo(); + // Check if it was the last UpdateBalance-Undo + LinkedList resultlist = (LinkedList)c.getResults(); + int undoresult = ((Integer)resultlist.get(2)).intValue(); + if (undoresult == LASTUNDO) balanceperformed = 0; + results.add(1, "avlinsert" + resultlist.get(1)); //$NON-NLS-1$ + } + + else if (c instanceof Insert) { + if (((Insert)c).hasPrevious()) { + c.undo(); + LinkedList resultlist = (LinkedList)c.getResults(); + results.add(1, "avl" + resultlist.get(1)); //$NON-NLS-1$ + } + } + + else { + // necessary for DoubleRotation, sets old RotateVisualisationStatus + // back to Normal + Command c3 = commands.get(currentPosition - 1); + if (c3 instanceof UpdateBalance) { + help = 0; + Set updatednodes = ((UpdateBalance)c3).getUpdatednodes(); + for (Node n : updatednodes) { + n.setVisualizationStatus(Visualizable.NORMAL); + } + } + + c.undo(); + + // sets all balances red + Command c4 = commands.get(currentPosition - 1); + if (c4 instanceof UpdateBalance) { + Set updatednodes = ((UpdateBalance)c4).getUpdatednodes(); + for (Node n : updatednodes) { + if (n.getVisualizationStatus() == Visualizable.NORMAL) + n.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.BALANCE); + } + } + results.add(1, oldsection); + } + } + + @SuppressWarnings("unchecked") + public void performBlockStep() { + Command c = commands.get(currentPosition); + if (c instanceof Insert) { + ((Insert)c).performBlockStep(); + List resultlist = c.getResults(); + int insertresult = ((Integer)resultlist.get(2)).intValue(); + results.clear(); + switch (insertresult) { + case DONE: + currentPosition++; + if (currentPosition == commands.size()) commands.add( + CommandFactory.createUpdateBalance(wn)); + results.add(0, resultlist.get(0)); + results.add(1, "avlinsert2"); //$NON-NLS-1$ + results.add(2, DONE); + break; + case FOUND: + currentPosition++; + results.add(0, resultlist.get(0)); + results.add(1, "avlinsert1"); //$NON-NLS-1$ + results.add(2, FOUND); + break; + // key already there, AVLInsert is finished + case WORKING: + results.add(0, resultlist.get(0)); + results.add(1, resultlist.get(1)); + results.add(2, WORKING); + break; + } + } + else if ((c instanceof RotateLeft) || (c instanceof RotateRight)) + perform(); + else if (c instanceof UpdateBalance) { + while (((UpdateBalance)c).hasNext()) perform(); + } + } + + @SuppressWarnings("unchecked") + public void undoBlockStep() { + if (commands.size() <= currentPosition) currentPosition--; + else if (currentPosition == 2 || currentPosition == 3) currentPosition--; + + Command c = commands.get(currentPosition); + results.clear(); + results.add(Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add("absatz"); //$NON-NLS-1$ + if (c instanceof Insert) { + ((Insert)c).undoBlockStep(); + results.set(1, "avlinsert1"); //$NON-NLS-1$ + } + else if ((c instanceof RotateLeft) || (c instanceof RotateRight)) + c.undo(); + else if (c instanceof UpdateBalance) { + if (balanceperformed == 0) { + currentPosition--; + Command c2 = commands.get(currentPosition); + c2.undo(); + return; + } + currentPosition++; + while (((UpdateBalance)c).hasPrevious()) undo(); + } + } + + private void setBalancesNormal(AVLNode n) { + if (n == null) return; + n.setVisualizationStatus(Visualizable.NORMAL); + setBalancesNormal((AVLNode)n.getLeftChild()); + setBalancesNormal((AVLNode)n.getRightChild()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/MacroCommand.java b/src/org/jalgo/module/avl/algorithm/MacroCommand.java new file mode 100644 index 0000000..0fd52b8 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/MacroCommand.java @@ -0,0 +1,144 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author Ulrike Fischer, Jean Christoph Jung + * + * Part of the design pattern "Command/Action/Transaction" (class MacroCommand + * of the pattern). contains a list of commands that are collected to one unit, + * so a macrocommand object can do more complex operations by performing many + * atomic commands. + */ +public abstract class MacroCommand +extends Command { + + protected String name; + protected List commands; + + /** "iterator" on the commands List. */ + protected int currentPosition; + + /** + * Constructs a MacroCommand.
      + * Initializes the command list, the currentPosition of the command + * iteration. Initializes the name of the MacroCommand with + * an default name. + */ + public MacroCommand() { + commands = new LinkedList(); + currentPosition = 0; + name = "noname"; //$NON-NLS-1$ + } + + /** + * @return true, if there is a command in the command list, + * that is not yet performed, false otherwise + */ + public boolean hasNext() { + if (commands.isEmpty() || (currentPosition >= commands.size())) + return false; + return true; + } + + /** + * @return true, if there is command in the command list, + * that can be undone, false otherwise + */ + public boolean hasPrevious() { + if (commands.size() > currentPosition) { + Command c = commands.get(currentPosition); + if ((currentPosition == 0) && (c instanceof MacroCommand)) + return ((MacroCommand)c).hasPrevious(); + return (currentPosition > 0); + } + return (currentPosition > 0); + } + + /** + * This methode need to be specifed by the concrete command. + */ + public abstract void perform(); + + /** + * This methode need to be specifed by the concrete command. + */ + public abstract void undo(); + + /** + * calls a few times perform(), so that logical units (block + * steps) are done in one step. The logical units are defined by the + * concrete macrocommand. + */ + public void performBlockStep() { + if (!hasNext()) return; + Command c = commands.get(currentPosition); + if (c instanceof MacroCommand) ((MacroCommand)c).performBlockStep(); + else { + do { + perform(); + if (!hasNext()) return; + c = commands.get(currentPosition); + if (c instanceof MacroCommand) return; + } + while (true); + } + } + + /** + * counterpart to performBlockStep undoes several calls of + * perform, jumps back always to the start of a logical unit. The logical + * units are defined by the concrete macrocommand. + */ + public void undoBlockStep() { + //TODO: what should this be? + if (!hasPrevious()) return; + } + + /** + * @return the name of the macrocommand + */ + public String getName() { + return name; + } + + /** + * cancels the algorithm. recovers the state before calling the first time + * perform. + */ + public void abort() { + while (hasPrevious()) undo(); + } + + /** + * completes the execution of the algorithm. performs all commands in the + * commandlist + */ + public void finish() { + while (hasNext()) perform(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/NoOperation.java b/src/org/jalgo/module/avl/algorithm/NoOperation.java new file mode 100644 index 0000000..03bd144 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/NoOperation.java @@ -0,0 +1,42 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +/** + * @author Ulrike Fischer + * + * The class NoOperation is empty. It has the task to help + * MacroCommand classes, if they need one more step. + */ +public class NoOperation +extends Command { + + public void perform() { + // this method has no effect + } + + public void undo() { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/Remove.java b/src/org/jalgo/module/avl/algorithm/Remove.java new file mode 100644 index 0000000..808f40e --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/Remove.java @@ -0,0 +1,252 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * Realizes the Deletion of a node (given by a key) in a searchtree, holding the + * searchtree property. + * + * @author Jean Christoph Jung + */ +public class Remove +extends MacroCommand +implements Constants { + + private WorkNode wn; + private SearchTree tree; + private Node nodeToDelete; + + /** + * @param w Reference to the the current Node; the key of the worknode is + * the key that will be deleted from the serchtree st. + * @param st the tree, the algorithm is working on. + */ + @SuppressWarnings("unchecked") + public Remove(WorkNode w, SearchTree st) { + super(); + name = Messages.getString("avl", "Alg_name.Remove"); //$NON-NLS-1$ //$NON-NLS-2$ + wn = w; + tree = st; + if (st.getRoot() == null) { + results.add(0, Messages.getString( + "avl", "Tree_empty_key_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "remove1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + } + else { // Tree not empty + commands.add(CommandFactory.createSearchAlg(w)); + results.add(0, name + + Messages.getString("avl", "_of") + //$NON-NLS-1$ //$NON-NLS-2$ + wn.getKey() + + Messages.getString("avl", "Started") + //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator") + + wn.getKey() + + Messages.getString("avl", "Key_search")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "remove1"); //$NON-NLS-1$ + results.add(2, WORKING); + } + tree.exportUncompressedLevelOrder(); + } + + /** + * perform does one step in the algorithm. + */ + @SuppressWarnings("unchecked") + public void perform() { + Command c = commands.get(currentPosition); + c.perform(); + + if (c instanceof SearchAlg) { + List resultlist = c.getResults(); + int SearchAlgresult = (Integer)resultlist.get(2); + switch (SearchAlgresult) { + case FOUND: + currentPosition++; + results.set(0, resultlist.get(0) + Messages.getString( + "avl", "Node_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.set(1, "remove2"); //$NON-NLS-1$ + results.set(2, WORKING); + nodeToDelete = wn.getNextToMe(); + nodeToDelete.setVisualizationStatus(Visualizable.FOCUSED + | Visualizable.LINE_NORMAL); + if (nodeToDelete.getRightChild() == null) commands.add( + CommandFactory.createRemoveNode(wn, tree, nodeToDelete)); + else commands.add(CommandFactory.createFindSuccessor(wn)); + break; + case WORKING: + results.set(0, resultlist.get(0)); + results.set(1, "remove1"); //$NON-NLS-1$ + results.add(2, WORKING); + break; + case NOTFOUND: + results.set(0, resultlist.get(0) + Messages.getString( + "avl", "Remove_aborted")); //$NON-NLS-1$ //$NON-NLS-2$ + results.set(1, "remove1"); //$NON-NLS-1$ + results.set(2, NOTFOUND); + currentPosition++; + break; + default: + results.set(2, WORKING); + break; + } + } + if (c instanceof FindSuccessor) { + List resultlist = c.getResults(); + int result = (Integer)resultlist.get(2); + switch (result) { + case WORKING: + results.set(0, resultlist.get(0)); + results.set(1, "remove3"); //$NON-NLS-1$ + results.set(2, WORKING); + break; + case FOUND: + currentPosition++; + commands.add(CommandFactory.createRemoveNode(wn, tree, + nodeToDelete)); + results.set(0, resultlist.get(0)); + results.set(1, "remove4"); //$NON-NLS-1$ + results.set(2, FOUND); + break; + default: + break; + } + } + if (c instanceof RemoveNode) { + results = c.getResults(); + results.set(1, "remove4"); //$NON-NLS-1$ + results.set(2, DONE); + currentPosition++; + } + } + + /** + * recovers the state before the last call of perform + */ + @SuppressWarnings("unchecked") + public void undo() { + Command c = null; + if (currentPosition >= commands.size()) { + currentPosition--; + c = commands.get(currentPosition); + } + else { + c = commands.get(currentPosition); + if (c instanceof RemoveNode) { + currentPosition--; + c = commands.get(currentPosition); + } + } + if ((c instanceof SearchAlg) && !((SearchAlg)c).hasPrevious()) return; + else if ((c instanceof FindSuccessor) + && !((FindSuccessor)c).hasPrevious()) { + currentPosition--; + c = commands.get(currentPosition); + } + + c.undo(); + + if (c instanceof FindSuccessor) results.set(1, "remove3"); //$NON-NLS-1$ + else if (c instanceof RemoveNode) results.set(1, "remove4"); //$NON-NLS-1$ + else if (c instanceof SearchAlg) results.set(1, "remove1"); //$NON-NLS-1$ + + // delete old objects, perform creates new ones + if ((c instanceof SearchAlg) || (c instanceof FindSuccessor)) { + if (commands.size() > currentPosition + 1) + commands.remove(currentPosition + 1); + } + results.set(0, Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Blocksteps: 1. SearchAlg 2. FindSuccessor 3. RemoveNode + */ + public void performBlockStep() { + if (!hasNext()) return; + Command c = commands.get(currentPosition); + if (c instanceof SearchAlg) { + while (c instanceof SearchAlg) { + perform(); + if (!hasNext()) return; + c = commands.get(currentPosition); + } + } + else if (c instanceof FindSuccessor) { + while (c instanceof FindSuccessor) { + perform(); + if (!hasNext()) return; + c = commands.get(currentPosition); + } + } + else if (c instanceof RemoveNode) { + perform(); + results = c.getResults(); + } + } + + /** + * Blocksteps: 1. SearchAlg 2. FindSuccessor 3. RemoveNode + */ + public void undoBlockStep() { + Command c = null; + if (currentPosition >= commands.size()) { + currentPosition--; + c = commands.get(currentPosition); + } + else { + c = commands.get(currentPosition); + if (c instanceof RemoveNode) { + currentPosition--; + c = commands.get(currentPosition); + } + } + + if ((c instanceof SearchAlg) && !((SearchAlg)c).hasPrevious()) return; + else if ((c instanceof FindSuccessor) + && !((FindSuccessor)c).hasPrevious()) { + currentPosition--; + c = commands.get(currentPosition); + } + + if (c instanceof SearchAlg) while (((SearchAlg)c).hasPrevious()) undo(); + else if (c instanceof FindSuccessor) + while (((FindSuccessor)c).hasPrevious()) undo(); + else c.undo(); + + // delete old objects, perform creates new ones + if ((c instanceof SearchAlg) || (c instanceof FindSuccessor)) { + if (commands.size() > currentPosition + 1) + commands.remove(currentPosition + 1); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/RemoveAVL.java b/src/org/jalgo/module/avl/algorithm/RemoveAVL.java new file mode 100644 index 0000000..577c2b8 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/RemoveAVL.java @@ -0,0 +1,358 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import java.util.List; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * Realizes the Deletion of a node (given by a key) in a searchtree, holding the + * searchtree property and the avl property. + * + * @author Jean Christoph Jung + */ +public class RemoveAVL +extends MacroCommand +implements Constants { + + private WorkNode wn; + private SearchTree tree; + private List updatebalancelist; + + private int help = 1; + + /** + * @param wn Reference to the the current Node; the key of the worknode is + * the key that will be deleted from the serchtree st. + * @param tree the tree, the algorithm is working on. + */ + @SuppressWarnings("unchecked") + public RemoveAVL(WorkNode wn, SearchTree tree) { + super(); + name = Messages.getString("avl", "Alg_name.Remove_AVL"); //$NON-NLS-1$ //$NON-NLS-2$ + this.wn = wn; + this.tree = tree; + if (tree.getRoot() == null) { + results.add(0, Messages.getString( + "avl", "Tree_empty_key_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + } + else { // Tree not empty + commands.add(CommandFactory.createRemove(wn, tree)); + results.add(0, name + + Messages.getString("avl", "_of") + //$NON-NLS-1$ //$NON-NLS-2$ + wn.getKey() + + Messages.getString("avl", "Started") + //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator") + + wn.getKey() + + Messages.getString("avl", "Key_search")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "avlremove1"); //$NON-NLS-1$ + results.add(2, WORKING); + } + } + + /** + * perform does one step in the algorithm. + */ + @SuppressWarnings("unchecked") + public void perform() { + Command c = commands.get(currentPosition); + c.perform(); + List resultlist = c.getResults(); + + if (c instanceof Remove) { + int removeresult = (Integer)resultlist.get(2); + switch (removeresult) { + case DONE: + currentPosition++; + if (tree.getHeight() == 0) { + results.set(0, Messages.getString( + "avl", "Remove_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + results.set(2, DONE); + break; + } + results = resultlist; + Node n = (Node)resultlist.get(3); + wn.setNextToMe(n); + commands.add(CommandFactory.createUpdateBalance(wn)); + results.set(1, "avlremove5"); //$NON-NLS-1$ + break; + case FOUND: + case WORKING: + results = resultlist; + results.set(1, "avl" + results.get(1)); //$NON-NLS-1$ + break; + case NOTFOUND: + results = resultlist; + results.set(1, "avl" + results.get(1)); //$NON-NLS-1$ + currentPosition++; + break; + default: + break; + } + } + + else if (c instanceof UpdateBalance) { + int balanceresult = ((Integer)resultlist.get(2)).intValue(); + updatebalancelist = resultlist; + + if (balanceresult == ROOT) { + results.set(0, resultlist.get(0) + Messages.getString( + "avl", "Root_reached_tree_balanced")); //$NON-NLS-1$ //$NON-NLS-2$ + currentPosition++; + setBalancesNormal((AVLNode)wn.getNextToMe()); + } + + else if (balanceresult == ROTATE) { + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + currentPosition++; + int direction = (Integer)resultlist.get(3); + if (direction == LEFT) { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + } + + else if (balanceresult == DOUBLEROTATE) { + currentPosition++; + AVLNode n = (AVLNode)resultlist.get(4); + wn.setNextToMe(n); + int direction = (Integer)resultlist.get(3); + if (direction == LEFT) { + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + help = 0; + } + else if (balanceresult == DONE) { + currentPosition++; + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + wn.setNextToMe(wn.getNextToMe().getParent()); + commands.add(CommandFactory.createUpdateBalance(wn)); + perform(); + return; + } + else { + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + } + results.set(1, "avlremove5"); //$NON-NLS-1$ + } + + else if (c instanceof RotateLeft || c instanceof RotateRight) { + setBalancesNormal((AVLNode)wn.getNextToMe()); + currentPosition++; + int balanceresult = (Integer)updatebalancelist.get(2); + results.set(0, resultlist.get(0)); + results.set(1, resultlist.get(1)); + if (balanceresult == DOUBLEROTATE && help == 0) { + wn.setNextToMe((AVLNode)updatebalancelist.get(6)); + if (((Integer)updatebalancelist.get(5)) == LEFT) { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateLeft(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_LEFT_ARROW + | Visualizable.BALANCE); + } + else { + if (currentPosition == commands.size()) commands.add( + CommandFactory.createRotateRight(wn, tree)); + wn.getNextToMe().setVisualizationStatus( + Visualizable.NORMAL | Visualizable.ROTATE_RIGHT_ARROW + | Visualizable.BALANCE); + } + help = 1; + } + else { + if (wn.getNextToMe().getParent() != null) { + wn.setNextToMe(wn.getNextToMe().getParent()); + commands.add(CommandFactory.createUpdateBalance(wn)); + results.set(0, resultlist.get(0) + Messages.getString( + "avl", "Partial_tree_balanced")); //$NON-NLS-1$ //$NON-NLS-2$ + } + else results.set(0, resultlist.get(0) + Messages.getString( + "avl", "N_tree_balanced")); //$NON-NLS-1$ //$NON-NLS-2$ + } + results.set(1, "avlremove5"); //$NON-NLS-1$ + } + } + + /** + * recovers the state before the last call of perform + */ + @SuppressWarnings("unchecked") + public void undo() { + Command c = null; + if (currentPosition >= commands.size()) { + currentPosition--; + c = commands.get(currentPosition); + } + else { + c = commands.get(currentPosition); + if ((c instanceof MacroCommand) && !((MacroCommand)c).hasPrevious()) { + currentPosition--; + c = commands.get(currentPosition); + } + } + + if ((c instanceof UpdateBalance) && !((UpdateBalance)c).hasNext()) { + c.undo(); + int k = currentPosition - 1; + Command c1 = commands.get(k); + while (k > 0 + && !(c1 instanceof RotateLeft || c1 instanceof RotateRight)) { + if (c1 instanceof UpdateBalance) c1.undo(); + k--; + c1 = commands.get(k); + } + results.set(1, "avlremove5"); //$NON-NLS-1$ + } + else { + c.undo(); + if (c instanceof Remove) results.set(1, "avl" + results.get(1)); //$NON-NLS-1$ + else results.set(1, "avlremove5"); //$NON-NLS-1$ + } + + if ((c instanceof Remove) || (c instanceof UpdateBalance)) { + while (commands.size() > currentPosition + 1) + commands.remove(currentPosition + 1); + } + results.set(0, Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Blocksteps: 1. Remove 2. UpdateBalance then either RotateLeft/RotateRight + * or UpdateBalance, perhaps more of them + */ + @SuppressWarnings("unchecked") + public void performBlockStep() { + if (!hasNext()) return; + Command c = commands.get(currentPosition); + if (c instanceof Remove) { + ((Remove)c).performBlockStep(); + results = c.getResults(); + results.set(1, "avl" + results.get(1)); //$NON-NLS-1$ + int removeresult = (Integer)results.get(2); + switch (removeresult) { + case DONE: + currentPosition++; + if (tree.getHeight() == 0) { + results.set(0, Messages.getString( + "avl", "Remove_finished")); //$NON-NLS-1$ //$NON-NLS-2$ + results.set(2, DONE); + break; + } + Node n = (Node)results.get(3); + wn.setNextToMe(n); + commands.add(CommandFactory.createUpdateBalance(wn)); + results.set(1, "avlremove5"); //$NON-NLS-1$ + break; + case FOUND: + case WORKING: + default: + break; + } + } + else if (c instanceof UpdateBalance) { + while (c instanceof UpdateBalance) { + perform(); + if (!hasNext()) return; + c = commands.get(currentPosition); + } + } + else perform(); + } + + /** + * Blocksteps: 1. Remove 2. UpdateBalance then either RotateLeft/RotateRight + * or UpdateBalance, perhaps more of them + */ + public void undoBlockStep() { + if (!hasPrevious()) return; + if (commands.size() <= currentPosition) currentPosition--; + + Command c = commands.get(currentPosition); + + if (c instanceof MacroCommand && !((MacroCommand)c).hasPrevious()) { + currentPosition--; + c = commands.get(currentPosition); + } + + if (c instanceof Remove && ((Remove)c).hasPrevious()) { + ((Remove)c).undoBlockStep(); + } + else if (c instanceof UpdateBalance) { + do { + while (((UpdateBalance)c).hasPrevious()) + undo(); + c = commands.get(--currentPosition); + } + while (c instanceof UpdateBalance); + currentPosition++; + } + else if (c instanceof RotateLeft || c instanceof RotateRight) undo(); + } + + private void setBalancesNormal(AVLNode n) { + if (n == null) return; + n.setVisualizationStatus(Visualizable.NORMAL); + setBalancesNormal((AVLNode)n.getLeftChild()); + setBalancesNormal((AVLNode)n.getRightChild()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/RemoveNode.java b/src/org/jalgo/module/avl/algorithm/RemoveNode.java new file mode 100644 index 0000000..d91b908 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/RemoveNode.java @@ -0,0 +1,236 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * + */ +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * @author Jean Christoph Jung + * + * Eliminates a node by replacing it according to the remove-algorithm. + */ +public class RemoveNode +extends Command +implements Constants { + + private WorkNode wn; + private SearchTree tree; + private Node nodeToRemove; + + private int fall = -1; + private boolean wasRoot = true; + private Node help = null; + + /** + * @param wn is next to the node that is successor of + * nodeToRemove + * @param tree is the searchtree that the key is removed from + * @param nodeToRemove the node to be deleted + */ + @SuppressWarnings("unchecked") + public RemoveNode(WorkNode wn, SearchTree tree, Node nodeToRemove) { + this.wn = wn; + this.tree = tree; + this.nodeToRemove = nodeToRemove; + results.add(0, ""); //$NON-NLS-1$ + results.add(1, "absatz"); //$NON-NLS-1$ + results.add(2, WORKING); + results.add(3, "helpnode"); //$NON-NLS-1$ + } + + /** + * differentiates the 3 basic cases (according to the algorithm) and + * replaces the node to remove by its successor or its left child + */ + @SuppressWarnings("unchecked") + @Override + public void perform() { + results.set(0, Messages.getString("avl", "Node_removed")); //$NON-NLS-1$ //$NON-NLS-2$ + /* Case 1: right child of node to delete is null */ + if (nodeToRemove.getRightChild() == null) { + fall = 1; + if (nodeToRemove == tree.getRoot()) { + tree.setRoot(nodeToRemove.getLeftChild()); + Node root = tree.getRoot(); + if (root != null) root.setParent(null); + results.set(2, DONE); + results.set(3, tree.getRoot()); + } + else { + Node parent = nodeToRemove.getParent(); + Node n = nodeToRemove.getLeftChild(); + if (n != null) n.setParent(parent); + if (parent.getKey() < nodeToRemove.getKey()) + parent.setRightChild(n); + else parent.setLeftChild(n); + wasRoot = false; + results.set(2, FOUND); + results.set(3, parent); + } + } + /* Case 2: the right child of nodetodelete has no left child */ + else if (nodeToRemove.getRightChild().getLeftChild() == null) { + fall = 2; + Node n = nodeToRemove.getRightChild(); + n.setLeftChild(nodeToRemove.getLeftChild()); + if (nodeToRemove.getLeftChild() != null) + nodeToRemove.getLeftChild().setParent(n); + if (nodeToRemove == tree.getRoot()) { + tree.setRoot(nodeToRemove.getRightChild()); + tree.getRoot().setParent(null); + } + else { + Node parent = nodeToRemove.getParent(); + n.setParent(parent); + if (parent.getKey() < n.getKey()) parent.setRightChild(n); + else parent.setLeftChild(n); + wasRoot = false; + } + n.setVisualizationStatus(Visualizable.NORMAL); + results.set(2, FOUND); + results.set(3, n); + } + /* Case 3: else */ + else { + fall = 3; + Node n = wn.getNextToMe(); + help = n.getParent(); + help.setLeftChild(null); + n.getParent().setLeftChild(n.getRightChild()); + if (n.getRightChild() != null) + n.getRightChild().setParent(n.getParent()); + n.setRightChild(nodeToRemove.getRightChild()); + nodeToRemove.getRightChild().setParent(n); + n.setParent(nodeToRemove.getParent()); + if (nodeToRemove == tree.getRoot()) { + tree.setRoot(n); + n.setParent(null); + } + else { + Node parent = nodeToRemove.getParent(); + if (parent.getKey() < n.getKey()) parent.setRightChild(n); + else parent.setLeftChild(n); + wasRoot = false; + } + + n.setLeftChild(nodeToRemove.getLeftChild()); + if (nodeToRemove.getLeftChild() != null) + nodeToRemove.getLeftChild().setParent(n); + n.setVisualizationStatus(Visualizable.NORMAL); + + results.set(2, FOUND); + results.set(3, help); + } + + CalcHeight ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + } + + /** + * recovers the state before the call of perform + */ + @Override + public void undo() { + switch (fall) { + case 1: + if (wasRoot == false) { + Node parent = nodeToRemove.getParent(); + if (nodeToRemove.getKey() < parent.getKey()) { + if (parent.getLeftChild() != null) + parent.getLeftChild().setParent(nodeToRemove); + parent.setLeftChild(nodeToRemove); + } + else { + if (parent.getRightChild() != null) + parent.getRightChild().setParent(nodeToRemove); + parent.setRightChild(nodeToRemove); + } + } + else { + if (tree.getRoot() == null) tree.setRoot(nodeToRemove); + else { + tree.getRoot().setParent(nodeToRemove); + tree.setRoot(nodeToRemove); + } + } + wn.setNextToMe(nodeToRemove); + break; + case 2: + if (wasRoot == false) { + nodeToRemove.getRightChild().setParent(nodeToRemove); + if (nodeToRemove.getLeftChild() != null) + nodeToRemove.getLeftChild().setParent(nodeToRemove); + Node parent = nodeToRemove.getParent(); + if (parent.getKey() < nodeToRemove.getKey()) + parent.setRightChild(nodeToRemove); + else parent.setLeftChild(nodeToRemove); + nodeToRemove.getRightChild().setLeftChild(null); + } + else { + tree.setRoot(nodeToRemove); + nodeToRemove.getRightChild().setLeftChild(null); + nodeToRemove.getRightChild().setParent(nodeToRemove); + if (nodeToRemove.getLeftChild() != null) + nodeToRemove.getLeftChild().setParent(nodeToRemove); + } + nodeToRemove.getRightChild().setVisualizationStatus( + Visualizable.FOCUSED | Visualizable.LINE_NORMAL); + wn.setNextToMe(nodeToRemove.getRightChild()); + break; + case 3: + Node n = nodeToRemove.getRightChild().getParent(); + if (nodeToRemove.getLeftChild() != null) + nodeToRemove.getLeftChild().setParent(nodeToRemove); + nodeToRemove.getRightChild().setParent(nodeToRemove); + n.setRightChild(help.getLeftChild()); + if (help.getLeftChild() != null) + help.getLeftChild().setParent(n); + n.setLeftChild(null); + n.setParent(help); + help.setLeftChild(n); + if (wasRoot == false) { + Node parent = nodeToRemove.getParent(); + if (parent.getKey() < nodeToRemove.getKey()) + parent.setRightChild(nodeToRemove); + else parent.setLeftChild(nodeToRemove); + } + else tree.setRoot(nodeToRemove); + wn.setNextToMe(help.getLeftChild()); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED | Visualizable.LINE_NORMAL); + break; + default: + return; + } + wasRoot = true; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/RotateLeft.java b/src/org/jalgo/module/avl/algorithm/RotateLeft.java new file mode 100644 index 0000000..ede484f --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/RotateLeft.java @@ -0,0 +1,126 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * Realizes a left rotation around a given node. + * + * @author Jean Christoph Jung + */ +public class RotateLeft +extends Command { + + private AVLNode n; + private WorkNode wn; + private SearchTree tree; + + private int uBalance = 0, wBalance = 0; + + /** + * @param tree in this tree the Rotation is done. + * @param wn the rotation is done around the node next to the worknode + */ + public RotateLeft(SearchTree tree, WorkNode wn) { + super(); + this.wn = wn; + this.n = (AVLNode)wn.getNextToMe(); + this.tree = tree; + } + + /** + * performs the rotation and actualizes the balances and heights + */ + @SuppressWarnings("unchecked") + public void perform() { + results.add(0, Messages.getString( + "avl", "Rotate_left_around") + n.getKey()); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "3a"); //$NON-NLS-1$ + + n.setVisualizationStatus(Visualizable.NORMAL); + AVLNode u = n; + AVLNode w = (AVLNode)u.getRightChild(); + AVLNode b = null; + if (w.getLeftChild() != null) b = (AVLNode)w.getLeftChild(); + u.setRightChild(b); + if (b != null) b.setParent(u); + w.setLeftChild(u); + w.setParent(u.getParent()); + u.setParent(w); + + if (w.getParent() != null) if (w.getKey() < w.getParent().getKey()) + w.getParent().setLeftChild(w); + else w.getParent().setRightChild(w); + else // w is root of the SearchTree + tree.setRoot(w); + + uBalance = u.getBalance(); + wBalance = w.getBalance(); + SearchTree.calculateBalances(w); + + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + + n = w; + wn.setNextToMe(n); + } + + /** + * undoes the rotation and set the old balances and heights + */ + public void undo() { + AVLNode w = n; + AVLNode u = (AVLNode)w.getLeftChild(); + AVLNode b = null; + if (u.getRightChild() != null) b = (AVLNode)u.getRightChild(); + + w.setLeftChild(b); + if (b != null) b.setParent(w); + u.setRightChild(w); + u.setParent(w.getParent()); + w.setParent(u); + + if (u.getParent() != null) if (u.getKey() < u.getParent().getKey()) + u.getParent().setLeftChild(u); + else u.getParent().setRightChild(u); + else tree.setRoot(u); + + u.setBalance(uBalance); + w.setBalance(wBalance); + + n = u; + wn.setNextToMe(n); + + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + + n.setVisualizationStatus(Visualizable.NORMAL | Visualizable.BALANCE + | Visualizable.ROTATE_LEFT_ARROW); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/RotateRight.java b/src/org/jalgo/module/avl/algorithm/RotateRight.java new file mode 100644 index 0000000..7631b93 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/RotateRight.java @@ -0,0 +1,126 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * Realizes a left rotation around a given node. + * + * @author Jean Christoph Jung + */ +public class RotateRight +extends Command { + + private WorkNode wn; + private AVLNode n; + private SearchTree tree; + + private int uBalance, vBalance; + + /** + * @param tree in this tree the Rotation is done. + * @param wn the rotation is done around the node next to the worknode + */ + public RotateRight(SearchTree tree, WorkNode wn) { + super(); + this.wn = wn; + this.n = (AVLNode)wn.getNextToMe(); + this.tree = tree; + } + + /** + * performs the rotation and actualizes the balances and heights + */ + @SuppressWarnings("unchecked") + public void perform() { + results.add(0, Messages.getString( + "avl", "Rotate_right_around") + n.getKey()); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "3a"); //$NON-NLS-1$ + + n.setVisualizationStatus(Visualizable.NORMAL); + AVLNode v = n; + AVLNode u = (AVLNode)v.getLeftChild(); + AVLNode b = null; + if (u.getRightChild() != null) b = (AVLNode)u.getRightChild(); + + v.setLeftChild(b); + if (b != null) b.setParent(v); + u.setRightChild(v); + u.setParent(v.getParent()); + v.setParent(u); + + if (u.getParent() != null) if (u.getKey() > u.getParent().getKey()) + u.getParent().setRightChild(u); + else u.getParent().setLeftChild(u); + else // u is the root of the SearchTree + tree.setRoot(u); + + uBalance = u.getBalance(); + vBalance = v.getBalance(); + SearchTree.calculateBalances(u); + n = u; + wn.setNextToMe(n); + + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + } + + /** + * undoes the rotation and set the old balances and heights + */ + public void undo() { + AVLNode u = n; + AVLNode v = (AVLNode)u.getRightChild(); + AVLNode b = null; + if (v.getLeftChild() != null) b = (AVLNode)v.getLeftChild(); + u.setRightChild(b); + if (b != null) b.setParent(u); + v.setParent(u.getParent()); + u.setParent(v); + v.setLeftChild(u); + + if (v.getParent() != null) if (v.getKey() > v.getParent().getKey()) + v.getParent().setRightChild(v); + else v.getParent().setLeftChild(v); + else // v is the root of the SearchTree + tree.setRoot(v); + + u.setBalance(uBalance); + v.setBalance(vBalance); + + n = v; + wn.setNextToMe(n); + + Command ch = CommandFactory.createCalcHeight(tree.getRoot()); + ch.perform(); + + n.setVisualizationStatus(Visualizable.NORMAL | Visualizable.BALANCE + | Visualizable.ROTATE_RIGHT_ARROW); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/Search.java b/src/org/jalgo/module/avl/algorithm/Search.java new file mode 100644 index 0000000..94d00ae --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/Search.java @@ -0,0 +1,212 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.*; +import org.jalgo.module.avl.*; + +/** + * @author Ulrike Fischer + * + * The class Search searches a key in the tree. + */ +public class Search +extends MacroCommand +implements Constants { + + private WorkNode wn; + + private boolean firstundo = false; + + /** + * @param wn reference to the position in the tree, holds the search key + */ + @SuppressWarnings("unchecked") + public Search(WorkNode wn) { + super(); + name = Messages.getString("avl", "Alg_name.Search"); //$NON-NLS-1$ //$NON-NLS-2$ + this.wn = wn; + + // checks if the tree is empty + if (wn.getNextToMe() == null) { + results.add(0, Messages.getString( + "avl", "Tree_empty_key_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + } + else { + commands.add(CommandFactory.createCompareKey(wn)); + results.add(0, wn.getKey() + Messages.getString( + "avl", "Key_search")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.getNextToMe().setVisualizationStatus(Visualizable.FOCUSED); + } + } + + /** + * Searches the key of the WorkNode in the tree, returns FOUND if the key + * was found, WORKING if the algorithm isn't yet finished or NOTFOUND if the + * key was not found. In the last case Search also returns the position to + * insert (LEFT or RIGHT). + */ + @SuppressWarnings("unchecked") + public void perform() { + results.clear(); + Command c = commands.get(currentPosition); + c.perform(); + currentPosition++; + + if (c instanceof NoOperation) { + results.add(0, Messages.getString("avl", "Key_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, FOUND); + wn.getNextToMe().setVisualizationStatus(Visualizable.NORMAL); + return; + } + + Integer compareresult = (Integer)c.getResults().get(0); + + switch (compareresult) { + case 0: { + results.add(0, wn.getKey() + " = " + wn.getNextToMe().getKey()); //$NON-NLS-1$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED | Visualizable.LINE_NORMAL); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createNoOperation()); + firstundo = true; + break; + // key found + } + + case -1: { + if (wn.getNextToMe().getLeftChild() == null) { + results.add(0, wn.getKey() + " < " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + results.add(3, LEFT); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + firstundo = true; + // end of Search, key not found + } + else { + results.add(0, wn.getKey() + " < " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_step_to_left")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.setNextToMe(wn.getNextToMe().getLeftChild()); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createCompareKey(wn)); + } + break; + } + + case 1: { + if (wn.getNextToMe().getRightChild() == null) { + results.add(0, wn.getKey() + " > " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + results.add(3, RIGHT); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + firstundo = true; + // end of Search, key not found + } + else { + results.add(0, wn.getKey() + " > " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_step_to_right")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.setNextToMe(wn.getNextToMe().getRightChild()); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createCompareKey(wn)); + } + break; + } + } + } + + /** + * Realizes undo by changing the position of the WorkNode + */ + @SuppressWarnings("unchecked") + public void undo() { + results.clear(); + results.add(Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add("search1"); //$NON-NLS-1$ + + currentPosition--; + Command c = commands.get(currentPosition); + + if (c instanceof NoOperation) wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED | Visualizable.LINE_NORMAL); + else if (firstundo) { + wn.setVisualizationStatus(Visualizable.NORMAL); + setNodesTo(wn.getNextToMe(), Visualizable.FOCUSED); + firstundo = false; + } + else { + wn.getNextToMe().setVisualizationStatus(Visualizable.NORMAL); + wn.setNextToMe(wn.getNextToMe().getParent()); + } + } + + /** + * Performs all single steps. + */ + public void performBlockStep() { + while (this.hasNext()) perform(); + } + + /** + * Realizes undo for all performs. + */ + public void undoBlockStep() { + while (this.hasPrevious()) undo(); + } + + private void setNodesTo(Node n, int status) { + while (n != null) { + n.setVisualizationStatus(status); + n = n.getParent(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/SearchAlg.java b/src/org/jalgo/module/avl/algorithm/SearchAlg.java new file mode 100644 index 0000000..6a73d4c --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/SearchAlg.java @@ -0,0 +1,199 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * + */ +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Constants; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; + +/** + * The class Search searches a key in the tree. + * + * @author Ulrike Fischer, Jean Christoph Jung + */ +public class SearchAlg +extends MacroCommand +implements Constants { + + private WorkNode wn; + private boolean firstundo = false; + + /** + * @param wn the WorkNode with the key to be searched in the tree + */ + @SuppressWarnings("unchecked") + public SearchAlg(WorkNode wn) { + super(); + name = Messages.getString("avl", "Alg_name.Search"); //$NON-NLS-1$ //$NON-NLS-2$ + this.wn = wn; + + // checks if the tree is empty + if (wn.getNextToMe() == null) { + results.add(0, Messages.getString( + "avl", "Tree_empty_key_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + } + else { + commands.add(CommandFactory.createCompareKey(wn)); + results.add(0, wn.getKey() + Messages.getString( + "avl", "Key_search")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.getNextToMe().setVisualizationStatus(Visualizable.FOCUSED); + } + } + + /** + * Searches the key of the WorkNode in the tree, returns FOUND if the key + * was found, WORKING if the algorithm isn't yet finished or NOTFOUND if the + * key was not found. In the last case Search also returns the position to + * insert (LEFT or RIGHT). + */ + @SuppressWarnings("unchecked") + public void perform() { + results.clear(); + Command c = commands.get(currentPosition); + c.perform(); + currentPosition++; + + Integer compareresult = (Integer)c.getResults().get(0); + + switch (compareresult) { + case 0: { + results.add(0, wn.getKey() + " = " + wn.getNextToMe().getKey()); //$NON-NLS-1$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, FOUND); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED | Visualizable.LINE_NORMAL); + firstundo = true; + break; + // key found + } + + case -1: { + if (wn.getNextToMe().getLeftChild() == null) { + results.add(0, wn.getKey() + " < " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + results.add(3, LEFT); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + firstundo = true; + // end of Search, key not found + } + else { + results.add(0, wn.getKey() + " < " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_step_to_left")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.setNextToMe(wn.getNextToMe().getLeftChild()); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createCompareKey(wn)); + } + break; + } + + case 1: { + if (wn.getNextToMe().getRightChild() == null) { + results.add(0, wn.getKey() + " > " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_not_found")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, NOTFOUND); + results.add(3, RIGHT); + wn.setVisualizationStatus(Visualizable.INVISIBLE); + setNodesTo(wn.getNextToMe(), Visualizable.NORMAL); + firstundo = true; + // end of Search, key not found + } + else { + results.add(0, wn.getKey() + " > " //$NON-NLS-1$ + + wn.getNextToMe().getKey() + + Messages.getString("avl", "Search_step_to_right")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add(1, "search1"); //$NON-NLS-1$ + results.add(2, WORKING); + wn.setNextToMe(wn.getNextToMe().getRightChild()); + wn.getNextToMe().setVisualizationStatus( + Visualizable.FOCUSED); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createCompareKey(wn)); + } + break; + } + } + } + + /** + * Realizes undo by changing the position of the WorkNode + */ + @SuppressWarnings("unchecked") + public void undo() { + results.clear(); + results.add(Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + results.add("search1"); //$NON-NLS-1$ + + currentPosition--; + //TODO: for what this line is here? +// Command c = commands.get(currentPosition); + + if (firstundo) { + wn.setVisualizationStatus(Visualizable.NORMAL); + setNodesTo(wn.getNextToMe(), Visualizable.FOCUSED); + firstundo = false; + } + else { + wn.getNextToMe().setVisualizationStatus(Visualizable.NORMAL); + wn.setNextToMe(wn.getNextToMe().getParent()); + } + } + + public void performBlockStep() { + while (this.hasNext()) perform(); + } + + public void undoBlockStep() { + while (this.hasPrevious()) undo(); + } + + private void setNodesTo(Node n, int status) { + while (n != null) { + n.setVisualizationStatus(status); + n = n.getParent(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/Traverse.java b/src/org/jalgo/module/avl/algorithm/Traverse.java new file mode 100644 index 0000000..e79c8a1 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/Traverse.java @@ -0,0 +1,49 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +/** + * TODO This class is currently not implemented, and therefore not being used. + * + * @author Ulrike Fischer + */ +public class Traverse +extends MacroCommand { + + public void perform() { + // this method has no effect + } + + public void undo() { + // this method has no effect + } + + public void performBlockStep() { + // this method has no effect + } + + public void undoBlockStep() { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/algorithm/UpdateBalance.java b/src/org/jalgo/module/avl/algorithm/UpdateBalance.java new file mode 100644 index 0000000..ec495f0 --- /dev/null +++ b/src/org/jalgo/module/avl/algorithm/UpdateBalance.java @@ -0,0 +1,193 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.algorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.*; +import org.jalgo.module.avl.datastructure.*; + +import java.util.*; + +/** + * @author Ulrike Fischer + * + * The class UpdateBalance gets a start node and calculates all + * balances using CalculateBalance beginning from this node. + */ +public class UpdateBalance +extends MacroCommand +implements Constants { + + private WorkNode wn; + private AVLNode currentNode = null; + private Set updatednodes; + private String oldsection; + + /** + * @param wn reference to the position in the tree, holds the + * nextToMe node where UpdateBalance + * begins + */ + public UpdateBalance(WorkNode wn) { + super(); + this.wn = wn; + updatednodes = new HashSet(); + commands.add(CommandFactory.createCalcBalance(wn)); + } + + /** + * Calculates all balances from the inserted node until it reaches the root + * or the balance of a node is 2 or -2. + */ + @SuppressWarnings("unchecked") + public void perform() { + results.clear(); + results.add(0, ""); //$NON-NLS-1$ + results.add(1, "absatz"); //$NON-NLS-1$ + + updatednodes.add(wn.getNextToMe()); + + Command c = commands.get(currentPosition); + c.perform(); + currentPosition++; + + if (c instanceof NoOperation) { + if (wn.getNextToMe().getParent() == null) results.add(2, ROOT); + else results.add(2, DONE); + results.set(1, oldsection); + return; + } + int balanceresult = (Integer)c.getResults().get(2); + + // if (currentNode==null) + // results.set(0,"Balance auf 0 gesetzt"); + // else + // results.set(0,"Balance aktualisiert: " + balanceresult); + + results.set(0, Messages.getString( + "avl", "UpdateBalance.Balance_set_to") + //$NON-NLS-1$ //$NON-NLS-2$ + balanceresult + + Messages.getString("avl", "UpdateBalance.Balance_set")); //$NON-NLS-1$ //$NON-NLS-2$ + + currentNode = (AVLNode)wn.getNextToMe(); + + if (balanceresult == 2) { + AVLNode r = (AVLNode)currentNode.getRightChild(); + if (r.getBalance() == -1) { + results.add(2, DOUBLEROTATE); + results.add(3, RIGHT); + results.add(4, r); + results.add(5, LEFT); + results.add(6, currentNode); + } + else { + results.add(2, ROTATE); + results.add(3, LEFT); + } + } + + else if (balanceresult == -2) { + AVLNode l = (AVLNode)currentNode.getLeftChild(); + if (l.getBalance() == 1) { + results.add(2, DOUBLEROTATE); + results.add(3, LEFT); + results.add(4, l); + results.add(5, RIGHT); + results.add(6, currentNode); + } + else { + results.add(2, ROTATE); + results.add(3, RIGHT); + } + } + else if (balanceresult == 0 && currentPosition != 1) { + oldsection = (String)c.getResults().get(1); + results.add(2, WORKING); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createNoOperation()); + } + else if (wn.getNextToMe().getParent() == null) { + oldsection = (String)c.getResults().get(1); + results.add(2, WORKING); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createNoOperation()); + } + else { + results.add(2, WORKING); + wn.setNextToMe(wn.getNextToMe().getParent()); + if (currentPosition == commands.size()) + commands.add(CommandFactory.createCalcBalance(wn)); + } + + results.set(1, c.getResults().get(1)); + } + + /** + * Sets all balances back to there previous ones. + */ + @SuppressWarnings("unchecked") + public void undo() { + if (currentPosition == 0) throw new NullPointerException(); + + results.clear(); + results.add(0, Messages.getString("avl", "Step_undone")); //$NON-NLS-1$ //$NON-NLS-2$ + + // necessary for DoubleRotation, sets RotateVisualisationStatus back + // to normal + if (!hasNext()) for (Node n : updatednodes) n.setVisualizationStatus( + Visualizable.BALANCE | Visualizable.NORMAL); + currentPosition--; + Command c = commands.get(currentPosition); + + if (c instanceof NoOperation) { + for (Node n : updatednodes) { + n.setVisualizationStatus(Visualizable.NORMAL + | Visualizable.BALANCE); + } + results.add(1, oldsection); + results.add(2, WORKING); + } + else { + c.undo(); + results.add(1, c.getResult(1)); + if (currentPosition == 0) { + results.add(2, LASTUNDO); + currentNode = null; + } + else results.add(2, DONE); + } + } + + public void performBlockStep() { + while (this.hasNext()) perform(); + } + + public void undoBlockStep() { + while (this.hasNext()) undo(); + } + + public Set getUpdatednodes() { + return updatednodes; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/datastructure/AVLNode.java b/src/org/jalgo/module/avl/datastructure/AVLNode.java new file mode 100644 index 0000000..5a41d1f --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/AVLNode.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.datastructure; + +/** + * The class AVLNode represents a node in an AVL tree. In + * addition to the fields of Node, an AVLNode has + * also a balance. + * + * @author Ulrike Fischer + */ +public class AVLNode +extends Node { + + private int balance; + + /** + * Constructs an AVLNode with the given key. A call to this + * constructor is equal to AVLNode(key, null). + * + * @param key the key of the node + */ + public AVLNode(int key) { + this(key, null); + } + + /** + * Constructs an AVLNode object with the given key and the + * given node as parent node. + * + * @param key the key of the node + * @param parent the parent node of this node + */ + public AVLNode(int key, AVLNode parent) { + super(key, parent); + balance = 0; + } + + /** + * Sets the balance of this node to the given integer. + * + * @param balance the new balance of this node + */ + public void setBalance(int balance) { + this.balance = balance; + } + + /** + * Retrieves the balance of this AVLNode. + * + * @return the balance of this node + */ + public int getBalance() { + return balance; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/datastructure/CVS/Entries b/src/org/jalgo/module/avl/datastructure/CVS/Entries new file mode 100644 index 0000000..6cc32a0 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/CVS/Entries @@ -0,0 +1,5 @@ +/AVLNode.java/1.4/Thu Jan 31 20:15:00 2008// +/Node.java/1.4/Thu Jan 31 20:15:00 2008// +/SearchTree.java/1.6/Thu Jan 31 20:15:00 2008// +/Visualizable.java/1.4/Thu Jan 31 20:15:00 2008// +/WorkNode.java/1.4/Thu Jan 31 20:15:00 2008// diff --git a/src/org/jalgo/module/avl/datastructure/CVS/Repository b/src/org/jalgo/module/avl/datastructure/CVS/Repository new file mode 100644 index 0000000..4347656 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/datastructure diff --git a/src/org/jalgo/module/avl/datastructure/CVS/Root b/src/org/jalgo/module/avl/datastructure/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/datastructure/Node.java b/src/org/jalgo/module/avl/datastructure/Node.java new file mode 100644 index 0000000..55a6741 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/Node.java @@ -0,0 +1,203 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.datastructure; + +import org.jalgo.module.avl.Constants; + +/** + * The class Node represents a node in a tree. It has a key value + * and references to his parent and child nodes. The height of the partial tree + * with this as root node is stored in the node directly. This approach is more + * efficient than calculating the height everytime it is needed. + * + * @author Ulrike Fischer, Alexander Claus + */ +public class Node +implements Visualizable, Constants { + + protected Node rightChild; + protected Node leftChild; + protected Node parent; + protected int key; + protected int visualizationStatus; + protected int height; + + /** + * Constructs a Node object with the given key. A call to + * this constructor is equal to Node(key, null). + * + * @param key the key of the node + */ + public Node(int key) { + this(key, null); + } + + /** + * Constructs a Node object with the given key and the given + * node as parent node. + * + * @param key the key of the node + * @param parent the parent node of this node + */ + public Node(int key, Node parent) { + this.key = key; + this.parent = parent; + leftChild = null; + rightChild = null; + setVisualizationStatus(NORMAL); + } + + /** + * Sets the parent node of this node to the given node. + * + * @param p the new parent node of this node + */ + public void setParent(Node p) { + parent = p; + } + + /** + * Retrieves the parent node of this node. If this is the root node of a + * tree, null is returned. + * + * @return the parent node of this node + */ + public Node getParent() { + return parent; + } + + /** + * Sets the left child of this node to the given node. + * + * @param n the new left child of this node + */ + public void setLeftChild(Node n) { + leftChild = n; + } + + /** + * Retrieves the left child of this node. + * + * @return the left child of this node + */ + public Node getLeftChild() { + return leftChild; + } + + /** + * Sets the right child of this node to the given node. + * + * @param n the new right child of this node + */ + public void setRightChild(Node n) { + rightChild = n; + } + + /** + * Retrieves the right child of this node. + * + * @return the right child of this node + */ + public Node getRightChild() { + return rightChild; + } + + /** + * Sets the key of this node to the given integer + * + * @param key the new key of the node + */ + public void setKey(int key) { + this.key = key; + } + + /** + * Retrieves the key of this node. + * + * @return the key of this node + */ + public int getKey() { + return key; + } + + /** + * Sets the height of the partial tree with this node as root node to the + * given integer. + * + * @param h the height of the child tree + */ + public void setHeight(int h) { + height = h; + } + + /** + * Retrieves the stored height of the partial tree with this node as root + * node. + * + * @return the height of the child tree + */ + public int getHeight() { + return height; + } + + /** + * Sets the visualization status of this node. + */ + public void setVisualizationStatus(int s) { + visualizationStatus = s; + } + + /** + * Retrieves the visualization status of this node. + */ + public int getVisualizationStatus() { + return visualizationStatus; + } + + /** + * Returns a String representation of this Node. Currently + * this String representation consists only of the key value. + * + * @return a String representation of this Node + */ + public String toString() { + return new StringBuffer().append(key).toString(); + } + + /** + * Tests if this instance of Node is equal to the given + * parameter. If the given parameter is an instance of Node, + * the key of the node is compared with the key of the other node. + * + * @param other the Object to be compared with + * + * @return true, if the given parameter is a node with the + * same key, false otherwise + */ + public boolean equals(Object other) { + if (other == null) return false; + if (other instanceof Node) return (key == ((Node)other).key); + return false; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/datastructure/SearchTree.java b/src/org/jalgo/module/avl/datastructure/SearchTree.java new file mode 100644 index 0000000..afddf34 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/SearchTree.java @@ -0,0 +1,374 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.datastructure; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.avl.algorithm.Command; +import org.jalgo.module.avl.algorithm.CommandFactory; +import org.jalgo.module.avl.algorithm.MacroCommand; + +/** + * The class SearchTree is the main data structure of the AVL + * module. It holds a reference to the root node and provides several methods + * for working with the tree. Some methods provide information about the tree, + * such as the weight, the height, the level of a specified node and so on. + * Other methods provide traversion of the tree in different orders. + * + * @author Matthias Schmidt, Jean Christoph Jung, Alexander Claus + */ +public class SearchTree { + + /** The root of the tree */ + private Node root; + + /** + * Constructs an empty SearchTree object. A call to this + * constructor is equal to SearchTree(null). + */ + public SearchTree() { + this(null); + } + + /** + * Constructs a new SearchTree object with the given root + * node. This root node can represent a complete partial tree, but + * attention: ensure to calculate the height of the tree! + * + * @param root the root of the tree + */ + public SearchTree(Node root) { + this.root = root; + } + + /** + * Sets the root of the tree to the given node. + * + * @param root the new root node + */ + public void setRoot(Node root) { + this.root = root; + } + + /** + * Retrieves the root node of this SearchTree. + * + * @return the root node of the tree + */ + public Node getRoot() { + return root; + } + + /** + * Prints this SearchTree in inorder to the standard output + * stream. This method is useful for debugging. + */ + public void printToConsole() { + System.out.println(exportInOrder()); + } + + /** + * Calculates the weight of this SearchTree. This means, the + * number of Nodes is returned. + * + * @return the weight of this SearchTree + */ + public int getWeight() { + return calcWeight(root); + } + + /** + * Calculates the weight of the given partial tree. + * + * @param node the root of the tree for which weight has to be calculated + * + * @return the weight of the given partial tree + */ + private int calcWeight(Node node) { + if (node == null) return 0; + return calcWeight(node.leftChild) + calcWeight(node.rightChild) + 1; + } + + /** + * Returns the height of this SearchTree. This method does + * not calculate the height. It only returns a precalculated value. So all + * algorithms, which can change the structure of the tree, have to calculate + * the height newly.
      + * This approach is introduced in order to have a efficient implementation, + * because the height of the tree is requested relatively often. + * + * @return the height of this SearchTree + */ + public int getHeight() { + if (root == null) return 0; + return root.getHeight(); + } + + /** + * Calculates the level of the given Node. This method is + * interesting for displaying the tree and for calculating the average + * height of this SearchTree. + * + * @param node the node, for which the level has to be calculated + * + * @return the level of the node + */ + public int getLevelFor(Node node) { + if (node == null) return -1; + + // here no Search-command is used, because this command changes the + // visualization status of some nodes + int level = 0; + Node temp = root; + while (temp != null) { + if (temp.getKey() < node.getKey()) temp = temp.getRightChild(); + else if (temp.getKey() > node.getKey()) temp = temp.getLeftChild(); + else return level + 1; + level++; + } + return level; + } + + /** + * Searches for the Node with the given key. + * + * @param key the key of the searched Node + * + * @return the Node with the given key, if it is in the tree, + * null otherwise + */ + public Node getNodeFor(int key) { + Node node = root; + while (node != null) { + if (node.getKey() < key) node = node.getRightChild(); + else if (node.getKey() > key) node = node.getLeftChild(); + else return node; + } + return null; + } + + /* Traversion of the Tree */ + + /** + * Traverses this SearchTree in inorder and puts the + * Nodes in a list. + * + * @return the Nodes of this SearchTree in + * inorder + */ + public List exportInOrder() { + List nodeList = new LinkedList(); + copyNodeToInOrderList(root, nodeList); + return nodeList; + } + + /** + * A helper method to get an inorder list of the Nodes of + * this SearchTree. + * + * @param node the currently watched node in traversion + * @param list an empty Node list to be filled + */ + private void copyNodeToInOrderList(Node node, List list) { + if (node == null) return; + copyNodeToInOrderList(node.getLeftChild(), list); + list.add(node); + copyNodeToInOrderList(node.getRightChild(), list); + } + + /** + * Traverses this SearchTree in postorder and puts the + * Nodes in a list. + * + * @return the Nodes of this SearchTree in + * postorder + */ + public List exportPostOrder() { + List nodeList = new LinkedList(); + copyNodeToPostOrderList(root, nodeList); + return nodeList; + } + + /** + * A helper method to get an postorder list of the Nodes of + * this SearchTree. + * + * @param node the currently watched node in traversion + * @param list an empty Node list to be filled + */ + private void copyNodeToPostOrderList(Node node, List list) { + if (node == null) return; + copyNodeToPostOrderList(node.getLeftChild(), list); + copyNodeToPostOrderList(node.getRightChild(), list); + list.add(node); + } + + /** + * Traverses this SearchTree in levelorder and puts the + * Nodes in a list. This method is currently interesting for + * serializing the SearchTree. + * + * @return the Nodes of this SearchTree in + * levelorder + */ + public List exportLevelOrder() { + Node[] uncompressedList = exportUncompressedLevelOrder(); + int size = uncompressedList.length; + List compressedList = new LinkedList(); + for (int i = 0; i < size; i++) { + if (uncompressedList[i] != null) + compressedList.add(uncompressedList[i]); + } + uncompressedList = null; + return compressedList; + } + + /** + * Traverses this SearchTree in levelorder and puts the + * Nodes in a list. This list has 2^(getHeight()-1)-1 + * entries. So it can contain many null values, but such an + * uncompressed list is interesting e.g. for displaying the tree. + * + * @return a riddled array of the Nodes of the tree + */ + public Node[] exportUncompressedLevelOrder() { + Node[] uncompressedList = new Node[(1 << getHeight()) - 1]; + copyNodeToLevelOrderList(root, uncompressedList, 1); + return uncompressedList; + } + + /** + * A helper method to get a levelordered list of the Nodes + * of this SearchTree. This list is riddled because of the + * possible unbalanced structure of the tree. The list to be filled has to + * be of the following type: Node[(1<<getHeight())-1] + * + * @param node the currently watched node in traversion + * @param list the Node array to be filled + * @param index the index of the currently watched node, important for level + * ordering + */ + private static void copyNodeToLevelOrderList(Node node, Node[] list, + int index) { + if (node == null) return; + list[index - 1] = node; + copyNodeToLevelOrderList(node.getLeftChild(), list, 2 * index); + copyNodeToLevelOrderList(node.getRightChild(), list, 2 * index + 1); + } + + /** + * Fills this SearchTree with the given keys, so that the + * structure of the tree is supported. Attention: the + * SearchTree is not cleared before inserting the values. If + * there are entries in the tree, they are keeped. If You want to use this + * operation to create a new tree with the given values, e.g. during + * deserializing, You have to ensure that this SearchTree is + * cleared before calling this operation. + * + * @param levelOrder the key values in levelorder + */ + public void importLevelOrder(List levelOrder) { + MacroCommand insert; + WorkNode wn; + for (int key : levelOrder) { + wn = new WorkNode(key); + wn.setNextToMe(root); + insert = CommandFactory.createInsert(wn, this); + while (insert.hasNext()) + insert.perform(); + } + + // update height fields + Command calcHeight = CommandFactory.createCalcHeight(root); + calcHeight.perform(); + // update balances + calculateBalances((AVLNode)root); + // TODO: nur Ãœbergangslösung, auskommentiertes soll hier rein + // Command calcAllBalances = CommandFactory.createCalcAllBalances(root); + // calcAllBalances.perform(); + } + + /** + * Removes all Nodes from this SearchTree. + */ + public void clear() { + root = null; + } + + // TODO: raus mit dieser methode! daf�r haben wir ein command. + // avltest, left- und rightrotation k�nnen das command benutzen. + // sonst duplizierter code... + public static int calculateBalances(AVLNode n) { + if (n == null) return 0; + int left = SearchTree.calculateBalances((AVLNode)n.getLeftChild()); + int right = SearchTree.calculateBalances((AVLNode)n.getRightChild()); + + n.setBalance(right - left); + return Math.max(right, left) + 1; + } + + /** + * Retrieves the node with the minimal key in the partial tree with the + * given root node. + * + * @param root the root node of the partial tree + * + * @return the Node with the minimal key in the tree + */ + public static Node getMinimumNode(Node root) { + if (root == null) return null; + if (root.getLeftChild() != null) + return getMinimumNode(root.getLeftChild()); + return root; + } + + /** + * Retrieves the node with the minimal key in the partial tree with the + * given root node. + * + * @param root the root node of the partial tree + * + * @return the Node with the minimal key in the tree + */ + public static Node getMaximumNode(Node root) { + if (root == null) return null; + if (root.getRightChild() != null) + return getMaximumNode(root.getRightChild()); + return root; + } + + /** + * Tests, if the given parameter is equal to this instance of + * SearchTree. + */ + public boolean equals(Object other) { + if (other == null) return false; + if (other instanceof SearchTree) return Arrays.asList( + exportUncompressedLevelOrder()).equals( + Arrays.asList(((SearchTree)other).exportUncompressedLevelOrder())); + return false; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/datastructure/Visualizable.java b/src/org/jalgo/module/avl/datastructure/Visualizable.java new file mode 100644 index 0000000..e993bf8 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/Visualizable.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 03.05.2005 */ +package org.jalgo.module.avl.datastructure; + +/** + * The interface Visualizable has to be implemented by data + * structures, which are intended to be visualized. With setting some flags the + * programmer can change the style of the data structure, or some decorations + * can be added. + * + * @author Ulrike Fischer + */ +public interface Visualizable { + + /** + * Sets the visualization status of the underlying data structure to the + * given value. The different flags can be combined with bitwise OR'ing. + * + * @param status the visualization flags + */ + public void setVisualizationStatus(int status); + + /** + * Retrieves the visualization status of the underlying data structure. With + * bitwise AND'ing the programmer can test, if the different flags are set. + * + * @return the visualization flags of the data structure + */ + public int getVisualizationStatus(); + + // the flags + /** Indicates that the data structure is painted normally. */ + public static final int NORMAL = 1; + /** Indicates that the data structure is hided. */ + public static final int INVISIBLE = 2; + /** Indicates that the data structure has to be painted highlighted. */ + public static final int FOCUSED = 4; + /** Indicates that the balance to the node has to be displayed. */ + public static final int BALANCE = 8; + /** Indicates that an insertion arrow to the left has to be painted. */ + public static final int LEFT_ARROW = 16; + /** Indicates that an insertion arrow to the right has to be painted. */ + public static final int RIGHT_ARROW = 32; + /** Indicates that an rotation arrow to the left has to be painted. */ + public static final int ROTATE_LEFT_ARROW = 64; + /** Indicates that an rotation arrow to the right has to be painted. */ + public static final int ROTATE_RIGHT_ARROW = 128; + /** Indicates that the connection to this node has to be painted normally. */ + public static final int LINE_NORMAL = 256; +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/datastructure/WorkNode.java b/src/org/jalgo/module/avl/datastructure/WorkNode.java new file mode 100644 index 0000000..11cc212 --- /dev/null +++ b/src/org/jalgo/module/avl/datastructure/WorkNode.java @@ -0,0 +1,78 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 25.04.2005 */ +package org.jalgo.module.avl.datastructure; + +/** + * The class WorkNode represents the working node for AVL tree + * algorithms. It contains a key and holds a reference to the Node, + * which is the currently watched node in algorithm. + * + * @author Ulrike Fischer + */ +public class WorkNode +extends Node { + + private Node nextToMe; + + /** + * Constructs a WorkNode object with the given key. A call to + * this constructor is equal to WorkNode(key, null). + * + * @param key the key of the working node + */ + public WorkNode(int key) { + this(key, null); + } + + /** + * Constructs a WorkNode object with the given key and the + * given Node reference. + * + * @param key the key of the working node + * @param next the currently watched node in algorithm + */ + public WorkNode(int key, Node next) { + super(key); + nextToMe = next; + } + + /** + * Retrieves the currently watched node in algorithm. + * + * @return the currently watched node + */ + public Node getNextToMe() { + return nextToMe; + } + + /** + * Sets the currently watched node to the given node. + * + * @param node the currently watched node in algorithm + */ + public void setNextToMe(Node node) { + nextToMe = node; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/de.properties b/src/org/jalgo/module/avl/de.properties new file mode 100644 index 0000000..7cc036c --- /dev/null +++ b/src/org/jalgo/module/avl/de.properties @@ -0,0 +1,135 @@ +Module_name=AVL - Bäume +Module_version=1.0 +Module_authors=Alexander Claus, Ulrike Fischer, Jean Christoph Jung, Sebastian Pape, Matthias Schmidt +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt binäre Suchbäume mit und ohne der AVL-Eigenschaft. +Module_description_2=Es werden die Algorithmen Suchen, Einfügen und Löschen visualisiert. Dabei können die Algorithmen interaktiv gesteuert werden. + +ModuleConnector.No_valid_AVL_file=Keine gültige AVL-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. +GUIController.Is_AVL_tree=Der aktuelle Baum hat die AVL - Eigenschaft\! +GUIController.Wish_to_change_to_AVL_mode=Möchten Sie jetzt in den AVL - Modus wechseln? +GUIController.Changed_to_AVL_mode=AVL-Modus angeschalten +GUIController.Is_no_AVL_tree=Der aktuelle Baum ist kein AVL - Baum\! +PaintArea.Status_message=Stellt den Baum graphisch dar +Hard_exception=Schwerer Ausnahmefehler: +Alg_desc_not_found_error=Xml-Datei nicht gefunden oder anderer Fehler + +Clear_tree=Baum löschen +Clear_tree_tooltip=Löscht den gesamten Baum +Clear_tree_warning=Der gesamte Baum wird gelöscht. +Show_welcome_screen=Willkommensbildschirm anzeigen +Show_welcome_screen_tooltip=Öffnet den Willkommensbildschirm +Wish_to_discard=Möchten Sie Ihre Änderungen verwerfen? + +Abort_algorithm=Algorithmus abbrechen +Abort_algorithm_tooltip=Bricht den laufenden Algorithmus ab +Undo=Schritt zurück +Undo_tooltip=Macht den letzten Schritt im aktuellen Algorithmus rückgängig +Undo_blockstep=Blockschritt zurück +Undo_blockstep_tooltip=Macht den letzen grösseren Schritt im aktuellen Algorithmus rückgängig +Perform=Nächster Schritt +Perform_tooltip=Führt den nächsten Schritt im aktuellen Algorithmus aus +Perform_blockstep=Nächster Blockschritt +Perform_blockstep_tooltip=Führt den nächsten grösseren Schritt im aktuellen Algorithmus aus +Finish_algorithm=Algorithmus beenden +Finish_algorithm_tooltip=Durchläuft den Algorithmus bis zum Ende +Beamer_mode=Beamermodus +AVL_mode=AVL-Modus +Switched_on=angeschalten +Switched_off=abgeschalten + +RGD.Generate_random_tree=Zufallsbaum erstellen +RGD.Node_count=Anzahl der Knoten: +RGD.AVL_property=AVL - Eigenschaft: +RGD.Visualization=Visualisierung: +RGD.No_visualization=keine +RGD.Stepwise=schrittweise +RGD.Automatical=automatisch +RGD.Button_ok=Ok +RGD.Button_cancel=Abbrechen +Warning_only_integers=Bitte nur ganze Zahlen eingeben\! +Warning_only_values_from=Nur Werte von +Warning_to=\ bis +Warning_valid=\ gültig\! +Navigator=Navigator +No_robot_error=Keine Maussprünge möglich. +LogPane.Status_message=Gibt erfolgte Aktionen logbuchartig wieder +LogPane.Update_error=Fehler beim Logbuch-Update +Unreachable_error=Sollte nicht auftreten... +InfoPane.Info=Info +InfoPane.Node_count=Anzahl Knoten: +InfoPane.Height=Baumhöhe: +InfoPane.Average_depth=Durchschnittliche Suchtiefe: +InfoPane.Status_message=Zeigt Informationen über den Baum an +DocuPane.Status_message=Zeigt den Algorithmustext an +DocuPane.Update_error=Fehler bei der Anzeige der Dokumentation: +ControlPane.Label=Kontroll-Bereich +ControlPane.Key=Schlüssel: +ControlPane.Insert_key=Geben Sie hier den Schlüssel ein +ControlPane.Random=Zufallswert +ControlPane.Random_tooltip=Erzeugt einen Zufallswert +ControlPane.Choose_algorithm=Auswahl eines Algorithmus: +ControlPane.Search_tooltip=Startet den Suchen-Algorithmus mit dem gegebenen Schlüssel +ControlPane.Insert_tooltip=Startet den Einfüge-Algorithmus mit dem gegebenen Schlüssel +Controller.aborted=\ abgebrochen +ControlPane.Remove_tooltip=Startet den Löschen-Algorithmus mit dem gegebenen Schlüssel +ControlPane.AVL_property=AVL - Modus +Controller.finished=\ beendet +ControlPane.AVL_test_tooltip=Testet den aktuellen Baum auf die AVL-Eigenschaft +Controller.No_alg_exception=Es läuft kein Algorithmus\! +Controller.No_next_exception=Es gibt keinen weiteren Schritt mehr\! +Controller.No_prev_exception=Es gibt keinen vorherigen Schritt mehr\! +ControlPane.Flow_control=Algorithmussteuerung: +Controller.Key_not_found=Schlüssel nicht im Baum enthalten +Controller.Log_exception=Algorithmusende noch nicht betrachtet +ControlPane.Anim_speed=Animationsgeschwindigkeit: +Controller.Key_exists=Schlüssel existiert bereits\! +Controller.Successful=\ erfolgreich +ControlPane.fast=schnell +ControlPane.slow=langsam +ControlPane.Anim_speed_tooltip=Stellt die Geschwindigkeit der Animation ein + +Alg_name.AVL_test=AVL-Test +Alg_name.Insert=Einfügen +Alg_name.Insert_AVL=AVL-Einfügen +Alg_name.Remove=Löschen +Alg_name.Remove_AVL=AVL-Löschen +Alg_name.Search=Suchen +Alg_name.Create_tree=Suchbaum Erstellen +Alg_name.Create_AVL_tree=AVL-Baum Erstellen + +CreateRandomTree.With=\ mit +CreateRandomTree.Nodes=\ Knoten +CreateRandomTree.Tree_finished=Suchbaum ist fertig +CreateRandomTree.AVL_finished=AVL-Baum ist fertig +Successor_found=nächstgrößeren Schlüssel gefunden +FindSuccessorStart.Step_to_right=einmal rechts gegangen +FindSuccessor.Step_to_left=links gegangen +_of=\ von +Started=\ gestartet +Insert.Key_found=\nSchlüssel muss nicht eingefügt werden +Insert_left=\ --> links einfügen +Insert_right=\ --> rechts einfügen +Insert_finished=Einfügen beendet +Step_undone=Schritt rückgängig gemacht +Key_search=\ suchen +Node_inserted=Knoten eingefügt +Node_removed=Knoten gelöscht +Node_found=\ Knoten gefunden +Key_found=Schlüssel gefunden +Tree_balanced=\nBaum ausgeglichen +Tree_empty_key_not_found=Baum ist leer, Schlüssel nicht gefunden +Remove_aborted=\ \nLöschen abgebrochen +Remove_finished=Löschen beendet +Root_reached_tree_balanced=Wurzel erreicht\nBaum ausgeglichen +Partial_tree_balanced=\nTeilbaum ausgeglichen +N_tree_balanced=\nBaum ausgeglichen +Rotate_left_around=Linksrotation um: +Rotate_right_around=Rechtsrotation um: +Search_not_found=\nnicht gefunden +Search_step_to_left=\ --> nach links gehen +Search_step_to_right=\ --> nach rechts gehen +UpdateBalance.Balance_set_to=Balance auf +UpdateBalance.Balance_set=\ gesetzt diff --git a/src/org/jalgo/module/avl/en.properties b/src/org/jalgo/module/avl/en.properties new file mode 100644 index 0000000..772d18f --- /dev/null +++ b/src/org/jalgo/module/avl/en.properties @@ -0,0 +1,135 @@ +Module_name=AVL - Trees +Module_version=1.0 +Module_authors=Alexander Claus, Ulrike Fischer, Jean Christoph Jung, Sebastian Pape, Matthias Schmidt +Module_license=GNU General Public License +Module_description_1=This module is about binary search trees with and without the AVL - property. +Module_description_2=The algorithms to be visualized are: Searching, Inserting and Deleting. The algorithms can be controlled interactively. + +ModuleConnector.No_valid_AVL_file=No valid AVL - file. +ModuleConnector.Loading_error=Error while loading the file. +ModuleConnector.File_damaged=Maybe the file is damaged. +GUIController.Is_AVL_tree=The current tree has the AVL - property\! +GUIController.Wish_to_change_to_AVL_mode=Do you wish to switch to the AVL - mode? +GUIController.Changed_to_AVL_mode=AVL - mode on +GUIController.Is_no_AVL_tree=The current tree is no AVL - tree\! +PaintArea.Status_message=Displays the tree graphically. +Hard_exception=Hard exception: +Alg_desc_not_found_error=Xml-file not found. + +Clear_tree=Clear tree +Clear_tree_tooltip=Clears the whole tree. +Clear_tree_warning=The tree will be cleared. +Show_welcome_screen=Show welcome screen +Show_welcome_screen_tooltip=Shows the welcome screen +Wish_to_discard=Do you wish to discard your changes? + +Abort_algorithm=Abort algorithm +Abort_algorithm_tooltip=Aborts the currently running algorithm +Undo=Undo +Undo_tooltip=Undoes the last step in current algorithm +Undo_blockstep=Undo block step +Undo_blockstep_tooltip=Undoes the last block step in current algorithm +Perform=Next step +Perform_tooltip=Performs the next step in current algorithm +Perform_blockstep=Next block step +Perform_blockstep_tooltip=Performs the next block step in current algorithm +Finish_algorithm=Finish algorithm +Finish_algorithm_tooltip=Runs the algorithm until it ends +Beamer_mode=Beamer-mode +AVL_mode=AVL - mode +Switched_on=on +Switched_off=off + +RGD.Generate_random_tree=Generate random-tree +RGD.Node_count=Number of nodes: +RGD.AVL_property=AVL - property: +RGD.Visualization=Visualization: +RGD.No_visualization=no visualization +RGD.Stepwise=stepwise +RGD.Automatical=automatically +RGD.Button_ok=Ok +RGD.Button_cancel=Cancel +Warning_only_integers=Please only insert integers\! +Warning_only_values_from=Only values from +Warning_to=\ to +Warning_valid=\ valid\! +Navigator=Navigator +No_robot_error=No mouse jumps possible. +LogPane.Status_message=Displays done actions in the style of a logbook +LogPane.Update_error=Error at log update +Unreachable_error=This error should not occur... +InfoPane.Info=Info +InfoPane.Node_count=Number of nodes: +InfoPane.Height=Tree-height: +InfoPane.Average_depth=Average depth: +InfoPane.Status_message=Shows informations about the tree +DocuPane.Status_message=Shows the algorithm text +DocuPane.Update_error=Error while displaying the documentation: +ControlPane.Label=Control-Center +ControlPane.Key=Key: +ControlPane.Insert_key=Insert key value here +ControlPane.Random=Random +ControlPane.Random_tooltip=Creates a random value +ControlPane.Choose_algorithm=Choose an algorithm: +ControlPane.Search_tooltip=Starts the search algorithm with the given key +ControlPane.Insert_tooltip=Starts the insert algorithm with the given key +Controller.aborted=\ aborted +ControlPane.Remove_tooltip=Starts the delete algorithm with the given key +ControlPane.AVL_property=AVL - mode +Controller.finished=\ finished +ControlPane.AVL_test_tooltip=Checks the current tree for the AVL - property +Controller.No_alg_exception=Currently is no algorithm running\! +Controller.No_next_exception=There is no next step\! +Controller.No_prev_exception=There is no previous step\! +ControlPane.Flow_control=Algorithm control: +Controller.Key_not_found=Key is not contained in tree +Controller.Log_exception=Exception because of unknown algorithm ending +ControlPane.Anim_speed=Animation speed: +Controller.Key_exists=The key exists already\! +Controller.Successful=\ successful +ControlPane.fast=fast +ControlPane.slow=slow +ControlPane.Anim_speed_tooltip=Sets the speed of the animation + +Alg_name.AVL_test=AVL-Test +Alg_name.Insert=Insert +Alg_name.Insert_AVL=AVL-Insert +Alg_name.Remove=Remove +Alg_name.Remove_AVL=AVL-Remove +Alg_name.Search=Search +Alg_name.Create_tree=Create search tree +Alg_name.Create_AVL_tree=Create AVL - tree + +CreateRandomTree.With=\ with +CreateRandomTree.Nodes=\ Nodes +CreateRandomTree.Tree_finished=Search tree is finished +CreateRandomTree.AVL_finished=AVL - tree is finished +Successor_found=successor found +FindSuccessorStart.Step_to_right=one step to the right +FindSuccessor.Step_to_left=step to the left +_of=\ of +Started=\ started +Insert.Key_found=\nKey doesn't have to be inserted +Insert_left=\ --> insert left +Insert_right=\ --> insert right +Insert_finished=Insert finished +Step_undone=Step undone +Key_search=\ search +Node_inserted=Node inserted +Node_removed=Node removed +Node_found=\ Node found +Key_found=Key found +Tree_balanced=\nTree balanced +Tree_empty_key_not_found=Tree is empty, key not found +Remove_aborted=\ \nRemove aborted +Remove_finished=Remove finished +Root_reached_tree_balanced=Root node reached\nTree balanced +Partial_tree_balanced=\nPartial tree balanced +N_tree_balanced=\nTree balanced +Rotate_left_around=Rotate left at: +Rotate_right_around=Rotate right at: +Search_not_found=\nnot found +Search_step_to_left=\ --> step to the left +Search_step_to_right=\ --> step to the right +UpdateBalance.Balance_set_to=Balance set to +UpdateBalance.Balance_set=\ diff --git a/src/org/jalgo/module/avl/gui/CVS/Entries b/src/org/jalgo/module/avl/gui/CVS/Entries new file mode 100644 index 0000000..9a8e7e4 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/CVS/Entries @@ -0,0 +1,8 @@ +/DisplayModeChangeable.java/1.4/Thu Jan 31 20:15:06 2008// +/DocuManager.java/1.9/Thu Jan 31 20:15:06 2008// +/GUIConstants.java/1.5/Thu Jan 31 20:15:06 2008// +/GUIController.java/1.14/Thu Jan 31 20:15:06 2008// +/Settings.java/1.5/Thu Jan 31 20:15:06 2008// +D/components//// +D/event//// +D/graphics//// diff --git a/src/org/jalgo/module/avl/gui/CVS/Repository b/src/org/jalgo/module/avl/gui/CVS/Repository new file mode 100644 index 0000000..e6f2f8e --- /dev/null +++ b/src/org/jalgo/module/avl/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/gui diff --git a/src/org/jalgo/module/avl/gui/CVS/Root b/src/org/jalgo/module/avl/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/gui/DisplayModeChangeable.java b/src/org/jalgo/module/avl/gui/DisplayModeChangeable.java new file mode 100644 index 0000000..593c42a --- /dev/null +++ b/src/org/jalgo/module/avl/gui/DisplayModeChangeable.java @@ -0,0 +1,43 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 18.06.2005 */ +package org.jalgo.module.avl.gui; + +/** + * The interface DisplayModeChangeable has to be implemented by + * all Components, whose display state should be dependent from a display mode + * setting. Such setting could be a presentation mode for working on a beamer or + * a normal display mode for working on a pc.
      + * Components, which implement this interface have to register themselves at the + * instance, which controls the display mode setting, as observers. + * + * @author Alexander Claus + */ +public interface DisplayModeChangeable { + + /** + * Invoked, if the display mode has changed. + */ + public void displayModeChanged(); +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/DocuManager.java b/src/org/jalgo/module/avl/gui/DocuManager.java new file mode 100644 index 0000000..8f762ad --- /dev/null +++ b/src/org/jalgo/module/avl/gui/DocuManager.java @@ -0,0 +1,301 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 26.04.2005 + */ +package org.jalgo.module.avl.gui; + +import java.util.Map; +import java.util.TreeMap; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.avl.Controller; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * @author Jean Christoph Jung + * + * The DocuManager parses an XML-file, that must have a certain form: ]> + * + * the constructor gets the name of the file and does all the parsing and save + * the content in a treemap . calling the methods + * getMapOfElements or getValue you can access + * that map. + */ +public class DocuManager +implements GUIConstants { + + /** + * @author Jean Christoph Jung + * + * internal class of DocuManager this class extends the DefaultHandler, + * and overwrites the methods characters, startelement, + * endelement . + */ + class XmlHandler + extends DefaultHandler { + + private final int ALGDESC = -1; + private final int STEP = 0; + private final int KEY = 1; + private final int TEXT = 2; + private final int LINE = 3; + + private Map mapOfElements; + private int flag = ALGDESC; + private String key; + private String value = ""; //$NON-NLS-1$ + private String line = ""; //$NON-NLS-1$ + private String startstring = "", endstring = ""; //$NON-NLS-1$ //$NON-NLS-2$ + + public XmlHandler() { + super(); + mapOfElements = new TreeMap(); + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attr) + throws SAXException { + if (qName.equalsIgnoreCase("AlgorithmDescription")) flag = ALGDESC; //$NON-NLS-1$ + else if (qName.equals("Step")) flag = STEP; //$NON-NLS-1$ + else if (qName.equals("Key")) flag = KEY; //$NON-NLS-1$ + else if (qName.equals("Text")) flag = TEXT; //$NON-NLS-1$ + else if (qName.equals("Line")) flag = LINE; //$NON-NLS-1$ + + if (attr != null) { + for (int i = 0; i < attr.getLength(); i++) { + String attribute = attr.getQName(i); + String temp = attr.getValue(i); + int k = -2; + + if (attribute.equals("startswith")) { //$NON-NLS-1$ + if (temp.contains("tab")) //$NON-NLS-1$ + startstring = startstring.concat("\t"); //$NON-NLS-1$ + if (temp.contains("nl")) //$NON-NLS-1$ + startstring = startstring.concat("\n"); //$NON-NLS-1$ + k = temp.indexOf("sp"); //$NON-NLS-1$ + if (k >= 0) { + char whitespaces = temp.charAt(k + 2); + while (whitespaces-- > '0') { + startstring = startstring.concat(" "); //$NON-NLS-1$ + } + } + } + if (attribute.equals("endswith")) { //$NON-NLS-1$ + if (temp.contains("tab")) //$NON-NLS-1$ + endstring = endstring.concat("\t"); //$NON-NLS-1$ + if (temp.contains("nl")) //$NON-NLS-1$ + endstring = endstring.concat("\n"); //$NON-NLS-1$ + k = temp.indexOf("sp"); //$NON-NLS-1$ + if (k >= 0) { + char whitespaces = temp.charAt(k + 2); + while (whitespaces-- > '0') { + endstring = endstring.concat(" "); //$NON-NLS-1$ + } + } + } + } + } + } + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + if (qName.equals("Step")) { //$NON-NLS-1$ + mapOfElements.put(key, value); + key = null; + value = ""; //$NON-NLS-1$ + } + if (qName.equals("Line")) { //$NON-NLS-1$ + value = value + startstring + line + endstring; + line = ""; //$NON-NLS-1$ + startstring = ""; //$NON-NLS-1$ + endstring = ""; //$NON-NLS-1$ + } + flag--; + } + + public void characters(char[] ch, int start, int length) + throws SAXException { + String s = new String(ch, start, length); + s = s.trim(); + if (flag == KEY) key = s; + else if (flag == LINE) { + // if (line==null) + // line = s; + // else { + line = line + s; + // } + } + } + + public Map getMapOfElements() { + return mapOfElements; + } + } + + private Map> mapOfAlgorithms; + private Map> offsets; + private Map> lengths; + + private final Controller controller; + + public DocuManager(Controller controller) { + this.controller = controller; + loadAlgorithmDescription(); + } + + /** + * creates the Algorithm description out of a xml-file - puts the + * description of the single algorithms in single maps - calculates the + * beginning and the length (in chars) of every section + */ + private void loadAlgorithmDescription() { + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + SAXParser saxParser = factory.newSAXParser(); + XmlHandler xmlhandler = new XmlHandler(); + saxParser.parse(getClass().getResourceAsStream( + Messages.getString("avl_res", //$NON-NLS-1$ + "Algorithm_text_base_"+Settings.getString("main", "Language"))), //$NON-NLS-1$ //$NON-NLS-2$ + xmlhandler); + Map mapOfElements = xmlhandler.getMapOfElements(); + + mapOfAlgorithms = new TreeMap>(); + offsets = new TreeMap>(); + lengths = new TreeMap>(); + + mapOfAlgorithms.put("search", new TreeMap()); //$NON-NLS-1$ + mapOfAlgorithms.put("insert", new TreeMap()); //$NON-NLS-1$ + mapOfAlgorithms.put("avlinsert", new TreeMap()); //$NON-NLS-1$ + mapOfAlgorithms.put("remove", new TreeMap()); //$NON-NLS-1$ + mapOfAlgorithms.put("avlremove", new TreeMap()); //$NON-NLS-1$ + + for (String key : mapOfElements.keySet()) { + if (key.startsWith("search")) //$NON-NLS-1$ + mapOfAlgorithms.get("search").put(key, //$NON-NLS-1$ + mapOfElements.get(key)); + if (key.startsWith("insert")) //$NON-NLS-1$ + mapOfAlgorithms.get("insert").put(key, //$NON-NLS-1$ + mapOfElements.get(key)); + if (key.startsWith("avlinsert")) //$NON-NLS-1$ + mapOfAlgorithms.get("avlinsert").put(key, //$NON-NLS-1$ + mapOfElements.get(key)); + if (key.startsWith("remove")) //$NON-NLS-1$ + mapOfAlgorithms.get("remove").put(key, //$NON-NLS-1$ + mapOfElements.get(key)); + if (key.startsWith("avlremove")) //$NON-NLS-1$ + mapOfAlgorithms.get("avlremove").put(key, //$NON-NLS-1$ + mapOfElements.get(key)); + } + + for (String key : mapOfAlgorithms.keySet()) { + Map m = mapOfAlgorithms.get(key); + + Map offsetmap = new TreeMap(); + Map lengthmap = new TreeMap(); + int offset = 0; + int length = 0; + + for (String key1 : m.keySet()) { + String text = mapOfElements.get(key1); + length = text.length(); + offsetmap.put(key1, offset); + lengthmap.put(key1, length); + offset += length; + } + offsets.put(key, offsetmap); + lengths.put(key, lengthmap); + } + } + catch (Throwable t) { + System.err.println(Messages.getString("avl", "Alg_desc_not_found_error")); //$NON-NLS-1$ + t.printStackTrace(); + } + } + + /** + * @return the offset of the current section, that means the position of the + * character, the section starts with + */ + public int getCurrentStepOffset() { + String key = getKey(controller.getAlgoName()); + String section = controller.getSection(); + + try { + return offsets.get(key).get(section); + } + catch (NullPointerException ex) { + return -1; + } + } + + /** + * @return the length of the current section, that means the section + * consists of how many characters + */ + public int getCurrentStepLength() { + String key = getKey(controller.getAlgoName()); + String section = controller.getSection(); + + try { + return lengths.get(key).get(section); + } + catch (NullPointerException ex) { + return -1; + } + } + + /** + * @return the description of the currentAlgorithm + */ + public Map getCurrentAlgorithmDescription() { + String name = controller.getAlgoName(); + String key = getKey(name); + if (key == null) return null; + return mapOfAlgorithms.get(key); + } + + private String getKey(String name) { + if (name.equals(Messages.getString("avl", "Alg_name.Search"))) return "search"; //$NON-NLS-1$ //$NON-NLS-2$ + if (name.equals(Messages.getString("avl", "Alg_name.Insert")) || name.equals(Messages.getString("avl", "Alg_name.Create_tree"))) //$NON-NLS-1$ //$NON-NLS-2$ + return "insert"; //$NON-NLS-1$ + if (name.equals(Messages.getString("avl", "Alg_name.Insert_AVL")) || name.equals(Messages.getString("avl", "Alg_name.Create_AVL_tree"))) //$NON-NLS-1$ //$NON-NLS-2$ + return "avlinsert"; //$NON-NLS-1$ + if (name.equals(Messages.getString("avl", "Alg_name.Remove"))) return "remove"; //$NON-NLS-1$ //$NON-NLS-2$ + if (name.equals(Messages.getString("avl", "Alg_name.Remove_AVL"))) return "avlremove"; //$NON-NLS-1$ //$NON-NLS-2$ + if (name.equals(Messages.getString("avl", "Alg_name.AVL_test"))) return "avltest"; //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/GUIConstants.java b/src/org/jalgo/module/avl/gui/GUIConstants.java new file mode 100644 index 0000000..8154c1a --- /dev/null +++ b/src/org/jalgo/module/avl/gui/GUIConstants.java @@ -0,0 +1,81 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.05.2005 */ +package org.jalgo.module.avl.gui; + +import java.awt.Color; +import java.awt.Font; + +import org.jalgo.module.avl.Constants; + +/** + * The interface Constants is a collection of several constant values, + * used in the GUI implementation of the AVL module. + * + * @author Alexander Claus + */ +public interface GUIConstants +extends Constants { + + /*------------------------display modes--------------------------*/ + /** Indicates, that display is tuned for working on a pc screen. */ + public static final int PC_MODE = 0; + /** Indicates, that display is tuned for working on a beamer. */ + public static final int BEAMER_MODE = 1; + + /*------------------------validity states-------------------------*/ + /** Indicates a valid input value. */ + public final static int VALID_INPUT = 0; + /** Indicates that input is no integer. */ + public final static int NO_INTEGER = 1; + /** Indicates that input value is out of the acceptable range. */ + public final static int NOT_IN_RANGE = 2; + /** Indicates that input is empty. */ + public final static int INPUT_EMPTY = 3; + + /*------------------------------colors----------------------------*/ + /** The background color in standard layout. */ + public final static Color STANDARD_BACKGROUND = new Color(212, 208, 200); + /** The background color in the welcome screen. */ + public final static Color WELCOME_SCREEN_BACKGROUND = new Color(51, 102, 153); + /** The font color in the welcome screen. */ + public final static Color WELCOME_SCREEN_FOREGROUND = new Color(254, 215, 0); + + /*------------------------------fonts-----------------------------*/ + /** The font used in the welcome screen. */ + public static final Font WELCOME_SCREEN_FONT = + new Font("SansSerif", Font.PLAIN, 16); + + /*------------------------visualization modes---------------------*/ + /** Indicates that automatical visualisation animation is selected. */ + public static final int AUTOMATICAL = 0; + /** Indicates that stepwise visualisation is selected. */ + public static final int STEPWISE = 1; + /** Indicates that no visualisation is selected. */ + public static final int NO_VISUALIZATION = 2; + + /*--------------------------message types-------------------------*/ + /** Indicates that displayed message is reset. */ + public static final int NO_MESSAGE = 0; + /** Indicates a message to be an error message. */ + public static final int ERROR_MESSAGE = 1; + /** Indicates a message to be an information message. */ + public static final int INFORMATION_MESSAGE = 2; +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/GUIController.java b/src/org/jalgo/module/avl/gui/GUIController.java new file mode 100644 index 0000000..1a043a4 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/GUIController.java @@ -0,0 +1,742 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 26.04.2005 */ +package org.jalgo.module.avl.gui; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JToolBar; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.ModuleConnector; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.components.ControlPane; +import org.jalgo.module.avl.gui.components.DocuPane; +import org.jalgo.module.avl.gui.components.InfoPane; +import org.jalgo.module.avl.gui.components.LogPane; +import org.jalgo.module.avl.gui.components.Navigator; +import org.jalgo.module.avl.gui.components.RandomGenerationDialog; +import org.jalgo.module.avl.gui.components.WelcomeScreen; +import org.jalgo.module.avl.gui.event.AbortAction; +import org.jalgo.module.avl.gui.event.ClearTreeAction; +import org.jalgo.module.avl.gui.event.FinishAction; +import org.jalgo.module.avl.gui.event.PerformAction; +import org.jalgo.module.avl.gui.event.PerformBlockStepAction; +import org.jalgo.module.avl.gui.event.ToggleDisplayModeAction; +import org.jalgo.module.avl.gui.event.UndoAction; +import org.jalgo.module.avl.gui.event.UndoBlockStepAction; +import org.jalgo.module.avl.gui.event.WelcomeAction; +import org.jalgo.module.avl.gui.graphics.Animator; +import org.jalgo.module.avl.gui.graphics.PaintArea; + +/** + * The class GUIController is the main class of the GUI of the + * AVL module. It initializes the layout of the different parts, offers methods + * to set the state of buttons etc., to show several dialogs and messages, and + * causes GUI-components to update when necessary. + * + * @author Alexander Claus + */ +public class GUIController +implements GUIConstants { + + // general references + private ModuleConnector connector; + private Controller controller; + private SearchTree tree; + + // components (based on SWT) + private WelcomeAction welcomeAction; + private ClearTreeAction clearTreeAction; + private AbstractAction abortAction; + private AbstractAction undoBlockStepAction; + private AbstractAction undoAction; + private AbstractAction performAction; + private AbstractAction performBlockStepAction; + private AbstractAction finishAction; + + // components (based on Swing) + private Frame swt_awt_bridge; + private JPanel contentPane; + private WelcomeScreen welcomeScreen; + private RandomGenerationDialog rgd; + private ControlPane controlPane; + private InfoPane infoPane; + private DocuPane docuPane; + private LogPane logPane; + private PaintArea paintArea; + private JScrollPane graphicPane; + + // layout stuff + private JSplitPane standardLayoutSplitPane; + private int graphicPaneInsetsX; + private int graphicPaneInsetsY; + private int northEastPaneWidth; + private int northEastPaneHeight; + private int logPaneHeight; + + private boolean isDialogOpen; + private Animator animator; + + private static final String lineSep = System.getProperty("line.separator"); //$NON-NLS-1$ + + /** + * Constructs the GUIController instance for the current AVL + * module instance.
      + * Initializes all layout components, especially the toolbar and the menu. + * Installs an AWT-Frame on the panel provided by the main program, so that + * GUI of the AVL module can be created on Swing base. + * + * @param connector the ModuleConnector of the AVL module + * @param controller the Controller instance of the AVL + * module + * @param st the SearchTree instance of the AVL module + */ + public GUIController(ModuleConnector connector, Controller controller, + SearchTree st) { + + this.connector = connector; + this.controller = controller; + this.tree = st; + + // install the main panel + JComponent rootPane = + JAlgoGUIConnector.getInstance().getModuleComponent(connector); + rootPane.setLayout(new BorderLayout()); + contentPane = new JPanel(); + rootPane.add(contentPane, BorderLayout.CENTER); + + // initialization of the following components is called before + // installToolbar() because of needed references + paintArea = new PaintArea(this, tree, controller); + logPane = new LogPane(controller); + docuPane = new DocuPane(this, controller); + installToolbar(); + installMenu(); + // init components + rgd = new RandomGenerationDialog(this, swt_awt_bridge, controller, + connector); + welcomeScreen = new WelcomeScreen(this); + controlPane = new ControlPane(this, controller); + infoPane = new InfoPane(tree); + graphicPane = new JScrollPane(paintArea); + graphicPane.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, + new Navigator(paintArea)); + + // store current insets for later layout validations (efficiency) + graphicPaneInsetsX = graphicPane.getInsets().left + + graphicPane.getInsets().right; + graphicPaneInsetsY = graphicPane.getInsets().top + + graphicPane.getInsets().bottom; + // force paint area to resize, if necessary (e.g. splitpane divider + // moved) + graphicPane.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + doLayout(); + } + }); + // on north pane are the paint area, the infobox and the control center + JPanel northPane = new JPanel(new BorderLayout()); + northPane.add(graphicPane, BorderLayout.CENTER); + JPanel northEastPane = new JPanel(new BorderLayout()); + northEastPane.add(infoPane, BorderLayout.NORTH); + northEastPane.add(controlPane, BorderLayout.CENTER); + northPane.add(northEastPane, BorderLayout.EAST); + // on south pane are the textareas: docupane and logpane + JPanel southPane = new JPanel(new BorderLayout()); + southPane.add(docuPane, BorderLayout.CENTER); + southPane.add(logPane, BorderLayout.EAST); + + // determine the main layout values: on basis of width and height of the + // northeast pane the size of the graphic-, log- and docupane are + // calculated + northEastPaneWidth = northEastPane.getMinimumSize().width; + northEastPaneHeight = northEastPane.getMinimumSize().height; + logPaneHeight = (logPane.getFontMetrics(logPane.getFont()).getHeight() + 2) + * 8 + logPane.getInsets().top + logPane.getInsets().bottom; + logPane.setMinimumSize( + new Dimension(northEastPaneWidth, logPaneHeight)); + logPane.setPreferredSize(new Dimension(northEastPaneWidth, + logPaneHeight)); + graphicPane.setMinimumSize(new Dimension(0, northEastPaneHeight)); + + // splitpane to adjust the height of the docu- and logpane + standardLayoutSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + false, northPane, southPane); + standardLayoutSplitPane.setOneTouchExpandable(true); + standardLayoutSplitPane.setResizeWeight(0.9); + standardLayoutSplitPane.setDividerLocation(northEastPaneHeight); + } + + /** + * Sets up the toolbar. + */ + private void installToolbar() { + JToolBar toolBar = + JAlgoGUIConnector.getInstance().getModuleToolbar(connector); + welcomeAction = new WelcomeAction(this, tree); + toolBar.add(createToolbarButton(welcomeAction)); + clearTreeAction = new ClearTreeAction(this, tree); + toolBar.add(createToolbarButton(clearTreeAction)); + toolBar.addSeparator(); + abortAction = new AbortAction(this, controller); + toolBar.add(createToolbarButton(abortAction)); + undoBlockStepAction = new UndoBlockStepAction(this, controller); + toolBar.add(createToolbarButton(undoBlockStepAction)); + undoAction = new UndoAction(this, controller); + toolBar.add(createToolbarButton(undoAction)); + performAction = new PerformAction(this, controller); + toolBar.add(createToolbarButton(performAction)); + performBlockStepAction = new PerformBlockStepAction(this, controller); + toolBar.add(createToolbarButton(performBlockStepAction)); + finishAction = new FinishAction(this, controller); + toolBar.add(createToolbarButton(finishAction)); + } + + /** + * Sets up the menu. + */ + private void installMenu() { + JMenu menu = JAlgoGUIConnector.getInstance().getModuleMenu(connector); + menu.add(welcomeAction); + menu.add(clearTreeAction); + menu.addSeparator(); + menu.add(abortAction); + menu.add(undoBlockStepAction); + menu.add(undoAction); + menu.add(performAction); + menu.add(performBlockStepAction); + menu.add(finishAction); + menu.addSeparator(); + menu.add(ToggleDisplayModeAction.getInstance()); + ToggleDisplayModeAction.registerTarget(paintArea); + ToggleDisplayModeAction.registerTarget(logPane); + ToggleDisplayModeAction.registerTarget(docuPane); + } + + /** + * Installs the standard layout of the AVL module. This means the + * composition of the graphical visualisation of the tree with control + * components and information/documentation panels. + */ + public void installStandardLayout() { + connector.setSaveStatus(tree.getHeight() != 0 ? + SaveStatus.NO_CHANGES : SaveStatus.NOTHING_TO_SAVE); + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + contentPane.setLayout(new BorderLayout()); + contentPane.add(standardLayoutSplitPane, BorderLayout.CENTER); + standardLayoutSplitPane.setDividerLocation( + standardLayoutSplitPane.getSize().height + - standardLayoutSplitPane.getInsets().bottom + - standardLayoutSplitPane.getDividerSize() - logPaneHeight); + + welcomeAction.setEnabled(true); + if (tree.getHeight() > 0) clearTreeAction.setEnabled(true); + else clearTreeAction.setEnabled(false); + + // reset components to clear input fields etc. + controlPane.reset(); + logPane.reset(); + docuPane.reset(); + + update(); + } + + /** + * Switches the layout to the welcome screen, where user can select tasks. + */ + public void installWelcomeScreen() { + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(welcomeScreen, BorderLayout.CENTER); + + connector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + setToolbarButtonsDisabled(); + contentPane.updateUI(); + contentPane.validate(); + } + + /** + * This method should be invoked, if something in visualization or tree + * state changes. It causes the appropriate components to update their + * contents. + */ + public void update() { + doLayout(); + paintArea.update(); + infoPane.update(); + docuPane.update(); + logPane.update(); + } + + /** + * Causes the paint area to resize if necessary. This method should be + * invoked if the state of the tree has changed. + */ + public void doLayout() { + contentPane.validate(); + paintArea.setPreferredSize(new Dimension( + graphicPane.getWidth() - graphicPaneInsetsX, + graphicPane.getHeight() - graphicPaneInsetsY)); + paintArea.revalidate(); + paintArea.repaint(); + } + + /** + * Shows a dialog, where user can create a random tree. + */ + public void showRandomGenerationDialog() { + rgd.open(); + } + + /** + * Checks the result of the AVL-Test algorithm and displays an appropriate + * dialog. If the test result is positive, a dialog is shown, where the user + * is asked for switching to AVL mode. Otherwise, a dialog is shown, + * indicating this result to the user. While the dialog is open, the + * balances of the tree are shown, so that the user can see, why the result + * is so or so. Closing this dialog without switching to AVL mode causes to + * hide the balances. + */ + public void showAVLTestDialog() { + connector.setSavingBlocked(true); + clearTreeAction.setEnabled(false); + welcomeAction.setEnabled(false); + // only for visualisation of balances + controller.setAVLMode(true); + update(); + isDialogOpen = true; + if (controller.getAVLTestResult()) { + if (JOptionPane.showConfirmDialog(controlPane, + Messages.getString("avl", "GUIController.Is_AVL_tree") + //$NON-NLS-1$ //$NON-NLS-2$ + lineSep + + Messages.getString("avl", "GUIController.Wish_to_change_to_AVL_mode"), //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("main", "DialogConstants.Question"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { //$NON-NLS-1$ + controller.putLogDescription( + Messages.getString("avl", "GUIController.Changed_to_AVL_mode")); //$NON-NLS-1$ //$NON-NLS-2$ + setAVLMode(true, true); + connector.setSaveStatus(tree.getHeight() > 0 ? + SaveStatus.CHANGES_TO_SAVE : SaveStatus.NOTHING_TO_SAVE); + connector.setSavingBlocked(false); + } + else { + // balance visualisation off + controller.setAVLMode(false); + // normalize visualisation + try { + controller.perform(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + ex.getMessage()); + } + update(); + connector.setSavingBlocked(false); + } + isDialogOpen = false; + if (tree.getHeight() > 0) clearTreeAction.setEnabled(true); + welcomeAction.setEnabled(true); + } + else { + // use this approach to show nonmodal dialog, which is always on top + // for navigating through highlighted balances + // store old state + final boolean avlEnabled = controlPane.isAVLToggleEnabled(); + final boolean buttonsEnabled = (controlPane.validateKey() == VALID_INPUT); + controlPane.setKeyInputEnabled(false); + controlPane.setAVLToggleEnabled(false); + controlPane.setAlgorithmButtonsEnabled(false); + + final Dialog d = new JOptionPane( + Messages.getString("avl", "GUIController.Is_no_AVL_tree"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.INFORMATION_MESSAGE, + JOptionPane.DEFAULT_OPTION).createDialog(controlPane, + Messages.getString("main", "DialogConstants.Info")); //$NON-NLS-1$ //$NON-NLS-2$ + d.setAlwaysOnTop(true); + d.setModal(false); + d.addComponentListener(new ComponentAdapter() { + @SuppressWarnings("synthetic-access") + public void componentHidden(ComponentEvent e) { + // balance visualisation off + controller.setAVLMode(false); + // normalize visualisation + try { + controller.perform(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + ex.getMessage()); + } + // restore state + controlPane.setKeyInputEnabled(true); + controlPane.setAVLToggleEnabled(avlEnabled); + controlPane.setAlgorithmButtonsEnabled(buttonsEnabled); + controlPane.setAVLTestEnabled(true); + + update(); + d.dispose(); + isDialogOpen = false; + if (tree.getHeight() > 0) clearTreeAction.setEnabled(true); + welcomeAction.setEnabled(true); + connector.setSavingBlocked(false); + } + }); + d.setVisible(true); + } + } + + /** + * Checks, if there is any dialog open. This method is necessary for + * avoiding conflicts, when closing the module and having dialogs open. + * + * @return true, if a dialog is open, false + * otherwise + */ + public boolean isDialogOpen() { + return isDialogOpen; + } + + /** + * Disables the toolbar buttons and the save buttons. + */ + public void setToolbarButtonsDisabled() { + setPerformButtonsEnabled(false); + setUndoButtonsEnabled(false); + welcomeAction.setEnabled(false); + clearTreeAction.setEnabled(false); + } + + /** + * Sets the enable status of the buttons perform, perform-blockstep, finish + * and abort on toolbar. + * + * @param b true, if buttons should be enabled, + * false otherwise + */ + private void setPerformButtonsEnabled(boolean b) { + performAction.setEnabled(b); + performBlockStepAction.setEnabled(b); + finishAction.setEnabled(b); + abortAction.setEnabled(b); + } + + /** + * Sets the enable status of the buttons undo and undo-blockstep on toolbar. + * + * @param b true, if buttons should be enabled, + * false otherwise + */ + private void setUndoButtonsEnabled(boolean b) { + undoAction.setEnabled(b); + undoBlockStepAction.setEnabled(b); + } + + /** + * Returns the documentation panel. This method is currently necessary for + * delegating this reference to the action handler. + * + * @return the documentation panel + */ + public DocuPane getDocuPane() { + return docuPane; + } + + /** + * Sets the enabled state of the buttons for running an algorithm. This + * method is called, when an algorithm is selected. + */ + public void algorithmStarted() { + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + clearTreeAction.setEnabled(false); + setUndoButtonsEnabled(false); + if (controller.algorithmHasNextStep()) { + setPerformButtonsEnabled(true); + controlPane.setAVLToggleEnabled(false); + controlPane.setAlgorithmButtonsEnabled(false); + controlPane.setKeyInputEnabled(false); + connector.setSavingBlocked(true); + controlPane.setMessage(null, NO_MESSAGE); + } + else controlPane.setMessage(controller.getResult(), + INFORMATION_MESSAGE); + // for explanation of the following step, see DocuPane.update() + setStepDirection(true); + docuPane.algorithmStarted(); + update(); + } + + /** + * Sets the enable state of the buttons when an algorithm is finished. + */ + public void algorithmFinished() { + if (controller.isAVLMode()) controlPane.setAVLToggleEnabled(true); + setPerformButtonsEnabled(false); + setUndoButtonsEnabled(true); + if (tree.getHeight() > 0) clearTreeAction.setEnabled(true); + controlPane.setKeyInputEnabled(true); + controlPane.validateKey(); + controlPane.setMessage(controller.getResult(), INFORMATION_MESSAGE); + controlPane.setAnimSpeedEnabled(false); + // enable save buttons + connector.setSavingBlocked(false); + // for explanation of the following step, see DocuPane.update() + setStepDirection(false); + } + + /** + * Sets the enable state of the buttons when an algorithm is aborted. + */ + public void algorithmAborted() { + if (getAnimator() != null && getAnimator().isRunning()) { + getAnimator().stopAnim(); + controlPane.setAnimSpeedEnabled(false); + // busy waiting for animator has being stopped to avoid race + // conditions + while (getAnimator().isRunning()) {/*busy waiting*/} + } + if (controller.isAVLMode() || tree.getHeight() == 0) + controlPane.setAVLToggleEnabled(true); + if (tree.getHeight() > 0) clearTreeAction.setEnabled(true); + setPerformButtonsEnabled(false); + setUndoButtonsEnabled(false); + controlPane.setKeyInputEnabled(true); + controlPane.validateKey(); + docuPane.reset(); + // enable save buttons + connector.setSavingBlocked(false); + update(); + } + + /** + * Sets the enable state of the buttons for running an algorithm. This + * method is called, when an algorithm was completely undone and now perform + * or perform blockstep is pressed. + */ + public void algorithmRestarted() { + // TODO: currently this method is invoked at regular algorithm start too + // so it isn't bad, but not efficient + setUndoButtonsEnabled(true); + if (controller.algorithmHasNextStep()) { + setPerformButtonsEnabled(true); + controlPane.setAlgorithmButtonsEnabled(false); + controlPane.setKeyInputEnabled(false); + connector.setSavingBlocked(true); + // for explanation of the following step, see DocuPane.update() + setStepDirection(true); + } + } + + /** + * Sets the enable state of the buttons when algorithm is completely undone. + */ + public void algorithmUndone() { + setUndoButtonsEnabled(false); + } + + /** + * Sets the enable state of the buttons for running an algorithm. This + * method is called, when algorithm was finished and undo is pressed. + */ + public void algorithmRestartedFromUndo() { + setPerformButtonsEnabled(true); + connector.setSavingBlocked(true); + clearTreeAction.setEnabled(false); + controlPane.setAVLToggleEnabled(false); + controlPane.setAlgorithmButtonsEnabled(false); + controlPane.setKeyInputEnabled(false); + controlPane.setMessage(null, NO_MESSAGE); + // for explanation of the following step, see DocuPane.update() + setStepDirection(true); + } + + /** + * Sets the enable state of the buttons for running the animation of + * generation of a random tree. Loads the algorithm text to the + * DocuPane.
      + * This method is called by RandomGenerationDialogActionHandler. + */ + public void randomAnimatorStarted() { + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + connector.setSavingBlocked(true); + controlPane.setAnimSpeedEnabled(true); + controlPane.setAlgorithmButtonsEnabled(false); + controlPane.setKeyInputEnabled(false); + abortAction.setEnabled(true); + // for explanation of the following step, see DocuPane.update() + setStepDirection(true); + docuPane.algorithmStarted(); + } + + /** + * Sets the current Animator. Currently this is only used + * for the RandomTreeAnimator. Other animations may be + * provided in later versions. + * + * @param animator the new Animator + * + * @see #getAnimator() + */ + public void setAnimator(Animator animator) { + this.animator = animator; + } + + /** + * Retrieves the current Animator. + * + * @return the current Animator + * + * @see #setAnimator(Animator) + */ + public Animator getAnimator() { + return animator; + } + + /** + * Sets the AVL mode. + * + * @param avlMode the AVL mode + * @param toggleEnabled true, if the AVL-mode-checkbox + * should be enabled, false otherwise + */ + public void setAVLMode(boolean avlMode, boolean toggleEnabled) { + controlPane.setAVLToggleSelected(avlMode); + controlPane.setAVLTestEnabled(!avlMode); + controller.setAVLMode(avlMode); + controlPane.setAVLToggleEnabled(toggleEnabled); + update(); + } + + /** + * Retrieves the algorithm flow control actions as JButton + * array. This buttons can be added e.g. to a JToolBar. + * + * @return an array of buttons + */ + public JButton[] getFlowControlButtons() { + JButton[] buttons = new JButton[6]; + buttons[0] = createToolbarButton(abortAction); + buttons[1] = createToolbarButton(undoBlockStepAction); + buttons[2] = createToolbarButton(undoAction); + buttons[3] = createToolbarButton(performAction); + buttons[4] = createToolbarButton(performBlockStepAction); + buttons[5] = createToolbarButton(finishAction); + return buttons; + } + + /** + * Creates a JButton object without border and text, which + * can be used in JToolBars + * + * @return a JButton instance with the given Action + */ + public JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton( + (Icon)a.getValue(Action.SMALL_ICON), + null, null); + button.setAction(a); + button.setText(""); + return button; + } + + /** + * A helper method for easy use of GridBagLayout + * + * @param comp the component to lay out + * @param gbl the instance of the GridBagLayout + * @param x the x coordinate in the grid + * @param y the y coordinate in the grid + * @param width the width in grid fields + * @param height the height in grid fields + * @param anchor the anchor position in the field, when component does not + * fill the field + * @param fill the mode how to fill the field + */ + public static void setGBC(Component comp, GridBagLayout gbl, int x, int y, + int width, int height, int anchor, int fill) { + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridx = x; + gbc.gridy = y; + gbc.gridwidth = width; + gbc.gridheight = height; + gbc.anchor = anchor; + gbc.fill = fill; + gbl.setConstraints(comp, gbc); + } + + /** Determines the direction of the current step. */ + private boolean performDirection; + + /** + * Sets the direction of the current step. This approach is a necessary + * trick for correctly scrolling in DocuPane. + * + * @param perform true, if the current step is a perform + * step, false, if the current step is an undo + * step + * + * @see DocuPane#update() + */ + public void setStepDirection(boolean perform) { + performDirection = perform; + } + + /** + * Retrieves, if the current step is a perform step. + * + * @return true, if the current step is a perform step, + * false, if the current step is an undo step + * + * @see #setStepDirection(boolean) + * @see DocuPane#update() + */ + public boolean isPerformStep() { + return performDirection; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/Settings.java b/src/org/jalgo/module/avl/gui/Settings.java new file mode 100644 index 0000000..c60f4b9 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/Settings.java @@ -0,0 +1,113 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.06.2005 */ +package org.jalgo.module.avl.gui; + +import java.awt.Color; + +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; + +import org.jalgo.module.avl.gui.graphics.GraphicsConstants; + +/** + * @author Alexander Claus + */ +public class Settings +implements GraphicsConstants, GUIConstants { + + /** + * The display mode indicates if the user is working on a pc display or on a + * beamer. This integer can be one of the constants PC_MODE, + * BEAMER_MODE defined in GUIConstants. + */ + public static int getDisplayMode() { + return org.jalgo.main.util.Settings.getBoolean("avl", "BeamerMode") + ? BEAMER_MODE : PC_MODE; + } + + public static void setDisplayMode(int mode) { + org.jalgo.main.util.Settings.setBoolean("avl", "BeamerMode", + (mode == BEAMER_MODE)); + } + + /** The delay time of steps in animation in milliseconds. */ + private static long STEP_DELAY = 500; + + public static long getStepDelay() { + return STEP_DELAY; + } + + public static void setStepDelay(long delay) { + STEP_DELAY = delay; + } + + /** The normal font style for log and documentation pane. */ + public static SimpleAttributeSet[] NORMAL_STYLE; + + /** The highlighted font style for log pane. */ + public static SimpleAttributeSet[] HIGHLIGHTED_STYLE; + + /** The highlighted font style for documentation pane. */ + public static SimpleAttributeSet[] DOCU_HIGHLIGHTED_STYLE; + + static { + NORMAL_STYLE = new SimpleAttributeSet[] {new SimpleAttributeSet(), + new SimpleAttributeSet()}; + StyleConstants.setFontFamily(NORMAL_STYLE[PC_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(NORMAL_STYLE[PC_MODE], 11); + + StyleConstants.setFontFamily(NORMAL_STYLE[BEAMER_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(NORMAL_STYLE[BEAMER_MODE], 15); + + HIGHLIGHTED_STYLE = new SimpleAttributeSet[] {new SimpleAttributeSet(), + new SimpleAttributeSet()}; + StyleConstants.setFontFamily(HIGHLIGHTED_STYLE[PC_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(HIGHLIGHTED_STYLE[PC_MODE], 11); + StyleConstants.setForeground(HIGHLIGHTED_STYLE[PC_MODE], Color.RED); + + StyleConstants.setFontFamily(HIGHLIGHTED_STYLE[BEAMER_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(HIGHLIGHTED_STYLE[BEAMER_MODE], 15); + StyleConstants.setForeground(HIGHLIGHTED_STYLE[BEAMER_MODE], Color.RED + .darker()); + + DOCU_HIGHLIGHTED_STYLE = new SimpleAttributeSet[] { + new SimpleAttributeSet(), new SimpleAttributeSet()}; + StyleConstants.setFontFamily(DOCU_HIGHLIGHTED_STYLE[PC_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(DOCU_HIGHLIGHTED_STYLE[PC_MODE], 11); + StyleConstants + .setForeground(DOCU_HIGHLIGHTED_STYLE[PC_MODE], Color.RED); + + StyleConstants.setFontFamily(DOCU_HIGHLIGHTED_STYLE[BEAMER_MODE], + "SansSerif"); //$NON-NLS-1$ + StyleConstants.setFontSize(DOCU_HIGHLIGHTED_STYLE[BEAMER_MODE], 11); + StyleConstants.setForeground(DOCU_HIGHLIGHTED_STYLE[BEAMER_MODE], + Color.RED.darker()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/CVS/Entries b/src/org/jalgo/module/avl/gui/components/CVS/Entries new file mode 100644 index 0000000..3fb97c3 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/CVS/Entries @@ -0,0 +1,8 @@ +/ControlPane.java/1.7/Thu Jan 31 20:15:07 2008// +/DocuPane.java/1.10/Thu Jan 31 20:15:07 2008// +/InfoPane.java/1.8/Thu Jan 31 20:15:07 2008// +/LogPane.java/1.8/Thu Jan 31 20:15:07 2008// +/Navigator.java/1.10/Thu Jan 31 20:15:07 2008// +/RandomGenerationDialog.java/1.7/Thu Jan 31 20:15:07 2008// +/WelcomeButton.java/1.4/Thu Jan 31 20:15:07 2008// +/WelcomeScreen.java/1.8/Thu Jan 31 20:15:07 2008// diff --git a/src/org/jalgo/module/avl/gui/components/CVS/Repository b/src/org/jalgo/module/avl/gui/components/CVS/Repository new file mode 100644 index 0000000..e0caf66 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/gui/components diff --git a/src/org/jalgo/module/avl/gui/components/CVS/Root b/src/org/jalgo/module/avl/gui/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/gui/components/ControlPane.java b/src/org/jalgo/module/avl/gui/components/ControlPane.java new file mode 100644 index 0000000..932f552 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/ControlPane.java @@ -0,0 +1,470 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.Component; +import java.awt.Dimension; +import java.util.Hashtable; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.JToolBar; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.event.ControlActionHandler; + +/** + * The class ControlPane represents a panel with several control + * elements for algorithms in the AVL module. Here the user can type in a key, + * and start an algorithm by selecting one of the buttons. Furthermore he can + * control the flow of the algorithm and set some options e.g. animation speed. + * Results of algorithms are displayed in a special field in this panel. + * + * @author Alexander Claus + */ +public class ControlPane +extends JPanel +implements GUIConstants { + + private static final long serialVersionUID = 5167913386704980330L; + // layout and control components + private JLabel messageLabel; + private JTextField keyTextField; + private JButton randomKeyButton; + private JButton startSearchButton; + private JButton startInsertButton; + private JButton startDeleteButton; + private JButton startAVLTestButton; + private JCheckBox avlMode; + private JSlider animSpeed; + + // helper variables + private int currentKey; + private ImageIcon errorIcon; + private ImageIcon infoIcon; + + /** + * Constructs a ControlPane object with the given references. + * The layout of the pane is created here. + * + * @param gui the module specific GUIController + * @param controller the module specific Controller + */ + public ControlPane(GUIController gui, Controller controller) { + ControlActionHandler action = new ControlActionHandler(gui, this, + controller); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBorder(BorderFactory.createTitledBorder(Messages.getString( + "avl", "ControlPane.Label"))); //$NON-NLS-1$ //$NON-NLS-2$ + + // messagePane contains the error message + JPanel messagePane = new JPanel(); + messagePane.setLayout(new BoxLayout(messagePane, BoxLayout.LINE_AXIS)); + messageLabel = new JLabel(); + errorIcon = new ImageIcon(Messages.getResourceURL( + "main", "Icon.Msg_error")); //$NON-NLS-1$ //$NON-NLS-2$ + infoIcon = new ImageIcon(Messages.getResourceURL( + "main", "Icon.Msg_info")); //$NON-NLS-1$ //$NON-NLS-2$ + messagePane.add(Box.createRigidArea(new Dimension(5, + errorIcon.getIconHeight() + 4))); + messagePane.add(messageLabel); + setMessage(null, NO_MESSAGE); + messagePane.setAlignmentX(Component.LEFT_ALIGNMENT); + add(messagePane); + + JPanel keyPane = new JPanel(); + keyPane.setLayout(new BoxLayout(keyPane, BoxLayout.LINE_AXIS)); + JLabel keyLabel = new JLabel(Messages.getString( + "avl", "ControlPane.Key")); //$NON-NLS-1$ //$NON-NLS-2$ + keyLabel.setAlignmentY(Component.CENTER_ALIGNMENT); + keyPane.add(keyLabel); + keyTextField = new JTextField(2); + keyTextField.setAlignmentY(Component.CENTER_ALIGNMENT); + keyTextField.setMaximumSize(new Dimension( + keyTextField.getMaximumSize().width, + keyTextField.getMinimumSize().height)); + // watch key input, show error messages if necessary (key must be + // integer between 0 and MAX_KEY) + keyTextField.getDocument().addDocumentListener(action); + keyTextField.setToolTipText(Messages.getString( + "avl", "ControlPane.Insert_key")); //$NON-NLS-1$ //$NON-NLS-2$ + keyTextField.addMouseListener(action); + keyTextField.addFocusListener(action); + keyPane.add(keyTextField); + + randomKeyButton = new JButton(Messages.getString( + "avl", "ControlPane.Random")); //$NON-NLS-1$ //$NON-NLS-2$ + randomKeyButton.setActionCommand("randomkey"); //$NON-NLS-1$ + randomKeyButton.setToolTipText(Messages.getString( + "avl", "ControlPane.Random_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + randomKeyButton.addActionListener(action); + randomKeyButton.addMouseListener(action); + randomKeyButton.setMnemonic('r'); + randomKeyButton.setAlignmentY(Component.CENTER_ALIGNMENT); + keyPane.add(randomKeyButton); + keyPane.setAlignmentX(Component.LEFT_ALIGNMENT); + add(keyPane); + + add(Box.createVerticalStrut(8)); + + JLabel algSelectLabel = new JLabel(Messages.getString( + "avl", "ControlPane.Choose_algorithm")); //$NON-NLS-1$ //$NON-NLS-2$ + algSelectLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + add(algSelectLabel); + + add(Box.createVerticalStrut(4)); + + // buttonPane contains the buttons for selecting an algorithm + JPanel buttonPane1 = new JPanel(); + buttonPane1.setLayout(new BoxLayout(buttonPane1, BoxLayout.LINE_AXIS)); + + startSearchButton = new JButton(Messages.getString( + "avl", "Alg_name.Search")); //$NON-NLS-1$ //$NON-NLS-2$ + startSearchButton.setActionCommand("search"); //$NON-NLS-1$ + startSearchButton.setToolTipText(Messages.getString( + "avl", "ControlPane.Search_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + startSearchButton.addActionListener(action); + startSearchButton.addMouseListener(action); + startSearchButton.setMnemonic('s'); + buttonPane1.add(startSearchButton); + + startInsertButton = new JButton(Messages.getString( + "avl", "Alg_name.Insert")); //$NON-NLS-1$ //$NON-NLS-2$ + startInsertButton.setActionCommand("insert"); //$NON-NLS-1$ + startInsertButton.setToolTipText(Messages.getString( + "avl", "ControlPane.Insert_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + startInsertButton.addActionListener(action); + startInsertButton.addMouseListener(action); + startInsertButton.setMnemonic('i'); + buttonPane1.add(startInsertButton); + + startDeleteButton = new JButton(Messages.getString( + "avl", "Alg_name.Remove")); //$NON-NLS-1$ //$NON-NLS-2$ + startDeleteButton.setActionCommand("delete"); //$NON-NLS-1$ + startDeleteButton.setToolTipText(Messages.getString( + "avl", "ControlPane.Remove_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + startDeleteButton.addActionListener(action); + startDeleteButton.addMouseListener(action); + + startDeleteButton.setMnemonic('l'); + // currently not used + startDeleteButton.setEnabled(false); + buttonPane1.add(startDeleteButton); + + buttonPane1.setAlignmentX(Component.LEFT_ALIGNMENT); + add(buttonPane1); + + add(Box.createVerticalStrut(4)); + + JPanel buttonPane2 = new JPanel(); + buttonPane2.setLayout(new BoxLayout(buttonPane2, BoxLayout.LINE_AXIS)); + + avlMode = new JCheckBox(Messages.getString( + "avl", "ControlPane.AVL_property")); //$NON-NLS-1$ //$NON-NLS-2$ + avlMode.setSelected(true); + avlMode.setActionCommand("toggleavl"); //$NON-NLS-1$ + avlMode.addActionListener(action); + buttonPane2.add(avlMode); + buttonPane2.add(Box.createHorizontalGlue()); + + startAVLTestButton = new JButton(Messages.getString( + "avl", "Alg_name.AVL_test")); //$NON-NLS-1$ //$NON-NLS-2$ + startAVLTestButton.setActionCommand("avltest"); //$NON-NLS-1$ + startAVLTestButton.setToolTipText(Messages.getString( + "avl", "ControlPane.AVL_test_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + startAVLTestButton.addActionListener(action); + startAVLTestButton.addMouseListener(action); + startAVLTestButton.setMnemonic('t'); + buttonPane2.add(startAVLTestButton); + + buttonPane2.setAlignmentX(Component.LEFT_ALIGNMENT); + add(buttonPane2); + + setAlgorithmButtonsEnabled(false); + + add(Box.createVerticalStrut(8)); + + JLabel flowControlLabel = new JLabel(Messages.getString( + "avl", "ControlPane.Flow_control")); //$NON-NLS-1$ //$NON-NLS-2$ + flowControlLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + add(flowControlLabel); + add(Box.createVerticalStrut(4)); + + JToolBar flowControl = new JToolBar(); + flowControl.setFloatable(false); + flowControl.setRollover(true); + flowControl.setAlignmentX(Component.CENTER_ALIGNMENT); + + JButton[] flowControlButtons = gui.getFlowControlButtons(); + for (JButton button : flowControlButtons) { + button.addMouseListener(action); + flowControl.add(button); + } + + JPanel flowControlPane = new JPanel(); + flowControlPane.setLayout(new BoxLayout(flowControlPane, + BoxLayout.PAGE_AXIS)); + flowControlPane.setAlignmentX(Component.LEFT_ALIGNMENT); + flowControlPane.add(Box.createHorizontalGlue()); + flowControlPane.add(flowControl); + flowControlPane.add(Box.createHorizontalGlue()); + add(flowControlPane); + + add(Box.createVerticalStrut(8)); + + JLabel animSpeedLabel = new JLabel(Messages.getString( + "avl", "ControlPane.Anim_speed")); //$NON-NLS-1$ //$NON-NLS-2$ + animSpeedLabel.setAlignmentX(Component.LEFT_ALIGNMENT); + add(animSpeedLabel); + + animSpeed = new JSlider(200, 2000, 1100); + animSpeed.setInverted(true); + animSpeed.setMinorTickSpacing(100); + animSpeed.setPaintTicks(true); + Hashtable labelTable = new Hashtable(); + labelTable.put(200, new JLabel(Messages.getString( + "avl", "ControlPane.fast"))); //$NON-NLS-1$ //$NON-NLS-2$ + labelTable.put(2000, new JLabel(Messages.getString( + "avl", "ControlPane.slow"))); //$NON-NLS-1$ //$NON-NLS-2$ + animSpeed.setLabelTable(labelTable); + animSpeed.setPaintLabels(true); + animSpeed.addChangeListener(action); + animSpeed.setToolTipText(Messages.getString( + "avl", "ControlPane.Anim_speed_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + animSpeed.addMouseListener(action); + animSpeed.setAlignmentX(Component.LEFT_ALIGNMENT); + animSpeed.setEnabled(false); + add(animSpeed); + } + + /** + * Puts a random integer value in the acceptable range to the key textfield. + * This range is defined in Constants. + */ + public void setRandomKey() { + keyTextField.setText( + Integer.toString((int)(Math.random() * MAX_KEY + MIN_KEY))); + } + + /** + * Checks the current input in the key text field, if a valid key is typed + * in. Returns an identifier, which determines the validity of the input. + * Furthermore an error message is displayed if the input is not a valid + * key. The constants used for this are implemented in + * GUIConstants. + * + * @return VALID_INPUT - if the input is a valid key
      + * INPUT_EMPTY - if the input is empty
      + * NO_INTEGER - if the input contains nonnumber + * characters
      + * NOT_IN_RANGE - if the input key is out of the + * acceptable range + */ + public int validateKey() { + int returnCode; + try { + currentKey = Integer.parseInt(keyTextField.getText()); + if (currentKey > MAX_KEY || currentKey < MIN_KEY) + returnCode = NOT_IN_RANGE; + else returnCode = VALID_INPUT; + } + catch (NumberFormatException ex) { + if (keyTextField.getText().length() == 0) returnCode = INPUT_EMPTY; + else returnCode = NO_INTEGER; + } + + switch (returnCode) { + case VALID_INPUT: + setMessage(null, NO_MESSAGE); + setAlgorithmButtonsEnabled(true); + break; + case NO_INTEGER: + setMessage(Messages.getString( + "avl", "Warning_only_integers"), //$NON-NLS-1$ //$NON-NLS-2$ + ERROR_MESSAGE); + setAlgorithmButtonsEnabled(false); + break; + case NOT_IN_RANGE: + setMessage( + Messages.getString( + "avl", "Warning_only_values_from") + //$NON-NLS-1$ //$NON-NLS-2$ + MIN_KEY + + Messages.getString( + "avl", "Warning_to") + //$NON-NLS-1$ //$NON-NLS-2$ + MAX_KEY + + Messages.getString( + "avl", "Warning_valid"), //$NON-NLS-1$ //$NON-NLS-2$ + ERROR_MESSAGE); + setAlgorithmButtonsEnabled(false); + break; + case INPUT_EMPTY: + setMessage(null, NO_MESSAGE); + setAlgorithmButtonsEnabled(false); + } + startAVLTestButton.setEnabled(!avlMode.isSelected()); + + return returnCode; + } + + /** + * Returns the value of the key textfield as an integer. Attention! Ensure + * to have validateKey() invoked before this method is + * called. + * + * @return the current key input + */ + public int getCurrentKey() { + return currentKey; + } + + /** + * Displays an error message with an icon and the given string to the user. + * + * @param msg the error message + * @param msgType one of the following integers defined in + * GUIConstants:
      + *     NO_MESSAGE
      + *     INFORMATION_MESSAGE
      + *     ERROR_MESSAGE + */ + public void setMessage(String msg, int msgType) { + switch (msgType) { + case NO_MESSAGE: + messageLabel.setIcon(null); + break; + case INFORMATION_MESSAGE: + messageLabel.setIcon(infoIcon); + break; + case ERROR_MESSAGE: + messageLabel.setIcon(errorIcon); + break; + } + messageLabel.setText(msg); + validate(); + } + + /** + * Sets the enable status of the algorithm selection buttons in standard + * layout. + * + * @param b true, if buttons should be enabled, + * false otherwise + */ + public void setAlgorithmButtonsEnabled(boolean b) { + startSearchButton.setEnabled(b); + startInsertButton.setEnabled(b); + startDeleteButton.setEnabled(b); + startAVLTestButton.setEnabled(b && !avlMode.isSelected()); + } + + /** + * Sets the enable status of the key input area in standard layout. + * + * @param b true, if input should be enabled, + * false otherwise + */ + public void setKeyInputEnabled(boolean b) { + keyTextField.setEnabled(b); + randomKeyButton.setEnabled(b); + } + + /** + * Sets the enable status of the AVL mode checkbox. + * + * @param b true, if AVL mode checkbox should be enabled, + * false otherwise + */ + public void setAVLToggleEnabled(boolean b) { + avlMode.setEnabled(b); + } + + /** + * Retrieves the enable status of the AVL mode checkbox. + * + * @return true, if checkbox is enabled, false + * otherwise + */ + public boolean isAVLToggleEnabled() { + return avlMode.isEnabled(); + } + + /** + * Sets the selected state of the AVL mode checkbox. + * + * @param b true, if checkbox should be selected, + * false otherwise + */ + public void setAVLToggleSelected(boolean b) { + avlMode.setSelected(b); + } + + /** + * Sets the enable status of the AVL-Test button. + * + * @param b true, if the button should be enabled, + * false otherwise + */ + public void setAVLTestEnabled(boolean b) { + startAVLTestButton.setEnabled(b); + } + + /** + * Sets the enable status of the animation speed control. + * + * @param b true, if the control should be enabled, + * false otherwise + */ + public void setAnimSpeedEnabled(boolean b) { + animSpeed.setEnabled(b); + } + + /** + * Restores the initial state of the ControlPane. + */ + public void reset() { + // Bugfix: the enable status of the input text field has to be changed + // before setting text, otherwise the program sometimes hangs on + // (type in a value, have a tree, press clear tree) + setKeyInputEnabled(false); + setKeyInputEnabled(true); + + keyTextField.setText(null); + setAlgorithmButtonsEnabled(false); + startAVLTestButton.setEnabled(!avlMode.isSelected()); + setMessage(null, NO_MESSAGE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/DocuPane.java b/src/org/jalgo/module/avl/gui/components/DocuPane.java new file mode 100644 index 0000000..0d166d3 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/DocuPane.java @@ -0,0 +1,195 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 28.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.BorderLayout; +import java.awt.Insets; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Map; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.gui.DisplayModeChangeable; +import org.jalgo.module.avl.gui.DocuManager; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.Settings; + +/** + * The class DocuPane provides a text component for displaying + * the algorithm text of the currently running algorithm. The current step is + * highlighted and scrolled to be visible at each time. + * + * @author Alexander Claus + */ +public class DocuPane +extends JPanel +implements DisplayModeChangeable, GUIConstants { + + private static final long serialVersionUID = -8080746921156718079L; + private GUIController gui; + private DocuManager manager; + private JTextPane textPane; + private DefaultStyledDocument doc; + + private Map steps; + private int lastHighlightedParagraphOffset = 0; + private int lastHighlightedParagraphLength = 0; + + /** + * Constructs a DocuPane object with the given references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public DocuPane(final GUIController gui, Controller controller) { + this.gui = gui; + manager = new DocuManager(controller); + + textPane = new JTextPane(); + textPane.setMargin(new Insets(2, 4, 2, 4)); + textPane.setEditable(false); + doc = new DefaultStyledDocument(); + textPane.setDocument(doc); + + setLayout(new BorderLayout()); + JScrollPane scrollPane = new JScrollPane(textPane, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + add(scrollPane, BorderLayout.CENTER); + + // the status line updater + textPane.addMouseListener(new MouseAdapter() { + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("avl", "DocuPane.Status_message")); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + } + + /** + * If the current step in algorithm has changed, the last step is set back + * to normal style, and the new step is highlighted and scrolled to be + * visible.
      + * For correct scrolling, here is a tricky approach implemented:
      + * Normally you would set the caret position first to the end of the text to + * be highlighted, then to the beginning. Unfortunately, only the last call + * to setCaretPosition(int) takes effect. Because of this, + * this method scrolls the text to the end, when performing a step + * "forward", and scrolls the text to the beginning, when undoing a step + * ("backward"). This is not really comfortable, but it is a workaround for + * a stable release. + */ + public void update() { + if (steps == null) return; + doc.setCharacterAttributes(lastHighlightedParagraphOffset, + lastHighlightedParagraphLength, Settings.NORMAL_STYLE[PC_MODE], + true); + lastHighlightedParagraphOffset = manager.getCurrentStepOffset(); + lastHighlightedParagraphLength = manager.getCurrentStepLength(); + if (lastHighlightedParagraphOffset >= 0) doc.setCharacterAttributes( + lastHighlightedParagraphOffset, lastHighlightedParagraphLength, + Settings.DOCU_HIGHLIGHTED_STYLE[Settings.getDisplayMode()], true); + // here the mentioned trick: + if (gui.isPerformStep()) textPane.setCaretPosition(Math.max(0, + lastHighlightedParagraphOffset + lastHighlightedParagraphLength)); + else textPane.setCaretPosition(Math.max(0, + lastHighlightedParagraphOffset)); + // FIXME: der folgende ansatz führt zu darstellungsfehlern, + // es wird zwar richtig positioniert, allerdings wird der text + // gelegentlich + // �berlagert, bzw. sogar in der paintarea dargestellt, + // vermutung: scrollRectToVisible() ist schuld... + // daher hier getrickst + // Rectangle visibleRect = textPane.getVisibleRect(); + // try {visibleRect.setLocation( + // textPane.modelToView(textPane.getCaretPosition()).getLocation());} + // catch (BadLocationException ex) {ex.printStackTrace();} + // textPane.scrollRectToVisible(visibleRect); + } + + /** + * Loads the algorithm text of the current algorithm by getting from + * DocuManager. + */ + public void algorithmStarted() { + steps = manager.getCurrentAlgorithmDescription(); + try { + doc.remove(0, doc.getLength()); + for (String key : steps.keySet()) { + doc.insertString(doc.getLength(), steps.get(key), + Settings.NORMAL_STYLE[PC_MODE]); + } + } + catch (BadLocationException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("avl", "DocuPane.Update_error") + //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator") + //$NON-NLS-1$ + ex.getMessage()); + } + } + + /** + * Removes all text from the component. + */ + public void reset() { + steps = null; + try { + doc.remove(0, doc.getLength()); + } + catch (BadLocationException ex) { + System.err.println(Messages.getString( + "avl", "Unreachable_error")); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * This method is called, when the display mode has changed between pc mode + * and beamer mode. As a result of this the size of the font is changed. + */ + public void displayModeChanged() { + if (lastHighlightedParagraphOffset+lastHighlightedParagraphLength == 0) + return; + doc.setCharacterAttributes(0, doc.getLength(), + Settings.NORMAL_STYLE[PC_MODE], true); + doc.setCharacterAttributes(lastHighlightedParagraphOffset, + lastHighlightedParagraphLength, + Settings.DOCU_HIGHLIGHTED_STYLE[Settings.getDisplayMode()], true); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/InfoPane.java b/src/org/jalgo/module/avl/gui/components/InfoPane.java new file mode 100644 index 0000000..98c8326 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/InfoPane.java @@ -0,0 +1,141 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 26.04.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class InfoPane represents a panel, where informations + * about the current instance of the SearchTree are displayed. + * This informations are:
        + *
      • the height of the tree
      • + *
      • the weight of the tree
      • + *
      • the average search depth of the tree
      • + * + * @author Alexander Claus + */ +public class InfoPane +extends JPanel { + + private static final long serialVersionUID = -3131790632990225572L; + + private SearchTree tree; + + private JLabel weight; + private JLabel height; + private JLabel averageDepth; + + /** + * Constructs an InfoPane object, which is backed by the + * given SearchTree. + * + * @param tree the SearchTree for which informations should + * be provided + */ + public InfoPane(SearchTree tree) { + this.tree = tree; + + GridBagLayout gbl = new GridBagLayout(); + setLayout(gbl); + setBorder(BorderFactory.createTitledBorder(Messages.getString( + "avl", "InfoPane.Info"))); //$NON-NLS-1$ //$NON-NLS-2$ + + JLabel weightLabel = new JLabel(Messages.getString( + "avl", "InfoPane.Node_count")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(weightLabel, gbl, 0, 0, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(weightLabel); + weight = new JLabel(); + GUIController.setGBC(weight, gbl, 1, 0, 1, 1, + GridBagConstraints.EAST, GridBagConstraints.NONE); + add(weight); + + JLabel heightLabel = new JLabel(Messages.getString( + "avl", "InfoPane.Height")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(heightLabel, gbl, 0, 1, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(heightLabel); + height = new JLabel(); + GUIController.setGBC(height, gbl, 1, 1, 1, 1, + GridBagConstraints.EAST, GridBagConstraints.NONE); + add(height); + + JLabel averageDepthLabel = new JLabel(Messages.getString( + "avl", "InfoPane.Average_depth")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(averageDepthLabel, gbl, 0, 2, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(averageDepthLabel); + averageDepth = new JLabel(); + GUIController.setGBC(averageDepth, gbl, 1, 2, 1, 1, + GridBagConstraints.EAST, GridBagConstraints.NONE); + add(averageDepth); + + // the status line updater + addMouseListener(new MouseAdapter() { + + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("avl", "InfoPane.Status_message")); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + + update(); + } + + /** + * Updates the informations by calculating or getting from the tree and + * displays them. + */ + public void update() { + weight.setText("" + tree.getWeight()); //$NON-NLS-1$ + height.setText("" + tree.getHeight()); //$NON-NLS-1$ + // calculate average search depth + List nodes = tree.exportInOrder(); + double depthSum = 0; + for (Node node : nodes) + depthSum += tree.getLevelFor(node); + double avgDepth = (int)(depthSum / nodes.size() * 10) / 10.0; + averageDepth.setText(Double.toString(avgDepth)); + doLayout(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/LogPane.java b/src/org/jalgo/module/avl/gui/components/LogPane.java new file mode 100644 index 0000000..6a0fb6f --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/LogPane.java @@ -0,0 +1,171 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 31.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.BorderLayout; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Queue; + +import javax.swing.JComponent; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.gui.DisplayModeChangeable; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.Settings; + +/** + * The class LogPane represents a scrollable logbook for logging + * actions occured during algorithms. The last entry is each highlighted for + * better recognition of the current action. + * + * @author Alexander Claus + */ +public class LogPane +extends JComponent +implements DisplayModeChangeable, GUIConstants { + + private static final long serialVersionUID = 8981036220693388871L; + private Controller controller; + private JTextPane textPane; + private DefaultStyledDocument doc; + + private String lineSeparator; + private Queue lastLogDescriptions; + private int lastHighlightedParagraphOffset = 0; + private int lastHighlightedParagraphLength = 0; + + /** + * Constructs a LogPane object with the given references. + * + * @param controller the Controller instance of the AVL + * module + */ + public LogPane(Controller controller) { + this.controller = controller; + lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$ + + textPane = new JTextPane(); + textPane.setMargin(new Insets(2, 4, 2, 4)); + textPane.setEditable(false); + doc = new DefaultStyledDocument(); + textPane.setDocument(doc); + + setLayout(new BorderLayout()); + JScrollPane scrollPane = new JScrollPane(textPane, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + add(scrollPane, BorderLayout.CENTER); + + // the status line updater + textPane.addMouseListener(new MouseAdapter() { + + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("avl", "LogPane.Status_message")); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + } + + /** + * Takes the last occured actions as queue from the Controller. + * This actions are prepared as strings for easy displaying. Highlights the + * last entry, sets the pre-last entry back to normal style. + */ + public void update() { + doc.setCharacterAttributes(lastHighlightedParagraphOffset, + lastHighlightedParagraphLength, + Settings.NORMAL_STYLE[Settings.getDisplayMode()], true); + + lastLogDescriptions = controller.getLogDescriptions(); + for (String logDesc : lastLogDescriptions) { + if (logDesc == null || logDesc.equals("")) continue; //$NON-NLS-1$ + lastHighlightedParagraphOffset = doc.getLength(); + try { + doc.insertString(doc.getLength(), logDesc + lineSeparator, + Settings.NORMAL_STYLE[Settings.getDisplayMode()]); + } + catch (BadLocationException ex) { + System.err.println(Messages.getString( + "avl", "LogPane.Update_error")); //$NON-NLS-1$ //$NON-NLS-2$ + } + lastHighlightedParagraphLength = logDesc.length() + + lineSeparator.length(); + } + doc.setCharacterAttributes(lastHighlightedParagraphOffset, + lastHighlightedParagraphLength, + Settings.HIGHLIGHTED_STYLE[Settings.getDisplayMode()], true); + textPane.setCaretPosition(lastHighlightedParagraphOffset + + lastHighlightedParagraphLength); + } + + /** + * Clears the logbook. + */ + public void reset() { + try { + doc.remove(0, doc.getLength()); + } + catch (BadLocationException ex) { + System.err.println(Messages.getString( + "avl", "Unreachable_error")); //$NON-NLS-1$ //$NON-NLS-2$ + } + lastHighlightedParagraphLength = 0; + lastHighlightedParagraphOffset = 0; + } + + /** + * This method is called, when the display mode has changed between pc mode + * and beamer mode. As a result of this the size of the font is changed. + */ + public void displayModeChanged() { + if (lastHighlightedParagraphOffset+lastHighlightedParagraphLength == 0) + return; + doc.setCharacterAttributes(0, lastHighlightedParagraphOffset, + Settings.NORMAL_STYLE[Settings.getDisplayMode()], true); + doc.setCharacterAttributes(lastHighlightedParagraphOffset, + lastHighlightedParagraphLength, + Settings.HIGHLIGHTED_STYLE[Settings.getDisplayMode()], true); + // scroll to end of text + Rectangle visibleRect = textPane.getVisibleRect(); + // force recalculating of height + textPane.getParent().doLayout(); + visibleRect.y = textPane.getHeight() - visibleRect.height; + textPane.scrollRectToVisible(visibleRect); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/Navigator.java b/src/org/jalgo/module/avl/gui/components/Navigator.java new file mode 100644 index 0000000..8372018 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/Navigator.java @@ -0,0 +1,266 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 29.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.AWTException; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.SystemColor; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import javax.swing.JComponent; +import javax.swing.JInternalFrame; +import javax.swing.Popup; +import javax.swing.PopupFactory; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.gui.graphics.PaintArea; + +/** + * The class Navigator is a special feature for scrollpanes. It + * can be added as e.g. lower right corner of the scrollpane and it gets a + * reference to the viewport of the scrollpane. When clicking in the corner a + * popup opens with a scaled preview of the viewport content. Dragging the mouse + * the user can navigate through the scrollpane. + * + * @author Alexander Claus + */ +public class Navigator +extends JComponent +implements MouseListener, MouseMotionListener { + + private static final long serialVersionUID = 2584571837248927562L; + + // general references + private PaintArea paintArea; + + // popup components + private Popup popup; + private JInternalFrame navigator; + private JComponent map; + private Point lowerRightCornerPoint; + + // variables for displaying + private static final int DIAGONAL = 200; + private double scale; + private Rectangle visibleRect; + private Image scaledImage; + private Point vrCorner; + private boolean mouseOver; + + // the "mouse mover" + private Robot robot; + + /** + * Constructs a Navigator object with the given references. + * + * @param paintArea the viewport of the scrollpane + */ + public Navigator(PaintArea paintArea) { + this.paintArea = paintArea; + + setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); + addMouseListener(this); + navigator = new JInternalFrame(Messages.getString( + "avl", "Navigator")); //$NON-NLS-1$ //$NON-NLS-2$ + // the map is responsible for displaying the preview + map = new JComponent() { + private static final long serialVersionUID = 4023482342502748131L; + + @SuppressWarnings("synthetic-access") + public void paint(Graphics g) { + // fill background + g.setColor(Color.WHITE); + g.fillRect(0, 0, getWidth(), getHeight()); + // draw preview, offset of 3px because of compensation of + // localisation conflicts caused by the SWT <-> Swing + // "cooperation" + g.drawImage(scaledImage, 3, 3, this); + // draw visible rect, offset like preview + updateVisibleRect(); + g.setColor(Color.RED); + g.drawRect(visibleRect.x + 3, visibleRect.y + 3, + visibleRect.width, visibleRect.height); + // paint border + super.paintBorder(g); + } + }; + map.setBorder(new EtchedBorder()); + navigator.add(map); + navigator.setCursor(Cursor.getPredefinedCursor( + Cursor.CROSSHAIR_CURSOR)); + // robot is responsible for automatically mouse moving + try { + robot = new Robot(); + } + catch (AWTException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "avl", "No_robot_error")); //$NON-NLS-1$ //$NON-NLS-2$ + ex.printStackTrace(); + robot = null; + } + } + + /** + * Calculates the scaled version of the visible rect new from getting the + * visible rect of the viewport. + */ + private void updateVisibleRect() { + visibleRect = paintArea.getVisibleRect(); + visibleRect.setRect(visibleRect.x * scale, visibleRect.y * scale, + visibleRect.width * scale, visibleRect.height * scale); + } + + /** + * When left mouse button is pressed, the popup is created and shown. The + * mouse cursor is moved to the center of the visible rect. + */ + public void mousePressed(MouseEvent e) { + // ensure that only the left mouse button is pressed once + if (e.getButton() != MouseEvent.BUTTON1 || e.getClickCount() > 1) return; + // force popup relicts to disappear + if (popup != null) popup.hide(); + + // calculate size of navigator frame + scale = DIAGONAL / Math.sqrt( + paintArea.getWidth() * paintArea.getWidth() + + paintArea.getHeight() * paintArea.getHeight()); + // border of 9px because of compensation of localisation conflicts + // caused by the SWT <-> Swing "cooperation" + map.setPreferredSize(new Dimension( + (int)(paintArea.getWidth() * scale) + 9, + (int)(paintArea.getHeight() * scale) + 9)); + // create scaled image of paint area + scaledImage = paintArea.getScaledImage(scale); + navigator.pack(); + navigator.setVisible(true); + + // create popup, where lower right corner is the + // lower right corner of the scrollpane + lowerRightCornerPoint = getLocationOnScreen(); + lowerRightCornerPoint.translate(getWidth(), getHeight()); + popup = PopupFactory.getSharedInstance().getPopup(this, navigator, + lowerRightCornerPoint.x - navigator.getWidth(), + lowerRightCornerPoint.y - navigator.getHeight()); + popup.show(); + // TODO: request focus on navigator does not work... + // move cursor to center of the visible rect + updateVisibleRect(); + vrCorner = navigator.getAccessibleContext().getAccessibleChild(0). + getAccessibleContext().getAccessibleComponent().getBounds(). + getLocation(); + if (robot != null) robot.mouseMove( + lowerRightCornerPoint.x - navigator.getWidth() + vrCorner.x + + (int)visibleRect.getCenterX(), + lowerRightCornerPoint.y - navigator.getHeight() + vrCorner.y + + (int)visibleRect.getCenterY()); + addMouseMotionListener(this); + } + + /** + * Releasing mouse causes to hide the navigator popup and to move the mouse + * cursor back to center of the corner component. + */ + public void mouseReleased(MouseEvent e) { + if (e.getButton() != MouseEvent.BUTTON1 || e.getClickCount() > 1) return; + popup.hide(); + // remove the listener to avoid drag events during initialization + // and hiding the popup + removeMouseMotionListener(this); + if (robot != null) robot.mouseMove( + lowerRightCornerPoint.x - getWidth() / 2, + lowerRightCornerPoint.y - getHeight() / 2); + } + + /** + * Highlights the corner component as selected. + */ + public void mouseEntered(MouseEvent e) { + mouseOver = true; + repaint(); + } + + /** + * Sets the selected state back to normal. + */ + public void mouseExited(MouseEvent e) { + mouseOver = false; + repaint(); + } + + /** + * Paints the corner content. + */ + public void paint(Graphics g) { + g.setColor(SystemColor.control); + g.fill3DRect(0, 0, getWidth(), getHeight(), !mouseOver); + g.setColor(Color.WHITE); + g.fill3DRect(4, 4, getWidth() - 8, getWidth() - 8, mouseOver); + g.fillRect(5, 5, getWidth() - 10, getWidth() - 10); + } + + /** + * Here the real navigation code. The viewport is scrolled to the rectangle + * centered at the event coordinates. + */ + public void mouseDragged(MouseEvent e) { + // calculate the upper left corner of the new visible rect + Point p = e.getPoint(); + p.translate(navigator.getWidth() - getWidth() - vrCorner.x, + navigator.getHeight() - getHeight() - vrCorner.y); + visibleRect.setLocation(p.x - visibleRect.width / 2, + p.y - visibleRect.height / 2); + paintArea.scrollRectToVisible(new Rectangle( + (int)(visibleRect.x / scale), + (int)(visibleRect.y / scale), + paintArea.getVisibleRect().width, + paintArea.getVisibleRect().height)); + map.repaint(); + } + + /** + * No action is performed here. + */ + public void mouseMoved(MouseEvent e) { + // this method has no effect + } + + /** + * No action is performed here. + */ + public void mouseClicked(MouseEvent e) { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/RandomGenerationDialog.java b/src/org/jalgo/module/avl/gui/components/RandomGenerationDialog.java new file mode 100644 index 0000000..1acab02 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/RandomGenerationDialog.java @@ -0,0 +1,317 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 20.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; + +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.ModuleConnector; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.event.RandomGenerationDialogActionHandler; + +/** + * The class RandomGenerationDialog represents a dialog for + * creating a random tree. It provides the setting of the number of nodes, the + * AVL property and the type of visualization. The three available visualization + * types are defined as constants in GUIConstants.
        + * The input of the number of nodes is validated on the fly and appropriate + * messages are displayed to the user, if the input is not valid.
        + * To show the dialog, call open(), all settings are reset + * before. + * + * @author Alexander Claus + */ +public class RandomGenerationDialog +extends JDialog +implements GUIConstants { + + private static final long serialVersionUID = 4752493355110066765L; + private Frame parent; + private RandomGenerationDialogActionHandler action; + + private JLabel errorIcon; + private JLabel errorMessage; + private JTextField textField; + private JCheckBox avlProperty; + private JRadioButton noVisualisation; + private JRadioButton stepWise; + private JRadioButton automatical; + private JButton ok; + private JButton cancel; + private int currentInput; + + /** + * Constructs a RandomGenerationDialog object with the given + * references. The dialog is only created here, to bring it to the screen, + * call open(). + * + * @param gui the GUIController instance of the AVL module + * @param parent the parent component to locate correctly on the screen + * @param controller the Controller instance of the AVL + * module + */ + public RandomGenerationDialog(GUIController gui, Frame parent, + Controller controller, ModuleConnector connector) { + super(parent, Messages.getString( + "avl", "RGD.Generate_random_tree"), true); //$NON-NLS-1$ //$NON-NLS-2$ + + this.parent = parent; + action = new RandomGenerationDialogActionHandler(controller, gui, this, + connector); + + GridBagLayout gbl = new GridBagLayout(); + setLayout(gbl); + + // messagePane contains the error message + JPanel messagePane = new JPanel(new BorderLayout(4, 4)); + errorIcon = new JLabel(new ImageIcon(Messages.getResourceURL( + "main", "Icon.Msg_error"))); //$NON-NLS-1$ //$NON-NLS-2$ + errorMessage = new JLabel(); + messagePane.add(errorIcon, BorderLayout.WEST); + messagePane.add(errorMessage, BorderLayout.CENTER); + messagePane.add(Box.createVerticalStrut(30), BorderLayout.EAST); + setErrorMessage(null); + GUIController.setGBC(messagePane, gbl, 0, 0, 3, 1, + GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL); + add(messagePane); + + JLabel countLabel = new JLabel(Messages.getString( + "avl", "RGD.Node_count")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(countLabel, gbl, 0, 1, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(countLabel); + textField = new JTextField(); + textField.getDocument().addDocumentListener(action); + + GUIController.setGBC(textField, gbl, 2, 1, 1, 1, + GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL); + add(textField); + JLabel avlLabel = new JLabel(Messages.getString( + "avl", "RGD.AVL_property")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(avlLabel, gbl, 0, 2, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(avlLabel); + avlProperty = new JCheckBox(); + GUIController.setGBC(avlProperty, gbl, 2, 2, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(avlProperty); + + JLabel visualizeLabel = new JLabel(Messages.getString( + "avl", "RGD.Visualization")); //$NON-NLS-1$ //$NON-NLS-2$ + GUIController.setGBC(visualizeLabel, gbl, 0, 3, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(visualizeLabel); + ButtonGroup visualization = new ButtonGroup(); + noVisualisation = new JRadioButton(Messages.getString( + "avl", "RGD.No_visualization")); //$NON-NLS-1$ //$NON-NLS-2$ + visualization.add(noVisualisation); + GUIController.setGBC(noVisualisation, gbl, 2, 3, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(noVisualisation); + stepWise = new JRadioButton(Messages.getString( + "avl", "RGD.Stepwise")); //$NON-NLS-1$ //$NON-NLS-2$ + visualization.add(stepWise); + GUIController.setGBC(stepWise, gbl, 2, 4, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(stepWise); + automatical = new JRadioButton(Messages.getString( + "avl", "RGD.Automatical")); //$NON-NLS-1$ //$NON-NLS-2$ + visualization.add(automatical); + GUIController.setGBC(automatical, gbl, 2, 5, 1, 1, + GridBagConstraints.WEST, GridBagConstraints.NONE); + add(automatical); + + ok = new JButton(Messages.getString( + "avl", "RGD.Button_ok")); //$NON-NLS-1$ //$NON-NLS-2$ + ok.setActionCommand("ok"); //$NON-NLS-1$ + ok.addActionListener(action); + ok.setDefaultCapable(true); + GUIController.setGBC(ok, gbl, 0, 6, 2, 1, GridBagConstraints.EAST, + GridBagConstraints.NONE); + add(ok); + + cancel = new JButton(Messages.getString( + "avl", "RGD.Button_cancel")); //$NON-NLS-1$ //$NON-NLS-2$ + cancel.setActionCommand("cancel"); //$NON-NLS-1$ + cancel.addActionListener(action); + GUIController.setGBC(cancel, gbl, 2, 6, 1, 1, + GridBagConstraints.CENTER, GridBagConstraints.NONE); + add(cancel); + + pack(); + } + + /** + * Retrieves the selection status of the AVL-mode-checkbox. + * + * @return true, if AVL mode is selected, false + * otherwise + */ + public boolean isAVLSelected() { + return avlProperty.isSelected(); + } + + /** + * Sets the enabled status of the OK button. + * + * @param b true, if the button should be enabled, + * false otherwise + */ + public void setOKEnabled(boolean b) { + ok.setEnabled(b); + } + + /** + * Validates the input string to be a valid integer in the acceptable range + * defined in Constants. Returns an identifier, which + * determines the validity of the input. Furthermore an error message is + * displayed if the input is not a valid key. The constants used for this + * are implemented in GUIConstants. + * + * @return VALID_INPUT - if the input is a valid key
        + * INPUT_EMPTY - if the input is empty
        + * NO_INTEGER - if the input contains nonnumber + * characters
        + * NOT_IN_RANGE - if the input key is out of the + * acceptable range + */ + public int validateInput() { + int returnCode; + try { + currentInput = Integer.parseInt(textField.getText()); + if (currentInput > MAX_KEY || currentInput < MIN_KEY) + returnCode = NOT_IN_RANGE; + else returnCode = VALID_INPUT; + } + catch (NumberFormatException ex) { + if (textField.getText().length() == 0) returnCode = INPUT_EMPTY; + else returnCode = NO_INTEGER; + } + switch (returnCode) { + case VALID_INPUT: + setErrorMessage(null); + setOKEnabled(true); + break; + case NO_INTEGER: + setErrorMessage(Messages.getString( + "avl", "Warning_only_integers")); //$NON-NLS-1$ //$NON-NLS-2$ + setOKEnabled(false); + break; + case NOT_IN_RANGE: + setErrorMessage(Messages.getString( + "avl", "Warning_only_values_from") + //$NON-NLS-1$ //$NON-NLS-2$ + MIN_KEY + + Messages.getString("avl", "Warning_to") + //$NON-NLS-1$ //$NON-NLS-2$ + MAX_KEY + + Messages.getString("avl", "Warning_valid")); //$NON-NLS-1$ //$NON-NLS-2$ + setOKEnabled(false); + break; + case INPUT_EMPTY: + setErrorMessage(null); + setOKEnabled(false); + } + return returnCode; + } + + /** + * Displays an error message with an icon and the given string to the user. + * + * @param msg the error message + */ + public void setErrorMessage(String msg) { + if (msg == null) { + errorIcon.setVisible(false); + errorMessage.setText(""); //$NON-NLS-1$ + } + else { + errorIcon.setVisible(true); + errorMessage.setText(msg); + } + validate(); + } + + /** + * Resets the settings to the initial state. + */ + private void reset() { + currentInput = 10; + textField.setText(String.valueOf(currentInput)); + avlProperty.setSelected(false); + noVisualisation.setSelected(true); + } + + /** + * Brings the dialog to the screen. First reset() is called. + */ + public void open() { + reset(); + setLocationRelativeTo(parent); + getRootPane().setDefaultButton(ok); + setVisible(true); + } + + /** + * Retrieves the number of nodes the tree should consist of. + * + * @return the number of nodes + */ + public int getNodeCount() { + return currentInput; + } + + /** + * Retrieves the selected visualization mode. The constants for this are + * defined in GUIConstants. + * + * @return
          + *
        • NO_VISUALIZATION - if the tree should be generated in + * background
        • + *
        • STEPWISE - if the generation should be confirmed + * stepwise by the user
        • + *
        • AUTOMATICAL - if the generation of the tree should + * run as an animation
        • + */ + public int getVisualizationMode() { + if (noVisualisation.isSelected()) return GUIConstants.NO_VISUALIZATION; + if (stepWise.isSelected()) return GUIConstants.STEPWISE; + return GUIConstants.AUTOMATICAL; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/WelcomeButton.java b/src/org/jalgo/module/avl/gui/components/WelcomeButton.java new file mode 100644 index 0000000..73896b0 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/WelcomeButton.java @@ -0,0 +1,91 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.04.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +import org.jalgo.module.avl.gui.event.WelcomeScreenActionHandler; + +/** + * The class WelcomeButton represents a rollover-enabled graphical + * button with a description, which can be displayed on mouse hovering. + * + * @author Alexander Claus + */ +public class WelcomeButton +extends JToggleButton { + + private static final long serialVersionUID = -1924541401853204950L; + private final ImageIcon desc; + + /** + * Constructs a WelcomeButton object with the given parameters. + * The description string is represented as a bitmap image, because of better + * layout on different platforms and the missing antialiasing of text on Swing + * components. + * + * @param defaultIcon the icon, which is displayed, when button is not selected + * @param rolloverIcon the icon, which is displayed on mouse hovering + * @param description the description string as image + * @param actionCommand the action command + * @param action an event handler implementing ActionListener + * and MouseListener + */ + public WelcomeButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + ImageIcon description, String actionCommand, + WelcomeScreenActionHandler action) { + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + //the standard rollover mechanism isn't used because of the following bug: + //click on an button holds the rollover state so that 2nd opening + //of welcome screen still highlights the button, even if mouse is not over + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + desc = description; + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension( + getIcon().getIconWidth(), + getIcon().getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(action); + } + + /** + * Retrieves the description of this WelcomeButton as image. + * + * @return the description string as image + */ + public ImageIcon getDescription() { + return desc; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/components/WelcomeScreen.java b/src/org/jalgo/module/avl/gui/components/WelcomeScreen.java new file mode 100644 index 0000000..4c3089e --- /dev/null +++ b/src/org/jalgo/module/avl/gui/components/WelcomeScreen.java @@ -0,0 +1,156 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 25.05.2005 */ +package org.jalgo.module.avl.gui.components; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.event.WelcomeScreenActionHandler; + +/** + * Class WelcomeScreen represents a screen with three buttons, + * where the user can choose what to do. The buttons are rollover enabled and a + * description of the selected task is displayed. + * + * @author Alexander Claus + */ +public class WelcomeScreen +extends JPanel +implements GUIConstants { + + private static final long serialVersionUID = -2019743374918523370L; + + private WelcomeScreenActionHandler action; + + // components + private WelcomeButton loadButton; + private WelcomeButton manualButton; + private WelcomeButton randomButton; + private JLabel descriptionLabel; + + /** + * Constructs a WelcomeScreen object with the given + * reference. + * + * @param gui the GUIController instance + */ + public WelcomeScreen(GUIController gui) { + action = new WelcomeScreenActionHandler(gui, this); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + + String lang = Settings.getString("main", "Language"); //$NON-NLS-1$ + if (!lang.equals("de")) lang = "en"; //$NON-NLS-1$ //$NON-NLS-2$ + loadButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_load")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_load_rollover")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_load_description_"+lang)), //$NON-NLS-1$ //$NON-NLS-2$ + "load", action); //$NON-NLS-1$ + manualButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_manual")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_manual_rollover")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_manual_description_"+lang)), //$NON-NLS-1$ //$NON-NLS-2$ + "createManually", action); //$NON-NLS-1$ + randomButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_random")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_random_rollover")), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon( + Messages.getResourceURL("avl", "Welcome_random_description_"+lang)), //$NON-NLS-1$ //$NON-NLS-2$ + "createRandomly", action); //$NON-NLS-1$ + + descriptionLabel = new JLabel(); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(WELCOME_SCREEN_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(loadButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(manualButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(randomButton); + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + } + + /** + * Displays the given string description on the screen. + * + * @param desc the task description string + */ + public void setDescription(Icon desc) { + descriptionLabel.setIcon(desc); + descriptionLabel.updateUI(); + } + + /** + * Sets the enabled status of the buttons. If the given value is + * false, also the description string is removed from the + * screen. + * + * @param b true, if the buttons should be enabled, + * false otherwise + */ + public void setButtonsEnabled(boolean b) { + loadButton.setEnabled(b); + manualButton.setEnabled(b); + randomButton.setEnabled(b); + if (!b) setDescription(null); + } + + /** + * Draws the background with a beautyful color ;o). Normally there would be + * the background color set with setBackground(..), but, under + * linux (GTK) this has no effect. So this is a workaround... + */ + @Override + protected void paintComponent(Graphics g) { + g.setColor(WELCOME_SCREEN_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/AbortAction.java b/src/org/jalgo/module/avl/gui/event/AbortAction.java new file mode 100644 index 0000000..83ffa83 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/AbortAction.java @@ -0,0 +1,81 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class AbortAction defines an Action object, + * which can be added to toolbars and menus. Performing this action aborts the + * currently running algorithm. + * + * @author Alexander Claus + */ +public class AbortAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs an AbortAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public AbortAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Abort_algorithm")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION,Messages.getString("avl", "Abort_algorithm_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, + new ImageIcon(Messages.getResourceURL("main", "Icon.Abort_algorithm"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + try { + controller.abort(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + gui.algorithmAborted(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/CVS/Entries b/src/org/jalgo/module/avl/gui/event/CVS/Entries new file mode 100644 index 0000000..4068675 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/CVS/Entries @@ -0,0 +1,12 @@ +/AbortAction.java/1.8/Thu Jan 31 20:15:02 2008// +/ClearTreeAction.java/1.7/Thu Jan 31 20:15:02 2008// +/ControlActionHandler.java/1.6/Thu Jan 31 20:15:02 2008// +/FinishAction.java/1.8/Thu Jan 31 20:15:02 2008// +/PerformAction.java/1.8/Thu Jan 31 20:15:02 2008// +/PerformBlockStepAction.java/1.8/Thu Jan 31 20:15:02 2008// +/RandomGenerationDialogActionHandler.java/1.8/Thu Jan 31 20:15:02 2008// +/ToggleDisplayModeAction.java/1.6/Thu Jan 31 20:15:02 2008// +/UndoAction.java/1.8/Thu Jan 31 20:15:02 2008// +/UndoBlockStepAction.java/1.8/Thu Jan 31 20:15:02 2008// +/WelcomeAction.java/1.8/Thu Jan 31 20:15:01 2008// +/WelcomeScreenActionHandler.java/1.6/Thu Jan 31 20:15:02 2008// diff --git a/src/org/jalgo/module/avl/gui/event/CVS/Repository b/src/org/jalgo/module/avl/gui/event/CVS/Repository new file mode 100644 index 0000000..8d02365 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/gui/event diff --git a/src/org/jalgo/module/avl/gui/event/CVS/Root b/src/org/jalgo/module/avl/gui/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/gui/event/ClearTreeAction.java b/src/org/jalgo/module/avl/gui/event/ClearTreeAction.java new file mode 100644 index 0000000..ad4d2bf --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/ClearTreeAction.java @@ -0,0 +1,87 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 06.06.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.DialogConstants; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.GUIController; + +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * The class ClearTreeAction defines an Action + * object, which can be added to SWT toolbars and menus. Performing this action + * asks the user for discarding his changes and if "OK" is selected, the tree is + * cleared. + * + * @author Alexander Claus + */ +public class ClearTreeAction +extends AbstractAction { + + private final GUIController gui; + private final SearchTree tree; + + /** + * Constructs a ClearTreeAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param tree the SearchTree instance to be the target of + * operation + */ + public ClearTreeAction(GUIController gui, SearchTree tree) { + this.gui = gui; + this.tree = tree; + putValue(NAME, Messages.getString("avl", "Clear_tree")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Clear_tree_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("main", "Icon.Clear"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + switch (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("avl", "Clear_tree_warning"), //$NON-NLS-1$ //$NON-NLS-2$ + DialogConstants.OK_CANCEL_OPTION)) { + case DialogConstants.OK_OPTION: + tree.clear(); + gui.setToolbarButtonsDisabled(); + gui.setAVLMode(true, true); + gui.installStandardLayout(); + break; + case DialogConstants.CANCEL_OPTION: + return; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/ControlActionHandler.java b/src/org/jalgo/module/avl/gui/event/ControlActionHandler.java new file mode 100644 index 0000000..0c82d14 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/ControlActionHandler.java @@ -0,0 +1,199 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 17.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.Settings; +import org.jalgo.module.avl.gui.components.ControlPane; + +/** + * The class ControlActionHandler represents an event handler for + * the ControlPane class. It handles button clicks, input events + * on textfields, mouse events for displaying status messages, focus events for + * marking the content of a textfield and change events for option controls. + * + * @author Alexander Claus + */ +public class ControlActionHandler +implements ActionListener, DocumentListener, MouseListener, GUIConstants, + ChangeListener, FocusListener { + + private GUIController gui; + private ControlPane controlPane; + private Controller controller; + + /** + * Contsructs a ControlActionHandler object with the given + * references. + * + * @param gui the GUIController instance + * @param controlPane the ControlPane instance, for which + * events are handled here + * @param controller the Controller instance + */ + public ControlActionHandler(GUIController gui, ControlPane controlPane, + Controller controller) { + this.gui = gui; + this.controlPane = controlPane; + this.controller = controller; + } + + /** + * Handles button clicks, starts algorithms. + */ + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("randomkey")) //$NON-NLS-1$ + controlPane.setRandomKey(); + else if (e.getActionCommand().equals("search")) { //$NON-NLS-1$ + controller.startSearch(controlPane.getCurrentKey()); + gui.algorithmStarted(); + } + else if (e.getActionCommand().equals("insert")) { //$NON-NLS-1$ + controller.startInsert(controlPane.getCurrentKey()); + gui.algorithmStarted(); + } + else if (e.getActionCommand().equals("delete")) { //$NON-NLS-1$ + controller.startRemove(controlPane.getCurrentKey()); + gui.algorithmStarted(); + } + else if (e.getActionCommand().equals("avltest")) { //$NON-NLS-1$ + gui.algorithmUndone(); + controlPane.validateKey(); + controller.startAVLTest(); + gui.showAVLTestDialog(); + } + else if (e.getActionCommand().equals("toggleavl")) { //$NON-NLS-1$ + boolean avlMode = ((JCheckBox)e.getSource()).isSelected(); + gui.algorithmAborted(); + controlPane.validateKey(); + controller.putLogDescription( + Messages.getString("avl", "AVL_mode") + //$NON-NLS-1$ //$NON-NLS-2$ + (avlMode ? Messages.getString("avl", "Switched_on") : //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("avl", "Switched_off"))); //$NON-NLS-1$ //$NON-NLS-2$ + gui.setAVLMode(avlMode, true); + } + } + + /** + * Invoked if input textfield has been edited. Causes to validate the input. + */ + public void insertUpdate(DocumentEvent e) { + controlPane.validateKey(); + } + + /** + * Invoked if input textfield has been edited. Causes to validate the input. + */ + public void removeUpdate(DocumentEvent e) { + controlPane.validateKey(); + } + + /** + * This method has no effect. + */ + public void changedUpdate(DocumentEvent e) { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void mouseClicked(MouseEvent e) { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void mousePressed(MouseEvent e) { + // this method has no effect + } + + /** + * This method has no effect. + */ + public void mouseReleased(MouseEvent e) { + // this method has no effect + } + + /** + * Causes to display the tooltip text of the event source in the status + * line. + */ + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getToolTipText()); + } + + /** + * Causes to remove the message from the status line. + */ + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + /** + * Invoked if animation speed control has been changed. + */ + public void stateChanged(ChangeEvent e) { + // TODO: check, what happens if more than one AVL modules are open + Settings.setStepDelay(((JSlider)e.getSource()).getValue()); + } + + /** + * Invoked if textfield is selected. Causes to select the whole input. + */ + public void focusGained(FocusEvent e) { + if (e.getSource() instanceof JTextField) + ((JTextField)e.getSource()).selectAll(); + } + + /** + * This method has no effect. + */ + public void focusLost(FocusEvent e) { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/FinishAction.java b/src/org/jalgo/module/avl/gui/event/FinishAction.java new file mode 100644 index 0000000..58bb429 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/FinishAction.java @@ -0,0 +1,82 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class FinishAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * finishes the currently running algorithm. + * + * @author Alexander Claus + */ +public class FinishAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs a FinishAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public FinishAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Finish_algorithm")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Finish_algorithm_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Finish_algorithm"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + try { + controller.finish(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + gui.algorithmFinished(); + gui.update(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/PerformAction.java b/src/org/jalgo/module/avl/gui/event/PerformAction.java new file mode 100644 index 0000000..f9e01d4 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/PerformAction.java @@ -0,0 +1,89 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Alexander Claus + */ +public class PerformAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public PerformAction(GUIController gui, Controller controller) { + super(); + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Perform")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Perform_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Perform_step"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + // first perform after complete undo, like new start of algorithm + if (!controller.algorithmHasPreviousStep()) gui.algorithmRestarted(); + + try { + controller.perform(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + // for explanation of the following step, see DocuPane.update() + gui.setStepDirection(true); + if (!controller.algorithmHasNextStep()) gui.algorithmFinished(); + + gui.update(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/PerformBlockStepAction.java b/src/org/jalgo/module/avl/gui/event/PerformBlockStepAction.java new file mode 100644 index 0000000..106e34a --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/PerformBlockStepAction.java @@ -0,0 +1,87 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class PerformBlockStepAction defines an + * Action object, which can be added to toolbars and menus. + * Performing this action causes the currently running algorithm to perform a + * block step. + * + * @author Alexander Claus + */ +public class PerformBlockStepAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs a PerformBlockStepAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public PerformBlockStepAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Perform_blockstep")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Perform_blockstep_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, + new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_blockstep"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(java.awt.event.ActionEvent e) { + // first perform after complete undo, like new start of algorithm + if (!controller.algorithmHasPreviousStep()) gui.algorithmRestarted(); + + try { + controller.performBlockStep(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + // for explanation of the following step, see DocuPane.update() + gui.setStepDirection(true); + if (!controller.algorithmHasNextStep()) gui.algorithmFinished(); + + gui.update(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.java b/src/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.java new file mode 100644 index 0000000..108d72e --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/RandomGenerationDialogActionHandler.java @@ -0,0 +1,134 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 26.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.ModuleConnector; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.components.RandomGenerationDialog; +import org.jalgo.module.avl.gui.graphics.RandomTreeAnimator; + +/** + * The class RandomGenerationDialogActionHandler represents an + * event handler for the RandomGenerationDialog class. It handles + * button clicks and key inputs. + * + * @author Alexander Claus + */ +public class RandomGenerationDialogActionHandler +implements ActionListener, DocumentListener, GUIConstants { + + private Controller controller; + private GUIController gui; + private RandomGenerationDialog dialog; + private ModuleConnector connector; + + /** + * Constructs a RandomGenerationDialogActionHandler object + * with the given references. + * + * @param controller the Controller instance of the AVL + * module + * @param gui the GUIController instance of the AVL module + * @param dialog the RandomGenerationDialog instance, for + * which events are handled here + */ + public RandomGenerationDialogActionHandler(Controller controller, + GUIController gui, RandomGenerationDialog dialog, + ModuleConnector connector) { + this.controller = controller; + this.gui = gui; + this.dialog = dialog; + this.connector = connector; + } + + /** + * Handles button clicks, starts the algorithm with choosen parameters. + */ + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("ok")) { //$NON-NLS-1$ + gui.setAVLMode(dialog.isAVLSelected(), false); + controller.createRandomTree(dialog.getNodeCount()); + + switch (dialog.getVisualizationMode()) { + case NO_VISUALIZATION: + try { + controller.finish(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + ex.getMessage()); + } + gui.installStandardLayout(); + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + // use alg.Finished() here, if stepwise backwards should be + // enabled + gui.algorithmAborted(); + break; + case STEPWISE: + gui.installStandardLayout(); + gui.algorithmStarted(); + break; + case AUTOMATICAL: + gui.installStandardLayout(); + gui.randomAnimatorStarted(); + gui.setAnimator(new RandomTreeAnimator(gui, controller)); + gui.getAnimator().start(); + } + } + dialog.dispose(); + } + + /** + * Invoked if input textfield has been edited. Causes to validate the input. + */ + public void insertUpdate(DocumentEvent e) { + dialog.validateInput(); + } + + /** + * Invoked if input textfield has been edited. Causes to validate the input. + */ + public void removeUpdate(DocumentEvent e) { + dialog.validateInput(); + } + + /** + * This method has no effect. + */ + public void changedUpdate(DocumentEvent e) { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.java b/src/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.java new file mode 100644 index 0000000..b0136ec --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/ToggleDisplayModeAction.java @@ -0,0 +1,106 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.06.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; + +import org.jalgo.main.util.Messages; + +import org.jalgo.module.avl.gui.DisplayModeChangeable; +import org.jalgo.module.avl.gui.GUIConstants; +import org.jalgo.module.avl.gui.Settings; + +/** + * The class ToggleDisplayAction defines a checkbox menuitem for + * switching between beamer mode and pc mode.
          + * Here the Singleton design pattern is implemented, in order that this setting + * takes global effect for all open instances of the AVL module.
          + * Components, which want to be notified, when display mode changes, have to + * register as observers. So ToggleDisplayAction acts as + * Observable. + * + * @author Alexander Claus + */ +public class ToggleDisplayModeAction +extends JCheckBoxMenuItem +implements ActionListener { + + // the singleton instance + private static ToggleDisplayModeAction instance; + + // the list of observers + private static List observers; + + /** + * Constructs the singleton instance of ToggleDisplayModeAction. + */ + private ToggleDisplayModeAction() { + super(Messages.getString("avl", "Beamer_mode"), //$NON-NLS-1$ //$NON-NLS-2$ + new ImageIcon(Messages.getResourceURL("main", "Icon.Beamer_mode")), //$NON-NLS-1$ //$NON-NLS-2$ + Settings.getDisplayMode() == GUIConstants.BEAMER_MODE); + observers = new LinkedList(); + addActionListener(this); + } + + /** + * Retrieves and, if necessary, initializes the singleton instance of + * ToggleDisplayModeAction. + * + * @return the singleton instance + */ + public static ToggleDisplayModeAction getInstance() { + if (instance == null) instance = new ToggleDisplayModeAction(); + return instance; + } + + /** + * Adds the given components to the list of targets, which will be notified, + * when action is performed. These components acts as observers. + * + * @param observer a component implementing + * DisplayModeChangeable + */ + public static void registerTarget(DisplayModeChangeable observer) { + observers.add(observer); + } + + /** + * Performs the action. The setting is changed globally and observers are + * notified. + */ + public void actionPerformed(ActionEvent e) { + Settings.setDisplayMode(isSelected() ? GUIConstants.BEAMER_MODE + : GUIConstants.PC_MODE); + for (DisplayModeChangeable observer : observers) { + observer.displayModeChanged(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/UndoAction.java b/src/org/jalgo/module/avl/gui/event/UndoAction.java new file mode 100644 index 0000000..bcad017 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/UndoAction.java @@ -0,0 +1,86 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class UndoAction defines an Action object, + * which can be added to toolbars or menus. Performing this action causes the + * currently running algorithm to undo a single step. + * + * @author Alexander Claus + */ +public class UndoAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs an UndoAction object with the given references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public UndoAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Undo")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Undo_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, + new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_step"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(java.awt.event.ActionEvent e) { + // for explanation of the following step, see DocuPane.update() + gui.setStepDirection(false); + // first undo after completion of algorithm + if (!controller.algorithmHasNextStep()) gui + .algorithmRestartedFromUndo(); + + try { + controller.undo(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + if (!controller.algorithmHasPreviousStep()) gui.algorithmUndone(); + + gui.update(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/UndoBlockStepAction.java b/src/org/jalgo/module/avl/gui/event/UndoBlockStepAction.java new file mode 100644 index 0000000..c94c730 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/UndoBlockStepAction.java @@ -0,0 +1,89 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; + +/** + * The class UndoBlockStepAction defines an Action + * object, which can be added to toolbars or menus. Performing this action + * causes the currently running algorithm to undo a block step. + * + * @author Alexander Claus + */ +public class UndoBlockStepAction +extends AbstractAction { + + private GUIController gui; + private Controller controller; + + /** + * Constructs an UndoBlockStepAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public UndoBlockStepAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString("avl", "Undo_blockstep")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString("avl", "Undo_blockstep_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_blockstep"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + // for explanation of the following step, see DocuPane.update() + gui.setStepDirection(false); + // first undo after completion of algorithm + if (!controller.algorithmHasNextStep()) + gui.algorithmRestartedFromUndo(); + + try { + controller.undoBlockStep(); + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(ex.getMessage()); + } + + if (!controller.algorithmHasPreviousStep()) gui.algorithmUndone(); + + gui.update(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/WelcomeAction.java b/src/org/jalgo/module/avl/gui/event/WelcomeAction.java new file mode 100644 index 0000000..038718b --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/WelcomeAction.java @@ -0,0 +1,90 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.DialogConstants; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.GUIController; + +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * The class WelcomeAction defines an Action + * object, which can be added to toolbars and menus. Performing this action asks + * the user for discarding his changes, and if so, switches the layout of the + * current AVL module instance to the welcome screen and clears the tree. If the + * user doesn't want to discard his changes, a new instance of the AVL module is + * opened. The question dialog can be cancelled too. + * + * @author Alexander Claus + */ +public class WelcomeAction +extends AbstractAction { + + private GUIController gui; + private SearchTree tree; + + /** + * Constructs a WelcomeAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param tree the SearchTree instance of the AVL module + */ + public WelcomeAction(GUIController gui, SearchTree tree) { + this.gui = gui; + this.tree = tree; + putValue(NAME, Messages.getString("avl", "Show_welcome_screen")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "avl", "Show_welcome_screen_tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("avl", "Module_logo"))); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + switch (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("avl", "Wish_to_discard"), //$NON-NLS-1$ //$NON-NLS-2$ + DialogConstants.YES_NO_CANCEL_OPTION)) { + case DialogConstants.YES_OPTION: + tree.clear(); + gui.installWelcomeScreen(); + break; + case DialogConstants.NO_OPTION: + JAlgoGUIConnector.getInstance().newModuleInstanceByName( + Messages.getString("avl", "Module_name")); //$NON-NLS-1$ //$NON-NLS-2$ + break; + case DialogConstants.CANCEL_OPTION: + return; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.java b/src/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.java new file mode 100644 index 0000000..da06a70 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/event/WelcomeScreenActionHandler.java @@ -0,0 +1,123 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 15.04.2005 */ +package org.jalgo.module.avl.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.components.WelcomeButton; +import org.jalgo.module.avl.gui.components.WelcomeScreen; + +/** + * The class WelcomeScreenActionHandler is an event handler for + * the WelcomeScreen class. It handles button clicks and mouse + * events for rollover mechanism. + * + * @author Alexander Claus + */ +public class WelcomeScreenActionHandler +implements ActionListener, MouseListener { + + private GUIController gui; + private WelcomeScreen screen; + + /** + * Constructs a WelcomeScreenActionHandler object with the + * given references. + * + * @param gui the GUIController instance + * @param screen the WelcomeScreen instance, for which this + * event handler is used + */ + public WelcomeScreenActionHandler(GUIController gui, WelcomeScreen screen) { + this.gui = gui; + this.screen = screen; + } + + /** + * Handles button clicks. + */ + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("load")) //$NON-NLS-1$ + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + else if (e.getActionCommand().equals("createManually")) { //$NON-NLS-1$ + gui.setAVLMode(true, true); + gui.installStandardLayout(); + } + else if (e.getActionCommand().equals("createRandomly")) { //$NON-NLS-1$ + screen.setButtonsEnabled(false); + gui.showRandomGenerationDialog(); + screen.setButtonsEnabled(true); + } + + ((WelcomeButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** + * Causes the event source button to highlight and to display its + * description string on screen. + */ + public void mouseEntered(MouseEvent e) { + WelcomeButton source = (WelcomeButton)e.getSource(); + if (!source.isEnabled()) return; + source.setSelected(true); + screen.setDescription(source.getDescription()); + } + + /** + * Causes the event source button to be displayed normally and to remove the + * description string from the screen. + */ + public void mouseExited(MouseEvent e) { + ((WelcomeButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** + * This method has no effect. + */ + public void mouseClicked(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + public void mousePressed(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + public void mouseReleased(MouseEvent e) { + // This method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/graphics/Animator.java b/src/org/jalgo/module/avl/gui/graphics/Animator.java new file mode 100644 index 0000000..cc97499 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/Animator.java @@ -0,0 +1,80 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 09.06.2005 */ +package org.jalgo.module.avl.gui.graphics; + +/** + * The class Animator represents a thread for running some animation. + * Subclasses have to override the run() method.
          + * At this time, animations are only supported for the generation of random trees. + * + * @author Alexander Claus + */ +public abstract class Animator +extends Thread +implements GraphicsConstants { + + public static final int STOPPED = 0; + public static final int RUNNING = 1; + public static final int STOP_REQUESTED = 2; + private int runningMode; + + /** + * Starts the animation. + */ + public synchronized void start() { + runningMode = RUNNING; + super.start(); + } + + /** + * Requests to stop the animation. Subclasses have to define, how and when to + * stop the thread. + */ + public void stopAnim() { + runningMode = STOP_REQUESTED; + } + + /** + * This method has to be invoked by subclasses, if the animation thread ends. + */ + protected void animStopped() { + runningMode = STOPPED; + } + + /** + * Retrieves the running state of the animation thread. + * + * @return true, if the thread is running, + * false otherwise + */ + public boolean isRunning() { + return runningMode != STOPPED; + } + + /** + * Retrieves, if the thread is requested to be stopped. + * + * @return true, if stop is requested, false otherwise + */ + protected boolean isStopRequested() { + return runningMode == STOP_REQUESTED; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/graphics/CVS/Entries b/src/org/jalgo/module/avl/gui/graphics/CVS/Entries new file mode 100644 index 0000000..29277e6 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/CVS/Entries @@ -0,0 +1,5 @@ +/Animator.java/1.3/Thu Jan 31 20:15:08 2008// +/GraphicsConstants.java/1.3/Thu Jan 31 20:15:08 2008// +/PaintArea.java/1.6/Thu Jan 31 20:15:08 2008// +/RandomTreeAnimator.java/1.6/Thu Jan 31 20:15:08 2008// +/RotateLeftAnimator.java/1.4/Thu Jan 31 20:15:08 2008// diff --git a/src/org/jalgo/module/avl/gui/graphics/CVS/Repository b/src/org/jalgo/module/avl/gui/graphics/CVS/Repository new file mode 100644 index 0000000..c8582ed --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/avl/gui/graphics diff --git a/src/org/jalgo/module/avl/gui/graphics/CVS/Root b/src/org/jalgo/module/avl/gui/graphics/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/avl/gui/graphics/GraphicsConstants.java b/src/org/jalgo/module/avl/gui/graphics/GraphicsConstants.java new file mode 100644 index 0000000..21f7ed1 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/GraphicsConstants.java @@ -0,0 +1,90 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.06.2005 */ +package org.jalgo.module.avl.gui.graphics; + +import java.awt.Color; +import java.awt.Font; + +/** + * The class GraphicsConstants is a collection of global constants + * for visualization in AVL module. It contains changeable and not changeable + * constants. Changeable constants are realized as an array, where the first entry + * defines the value of the constant in pc mode, and the second constant defines + * the value of the constant in beamer mode. To get the currently set value, + * you get the index from the Settings class. + * + * @author Alexander Claus + */ +public interface GraphicsConstants { + + /* changeable constants */ + + /*--------------------------graphical layout----------------------*/ + /** The distance between two nodes along the x axis. */ + public static final int[] X_DIST_NODES = new int[] {35, 46}; + /** The distance between two nodes along the y axis. */ + public static final int[] Y_DIST_NODES = new int[] {60, 75}; + /** The diameter of a node. */ + public static final int[] NODE_DIAMETER = new int[] {34, 45}; + /** The distance between focused node and working node along x axis. */ + public static final int[] X_DIST_WN = new int[] {40, 51}; + + /*------------------------------fonts-----------------------------*/ + /** The font used for the key in a node. */ + public static final Font[] KEY_FONT = new Font[] { + new Font("SansSerif", Font.BOLD, 18), + new Font("SansSerif", Font.BOLD, 23)}; + /** The font used for the balance of a node. */ + public static final Font[] BALANCE_FONT = new Font[] { + new Font("SansSerif", Font.BOLD, 13), + new Font("SansSerif", Font.BOLD, 15)}; + /** The font used for the balance of a node when it is highlighted. */ + public static final Font[] BALANCE_FONT_RED = new Font[] { + new Font("SansSerif", Font.BOLD, 18), + new Font("SansSerif", Font.BOLD, 20)}; + /** The font used for the caption of the rotation-arrow. */ + public static final Font[] ROTATION_ARROW_FONT = new Font[] { + new Font("SansSerif", Font.BOLD, 18), + new Font("SansSerif", Font.BOLD, 23)}; + + /*------------------------------colors----------------------------*/ + /** The color the worknode is filled with. */ + public static final Color[] COLOR_FOCUSED_WNODE = new Color[]{ + Color.RED, Color.RED.darker()}; + + /*--------------------------paint area margins--------------------*/ + /** The top margin of the paint area. */ + public static final int[] MARGIN_TOP = new int[] {50, 60}; + /** The bottom margin of the paint area. */ + public static final int[] MARGIN_BOTTOM = new int[] {50, 60}; + /** The left margin of the paint area. */ + public static final int[] MARGIN_LEFT = new int[] {70, 80}; + /** The right margin of the paint area. */ + public static final int[] MARGIN_RIGHT = new int[] {70, 80}; + + /* not changeable constants */ + + /*------------------------------colors----------------------------*/ + /** The color a focused node is filled with. */ + public static final Color COLOR_FOCUSED_NODE = new Color(50,200,0); + /** The color a focused arrow is painted with. */ + public static final Color COLOR_FOCUSED_ARROW = new Color(50,180,0); +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/graphics/PaintArea.java b/src/org/jalgo/module/avl/gui/graphics/PaintArea.java new file mode 100644 index 0000000..ac62217 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/PaintArea.java @@ -0,0 +1,626 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 28.04.2005 + */ +package org.jalgo.module.avl.gui.graphics; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.List; + +import javax.swing.JComponent; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.datastructure.AVLNode; +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.datastructure.Visualizable; +import org.jalgo.module.avl.datastructure.WorkNode; +import org.jalgo.module.avl.gui.DisplayModeChangeable; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.Settings; + +/** + * The class PaintArea represents a component, where the "really + * important thing" of the AVL module is located. Here the instance of the + * SearchTree is displayed and algorithms are visualized.
          + * How to paint the nodes in different styles is realized with flags, which are + * set to each node. For details see Visualizable.
          + * Future versions may support animations between single algorithm steps, but + * currently this is not implemented in order to release a stable version. + * + * @author Sebastian Pape, Alexander Claus + * @see org.jalgo.module.avl.datastructure.Visualizable + */ +public class PaintArea +extends JComponent +implements DisplayModeChangeable, GraphicsConstants { + + //general references + private GUIController gui; + private SearchTree tree; + private Controller controller; + + //the offscreen context + private BufferedImage offI; + private Graphics2D offG; + + //layout variables + private int width; + private int height; + + //the content of the tree in several traversions + private List nodeInOrder; + private List nodePostOrder; + + //display tuning + private int xDiff; + private FontMetrics FM_KEY_FONT; + private FontMetrics FM_BALANCE_FONT; + private FontMetrics FM_BALANCE_FONT_RED; + private FontMetrics FM_ROTATION_ARROW_FONT; + private int KEY_HEIGHT; + private int BALANCE_RED_HEIGHT; + + //animation stuff, currently deactivated in order to release a stable version +// private boolean animMode = false; +// private Animator animator; +// private boolean doAnimIfNecessary; + + /** + * Constructs a PaintArea object with the given references. + * + * @param gui the GUIController instance of the AVL module + * @param tree the SearchTree instance to be displayed + * @param controller the Controller instance of the AVL module + */ + public PaintArea(final GUIController gui, SearchTree tree, + Controller controller) { + this.gui = gui; + this.tree = tree; + this.controller = controller; + + //displayModeChanged() is not called here because of nullpointerexception + //when calling the first time + FM_KEY_FONT = getFontMetrics(KEY_FONT[Settings.getDisplayMode()]); + FM_BALANCE_FONT = getFontMetrics(BALANCE_FONT[Settings.getDisplayMode()]); + FM_BALANCE_FONT_RED = getFontMetrics( + BALANCE_FONT_RED[Settings.getDisplayMode()]); + FM_ROTATION_ARROW_FONT = getFontMetrics( + ROTATION_ARROW_FONT[Settings.getDisplayMode()]); + KEY_HEIGHT = FM_KEY_FONT.getAscent(); + BALANCE_RED_HEIGHT = FM_BALANCE_FONT_RED.getAscent(); + + //initiale gr�sse bewusst sehr gross gew�hlt, um nicht zu oft offscreen + //image zu vergr�ssern -> performance + updateOffscreenSize(2000, 2000); + + //the status line updater + addMouseListener(new MouseAdapter() { + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("avl", "PaintArea.Status_message")); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + } + + /** + * This method is invoked, if the size of the paint area has changed or + * possibly has changed. The size of the offscreen context is increased, if + * necessary. Because of this is a slow operation, the offscreen context + * initially has been sized large enough for most trees. + * + * @param w the new minimum width of the offscreen context + * @param h the new minimum height of the offscreen context + */ + private void updateOffscreenSize(int w, int h) { + if (w <= width && h <= height) return; + offI = new BufferedImage( + Math.max(width, w), + Math.max(height, h), + BufferedImage.TYPE_INT_RGB); + offG = offI.createGraphics(); + offG.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + } + + /** + * Calls paint(). + */ + public void update(Graphics g) { + paint(g); + } + + /** + * Paints the tree and the working node to the offscreen context and paints + * the offscreen image to the screen graphics object. + */ + public void paint(Graphics g) { +/* if (animMode) { + if (animator.isRunning()) { + g.drawImage(offI, 0, 0, this); + return; + } + animMode = false; + animator = null; + }*/ + + offG.setColor(Color.WHITE); + offG.fillRect(0, 0, width, height); + drawTree(); + drawWorkingNode(); + + g.drawImage(offI, 0, 0, this); + +/* if (animMode) { + animator.start(); + }*/ + } + + /** + * Retrieves the x coordinate of the given node. + * + * @param node the node to be painted. + * + * @return the x coordinate of the given node. + */ + public int getXFor(Node node) { + return MARGIN_LEFT[Settings.getDisplayMode()] + + X_DIST_NODES[Settings.getDisplayMode()]*nodeInOrder.indexOf(node) + + xDiff; + } + + /** + * Retrieves the y coordinate of the given node. + * + * @param node the node to be painted. + * + * @return the y coordinate of the given node. + */ + public int getYFor(Node node){ + return MARGIN_TOP[Settings.getDisplayMode()]+ + (tree.getLevelFor(node)-1)*Y_DIST_NODES[Settings.getDisplayMode()]; + } + + /** + * Iterates over the nodes of the tree in post order and draws the nodes and + * node decorations. + * + * @see #drawNode(int, int, Node) + * @see #drawNodeDecorations(int, int, Node) + */ + private void drawTree() { + if (tree.getRoot() == null) return; + + int x; + int y; + Node currentNode; + + for (int i=0; igetVisualizationStatus()
          . + * + * @param x the x coordinate + * @param y the y coordinate + * @param node the node to be painted + * + * @see Visualizable + */ + public void drawNode(int x, int y, Node node) { + int key = node.getKey(); + String key_string = String.valueOf(key); + int key_width; + + // Zeichnen des Knotens + offG.setColor(Color.BLACK); + offG.fillOval(x-NODE_DIAMETER[Settings.getDisplayMode()]/2, y-NODE_DIAMETER[Settings.getDisplayMode()]/2, NODE_DIAMETER[Settings.getDisplayMode()], NODE_DIAMETER[Settings.getDisplayMode()]); + if ((node.getVisualizationStatus()&Visualizable.NORMAL) != 0) + offG.setColor(Color.YELLOW); + else + offG.setColor(COLOR_FOCUSED_NODE); + + offG.fillOval(x-(NODE_DIAMETER[Settings.getDisplayMode()]-4)/2, y-(NODE_DIAMETER[Settings.getDisplayMode()]-4)/2, NODE_DIAMETER[Settings.getDisplayMode()]-4, NODE_DIAMETER[Settings.getDisplayMode()]-4); + + // Beschriftung des Knotens + offG.setColor(Color.BLACK); + offG.setFont(KEY_FONT[Settings.getDisplayMode()]); + key_width = FM_KEY_FONT.stringWidth(key_string); + offG.drawString(key_string, x-(key_width/2),y+(KEY_HEIGHT/4)+2); + } + + /** + * Draws the balance of the node, if the tree is an AVL tree. Draws the arrows + * for rotation, if necessary. + * + * @param x the x coordinate + * @param y the y coordinate + * @param node the node, for which decorations have to be painted + */ + private void drawNodeDecorations(int x, int y, Node node) { + // Beschriftung der Balance + if (controller.isAVLMode()){ + int balance = ((AVLNode)node).getBalance(); + String balance_string = String.valueOf(balance); + if ((node.getVisualizationStatus()&Visualizable.BALANCE) != 0){ + int balance_width = FM_BALANCE_FONT_RED.stringWidth(balance_string); + offG.setColor(Color.RED); + offG.setFont(BALANCE_FONT_RED[Settings.getDisplayMode()]); + offG.drawString(balance_string,x-(balance_width)/2, y-NODE_DIAMETER[Settings.getDisplayMode()]/2-2); + } + else { + int balance_width = FM_BALANCE_FONT.stringWidth(balance_string); + offG.setColor(Color.BLUE); + offG.setFont(BALANCE_FONT[Settings.getDisplayMode()]); + offG.drawString(balance_string,x-(balance_width)/2, y-NODE_DIAMETER[Settings.getDisplayMode()]/2-2); + } + } + + //Zeichnen der Rotationspfeile + if ((node.getVisualizationStatus()&Visualizable.ROTATE_LEFT_ARROW) != 0) { + drawLeftRotationArrow(x, y, node); +// if (doAnimIfNecessary) { +// animMode = true; + //TODO: register animator in guicontroller for stopping +// animator = new RotateLeftAnimator(this, offG, node); +// doAnimIfNecessary = false; +// } + } + else { + if ((node.getVisualizationStatus()&Visualizable.ROTATE_RIGHT_ARROW) != 0) + drawRightRotationArrow(x, y, node); + } + } + + /** + * Calculates the location of the working node and draws it. Draws insertion + * arrows, if necessary. + */ + private void drawWorkingNode() { + WorkNode wnode; + if ((wnode = controller.getWorkNode()) == null) return; + + int x; + int y; + Node nextToWnode = wnode.getNextToMe(); + if (nextToWnode == null) { + x = width/2-X_DIST_WN[Settings.getDisplayMode()]; + y = MARGIN_TOP[Settings.getDisplayMode()]; + } + else { + x = getXFor(nextToWnode)-X_DIST_WN[Settings.getDisplayMode()]; + y = getYFor(nextToWnode); + } + int key = wnode.getKey(); + String key_string = String.valueOf(key); + int key_width; + int visualstat = wnode.getVisualizationStatus(); + // if visualstatus == 1 then visible else unvisible + if ((visualstat&Visualizable.NORMAL) != 0) { + // Zeichnen des Arbeitsknotens + offG.setColor(Color.BLACK); + offG.fillOval( + x-NODE_DIAMETER[Settings.getDisplayMode()]/2, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2, + NODE_DIAMETER[Settings.getDisplayMode()], + NODE_DIAMETER[Settings.getDisplayMode()]); + offG.setColor(COLOR_FOCUSED_WNODE[Settings.getDisplayMode()]); + offG.fillOval( + x-(NODE_DIAMETER[Settings.getDisplayMode()]-4)/2, + y-(NODE_DIAMETER[Settings.getDisplayMode()]-4)/2, + NODE_DIAMETER[Settings.getDisplayMode()]-4, + NODE_DIAMETER[Settings.getDisplayMode()]-4); + // Beschriftung des Arbeitsknotens + offG.setColor(Color.WHITE); + offG.setFont(KEY_FONT[Settings.getDisplayMode()]); + key_width = FM_KEY_FONT.stringWidth(key_string); + offG.drawString(key_string, x-(key_width/2),y+(KEY_HEIGHT/4)+2); + } + // Zeichnen der Pfeile + if ((visualstat&Visualizable.LEFT_ARROW) != 0) + drawLeftArrow( + (x-NODE_DIAMETER[Settings.getDisplayMode()]/2)+ + X_DIST_WN[Settings.getDisplayMode()], + y+NODE_DIAMETER[Settings.getDisplayMode()]/2); + else if ((visualstat&Visualizable.RIGHT_ARROW) != 0) + drawRightArrow( + (x+NODE_DIAMETER[Settings.getDisplayMode()]/2)+ + X_DIST_WN[Settings.getDisplayMode()], + y+NODE_DIAMETER[Settings.getDisplayMode()]/2); + } + + /** + * Draws the line between the given node and its parent node. The style of the + * line is defined by the flags of the node. + * + * @param x1 the start x coordinate + * @param y1 the start y coordinate + * @param x2 the end x coordinate + * @param y2 the end y coordinate + * @param currentNode the child node in this connection + */ + public void drawLine(int x1, int y1, int x2, int y2, Node currentNode){ + if (currentNode == null) return; + int visualstat = currentNode.getVisualizationStatus(); + if ((visualstat&Visualizable.FOCUSED) != 0){ + if((visualstat&Visualizable.LINE_NORMAL) != 0) + offG.setColor(Color.BLACK); + else + offG.setColor(COLOR_FOCUSED_ARROW); + } + else + offG.setColor(Color.BLACK); + + + offG.setStroke( new BasicStroke(2) ); + offG.drawLine(x1, y1, x2, y2); + } + + /** + * Draws an arrow for inserting a new node as left child. + * + * @param x the x coordinate of the startpoint + * @param y the y coordinate of the startpoint + */ + private void drawLeftArrow(int x,int y) { + double theta2; + int headLength = 10; + int headwidth = 7; + int x2 = x-19; + int y2 = y+30; + int deltaX = (x2-x); + int deltaY = (y2-y); + double theta = Math.atan((double)(deltaY)/(double)(deltaX)); + if (deltaX < 0.0) theta2 = theta+Math.PI; + else theta2 = theta; + int lengthdeltaX =- (int)(Math.cos(theta2)*headLength); + int lengthdeltaY =- (int)(Math.sin(theta2)*headLength); + int widthdeltaX = (int)(Math.sin(theta2)*headwidth); + int widthdeltaY = (int)(Math.cos(theta2)*headwidth); + offG.setColor(COLOR_FOCUSED_ARROW); + offG.setStroke(new BasicStroke(2)); + offG.drawLine(x,y,x2,y2); + offG.drawLine(x2,y2, + x2+lengthdeltaX+widthdeltaX,y2+lengthdeltaY-widthdeltaY); + offG.drawLine(x2,y2, + x2+lengthdeltaX-widthdeltaX,y2+lengthdeltaY+widthdeltaY); + } + + /** + * Draws an arrow for inserting a new node as right child. + * + * @param x the x coordinate of the startpoint + * @param y the y coordinate of the startpoint + */ + private void drawRightArrow(int x,int y) { + double theta2; + int headLength = 10; + int headwidth = 7; + int x2 = x+20; + int y2 = y+32; + int deltaX = (x2-x); + int deltaY = (y2-y); + double theta = Math.atan((double)(deltaY)/(double)(deltaX)); + if (deltaX < 0.0) theta2 = theta+Math.PI; + else theta2 = theta; + int lengthdeltaX =- (int)(Math.cos(theta2)*headLength); + int lengthdeltaY =- (int)(Math.sin(theta2)*headLength); + int widthdeltaX = (int)(Math.sin(theta2)*headwidth); + int widthdeltaY = (int)(Math.cos(theta2)*headwidth); + offG.setColor(COLOR_FOCUSED_ARROW); + offG.setStroke(new BasicStroke(2)); + offG.drawLine(x,y,x2,y2); + offG.drawLine(x2,y2, + x2+lengthdeltaX+widthdeltaX,y2+lengthdeltaY-widthdeltaY); + offG.drawLine(x2,y2, + x2+lengthdeltaX-widthdeltaX,y2+lengthdeltaY+widthdeltaY); + } + + /** + * Draws an arrow indicating that a left rotation will be performed. + * + * @param x the x coordinate + * @param y the y coordinate + */ + private void drawLeftRotationArrow(int x, int y, Node currentnode){ + int arc_width = 80; + offG.setColor(Color.RED); + offG.setStroke(new BasicStroke(3)); + offG.drawArc( + x-arc_width/2, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT-2, + arc_width, 50, 45, 90); + int x_p[] = {x-33, x-26, x-19}; + int y_p[] = { + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT+7, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT-6, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT+10}; + offG.fillPolygon(x_p, y_p, 3); + offG.setFont(ROTATION_ARROW_FONT[Settings.getDisplayMode()]); + offG.drawString("L("+currentnode.getKey()+")",x+NODE_DIAMETER[Settings.getDisplayMode()]/2+2,y); + } + + /** + * Draws an arrow indicating that a right rotation will be performed. + * + * @param x the x coordinate + * @param y the y coordinate + */ + private void drawRightRotationArrow(int x, int y, Node currentnode){ + int arc_width = 80; + offG.setColor(Color.RED); + offG.setStroke(new BasicStroke(3)); + offG.drawArc( + x-arc_width/2, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT-2, + arc_width, 50, 45, 90); + int x_p[] = {x+31, x+24, x+17}; + int y_p[] = { + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT+7, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT-6, + y-NODE_DIAMETER[Settings.getDisplayMode()]/2-BALANCE_RED_HEIGHT+10}; + offG.fillPolygon(x_p, y_p, 3); + offG.setFont(ROTATION_ARROW_FONT[Settings.getDisplayMode()]); + String string = "R("+currentnode.getKey()+")"; + int string_width = FM_ROTATION_ARROW_FONT.stringWidth(string); + offG.drawString(string,x-NODE_DIAMETER[Settings.getDisplayMode()]/2-string_width-2,y); + } + + /** + * Sets the preferred size of this component. The given size is the bound, + * which the parent component (e.g. a scrollpane) expects, when content is + * larger, the given values are ignored. + */ + public void setPreferredSize(Dimension size) { + int nodes = tree.getWeight(); + int newWidth = Math.max( + (nodes-1)*X_DIST_NODES[Settings.getDisplayMode()] + + MARGIN_LEFT[Settings.getDisplayMode()] + + MARGIN_RIGHT[Settings.getDisplayMode()], + size.width); + int newHeight = Math.max( + (tree.getHeight()-1)*Y_DIST_NODES[Settings.getDisplayMode()] + + MARGIN_TOP[Settings.getDisplayMode()] + + MARGIN_BOTTOM[Settings.getDisplayMode()], + size.height); + updateOffscreenSize(newWidth, newHeight); + width = newWidth; + height = newHeight; + super.setPreferredSize(new Dimension(width, height)); + // berechnen der x-verschiebung zur zentrierung des baumes + xDiff = (width - + MARGIN_LEFT[Settings.getDisplayMode()] - + MARGIN_RIGHT[Settings.getDisplayMode()] - + (nodes-1)*X_DIST_NODES[Settings.getDisplayMode()])/2; + } + + /** + * Returns a scaled image of the content of this PaintArea. + * This method is necessary e.g. for previewing and navigating. + * + * @param scale the scale for the transformation + * + * @return an Image which is a scaled version of the content + */ + public Image getScaledImage(double scale) { + return offI.getSubimage(0, 0, width, height).getScaledInstance( + (int)(scale*width), + (int)(scale*height), Image.SCALE_SMOOTH); + } + + /** + * Scrolls the working node as good as possible to the center of the area. + */ + public void scrollWorkNodeToCenter() { + if (tree.getHeight() == 0) return; + Rectangle visibleRect = getVisibleRect(); + visibleRect.x = getXFor(controller.getWorkNode().getNextToMe())- + visibleRect.width/2; + visibleRect.y = getYFor(controller.getWorkNode().getNextToMe())- + visibleRect.height/2; + scrollRectToVisible(visibleRect); + } + + /** + * Notifies this PaintArea object, that content has changed. + * Prepares some calculations for displaying and calls repaint(). + */ + public void update() { + nodeInOrder = tree.exportInOrder(); + nodePostOrder = tree.exportPostOrder(); + scrollWorkNodeToCenter(); +// doAnimIfNecessary = true; + repaint(); + } + + /** + * This method is called, when the display mode has changed between pc mode + * and beamer mode. As a result of this the size of the fonts, the size of + * the nodes and some colors are changed. + */ + public void displayModeChanged() { + FM_KEY_FONT = getFontMetrics(KEY_FONT[Settings.getDisplayMode()]); + FM_BALANCE_FONT = getFontMetrics(BALANCE_FONT[Settings.getDisplayMode()]); + FM_BALANCE_FONT_RED = getFontMetrics( + BALANCE_FONT_RED[Settings.getDisplayMode()]); + FM_ROTATION_ARROW_FONT = getFontMetrics(ROTATION_ARROW_FONT[Settings.getDisplayMode()]); + KEY_HEIGHT = FM_KEY_FONT.getAscent(); + BALANCE_RED_HEIGHT = FM_BALANCE_FONT_RED.getAscent(); + gui.doLayout(); + //TODO: find out, why scrolling does not work when switching to beamer mode + scrollWorkNodeToCenter(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.java b/src/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.java new file mode 100644 index 0000000..f478f0b --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/RandomTreeAnimator.java @@ -0,0 +1,85 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 21.05.2005 */ +package org.jalgo.module.avl.gui.graphics; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.avl.Controller; +import org.jalgo.module.avl.NoActionException; +import org.jalgo.module.avl.gui.GUIController; +import org.jalgo.module.avl.gui.Settings; + +/** + * Class RandomTreeAnimator provides an animation thread for + * automatical creation of a SearchTree. + * + * @author Alexander Claus + */ +public class RandomTreeAnimator +extends Animator { + + private GUIController gui; + private Controller controller; + + /** + * Constructs a RandomTreeAnimator object with the given + * references. + * + * @param gui the GUIController of the current AVL module + * instance + * @param controller the Controller of the current AVL module + */ + public RandomTreeAnimator(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + } + + /** + * The "program code" of the animator thread. Goes stepwise through the + * current algorithm until finished. + */ + public void run() { + while (controller.algorithmHasNextStep() && !isStopRequested()) { + try { + controller.perform(); + gui.update(); + sleep(Settings.getStepDelay()); + } + catch (InterruptedException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("avl", "Hard_exception") //$NON-NLS-1$ //$NON-NLS-2$ + + System.getProperty("line.separator") + ex.getMessage()); //$NON-NLS-1$ + return; + } + catch (NoActionException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + ex.getMessage()); + return; + } + } + if (!isStopRequested()) gui.algorithmFinished(); + animStopped(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.java b/src/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.java new file mode 100644 index 0000000..93e1c57 --- /dev/null +++ b/src/org/jalgo/module/avl/gui/graphics/RotateLeftAnimator.java @@ -0,0 +1,162 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 09.06.2005 */ +package org.jalgo.module.avl.gui.graphics; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.lang.Math; + +import org.jalgo.module.avl.datastructure.Node; +import org.jalgo.module.avl.datastructure.SearchTree; +import org.jalgo.module.avl.gui.Settings; + +/** + * @author Alexander Claus, Sebastian Pape + */ +public class RotateLeftAnimator +extends Animator { + + private final PaintArea pa; + private final Graphics2D offG; + private final Node pivot; + + private Rectangle boundingRect; + + public RotateLeftAnimator(PaintArea pa, Graphics2D offG, Node pivot) { + this.pa = pa; + this.offG = offG; + this.pivot = pivot; + boundingRect = new Rectangle(); + boundingRect.x = pa.getXFor(SearchTree.getMinimumNode(pivot)) + - NODE_DIAMETER[Settings.getDisplayMode()] / 2 - 1; + boundingRect.y = pa.getYFor(pivot) + - NODE_DIAMETER[Settings.getDisplayMode()] / 2 - 1; + boundingRect.width = pa.getXFor(SearchTree.getMaximumNode(pivot)) + - pa.getXFor(SearchTree.getMinimumNode(pivot)) + + NODE_DIAMETER[Settings.getDisplayMode()] + 2; + boundingRect.height = (pivot.getHeight() - 1) + * Y_DIST_NODES[Settings.getDisplayMode()] + + NODE_DIAMETER[Settings.getDisplayMode()] + 2; + } + + public void run() { + + double xd = 0; + double l_anf = 0; + double l_ende = 0; + double l_diff = 0; + + if (pivot.getRightChild().getLeftChild() != null) { + + // Abstand zwischen rechten Knoten und linken Knoten des Knotens, + // der umgehangen wird (für animierte Linie) + xd = (float)(pa.getXFor(pivot.getRightChild()) - pa.getXFor(pivot)) + / Y_DIST_NODES[Settings.getDisplayMode()]; + // Berechnung der Länge der animierten Linie zum alten parent-node + // und zum neuen parent-node + l_anf = Math.sqrt(Math.pow( + (pa.getXFor(pivot.getRightChild()) - + pa.getXFor(pivot.getRightChild().getLeftChild())), + 2) + + Math.pow(Y_DIST_NODES[Settings.getDisplayMode()], 2)); + l_ende = Math.sqrt(Math.pow( + (pa.getXFor(pivot.getRightChild().getLeftChild()) - + pa.getXFor(pivot)), + 2) + + Math.pow(Y_DIST_NODES[Settings.getDisplayMode()], 2)); + l_diff = (l_anf - l_ende) / Y_DIST_NODES[Settings.getDisplayMode()]; + } + + for (int y = 0; y <= Y_DIST_NODES[Settings.getDisplayMode()]; y++) { + offG.setColor(Color.WHITE); + offG.fillRect(boundingRect.x, boundingRect.y, boundingRect.width, + boundingRect.height); + pa.drawTree(pivot.getRightChild().getRightChild(), 0, -y); + pa.drawTree(pivot.getLeftChild(), 0, y); + + // zeichnet pivot RightChild.LeftChild (Umhängen des Knoten) und + // Teilbäume + if (pivot.getRightChild().getLeftChild() != null) { + double xd_y = (xd * y); + int y_l = (int)Math.sqrt( + Math.pow(l_anf - (l_diff * y), 2) - + Math.pow((pa.getXFor(pivot.getRightChild()) - + pa.getXFor(pivot.getRightChild().getLeftChild())) - + (int)xd_y, + 2)); + int y_l_hoehe = + pa.getYFor(pivot.getRightChild().getLeftChild()) - y_l; + // Falls der Y-Wert der umgehängten Linie aus dem Viereck + // herausragt + if (y_l_hoehe <= (pa.getYFor(pivot) + - NODE_DIAMETER[Settings.getDisplayMode()] / 2 - 1)) + y_l_hoehe = pa.getYFor(pivot) + - NODE_DIAMETER[Settings.getDisplayMode()] / 2; + + pa.drawTree( + pivot.getRightChild().getLeftChild().getRightChild(), 0, 0); + pa.drawTree( + pivot.getRightChild().getLeftChild().getLeftChild(), 0, 0); + + pa.drawLine( + pa.getXFor(pivot.getRightChild().getLeftChild()), + pa.getYFor(pivot.getRightChild().getLeftChild()), + pa.getXFor(pivot.getRightChild()) - (int)xd_y, + y_l_hoehe, + pivot); + + /* + * pa.drawLine(pa.getXFor(pivot.getRightChild().getLeftChild()), + * pa.getYFor(pivot.getRightChild().getLeftChild()), + * pa.getXFor(pivot.getRightChild())-xd2, + * pa.getYFor(pivot.getRightChild()),pivot); + */ + pa.drawNode(pa.getXFor(pivot.getRightChild().getLeftChild()), + pa.getYFor(pivot.getRightChild().getLeftChild()), pivot + .getRightChild().getLeftChild()); + } + + pa.drawLine( + pa.getXFor(pivot.getRightChild()), + pa.getYFor(pivot.getRightChild()) - y, + pa.getXFor(pivot), + pa.getYFor(pivot) + y, + pivot); + pa.drawNode( + pa.getXFor(pivot.getRightChild()), + pa.getYFor(pivot.getRightChild()) - y, pivot.getRightChild()); + pa.drawNode(pa.getXFor(pivot), pa.getYFor(pivot) + y, pivot); + pa.repaint(); + try { + Thread.sleep(30); + } + catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + animStopped(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/avl/res.properties b/src/org/jalgo/module/avl/res.properties new file mode 100644 index 0000000..097bcc9 --- /dev/null +++ b/src/org/jalgo/module/avl/res.properties @@ -0,0 +1,18 @@ +Module_logo=/avl_pix/logo.gif +Algorithm_text_base_de=/avl_algdesc.de.xml +Algorithm_text_base_en=/avl_algdesc.en.xml + +Welcome_load=/avl_pix/welcome_load.gif +Welcome_load_rollover=/avl_pix/welcome_load_rollover.gif +Welcome_load_description_de=/avl_pix/welcome_load_desc_de.gif +Welcome_load_description_en=/avl_pix/welcome_load_desc_en.gif +Welcome_manual=/avl_pix/welcome_manual.gif +Welcome_manual_rollover=/avl_pix/welcome_manual_rollover.gif +Welcome_manual_description_de=/avl_pix/welcome_manual_desc_de.gif +Welcome_manual_description_en=/avl_pix/welcome_manual_desc_en.gif +Welcome_random=/avl_pix/welcome_random.gif +Welcome_random_rollover=/avl_pix/welcome_random_rollover.gif +Welcome_random_description_de=/avl_pix/welcome_random_desc_de.gif +Welcome_random_description_en=/avl_pix/welcome_random_desc_en.gif + +HelpSet_Name=/help/jhelp/avl_help.hs \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/CVS/Entries b/src/org/jalgo/module/bfsdfs/CVS/Entries new file mode 100644 index 0000000..656ea4e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/CVS/Entries @@ -0,0 +1,10 @@ +/ModuleConnector.java/1.1/Wed Dec 8 13:47:54 2010// +/ModuleInfo.java/1.1/Wed Dec 8 13:47:54 2010// +D/algorithms//// +D/controller//// +/de.properties/1.1/Wed Dec 8 13:47:54 2010// +/en.properties/1.1/Wed Dec 8 13:47:54 2010// +D/graph//// +D/gui//// +/res.properties/1.1/Wed Dec 8 13:47:54 2010// +D/undo//// diff --git a/src/org/jalgo/module/bfsdfs/CVS/Repository b/src/org/jalgo/module/bfsdfs/CVS/Repository new file mode 100644 index 0000000..a2a0817 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs diff --git a/src/org/jalgo/module/bfsdfs/CVS/Root b/src/org/jalgo/module/bfsdfs/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/ModuleConnector.java b/src/org/jalgo/module/bfsdfs/ModuleConnector.java new file mode 100644 index 0000000..3bfc60d --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/ModuleConnector.java @@ -0,0 +1,171 @@ +package org.jalgo.module.bfsdfs; + +import java.io.*; +import java.util.Properties; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.algorithms.BFS; +import org.jalgo.module.bfsdfs.algorithms.DFS; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GUIController; +/** + * Interface for j-Algo. See j-Algo developer documentation for further details. + * @author Thomas Görres + * + */ +public class ModuleConnector extends AbstractModuleConnector { + /** Name of the file for module-specific properties */ + private static final String PROPFILE_NAME = ".bfsdfs.prop"; + + /** Comment for the module's property file */ + private static final String PROPFILE_COMMENT = "Properties for the j-Algo module BFS/DFS"; + + /** Property that contains the name of the last opened file*/ + private static final String PROPERTY_LAST_FILE = "last.file"; + + /** Stores the full file name of the currently opened file */ + private static String currentFileName; + + /** + * Initializes the module + */ + private static GUIController guiController; + private static GraphController graphController; + private static BFS bfs; + private static DFS dfs; + + @Override public void init() { + JAlgoGUIConnector.getInstance().getModuleMenu(this).setEnabled(false); + ModuleConnector.graphController = new GraphController(this); + ModuleConnector.bfs = new BFS(graphController); + ModuleConnector.dfs = new DFS(graphController); + ModuleConnector.guiController = new GUIController(this, bfs, dfs, graphController); + } + + /** + * Runs the module + */ + @Override public void run() { + ModuleConnector.guiController.installWelcomeScreen(); + } + + public void setDataFromFile(ByteArrayInputStream data) { + graphController.setDataFromFile(data); + + } + + + public ByteArrayOutputStream getDataForFile() { + return graphController.getDataForFile(); + } + + + /** + * Not implemented + */ + @Override public void print() {} + + public static GUIController getGuiController() { + return guiController; + } + + public static GraphController getGraphController() { + return graphController; + } + + public static BFS getBfs() { + return bfs; + } + + public static DFS getDfs() { + return dfs; + } + + /** + * Saves the current filename before closing + */ + @Override + public boolean close() { + saveCurrentFilename(); + return super.close(); + } + + /** + * Loads the graph from the specified file. The file has to be in j-Algo file format. + * @param filename name of the file that contains the graph + * @author Thomas Görres + */ + public static void loadFromFile(String filename) { + if (null == filename) + return; + + currentFileName = filename; + + try { + JAlgoMain.getInstance().openFile(filename, true); + } catch (Exception e) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString("bfsdfs", "ModuleConnector.Loading_error")); + } + } + + /** + * Loads the graph from the last opened file. If the last opened file is not known, calling this + * method has no effect + * @author Thomas Görres + */ + public static void loadFromLastFile() { + loadFromFile(loadLastFilename()); + } + + /** + * Stores the name of the currently loaded file in the {@linkplain #PROPFILE_NAME module's property file}. + * If no file is opened, calling this method has no effect. + * + * @author Thomas Görres + */ + private void saveCurrentFilename() { + if (null == currentFileName) + currentFileName = getOpenFileName(); + + if (null == currentFileName || "" == currentFileName) + return; + + Properties fileHistory = new Properties(); + fileHistory.put(PROPERTY_LAST_FILE, currentFileName); + + try { + fileHistory.store(new FileOutputStream(PROPFILE_NAME), PROPFILE_COMMENT); + } catch (Exception e) { + /* non-critical error, is ignored */ + } + } + + /** + * Loads the name of the last loaded file from the {@linkplain #PROPFILE_NAME module's property file}. + * @return name of the last loaded file or null, if it could not be loaded + * @author Thomas Görres + */ + private static String loadLastFilename() { + Properties fileHistory = new Properties(); + try { + fileHistory.load(new FileInputStream(PROPFILE_NAME)); + } catch (IOException e) { + return null; + } + return fileHistory.get(PROPERTY_LAST_FILE).toString(); + } + + /** + * Checks whether the last loaded file is known. If so it may be loaded by calling + * {@link #loadFromLastFile()} + * @return true if the last loaded file is known + * @author Thomas Görres + */ + public static boolean islastOpenedFileKnown() { + return loadLastFilename() != null; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/ModuleInfo.java b/src/org/jalgo/module/bfsdfs/ModuleInfo.java new file mode 100644 index 0000000..7537273 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/ModuleInfo.java @@ -0,0 +1,50 @@ +package org.jalgo.module.bfsdfs; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + private static IModuleInfo instance; + + + private ModuleInfo() {} + + /** + * Retrieves a singleton instance of IModuleInfo + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "BFS / DFS"; + } + + public String getVersion() { + return "0.9"; + } + + public String getAuthor() { + return "Florian Dornbusch, Thomas Görres, Anselm Schmidt, Johannes Siegert, Ephraim Zimmer"; + } + + public String getDescription() { + return Messages.getString("bfsdfs", "ModuleInfo.description"); + } + + public URL getLogoURL() { + return Messages.getResourceURL("bfsdfs", "ui.Logo_small"); + } + + public String getLicense() { + return "Public Domain. Welcome Screen Icons CC Oxygen (www.oxygen-icons.org)"; + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("bfsdfs","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/algorithms/Algo.java b/src/org/jalgo/module/bfsdfs/algorithms/Algo.java new file mode 100644 index 0000000..86b22c4 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/Algo.java @@ -0,0 +1,454 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import java.awt.Point; +import java.util.*; +import java.util.logging.Logger; + +import org.jalgo.module.bfsdfs.algorithms.stack.NodeQueueStack; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.algorithms.stack.StackObserver; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.graph.*; +import org.jalgo.module.bfsdfs.undo.*; + +/** + * Abstraction for algorithms working on a graph. Algo takes a graph as input and + * generates as output: + *
            + *
          • a tree containing the graph's nodes; two tree nodes are connected only when + * the equivalent graph nodes are connected
          • + *
          • a stack of graph nodes. The construction of this stack must be implemented + * by the subclasses of Algo
          • + *
          + * + * @author Thomas Görres + * + */ +public abstract class Algo extends Undoable implements GraphObserver { + /** for reading the graph the algorithm works on */ + protected GraphController graph; + + /** Tree the algorithm generates */ + private AlgoGraph tree; + + /** Stack the algorithm generates */ + private NodeQueueStack stack; + + /** Set true if the algorithm is running */ + private boolean isRunning; + + /** Set true if the algorithm has finished */ + private boolean isFinished; + + /** Set true if the default successor's order should + * be shuffled to simulate nondeterminism */ + private boolean shuffleDefaultSuccessors; + + private Logger logger; + + /** + * Remembers the status for all nodes already found + */ + private Map statusPerNode; + + /** + * The current waiting node. It is difficult to read it + * from the stack every time it is needed, so it's stored here. + */ + private int currentNode; + + /** + * The current start node. It is difficult to read it + * from the stack every time it is needed. + */ + private int startNode; + + /** + * + * @param graphController the graph controller that holds the graph this algorithm is working on + */ + public Algo(GraphController graphController) { + logger = Logger.getLogger(this.getClass().getName()); + + // store graph and observe it + this.graph = graphController; + graphController.addGraphObserver(this); + + // create stack and tree + stack = new NodeQueueStack(); + tree = new AlgoGraph(); + + statusPerNode = new HashMap(); + + // set default start node + setDefaultStartNode(); + + isRunning = false; + isFinished = false; + shuffleDefaultSuccessors = false; + } + + /** + * Overrides the start node. The start node's successors are the first ones + * to be put on the stack. Calling this method has no effect if the algorithm is running + * or finished + * @param newStartNode index of the new start node + * @throws NoSuchElementException thrown if no node exists with the specified index. + * In this case, the current start node is kept. + */ + public void setStartNode(int newStartNode) throws NoSuchElementException { + if (newStartNode == startNode) return; + + if (isFinished) { + logger.info("Start node will not be changed, algorithm is finished."); + return; + } + + // assert that the specified node exists + if (!graph.getNodes().contains(newStartNode)) { + logger.severe("Start node cannot be changed, specified node "+newStartNode+" not found."); + throw new NoSuchElementException("Graph does not contain node "+newStartNode); + } + + // store the new start node + this.startNode = newStartNode; + + // set start node as current algo node + setCurrentNode(startNode); + } + + /** + * Returns the status of each node already found + * @return + */ + protected Map getStatusPerNode() { + return statusPerNode; + } + + + /** + * Sets the node with the smallest index as start node. If the graph is empty, + * the start node is left unchanged. + */ + private void setDefaultStartNode() { + // get all nodes + Collection allNodes = graph.getNodes(); + + // return if the graph is empty + if (allNodes.isEmpty()) + return; + + // find node with the smallest index + int smallestYet = Integer.MAX_VALUE; + for (int node: allNodes) + if (node < smallestYet) + smallestYet = node; + + // set that node as start node + setStartNode(smallestYet); + } + + /** + * Overrides the order in which the successors of the current node will be handled by Algo. + * This method has no effect if the algorithm is running. This method replaces all {@linkplain NodeStatus untouched} + * nodes on the stack with the specified ones. + * @param successors indices of all direct successor nodes of the current node, in the desired order. Node + * indices that do not belong to a direct successor are ignored. If null, the current successor order + * is kept. + * @throws IllegalArgumentException thrown if the argument does not contain the indices of all direct successor + * nodes. In this case, the current successor order is kept. Not thrown if the argument is null! + */ + public void setSuccessorOrder(List successors) throws IllegalArgumentException { + if (!isRunning) return; + if (!successors.containsAll(stack.getUntouched()) || !stack.getUntouched().containsAll(successors)) + throw new IllegalArgumentException("Specified successors "+successors+" do not match current successors "+stack.getUntouched()+"."); + logger.info("Successors set to "+successors+" (was "+stack.getUntouched()+")."); + stack.replaceUntouched(successors); + chooseNextNode(); + } + + /** + * Performs an algorithm step. The step is responsible for + *
            + *
          • modifying the tree
          • + *
          • modifying the stack
          • + *
          • starting, finishing and resetting the algorithm
          • + *
          + */ + abstract public void step(); + + /** + * Toggles the nondeterminism on or off. If it's on, this algorithm chooses the + * order of next nodes randomly + * @return true if the nondeterminism is toggled on + */ + public boolean toggleNondeterminism() { + return shuffleDefaultSuccessors = !shuffleDefaultSuccessors; + } + + /** + * Returns the start node + * @return index of the start node + */ + public int getStartNode() { + return startNode; + } + + /** + * Calculates the distance from the start node to the specified node + * @return the node's distance from the start node or {@link Integer#MAX_VALUE} + * if the node is not contained in the tree yet + */ + protected int calculateDistance(int node) { + if (!tree.getNodesAsInteger().contains(node)) + return Integer.MAX_VALUE; + + // start node always has distance 0 from itself + if (startNode == node) + return 0; + + // get preceding nodes + List predecessors = graph.getPredecessors(node); + + // nodes that are not the start node and have no predecessors + // cannot be reached - their distance is set infinite + if (predecessors.isEmpty()) + return Integer.MAX_VALUE; + + // get distance of one predecessor. In the tree generated by an algorithm, + // a node only has one predecessor. This assumption is not critical to the + // module, so other predecessors are just ignored. + int predecessorDistance = Integer.MAX_VALUE; + for (int pre: predecessors) { + predecessorDistance = tree.getNodeDistance(pre); + if (startNode == pre) { + predecessorDistance = 0; + break; + } else if (Integer.MAX_VALUE != predecessorDistance) + break; + } + + // MAX_VALUE is used as infinite, so no distance can be greater than MAX_VALUE + if (Integer.MAX_VALUE == predecessorDistance) + return Integer.MAX_VALUE; + + return predecessorDistance + 1; + } + + /** + * Returns the tree generated by this algorithm. The tree may not be complete if the algorithm + * has not yet finished. + * @return tree generated by this algorithm + */ + public AlgoGraph getTree() { + return tree; + } + + /** + * Returns the node stack generated by this algorithm. The stack may change after each step. + * @return node stack generated by this algorithm + */ + public NodeQueueStack getStack() { + return stack; + } + + /** + * Returns the node this algorithm is currently working on. That is the last + * waiting node on the stack. + * @return index of the node this algorithm is currently working on + */ + protected int getCurrentNode() { + return currentNode; + } + + /** + * Adds the specified observer to the node queue stack's observers + * @param observer + */ + public void addStackObserver(StackObserver observer) { + stack.addStackObserver(observer); + } + + /** + * Removes the specified observer from the node queue stack's observers + * @param observer + */ + public void removeStackObserver(StackObserver observer) { + stack.removeStackObserver(observer); + } + + /** + * Adds the specified observer to the tree's observers + * @param observer + */ + public void addTreeObserver(AlgoGraphObserver observer) { + tree.addAlgoGraphObserver(observer); + } + + /** + * Removes the specified observer from the tree's observers + * @param observer + */ + public void removeTreeObserver(AlgoGraphObserver observer) { + tree.removeAlgoGraphObserver(observer); + } + + /** + * Indicates whether this algorithm is running + * @return true if this algorithm started and did not finish yet + */ + public boolean isRunning() { + return isRunning; + } + + /** + * Indicates whether this algorithm has finished + * @return true if this algorithm has finished + */ + public boolean isFinished() { + return isFinished; + } + + /** + * Sets this algorithm running and adds the start node to stack and tree. Calling this + * method has no effect if the algorithm is already running. + */ + protected void start() { + if (isRunning) return; + isFinished = false; + isRunning = true; + stack.addNode(startNode); + } + + /** + * Sets this algorithm finished and not running. + */ + protected void finish() { + isFinished = true; + isRunning = false; + } + + /** + * Sets this algorithm not finished and not running. + */ + protected void reset() { + isRunning = false; + isFinished = false; + stack.setNodeUntouched(startNode); + stack.removeTopQueue(); + //stack.addNode(startNode); + } + + /** + * Sets the node the algorithm should work on + * @param currentNode the new current node + */ + protected void setCurrentNode(int currentNode) { + this.currentNode = currentNode; + } + + /** + * Resets the algorithm when an edge was added + */ + public void onEdgeAdded(int startNode, int endNode) { + undoAll(); + } + + /** + * Resets the algorithm when an edge was removed + */ + public void onEdgeRemoved(int startNode, int endNode) { + undoAll(); + } + + /** + * Resets the algorithm when the graph was reloaded + */ + public void onGraphLoaded() { + undoAll(); + setDefaultStartNode(); + } + + /** + * Resets the algorithm when a node was added + */ + public void onNodeAdded(int node, Point pos) { + undoAll(); + } + + /** + * Not implemented + */ + public void onNodeMoved(int node, Point pos) {} + + /** + * Resets the algorithm when a node was removed. If the + * start node was removed, a new start node is chosen. + */ + public void onNodeRemoved(int node) { + undoAll(); + setDefaultStartNode(); + } + + /** + * Resets the algorithm when a node was changed + */ + public void onNodeChanged(int oldNodeId, int newNodeId) { + undoAll(); + } + + /** + * Resets the algorithm when an edge was changed + */ + public void onEdgeChanged(int oldStartNode, int oldEndNode, + int newStartNode, int newEndNode) { + undoAll(); + } + + /** + * Reads the successors of the current node from the graph. Successors + * which are already in the tree. The successors never include the current node itself. + * @return indices of the current node's successors that are not yet in + * the tree + */ + protected List getDefaultSuccessors() { + // get direct successors from the graph + List successors = graph.getSuccessors(currentNode); + + // filter successors: ignore nodes already in the tree + Collection nodesToRemove = tree.getNodesAsInteger(); + nodesToRemove.removeAll(stack.getUntouched()); + successors.removeAll(nodesToRemove); + + if (shuffleDefaultSuccessors) + Collections.shuffle(successors); + + return successors; + } + + /** + * Sets a new "current node". This method chooses the next waiting + * node from the topmost stack line. If no node is waiting, the next untouched node is chosen. + * If no waiting and no untouched nodes are in the topmost stack line, the + * current node is chosen. + */ + protected void chooseNextNode() { + // choose current node if the stack is empty + if (getStack().isEmpty()) + return; + + // choose next untouched node if there is one + if (!getStack().getUntouched().isEmpty()) { + setCurrentNode(getStack().getUntouched().get(0)); + return; + } + + // choose next waiting node if there is one + if (!getStack().getWaiting().isEmpty()) { + int firstWaiting = getStack().getWaiting().get(0); + if (getCurrentNode() != firstWaiting) + setCurrentNode(firstWaiting); + return; + } + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/AlgoStep.java b/src/org/jalgo/module/bfsdfs/algorithms/AlgoStep.java new file mode 100644 index 0000000..7bd40b7 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/AlgoStep.java @@ -0,0 +1,329 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.undo.Step; + +/** + * Abstraction for steps of algorithms working on a graph. This class takes care of + *
            + *
          • modifying the tree
          • + *
          • modifying the stack (implemented by subclasses)
          • + *
          • starting, finishing and resetting the algorithm
          • + *
          + * @author Thomas Görres + * + */ +abstract class AlgoStep implements Step { + /** Log level for the {@link #log} method */ + protected static final Level LOGGER_LEVEL = Level.INFO; + + protected Logger logger; + protected Algo algo; + protected GraphController graphController; + + /** Nodes added to the tree by {@link execute} **/ + private List newTreeNodes; + + /** Edges added to the tree by {@link execute} */ + private Map> newTreeEdges; + + /** Stores the removed finished nodes, if {@link execute} removed a queue */ + private List removedFinishedNodes; + + /** Set true, if {@link execute} removed the top queue */ + private boolean topQueueRemoved; + + /** Stores the owner of the removed queue if {@link execute} removed a queue */ + private int removedQueueOwner; + + /** Value of {@link Algo#isFinished()} before execution */ + private boolean oldIsFinished; + + /** Value of {@link Algo#isRunning()} before execution */ + private boolean oldIsRunning; + + /** Value of {@link Algo#getCurrentNode()} before execution */ + private int oldCurrentNode; + + /** + * Creates a new AlgoStep + * @param algo an Algo which knows the stack and tree this step + * will modify + * @param graphController a GraphController to read out the graph + * this step will work on + */ + public AlgoStep(Algo algo, GraphController graphController) { + logger = Logger.getLogger(getClass().getName()); + + this.graphController = graphController; + this.algo = algo; + + topQueueRemoved = false; + } + + /* + * (non-Javadoc) + * @see org.jalgo.module.bfsdfs.undo.Step#execute() + */ + public void execute() { + oldIsFinished = algo.isFinished(); + oldIsRunning = algo.isRunning(); + oldCurrentNode = algo.getCurrentNode(); + + if (algo.isFinished()) return; + + if (!algo.isRunning()) algo.start(); + + undoShowSuccessorsInTree(); + + if (algo.getStack().isFinished()) { + removedQueueOwner = algo.getStack().getOwner(); + removeSuccessors(); + } + + /* + * Process new tree nodes + */ + else { + newTreeNodes = getNewTreeNodes(); + + // modify tree: add new tree nodes + if (!newTreeNodes.isEmpty()) { + addTreeNodes(newTreeNodes); + if (algo.getStartNode() != algo.getCurrentNode()) + addTreeEdges(getNodesPredecessor(), newTreeNodes); + } + + // modify stack: set new tree nodes waiting + algo.getStack().nodeStatusUp(newTreeNodes); + addSuccessorsToStack(); + + // modify status map: set new tree nodes waiting + for (int node: newTreeNodes) + algo.getStatusPerNode().put(node, NodeStatus.WAITING); + } + + /* + * Continue within the current tree, if it is not finished + */ + if (!algo.getStack().isAllFinished() && !algo.getStack().isEmpty()) { + algo.chooseNextNode(); + showSuccessorsInTree(); + } + + /* + * Find a new tree or finish algorithm, if the current tree is finished + */ + else newTreeOrFinish(); + + log(algo.getClass().getSimpleName()+" step executed"); + } + + /* + * (non-Javadoc) + * @see org.jalgo.module.bfsdfs.undo.Step#undo() + */ + public void undo() { + undoShowSuccessorsInTree(); + + if (oldIsFinished) + return; + + + if (!algo.getStack().isAllFinished() && !algo.getStack().isEmpty()) + undoNewTreeOrFinish(); + + if (topQueueRemoved) { + undoRemoveSuccessors(); + algo.setCurrentNode(oldCurrentNode); + } else { + algo.setCurrentNode(oldCurrentNode); + undoAddSuccessorsToStack(); + + algo.getStack().nodeStatusDown(newTreeNodes); + + undoAddTreeEdges(); + undoAddTreeNodes(); + + // update status map + for (int node: newTreeNodes) + algo.getStatusPerNode().put(node, NodeStatus.UNTOUCHED); + + // re-add untouched nodes so that StackObserver#onNodesAdded(List) is called + if (mayChooseSuccessorsAgain()) { + List untouched = algo.getStack().getUntouched(); + algo.getStack().replaceUntouched(null); + algo.getStack().addNodes(untouched); + } + } + + showSuccessorsInTree(); + + if (!oldIsRunning) { + algo.reset(); + return; + } + else + algo.start(); + + log(algo.getClass().getSimpleName()+" step undone"); + } + + /** + * Shows the possible successors of the current node in the tree. This method + * adds nodes to the tree, so #undoShowSuccessorsInTree must be called in order + * prior to any tree manipulation. + */ + private void showSuccessorsInTree() { + for (int node: algo.getStack().getUntouched()) + if (node != algo.getStartNode() ) + algo.getTree().addNode(node, graphController.getNodePosition(node)); + } + + /** + * Decides whether the successor order can be chosen again after an undo operation + * @return true if the successor order can be chosen again + */ + private boolean mayChooseSuccessorsAgain() { + if (algo.getStack().getUntouched().isEmpty()) return false; + List graphPreds = graphController.getPredecessors(algo.getStack().getUntouched().get(0)); + Collection neighbors = algo.getTree().getSuccessors(graphPreds.get(0)); + return neighbors.isEmpty(); + } + + /** + * Removes all untouched nodes except the start node from the tree + */ + private void undoShowSuccessorsInTree() { + for (int node: algo.getStack().getUntouched()) + if (node != algo.getStartNode() && algo.getTree().containsNode(node)) + algo.getTree().removeNode(node); + } + + /** + * Logs the current node, tree nodes and stack + * @param title first line of the log entry + */ + private void log(String title) { + StringBuffer buf = new StringBuffer(title); + buf.append("\n new tree: "+algo.getTree().getNodesAsInteger()+", "+algo.getTree().getEdges()); + buf.append("\n new stack: "+algo.getStack()); + buf.append("\n new current node: "+algo.getCurrentNode()); + logger.log(LOGGER_LEVEL, buf.toString()); + } + + /** + * Manipulates the stack + */ + protected abstract void addSuccessorsToStack(); + + /** + * Undoes {@link #addSuccessorsToStack()} + */ + protected abstract void undoAddSuccessorsToStack(); + + /** + * Removes the top queue and sets its owner finished + */ + private void removeSuccessors() { + // remember top queue and its owner for undo + removedFinishedNodes = algo.getStack().getFinished(); + removedQueueOwner = algo.getStack().getOwner(); + + // remove top queue and set its owner finished + algo.getStack().removeTopQueueAndFinishOwner(); + + // update status map + algo.getStatusPerNode().put(removedQueueOwner, NodeStatus.FINISHED); + + algo.setCurrentNode(removedQueueOwner); + + topQueueRemoved = true; + } + + /** + * Undoes {@link #removeSuccessors()} if it was executed + */ + private void undoRemoveSuccessors() { + if (!topQueueRemoved) return; + + algo.getStack().nodeStatusDown(removedQueueOwner); + + algo.getStack().addQueue(removedQueueOwner); + algo.getStack().addNodes(removedFinishedNodes); + for (int node: removedFinishedNodes) { + algo.getStack().setNodeFinished(node); + } + } + + /** + * Adds the specified nodes to the tree + */ + private void addTreeNodes(Collection nodes) { + newTreeNodes = new LinkedList(); + for (int node: nodes) { + algo.getTree().addNode(node, graphController.getNodePosition(node)); + algo.getTree().setNodeDistance(node, algo.calculateDistance(node)); + newTreeNodes.add(node); + } + } + + /** + * Adds the specified edges to the tree + * @param predecessor index of the node at each edge's beginning + * @param nodes indices of the nodes at the edge's ending + */ + private void addTreeEdges(int predecessor, Collection nodes) { + newTreeEdges = new HashMap>(); + for (int node: nodes) { + algo.getTree().addEdge(predecessor, node); + newTreeEdges.put(predecessor, nodes); + } + } + + + /** + * Undoes {@link #addTreeNodes(Collection)} if it was executed + */ + private void undoAddTreeNodes() { + if (null == newTreeNodes) return; + for (int node: newTreeNodes) { + algo.getTree().removeNode(node);} + } + + /** + * Undoes {@link #addTreeEdges(int, Collection)} if it was executed + */ + private void undoAddTreeEdges() { + if (null == newTreeEdges) return; + for (int node1: newTreeEdges.keySet()) + for (int node2: newTreeEdges.get(node1)) + algo.getTree().removeEdge(node1, node2); + } + + /** + * Chooses the untouched nodes that should be added to the tree and set waiting + */ + protected abstract List getNewTreeNodes(); + + /** + * Returns the predecessor for all nodes that are found in this step + * @return index of the preceding node + */ + protected abstract int getNodesPredecessor(); + + /** + * Tries to start a new tree or finishes if none could be started. This method sets the algorithm's start node + * and current node to a graph node that is not yet found. This is necessary + * to find all nodes, as there may still be nodes in the graph that are not found + * even when the current tree is finished. + */ + protected abstract void newTreeOrFinish(); + + protected abstract void undoNewTreeOrFinish(); +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/BFS.java b/src/org/jalgo/module/bfsdfs/algorithms/BFS.java new file mode 100644 index 0000000..8ba8c1e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/BFS.java @@ -0,0 +1,18 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import org.jalgo.module.bfsdfs.controller.GraphController; + +/** + * Breadth-first-search algorithm for graphs + * @author Thomas Görres + * + */ +public class BFS extends Algo { + public BFS(GraphController graphController) { + super(graphController); + } + + @Override public void step() { + makeUndoableStep(new BFSStep(this, graph)); + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/BFSStep.java b/src/org/jalgo/module/bfsdfs/algorithms/BFSStep.java new file mode 100644 index 0000000..946ef60 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/BFSStep.java @@ -0,0 +1,74 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import java.util.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +/** + * Step of a breadth-first-search algorithm + * @author Thomas Görres + * + */ +public class BFSStep extends AlgoStep { + private boolean nodeUpped; + private int nodeUppedIndex; + + public BFSStep(Algo algo, GraphController graphController) { + super(algo, graphController); + nodeUpped = false; + } + + @Override protected void addSuccessorsToStack() { + List successors = algo.getDefaultSuccessors(); + System.out.println("succ: "+successors); + + // If current node is waiting and has no successors, it should be finished. + // + // If another node is waiting, it must be the current node's predecessor. + // As the current node is on the stack now, it's predecessor should be + // finished. + if (!algo.getStack().getWaiting().isEmpty()) { + int waiting = algo.getStack().getWaiting().get(0); + if (successors.isEmpty() || algo.getCurrentNode() != waiting) { + nodeUpped = true; + nodeUppedIndex = waiting; + algo.getStack().nodeStatusUp(waiting); + } + + // if there still is another waiting nodes, proceed with it instead of the current node + if (!algo.getStack().getWaiting().isEmpty()) + algo.setCurrentNode(algo.getStack().getWaiting().get(0)); + } + algo.getStack().addNodes(algo.getDefaultSuccessors()); + } + + @Override protected void undoAddSuccessorsToStack() { + if (nodeUpped) + algo.getStack().nodeStatusDown(nodeUppedIndex); + algo.getStack().replaceUntouched(null); + } + + @Override + protected List getNewTreeNodes() { + return algo.getStack().getUntouched(); + } + + @Override + protected int getNodesPredecessor() { + if (algo.getCurrentNode() == algo.getStartNode()) + throw new NoSuchElementException("Current node is start node, no predecessor exists."); + + if (!algo.getStack().getWaiting().isEmpty()) + return algo.getStack().getWaiting().get(0); + + throw new NoSuchElementException("No predecessor found."); + } + + @Override + protected void newTreeOrFinish() { + // BFS cannot create more than one tree + algo.finish(); + } + + @Override + protected void undoNewTreeOrFinish() {} +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/CVS/Entries b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Entries new file mode 100644 index 0000000..29fabec --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Entries @@ -0,0 +1,8 @@ +/Algo.java/1.1/Wed Dec 8 13:47:54 2010// +/AlgoStep.java/1.1/Wed Dec 8 13:47:54 2010// +/BFS.java/1.1/Wed Dec 8 13:47:54 2010// +/BFSStep.java/1.1/Wed Dec 8 13:47:54 2010// +/DFS.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSStep.java/1.1/Wed Dec 8 13:47:54 2010// +D/stack//// +D/test//// diff --git a/src/org/jalgo/module/bfsdfs/algorithms/CVS/Repository b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Repository new file mode 100644 index 0000000..58c0dce --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/algorithms diff --git a/src/org/jalgo/module/bfsdfs/algorithms/CVS/Root b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/algorithms/DFS.java b/src/org/jalgo/module/bfsdfs/algorithms/DFS.java new file mode 100644 index 0000000..a9f6255 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/DFS.java @@ -0,0 +1,18 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import org.jalgo.module.bfsdfs.controller.GraphController; + +/** + * Depth-first-search algorithm for graphs + * @author Thomas Görres + * + */ +public class DFS extends Algo { + public DFS(GraphController graphController) { + super(graphController); + } + + @Override public void step() { + makeUndoableStep(new DFSStep(this, graph)); + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/DFSStep.java b/src/org/jalgo/module/bfsdfs/algorithms/DFSStep.java new file mode 100644 index 0000000..cd0b500 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/DFSStep.java @@ -0,0 +1,77 @@ +package org.jalgo.module.bfsdfs.algorithms; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; + +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.controller.GraphController; + +/** + * Step of a depth-first-search algorithm + * @author Thomas Görres + * + */ +class DFSStep extends AlgoStep { + boolean queueAdded; + + private int oldStartNode, newStartNode; + + private boolean startNodeSet; + + public DFSStep(Algo algo, GraphController graphController) { + super(algo, graphController); + queueAdded = false; + startNodeSet = false; + oldStartNode = algo.getStartNode(); + } + + @Override protected void addSuccessorsToStack() { + queueAdded = algo.getStack().addQueue(algo.getCurrentNode(), algo.getDefaultSuccessors()); + } + + @Override protected void undoAddSuccessorsToStack() { + if (queueAdded) algo.getStack().removeTopQueue(); + } + + @Override + protected List getNewTreeNodes() { + if (algo.getStack().getUntouched().isEmpty()) + return Collections.emptyList(); + + int firstNodeUntouched = algo.getStack().getUntouched().get(0); + return Arrays.asList(firstNodeUntouched); + } + + @Override + protected int getNodesPredecessor() { + if (algo.getCurrentNode() == algo.getStartNode()) + throw new NoSuchElementException("Current node is start node, no predecessor exists."); + + return algo.getStack().getOwner(); + } + + @Override + protected void newTreeOrFinish() { + for (int node: graphController.getNodes()) + if (algo.getStatusPerNode().get(node) == null) { + newStartNode = node; + startNodeSet = true; + algo.setStartNode(node); + algo.getStack().addNode(node); + algo.getStatusPerNode().put(node, NodeStatus.UNTOUCHED); + algo.chooseNextNode(); + return; + } + algo.finish(); + } + + @Override + protected void undoNewTreeOrFinish() { + if (!startNodeSet) return; + algo.getStatusPerNode().put(newStartNode, null); + algo.getStack().replaceUntouched(null); + algo.setStartNode(oldStartNode); + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Entries b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Entries new file mode 100644 index 0000000..20e3594 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Entries @@ -0,0 +1,5 @@ +/NodeQueue.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeQueueStack.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeStatus.java/1.1/Wed Dec 8 13:47:54 2010// +/QueueObserver.java/1.1/Wed Dec 8 13:47:54 2010// +/StackObserver.java/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Repository b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Repository new file mode 100644 index 0000000..9311283 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/algorithms/stack diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Root b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.java b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.java new file mode 100644 index 0000000..b07e396 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueue.java @@ -0,0 +1,477 @@ +package org.jalgo.module.bfsdfs.algorithms.stack; + +import java.util.*; + +/** + * A queue of nodes. Nodes are represented by an unique integer index. A queue cannot contain the same node twice. + *

          + * Each NodeQueue has an "owner", a node it belongs to. The queue cannot contain nodes with the same + * index as its owner. + *

          + * Each node is in one of three states: + *

            + *
          • untouched: {@link NodeStatus#UNTOUCHED}
          • + *
          • waiting: {@link NodeStatus#WAITING}
          • + *
          • finished: {@link NodeStatus#FINISHED}
          • + *
          + * @author Thomas Görres + * + */ +class NodeQueue { + /** Default status for newly added nodes */ + public static final NodeStatus DEFAULT_STATUS = NodeStatus.UNTOUCHED; + + private List nodes; + private int owner; + private Collection observers; + + /** + * Initializes an empty NodeQueue with the specified owner + * @param owner index of the node that owns this queue + */ + public NodeQueue(int owner) { + nodes = new LinkedList(); + observers = new ArrayList(); + this.owner = owner; + } + + /** + * Initializes an empty NodeQueue with the specified owner and adds + * @param owner index of the node that owns this queue + * @param observers observers that should be added to this NodeQueue + * the specified observers + */ + public NodeQueue(int owner, Collection observers) { + this(owner); + this.observers.addAll(observers); + } + + /** + * Checks if the specified node is contained in this queue + * @param nodeIndex index of the searched node + * @return true if this queue contains that node + */ + public boolean containsNode(int nodeIndex) { + return null != findNode(nodeIndex); + } + + /** + * Returns the number of nodes in this queue + * @return number of nodes in this queue + */ + public int size() { + return nodes.size(); + } + + /** + * Adds the specified observer + * @param observer + */ + public void addQueueObserver(QueueObserver observer) { + if (null == observer) return; + observers.add(observer); + } + + /** + * Removes the specified observer + * @param observer + */ + public void removeQueueObserver(QueueObserver observer) { + if (null == observer) return; + observers.remove(observer); + } + + /** + * Returns the status of the specified node + * @param node + * @return the node's status or null, if the node + * is not contained in the topmost queue + */ + public NodeStatus getNodeStatus(int node) { + Node targetNode = findNode(node); + if (null == targetNode) return null; + else return targetNode.status; + } + + + /** + * Returns all untouched nodes + * @return indices of all untouched nodes, ordered as they are in the queue + */ + public ListgetUntouched() { + return nodesToInts(findNodes(NodeStatus.UNTOUCHED)); + } + + /** + * Returns all nodes in this queue + * @return indices of all nodes, ordered as they are in the queue + */ + public ListgetAllNodes() { + return nodesToInts(nodes); + } + + + /** + * Returns all waiting nodes + * @return indices of all waiting nodes, ordered as they are in the queue + */ + public ListgetWaiting() { + return nodesToInts(findNodes(NodeStatus.WAITING)); + } + + + /** + * Returns all finished nodes + * @return indices of all finished nodes, ordered as they are in the queue + */ + public ListgetFinished() { + return nodesToInts(findNodes(NodeStatus.FINISHED)); + } + + + /** + * Sets a new status for the specified node + * @param nodeIndex index of the node. If the queue does not contain the specified node, + * calling this method has no effect. + * @param status new status for that node. If null, the current status is kept. + */ + private void setNodeStatus(int nodeIndex, NodeStatus status) { + if (null == status) return; + + Node targetNode = findNode(nodeIndex); + if (null == targetNode) return; + + targetNode.status = status; + + // notify observers + for (QueueObserver o: observers) + o.onStatusChanged(nodeIndex, targetNode.status); + } + + /** + * Sets the specified node finished. This sets the node's status to + * {@link NodeStatus#FINISHED}. If the queue does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeFinished(int nodeIndex) { + setNodeStatus(nodeIndex, NodeStatus.FINISHED); + } + + /** + * Sets the specified node waiting. This sets the node's status to + * {@link NodeStatus#WAITING}. If the queue does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeWaiting(int nodeIndex) { + setNodeStatus(nodeIndex, NodeStatus.WAITING); + } + + /** + * Sets the specified node untouched. This sets the node's status to + * {@link NodeStatus#UNTOUCHED}. If the queue does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeUntouched(int nodeIndex) { + setNodeStatus(nodeIndex, NodeStatus.UNTOUCHED); + } + + public void nodeStatusDown(List nodeIndices) { + if (null == nodeIndices) return; + for (int index: nodeIndices) + nodeStatusDown(index); + } + + /** + * Changes the status of the specified node, depending on its current status. + *
            + *
          • if the node is finished, it is set waiting
          • + *
          • if the node is waiting, it is set untouched
          • + *
          • if the node is untouched, its status is not changed
          • + *
          + * If the queue does not contain the specified node, calling this method has no + * effect. + * @param nodeIndex index of the node + */ + public void nodeStatusDown(int nodeIndex) { + Node targetNode = findNode(nodeIndex); + if (null == targetNode) return; + + boolean statusChanged = false; + + switch(targetNode.status) { + case FINISHED: + targetNode.status = NodeStatus.WAITING; + statusChanged = true; + break; + case WAITING: + targetNode.status = NodeStatus.UNTOUCHED; + statusChanged = true; + } + + // notify observers + if (statusChanged) + for (QueueObserver o: observers) + o.onStatusChanged(nodeIndex, targetNode.status); + } + + public void nodeStatusUp(List nodeIndices) { + if (null == nodeIndices) return; + for (int index: nodeIndices) + nodeStatusUp(index); + } + + /** + * Changes the status of the specified node, depending on its current status. + *
            + *
          • if the node is untouched, it is set waiting
          • + *
          • if the node is waiting, it is set finished
          • + *
          • if the node is finished, its status is not changed
          • + *
          + * If the queue does not contain the specified node, calling this method has no + * effect. + * @param nodeIndex index of the node + */ + public void nodeStatusUp(int nodeIndex) { + Node targetNode = findNode(nodeIndex); + if (null == targetNode) return; + + boolean statusChanged = false; + + switch(targetNode.status) { + case UNTOUCHED: + targetNode.status = NodeStatus.WAITING; + statusChanged = true; + break; + case WAITING: + targetNode.status = NodeStatus.FINISHED; + statusChanged = true; + break; + } + + // notify observers + if (statusChanged) + for (QueueObserver o: observers) + o.onStatusChanged(nodeIndex, targetNode.status); + } + + + /** + * Deletes all untouched nodes and adds the specified nodes to the queue. If the specified node list is + * null or empty, calling this method has no effect + * @param replacement indices of the replacing nodes + */ + public void replaceUntouched(List replacement) { + // remove untouched nodes + List nodesToRemove = new LinkedList(); + for (Node node: nodes) + for (int targetNode: getUntouched()) + if (node.index == targetNode) + nodesToRemove.add(node); + List oldUntouched = getUntouched(); + nodes.removeAll(nodesToRemove); + + // add replacement + addNodesSilently(replacement); + + // notify observers + for (QueueObserver o: observers) + o.onUntouchedReplaced(oldUntouched, replacement); + } + + + /** + * Adds a node to the queue. + *

          + * This method ignores nodes that: + *

            + *
          • already are in the queue
          • + *
          • have the same index as the queue owner
          • + *
          + * @param nodeIndex index of the node to add + * @return true if the stack changed in result of this call + */ + public boolean addNode(int nodeIndex) { + return addNodes(Arrays.asList(nodeIndex)); + } + + + /** + * Adds several nodes to the queue. + *

          + * This method ignores nodes that: + *

            + *
          • already are in the queue
          • + *
          • have the same index as the queue owner
          • + *
          + *

          + * If the specified node list is + * null or empty, calling this method has no effect. + * @param nodeIndices indices of the nodes to add + * @return true if the stack changed in result of this call + */ + public boolean addNodes(List nodeIndices) { + if (!addNodesSilently(nodeIndices)) + return false; + + // notify observers + for (QueueObserver o: observers) + o.onNodesAdded(nodeIndices); + + return true; + } + + /** + * Adds several nodes to the queue without notifying the observers + *

          + * This method ignores nodes that: + *

            + *
          • already are in the queue
          • + *
          • have the same index as the queue owner
          • + *
          + *

          + * If the specified node list is + * null or empty, calling this method has no effect. + * @param nodeIndices indices of the nodes to add + * @return true if the stack changed in result of this call + */ + protected boolean addNodesSilently(List nodeIndices) { + if (null == nodeIndices || nodeIndices.isEmpty()) + return false; + + for (int index: nodeIndices) { + if (index == owner) continue; + Node n = new Node(index); + if (nodes.contains(n)) continue; + nodes.add(n); + } + + return true; + } + + /** + * Returns the owner of this queue + * @return the owning node's index + */ + public int getOwner() { + return owner; + } + + + /** + * Finds all nodes with the specified status + * @param wantedStatus the status to search for + * @return all nodes with that status + */ + protected List findNodes(NodeStatus wantedStatus) { + // guard clause for null argument + if (null == wantedStatus) return Collections.emptyList(); + + // search nodes + List result = new LinkedList(); + for (Node n: nodes) { + if (wantedStatus.equals(n.status)) + result.add(n); + } + + return result; + } + + + /** + * Finds all nodes with the specified index + * @param wantedID the index to search for + * @return node with that index + */ + protected Node findNode(int wantedIndex) { + for (Node n: nodes) + if (wantedIndex == n.index) + return n; + + return null; + } + + + /** + * Creates a list of the specified nodes' indices + * @param nodeList a list of nodes + * @return that nodes' indices as unmodifiable list + */ + protected List nodesToInts(List nodeList) { + if (null == nodeList) return null; + + List intList = new LinkedList(); + for (Node n: nodeList) + intList.add(n.index); + return Collections.unmodifiableList(intList); + } + + /** + * Returns a human-readable form of this NodeQueues + */ + @Override public String toString() { + List nodeStrings = new LinkedList(); + for (Node n: nodes) nodeStrings.add(n.toString()); + return owner+":"+nodeStrings.toString(); + } + + /** + * Checks if all nodes are finished + * @return true if the queue contains only finished + * nodes + */ + public boolean isFinished() { + for (Node n: nodes) + if (n.status != NodeStatus.FINISHED) + return false; + return true; + } + + /** + * Simple data class for a node + * @author Thomas Görres + * + */ + private class Node { + public NodeStatus status; + public int index; + + /** + * Initializes a node with the specified index. Default status: untouched. + * @param id index of the node + */ + public Node(int index) { + status = DEFAULT_STATUS; + this.index = index; + } + + /** + * A node equals another node, if their indices are equal + */ + @Override public boolean equals(Object o) { + if (!(o instanceof Node)) return false; + Node n = (Node)o; + return n.index == index; + } + + /** + * Returns a human-readable form of this node + */ + @Override public String toString() { + StringBuffer buf = new StringBuffer(String.valueOf(index)); + switch(status) { + case UNTOUCHED: + buf.append(":u"); + break; + case WAITING: + buf.append(":w"); + break; + case FINISHED: + buf.append(":f"); + } + return buf.toString(); + } + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.java b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.java new file mode 100644 index 0000000..ea19972 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeQueueStack.java @@ -0,0 +1,493 @@ +package org.jalgo.module.bfsdfs.algorithms.stack; + +import java.util.*; + +/** + * A stack of node queues. Nodes are represented by integer indices. + * @author Thomas Görres + * + */ +public class NodeQueueStack { + /** Default queue owner */ + public static final int DEFAULT_OWNER = 0; + + private List queues; + private List observers; + + private int currentNode; + + /** + * Initializes an empty NodeStack + */ + public NodeQueueStack() { + queues = new LinkedList(); + observers = new LinkedList(); + } + + /** + * Returns a list of all queue owners + * @return index of each queue owner, beginning with the bottommost queue + */ + protected List getQueueOwners() { + List owners = new LinkedList(); + for (NodeQueue q: queues) owners.add(q.getOwner()); + return owners; + } + + /** + * Changes the status of the specified node, depending on its current status. + *

            + *
          • if the node is finished, it is set waiting
          • + *
          • if the node is waiting, it is set untouched
          • + *
          • if the node is untouched, its status is not changed
          • + *
          + * If the stack does not contain the specified node, calling this method has no + * effect. + * @param nodeIndex index of the node + */ + public void nodeStatusDown(int nodeIndex) { + for (NodeQueue q: queues) + q.nodeStatusDown(nodeIndex); + + this.updateCurrentNode(); + } + + public void nodeStatusDown(List nodeIndices) { + if (null == nodeIndices) return; + for (NodeQueue q: queues) + q.nodeStatusDown(nodeIndices); + + updateCurrentNode(); + } + + /** + * Changes the status of the specified node, depending on its current status. + *
            + *
          • if the node is untouched, it is set waiting
          • + *
          • if the node is waiting, it is set finished
          • + *
          • if the node is finished, its status is not changed
          • + *
          + * If the stack does not contain the specified node, calling this method has no + * effect. + * @param nodeIndex index of the node + */ + public void nodeStatusUp(int nodeIndex) { + for (NodeQueue q: queues) + q.nodeStatusUp(nodeIndex); + + // notify observers if all nodes are finished now + if (1 == queues.size() && isFinished()) + for (StackObserver o: observers) + o.onAllNodesFinished(); + + this.updateCurrentNode(); + } + + public void nodeStatusUp(List nodeIndices) { + if (null == nodeIndices) return; + for (NodeQueue q: queues) + q.nodeStatusUp(nodeIndices); + + this.updateCurrentNode(); + } + + /** + * Returns the owner of the topmost queue + * @return index of the of the topmost queue. If no queue is in the stack, + * -1 is returned. + */ + public int getOwner() { + NodeQueue firstQueue = getTopQueue(); + if (null == firstQueue) return -1; + + return firstQueue.getOwner(); + } + + /** + * Returns the status of the specified node + * @param node + * @return the node's status or null, if the node + * is not contained in the topmost queue + */ + public NodeStatus getNodeStatus(int node) { + if (isEmpty()) return null; + return getTopQueue().getNodeStatus(node); + } + + /** + * Returns the topmost queue + * @return the topmost queue. If no queue is in the stack, null + * is returned. + */ + private NodeQueue getTopQueue() { + if (queues.isEmpty()) return null; + return (NodeQueue)(queues.get(queues.size()-1)); + } + + /** + * Returns all waiting nodes of the topmost queue + * @return indices of all waiting nodes, ordered as they are in the queue + */ + public List getWaiting() { + if (queues.isEmpty()) return Collections.emptyList(); + return getTopQueue().getWaiting(); + } + + /** + * Returns all finished nodes of the topmost queue + * @return indices of all finished nodes, ordered as they are in the queue + */ + public List getFinished() { + if (queues.isEmpty()) return Collections.emptyList(); + return getTopQueue().getFinished(); + } + + /** + * Checks if all nodes of the topmost queue are finished + * @return true if the topmost queue contains only finished + * nodes + */ + public boolean isFinished() { + if (queues.isEmpty()) return false; + return getTopQueue().isFinished(); + } + + /** + * Checks if all nodes of every queue in the stack are finished + * @return true if the stack contains only finished queues + * @see #isFinished() + */ + public boolean isAllFinished() { + if (queues.isEmpty()) return false; + + for (NodeQueue q: queues) + if (!q.isFinished()) return false; + return true; + } + + /** + * Removes the top queue and sets its owner finished + */ + public void removeTopQueueAndFinishOwner() { + if (queues.isEmpty()) return; + + int finishedOwner = getOwner(); + removeTopQueue(); + setNodeFinished(finishedOwner); + } + + /** + * Returns all untouched nodes of the topmost queue + * @return indices of all waiting nodes, ordered as they are in the queue + */ + public List getUntouched() { + if (queues.isEmpty()) return Collections.emptyList(); + return getTopQueue().getUntouched(); + } + + /** + * Returns the nodes of all queues in this stack + * @return indices of all nodes in the stack + */ + public Collection getAllNodes() { + Collection nodes = new LinkedList(); + + for (NodeQueue q: queues) + nodes.addAll(q.getAllNodes()); + + return nodes; + } + + /** + * Returns the untouched nodes of all queues in this stack + * @return indices of all nodes in the stack + */ + public Collection getAllUntouched() { + Collection nodes = new LinkedList(); + + for (NodeQueue q: queues) + nodes.addAll(q.getUntouched()); + + return nodes; + } + + /** + * Returns the waiting nodes of all queues in this stack + * @return indices of all nodes in the stack + */ + public Collection getAllWaiting() { + Collection nodes = new LinkedList(); + + for (NodeQueue q: queues) + nodes.addAll(q.getWaiting()); + + return nodes; + } + + /** + * Returns the finished nodes of all queues in this stack + * @return indices of all nodes in the stack + */ + public Collection getAllFinished() { + Collection nodes = new LinkedList(); + + for (NodeQueue q: queues) + nodes.addAll(q.getFinished()); + + return nodes; + } + + /** + * Puts a queue on the top of the stack and fills it with the specified nodes + * @param owner index of the node that owns the new queue. If a queue with this + * owner already exists, calling this method has no effect + * @param nodeIndices indices of the nodes which the new queue should contain + * @return true if the stack changed in result of this call + */ + public boolean addQueue(int owner, List nodeIndices) { + if (getQueueOwners().contains(owner)) return false; + + // add queue + queues.add(new NodeQueue(owner, observers)); + + // notify observers + if (1 == queues.size()) + for (StackObserver o: observers) + o.onFirstQueueAdded(owner); + else + for (StackObserver o: observers) + o.onQueueAdded(owner); + + // add nodes + addNodes(nodeIndices); + + return true; + } + + /** + * Puts an empty queue on the top of the stack + * @param owner index of the node that owns the new queue. If a queue with this + * owner already exists, calling this method has no effect + * @return true if the stack changed in result of this call + */ + public boolean addQueue(int owner) { + return addQueue(owner, null); + } + + /** + * Adds a node to the topmost queue. If there is no queue in the stack, + * a queue is created first, with {@link NodeQueue#DEFAULT_OWNER} as owner. + * @param node the node's index + * @return true if the stack changed in result of this call + * @see NodeQueue#addNode(int) + */ + public boolean addNode(int node) { + // create queue first if necessary + if (queues.isEmpty()) addQueue(DEFAULT_OWNER); + + // add node to topmost queue + boolean wasAdded = getTopQueue().addNode(node); + + if (wasAdded) updateCurrentNode(); + + return wasAdded; + } + + /** + * Adds several nodes to the topmost queue. If there is no queue in the stack, + * a queue is created first, with {@link NodeQueue#DEFAULT_OWNER} as owner. + * @param nodes the nodes' indices. null or an empty list is ignored + * @return true if the stack changed in result of this call + * @see NodeQueue#addNode(int) + */ + public boolean addNodes(List nodes) { + // ignore null or empty list + if (null == nodes || nodes.isEmpty()) return false; + + // create queue first if necessary + if (queues.isEmpty()) addQueue(DEFAULT_OWNER); + + // add nodes to topmost queue + boolean wasAdded = getTopQueue().addNodes(nodes); + + if (wasAdded && 1 == nodes.size()) + updateCurrentNode(); + + return wasAdded; + } + + /** + * Sets the specified node untouched. This sets the node's status to + * {@link NodeStatus#UNTOUCHED}. If the stack does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeUntouched(int node) { + if (isEmpty()) return; + for (NodeQueue q: queues) + q.setNodeUntouched(node); + + this.updateCurrentNode(); + } + + /** + * Sets the specified node waiting. This sets the node's status to + * {@link NodeStatus#WAITING}. If the stack does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeWaiting(int node) { + if (isEmpty()) return; + for (NodeQueue q: queues) + q.setNodeWaiting(node); + + this.updateCurrentNode(); + } + + /** + * Sets the specified node finished. This sets the node's status to + * {@link NodeStatus#FINISHED}. If the stack does not contain the specified node, + * calling this method has no effect. + * @param nodeIndex index of the node + */ + public void setNodeFinished(int node) { + if (isEmpty()) return; + + // change status of all affected nodes + for (NodeQueue q: queues) + q.setNodeFinished(node); + + // notify observers if all nodes are finished now + if (1 == queues.size() && isFinished()) + for (StackObserver o: observers) + o.onAllNodesFinished(); + + this.updateCurrentNode(); + } + + /** + * Adds the specified observer + * @param o + */ + public void addStackObserver(StackObserver o) { + if (null == o) return; + + observers.add(o); + + // Adds this observer to all queues. This way, this class does not have + // to notify the observers itself after a queue was modified + for (NodeQueue q: queues) + q.addQueueObserver(o); + } + + /** + * Removes the specified observer + * @param o + */ + public void removeStackObserver(StackObserver o) { + if (null == o) return; + + observers.remove(o); + + for (NodeQueue q: queues) + q.removeQueueObserver(o); + } + + /** + * Deletes all untouched nodes of the topmost queue and adds the specified nodes to the queue. + * If the specified node list is null or empty, calling this method has no effect + * @param replacement indices of the replacing nodes + */ + public void replaceUntouched(List replacement) { + if (queues.isEmpty()) return; + + // replace untouched nodes of topmost queue + getTopQueue().replaceUntouched(replacement); + + if (null != replacement && 1 == replacement.size()) + updateCurrentNode(); + } + + /** + * Removes the topmost queue from the stack. If the stack is empty, calling + * this method has no effect + */ + public void removeTopQueue() { + if (queues.isEmpty()) return; + + // remove topmost queue + queues.remove(queues.size()-1); + + // notify observers + for (StackObserver o: observers) { + o.onTopQueueRemoved(); + if (queues.isEmpty()) + o.onAllQueuesRemoved(); + } + } + + /** + * Returns a human-readable form of this NodeQueueStack + */ + @Override public String toString() { + StringBuffer buf = new StringBuffer(); + for (NodeQueue q: queues) + buf.append(q+" "); + if (0 != buf.length()) buf.deleteCharAt(buf.lastIndexOf(" ")); + return new String(buf); + } + + /** + * Checks if the stack is empty + * @return true if the stack contains no queues + */ + public boolean isEmpty() { + return queues.isEmpty(); + } + + /** + * Returns the number of queues in this stack + * @return number of queues + */ + public int size() { + return queues.size(); + } + + /** + * Reads the current node from the stack and notifies the observers + * if it changed. + * @see #getCurrentNode() + */ + protected void updateCurrentNode() { + int newCurrentNode = currentNode; + + // read current node + if (1 == queues.size() && 1 == queues.get(0).size()) + newCurrentNode = queues.get(0).getAllNodes().get(0); + else + for (NodeQueue q: queues) + if (!q.getWaiting().isEmpty()) + newCurrentNode = q.getWaiting().get(0); + + // change current node + if (newCurrentNode == currentNode) return; + currentNode = newCurrentNode; + + // notify observers + for (StackObserver o: observers) + o.onCurrentNodeChanged(currentNode); + } + + /** + * Returns the current node. The current node is... + *
            + *
          • the first node, if there is only one node in the stack
          • + *
          • unchanged, if there are more than one but no waiting nodes in the stack
          • + *
          • the first waiting node of the topmost queue (which contains waiting nodes)
          • + *
          + * @return index of the current node + */ + public int getCurrentNode() { + return currentNode; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.java b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.java new file mode 100644 index 0000000..926c4ac --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/NodeStatus.java @@ -0,0 +1,23 @@ +package org.jalgo.module.bfsdfs.algorithms.stack; + +/** + * Indicates the status of a node in an algorithm's NodeStack + * @author Thomas Görres + * + */ +public enum NodeStatus { + /** + * Indicates that a node is not yet known to the algorithm + */ + UNTOUCHED, + + /** + * Indicates that a node is used by the algorithm + */ + WAITING, + + /** + * Indicates that a node is no longer used by the algorithm + */ + FINISHED; +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.java b/src/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.java new file mode 100644 index 0000000..46a59f3 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/QueueObserver.java @@ -0,0 +1,30 @@ +package org.jalgo.module.bfsdfs.algorithms.stack; + +import java.util.*; + +/** + * Interface for observers of an algorithm's {@link NodeQueueStack} + * @author Thomas Görres + * + */ +interface QueueObserver { + /** + * Invoked when nodes were added to the topmost queue + * @param nodes indices of the added nodes + */ + public void onNodesAdded(List nodes); + + /** + * Invoked when the status of a node changed + * @param node index of the affected node + * @param newStatus the node's new status + */ + public void onStatusChanged(int node, NodeStatus newStatus); + + /** + * Invoked when the untouched nodes where replaced + * @param oldNodes indices of the replaced untouched nodes + * @param newNodes indices of the new untouched nodes + */ + public void onUntouchedReplaced(List oldNodes, List newNodes); +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.java b/src/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.java new file mode 100644 index 0000000..85db06f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/stack/StackObserver.java @@ -0,0 +1,47 @@ +package org.jalgo.module.bfsdfs.algorithms.stack; + +public interface StackObserver extends QueueObserver { + /** + * Invoked when a queue was added to the stack. Attention: in case of the very first queue, + * {@link #onFirstQueueAdded(int)} is invoked instead! + * @param owner index of the queue owner + */ + public void onQueueAdded(int owner); + + /** + * Invoked when the first queue is added to the empty stack. This will + * happen when the algorithm that uses the stack is started. + *

          Note that {@link #onQueueAdded(int)} is not called seperately for the first queue. + * @param startNode index of the first queue's owner + */ + public void onFirstQueueAdded(int owner); + + /** + * Invoked when all nodes reached the finished-status. This will happen + * when the algorithm that uses the stack is finished. + */ + public void onAllNodesFinished(); + + /** + * Invoked when the topmost queue was removed + */ + public void onTopQueueRemoved(); + + /** + * Invoked when all queues where removed + */ + public void onAllQueuesRemoved(); + + /** + * Invoked when the current node changed. + *

          + * The current node is... + *

            + *
          • the first node, if there is only one node in the stack
          • + *
          • unchanged, if there are more than one but no waiting nodes in the stack
          • + *
          • the first waiting node of the topmost queue (which contains waiting nodes)
          • + *
          + * @param newCurrentNode index of the new current node + */ + public void onCurrentNodeChanged(int newCurrentNode); +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.java b/src/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.java new file mode 100644 index 0000000..2e15bc3 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/AlgoTest.java @@ -0,0 +1,201 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import static org.junit.Assert.*; + +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.algorithms.stack.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +import java.util.*; +import org.junit.Test; + +/** + * Abstraction for unit tests of {@link Algo} implementations. + * @author Thomas Görres + * + */ +abstract public class AlgoTest { + private Algo algo; + + protected abstract Algo getAlgo(); + + protected abstract GraphController getGraph(); + + public AlgoTest() { + algo = getAlgo(); + } + + @Test public void testSteps() { + int stepNumber = 0; + Collection usedStartNodes = new TreeSet(); + + while (!algo.isFinished()) { + algo.step(); + stepNumber++; + usedStartNodes.add(algo.getStartNode()); + + algo.setSuccessorOrder(algo.getStack().getUntouched()); + + /* + * Asserts that stack content is as expected + */ + String expectedStack = null; + try { + expectedStack = expectedStack(stepNumber); + } catch (IndexOutOfBoundsException e) { + fail("No expected stack content defined for step "+stepNumber+"."); + } + assertEquals("Step "+stepNumber+" did not work on stack.", expectedStack, stackAsString()); + + /* + * Asserts that tree contains all expected nodes + */ + Collection expectedTreeNodes = null; + try { + expectedTreeNodes = expectedTreeNodes(stepNumber); + } catch (IndexOutOfBoundsException e) { + fail("No expected tree content defined for step "+stepNumber+"."); + } + assertTrue("Step "+stepNumber+" did not work on tree. expected nodes: "+expectedTreeNodes+" but was: "+treeNodesAsString(), + algo.getTree().getNodesAsInteger().containsAll(expectedTreeNodes)); + + /* + * Assert node distance + */ + for (int node: expectedTreeNodes) { + int expectedDistance = 0; + try { + expectedDistance = expectedDistance(node); + } catch (IndexOutOfBoundsException e) { + fail("No node distance defined for node "+node+"."); + } + assertEquals("Wrong distance for node "+node+".", expectedDistance, algo.getTree().getNodeDistance(node)); + } + + /* + * Asserts that new edges are as expected + */ + for (int treeNode: expectedTreeNodes) { + if (usedStartNodes.contains(treeNode)) continue; + + // get expected predecessor + int expectedPredecessor = 0; + try { + expectedPredecessor = expectedPredecessor(treeNode); + } catch (IndexOutOfBoundsException e) { + fail("No expected predecessor defined for tree node "+treeNode+"."); + } + + // get actual predecessor + int actualPredecessor = 0; + try { + actualPredecessor = algo.getTree().getPredecessors(treeNode).get(0); + } catch (IndexOutOfBoundsException e) { + fail("Tree node "+treeNode+" has no predecessor. Expected: "+expectedPredecessor); + } + + // compare + assertEquals("Wrong predecessor for tree node "+treeNode+".", expectedPredecessor, actualPredecessor); + } + } + } + + @Test public void runAllResetAllRunAll() { + while (!algo.isFinished()) + algo.step(); + algo.undoAll(); + testSteps(); + } + + @Test public void testUndoRedo() { + String stackBefore1, stackAfter1, treeBefore1, treeAfter1; + String stackBefore2, stackAfter2, treeBefore2, treeAfter2; + while(!algo.isFinished()) { + stackBefore1 = stackAsString(); + treeBefore1 = treeNodesAsString(); + algo.step(); + stackAfter1 = stackAsString(); + treeAfter1 = treeNodesAsString(); + stackBefore2 = stackAsString(); + treeBefore2 = treeNodesAsString(); + algo.step(); + stackAfter2 = stackAsString(); + treeAfter2 = treeNodesAsString(); + + algo.undo(); + assertEquals("Undo from "+stackAfter2+" did not work on stack.", stackBefore2, stackAsString()); + assertEquals("Undo from "+stackAfter2+" did not work in tree.", treeBefore2, treeNodesAsString()); + algo.undo(); + assertEquals("Undo from "+stackAfter1+" did not work on stack.", stackBefore1, stackAsString()); + assertEquals("Undo from "+stackAfter1+" did not work in tree.", treeBefore1, treeNodesAsString()); + algo.redo(); + assertEquals("Redo did not work on stack", stackAfter1, stackAsString()); + assertEquals("Redo did not work in tree", treeAfter1, treeNodesAsString()); + algo.redo(); + assertEquals("Redo did not work on stack", stackAfter2, stackAsString()); + assertEquals("Redo did not work in tree", treeAfter2, treeNodesAsString()); + } + algo.undoAll(); + + assertFalse("All steps undone, algorithm still running.", algo.isRunning()); + assertFalse("All steps undone, algorithm still finished.", algo.isFinished()); +// assertTrue("Stack is not empty after reset.", algo.getStack().isEmpty()); + assertTrue("Tree is not empty after reset.", algo.getTree().getNodes().isEmpty()); + } + + private String stackAsString() { + return algo.getStack().toString(); + } + + private String treeNodesAsString() { + return algo.getTree().getNodesAsInteger().toString(); + } + + /** + * Returns the expected stack content after the specified step. + * @param stepNumber number of the step. First step is 1! + * @return expected stack content, formatted as in {@link NodeQueueStack#toString()} + */ + protected abstract String expectedStack(int stepNumber) throws IndexOutOfBoundsException; + + + /** + * Returns the expected tree content after the specified step. + * @param stepNumber number of the step. First step is 1! + * @return indices of the nodes expected in the tree + */ + protected abstract Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException; + + /** + * Returns the expected distance for the specified node + * @param nodeIndex index of the node + * @return epxected distance for that node + */ + protected abstract int expectedDistance(int nodeIndex) throws IndexOutOfBoundsException; + + /** + * Returns the expected predecessor of the specified tree node + * @param nodeIndex + * @return + */ + protected abstract int expectedPredecessor(int nodeIndex) throws IndexOutOfBoundsException; + + @Test public void testDefaultStartNode() { + assertEquals("Default start node is not 1.", 1, algo.getStartNode()); + } + + @Test public void setInvalidStartNode() { + // find an invalid node + int invalidNode = -999; + while (algo.getTree().getNodesAsInteger().contains(invalidNode)) + invalidNode--; + + try { + algo.setStartNode(invalidNode); + } catch(NoSuchElementException e) { + /* expected exception */ + return; + } + fail("Setting invalid start node threw no IndexOutOfBoundsException."); + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.java b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.java new file mode 100644 index 0000000..ad1531b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest.java @@ -0,0 +1,104 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class BFSTest extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2, + Integer.MAX_VALUE, + Integer.MAX_VALUE, + 3, + 3 + }; + + private String[] expectedStack = { + null, + "0:[1:w, 2:u, 3:u]", + "0:[1:f, 2:w, 3:w]", + "0:[1:f, 2:f, 3:w, 4:u]", + "0:[1:f, 2:f, 3:f, 4:w, 7:u, 8:u]", + "0:[1:f, 2:f, 3:f, 4:f, 7:w, 8:w]", + "0:[1:f, 2:f, 3:f, 4:f, 7:f, 8:w]", + "0:[1:f, 2:f, 3:f, 4:f, 7:f, 8:f]", + "" + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2,3}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 1, 3, null, null, 4, 4 + }; + + @Override + protected Algo getAlgo() { + return new BFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) { + return expectedStack[stepNumber]; + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } + + + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=8; i++) + gc.addNode(new Point()); + + gc.addEdge(1,1); + gc.addEdge(1,2); + gc.addEdge(2,1); + gc.addEdge(1,3); + gc.addEdge(3,4); + gc.addEdge(4,3); + gc.addEdge(3,1); + gc.addEdge(5,6); + gc.addEdge(6,6); + gc.addEdge(6,1); + gc.addEdge(4,7); + gc.addEdge(4,8); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.java b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.java new file mode 100644 index 0000000..d63ac0b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest2.java @@ -0,0 +1,91 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class BFSTest2 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2, + 2 + }; + + private String[] expectedStack = { + null, + "0:[1:w, 2:u, 3:u]", + "0:[1:f, 2:w, 3:w]", + "0:[1:f, 2:f, 3:w, 4:u, 5:u]", + "0:[1:f, 2:f, 3:f, 4:w, 5:w]", + "0:[1:f, 2:f, 3:f, 4:f, 5:w]", + "0:[1:f, 2:f, 3:f, 4:f, 5:f]", + "" + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2,3}, + {1,2,3}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 1, 3, 3 + }; + + @Override + protected Algo getAlgo() { + return new BFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) { + return expectedStack[stepNumber]; + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } + + + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=5; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(1,3); + gc.addEdge(3,4); + gc.addEdge(3,5); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.java b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.java new file mode 100644 index 0000000..14564f7 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/BFSTest3.java @@ -0,0 +1,96 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class BFSTest3 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2, + 3, + 2 + }; + + private String[] expectedStack = { + null, + "0:[1:w, 2:u, 3:u]", + "0:[1:f, 2:w, 3:w, 4:u]", + "0:[1:f, 2:f, 3:w, 4:w, 6:u]", + "0:[1:f, 2:f, 3:f, 4:w, 6:w, 5:u]", + "0:[1:f, 2:f, 3:f, 4:f, 6:w, 5:w]", + "0:[1:f, 2:f, 3:f, 4:f, 6:f, 5:w]", + "0:[1:f, 2:f, 3:f, 4:f, 6:f, 5:f]", + "" + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4,6}, + {1,2,3,4,6}, + {1,2,3,4,6,5}, + {1,2,3,4,6,5}, + {1,2,3,4,6,5}, + {1,2,3,4,6,5} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 1, 2, 4, 3 + }; + + @Override + protected Algo getAlgo() { + return new BFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) { + return expectedStack[stepNumber]; + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } + + + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=6; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(1,3); + gc.addEdge(3,6); + gc.addEdge(2,4); + gc.addEdge(4,5); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Entries b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Entries new file mode 100644 index 0000000..627080f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Entries @@ -0,0 +1,10 @@ +/AlgoTest.java/1.1/Wed Dec 8 13:47:54 2010// +/BFSTest.java/1.1/Wed Dec 8 13:47:54 2010// +/BFSTest2.java/1.1/Wed Dec 8 13:47:54 2010// +/BFSTest3.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest2.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest3.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest4.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest5.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTest6.java/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Repository b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Repository new file mode 100644 index 0000000..0b3dc19 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/algorithms/test diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Root b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.java new file mode 100644 index 0000000..05f0443 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest.java @@ -0,0 +1,130 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2, + 0, + 1, + 3, + 3 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[2:u, 3:u]", + "0:[1:w] 1:[2:w, 3:u] 2:[]", + "0:[1:w] 1:[2:f, 3:u]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:u]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:w] 4:[7:u, 8:u]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:w] 4:[7:w, 8:u] 7:[]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:w] 4:[7:f, 8:u]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:w] 4:[7:f, 8:w] 8:[]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:w] 4:[7:f, 8:f]", + "0:[1:w] 1:[2:f, 3:w] 3:[4:f]", + "0:[1:w] 1:[2:f, 3:f]", + "0:[1:f, 5:u]", + "0:[1:f, 5:w] 5:[6:u]", + "0:[1:f, 5:w] 5:[6:w] 6:[]", + "0:[1:f, 5:w] 5:[6:f]", + "0:[1:f, 5:f]", + "0:[]" + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2}, + {1,2}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4,7}, + {1,2,3,4,7}, + {1,2,3,4,7}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8}, + {1,2,3,4,7,8,5}, + {1,2,3,4,7,8,5,6}, + {1,2,3,4,7,8,5,6}, + {1,2,3,4,7,8,5,6}, + {1,2,3,4,7,8,5,6} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 1, 3, null, 5, 4, 4 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=8; i++) + gc.addNode(new Point()); + + gc.addEdge(1,1); + gc.addEdge(1,2); + gc.addEdge(2,1); + gc.addEdge(1,3); + gc.addEdge(3,4); + gc.addEdge(4,3); + gc.addEdge(3,1); + gc.addEdge(5,6); + gc.addEdge(6,6); + gc.addEdge(6,1); + gc.addEdge(4,7); + gc.addEdge(4,8); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.java new file mode 100644 index 0000000..db99a00 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest2.java @@ -0,0 +1,100 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest2 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 2, + 3 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[2:u, 4:u]", + "0:[1:w] 1:[2:w, 4:u] 2:[3:u]", + "0:[1:w] 1:[2:w, 4:u] 2:[3:w] 3:[4:u]", + "0:[1:w] 1:[2:w, 4:w] 2:[3:w] 3:[4:w] 4:[]", + "0:[1:w] 1:[2:w, 4:f] 2:[3:w] 3:[4:f]", + "0:[1:w] 1:[2:w, 4:f] 2:[3:f]", + "0:[1:w] 1:[2:f, 4:f]", + "0:[1:f]", + "", + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2}, + {1,2,3}, + {1,2,3}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 2, 3 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=4; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(2,3); + gc.addEdge(3,4); + gc.addEdge(1,4); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.java new file mode 100644 index 0000000..4ba89cf --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest3.java @@ -0,0 +1,109 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest3 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 2, + 3, + 4 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[2:u, 4:u]", + "0:[1:w] 1:[2:w, 4:u] 2:[3:u]", + "0:[1:w] 1:[2:w, 4:u] 2:[3:w] 3:[4:u]", + "0:[1:w] 1:[2:w, 4:w] 2:[3:w] 3:[4:w] 4:[5:u]", + "0:[1:w] 1:[2:w, 4:w] 2:[3:w] 3:[4:w] 4:[5:w] 5:[]", + "0:[1:w] 1:[2:w, 4:w] 2:[3:w] 3:[4:w] 4:[5:f]", + "0:[1:w] 1:[2:w, 4:f] 2:[3:w] 3:[4:f]", + "0:[1:w] 1:[2:w, 4:f] 2:[3:f]", + "0:[1:w] 1:[2:f, 4:f]", + "0:[1:f]", + "", + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2}, + {1,2,3}, + {1,2,3}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5}, + {1,2,3,4,5} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 2, 3, 4 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=5; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(2,3); + gc.addEdge(3,4); + gc.addEdge(4,5); + gc.addEdge(1,4); + gc.addEdge(4,4); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.java new file mode 100644 index 0000000..4a4bc98 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest4.java @@ -0,0 +1,99 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest4 extends AlgoTest { + public static void main(String[] args) { + new DFSTest4().testSteps(); + } + + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[2:u, 3:u]", + "0:[1:w] 1:[2:w, 3:u] 2:[3:u]", + "0:[1:w] 1:[2:w, 3:w] 2:[3:w] 3:[]", + "0:[1:w] 1:[2:w, 3:f] 2:[3:f]", + "0:[1:w] 1:[2:f, 3:f]", + "0:[1:f]", + "", + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2}, + {1,2,3}, + {1,2,3}, + {1,2,3}, + {1,2,3}, + {1,2,3} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 2 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=3; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(1,3); + gc.addEdge(2,3); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.java new file mode 100644 index 0000000..b69d1a0 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest5.java @@ -0,0 +1,101 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest5 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 1, + 1, + 2, + 3 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[2:u, 3:u]", + "0:[1:w] 1:[2:w, 3:u] 2:[3:u]", + "0:[1:w] 1:[2:w, 3:w] 2:[3:w] 3:[4:u]", + "0:[1:w] 1:[2:w, 3:w] 2:[3:w] 3:[4:w] 4:[]", + "0:[1:w] 1:[2:w, 3:w] 2:[3:w] 3:[4:f]", + "0:[1:w] 1:[2:w, 3:f] 2:[3:f]", + "0:[1:w] 1:[2:f, 3:f]", + "0:[1:f]", + "", + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,2}, + {1,2,3}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4}, + {1,2,3,4} + }; + + private Integer[] expectedPredecessors = { + null, null, 1, 2, 3 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=4; i++) + gc.addNode(new Point()); + + gc.addEdge(1,2); + gc.addEdge(1,3); + gc.addEdge(2,3); + gc.addEdge(3,4); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.java b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.java new file mode 100644 index 0000000..8139ef2 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/algorithms/test/DFSTest6.java @@ -0,0 +1,109 @@ +package org.jalgo.module.bfsdfs.algorithms.test; + +import java.awt.Point; +import java.util.*; +import org.jalgo.module.bfsdfs.algorithms.*; +import org.jalgo.module.bfsdfs.controller.GraphController; + +public class DFSTest6 extends AlgoTest { + private int[] expectedDistance = { + Integer.MAX_VALUE, + 0, + 2, + 2, + 1, + 1 + }; + + private String[] expectedStack = { + null, + "0:[1:w] 1:[4:u, 5:u]", + "0:[1:w] 1:[4:w, 5:u] 4:[3:u]", + "0:[1:w] 1:[4:w, 5:u] 4:[3:w] 3:[]", + "0:[1:w] 1:[4:w, 5:u] 4:[3:f]", + "0:[1:w] 1:[4:f, 5:u]", + "0:[1:w] 1:[4:f, 5:w] 5:[2:u]", + "0:[1:w] 1:[4:f, 5:w] 5:[2:w] 2:[]", + "0:[1:w] 1:[4:f, 5:w] 5:[2:f]", + "0:[1:w] 1:[4:f, 5:f]", + "0:[1:f]", + "", + }; + + private Integer[][] expectedTreeNodes = { + null, + {1}, + {1,4}, + {1,4,3}, + {1,4,3}, + {1,4,3}, + {1,4,3,5}, + {1,4,3,5}, + {1,4,3,5}, + {1,4,3,5}, + {1,4,3,5}, + {1,4,3,5} + }; + + private Integer[] expectedPredecessors = { + null, null, 5, 4, 1, 1 + }; + + @Override + protected Algo getAlgo() { + return new DFS(getGraph()); + } + + @Override + protected String expectedStack(int stepNumber) throws IndexOutOfBoundsException { + try { + return expectedStack[stepNumber]; + } catch(ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected Collection expectedTreeNodes(int stepNumber) throws IndexOutOfBoundsException { + try { + return Arrays.asList(expectedTreeNodes[stepNumber]); + } catch (ArrayIndexOutOfBoundsException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected GraphController getGraph() { + GraphController gc = new GraphController(); + + for (int i=1; i<=5; i++) + gc.addNode(new Point()); + + gc.addEdge(1,5); + gc.addEdge(5,1); + gc.addEdge(5,2); + gc.addEdge(2,5); + gc.addEdge(1,4); + gc.addEdge(4,1); + gc.addEdge(4,3); + gc.addEdge(3,4); + + return gc; + } + + @Override + protected int expectedPredecessor(int nodeIndex) + throws IndexOutOfBoundsException { + try { + return expectedPredecessors[nodeIndex]; + } catch(NullPointerException e) { + throw new IndexOutOfBoundsException(); + } + } + + @Override + protected int expectedDistance(int nodeIndex) + throws IndexOutOfBoundsException { + return expectedDistance[nodeIndex]; + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.java b/src/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.java new file mode 100644 index 0000000..e07d59c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/AddDoubleEdge.java @@ -0,0 +1,60 @@ +package org.jalgo.module.bfsdfs.controller; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; + +/** + * A {@link Step} from undo package it realized that a + * AddDoubleEdge step can be undoable. + * @author Johannes Siegert + * + */ +class AddDoubleEdge extends DesignStep { + + private int startNode = 0; + private int endNode = 0; + + private GraphController graphController = null; + + /** + * @param observableGraph + * @param startNode the start node of the edge + * @param endNode the end node of the edge + */ + public AddDoubleEdge(ObservableGraph observableGraph, + int startNode, int endNode, GraphController graphController){ + super(observableGraph); + this.graphController = graphController; + this.startNode = startNode; + this.endNode = endNode; + } + + public void execute() { + this.getObservableGraph().addEdge(this.startNode, this.endNode); + this.getObservableGraph().addEdge(this.endNode, this.startNode); + } + + public void undo() { + boolean firstEdgeRemove = true; + boolean secondEdgeRemove = true; + for (Step step : this.graphController.getUndoableSteps()){ + if (step instanceof AddEdge){ + int edgeStartNode = ((AddEdge)step).getStartNode(); + int edgeEndNode = ((AddEdge)step).getEndNode(); + if ((this.startNode == edgeStartNode)&&(this.endNode == edgeEndNode)){ + firstEdgeRemove = false; + } + if((this.startNode == edgeEndNode)&&(this.endNode == edgeStartNode)){ + secondEdgeRemove = false; + } + } + } + + if (firstEdgeRemove){ + this.getObservableGraph().removeEdge(this.startNode, this.endNode); + } + if (secondEdgeRemove){ + this.getObservableGraph().removeEdge(this.endNode, this.startNode); + } + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/AddEdge.java b/src/org/jalgo/module/bfsdfs/controller/AddEdge.java new file mode 100644 index 0000000..e47e6fc --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/AddEdge.java @@ -0,0 +1,42 @@ +package org.jalgo.module.bfsdfs.controller; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; + +/** + * A {@link Step} from undo package it realized that a + * AddEdge step can be undoable. + * @author Johannes Siegert + * + */ +class AddEdge extends DesignStep{ + private int startNode = 0; + private int endNode = 0; + + /** + * @param observableGraph + * @param startNode the start node of the edge + * @param endNode the end node of the edge + */ + public AddEdge(ObservableGraph observableGraph,int startNode, int endNode){ + super(observableGraph); + this.startNode = startNode; + this.endNode = endNode; + } + + public void execute() { + this.getObservableGraph().addEdge(this.startNode,this.endNode); + } + + public void undo() { + this.getObservableGraph().removeEdge(this.startNode, this.endNode); + } + + public int getStartNode() { + return startNode; + } + + public int getEndNode() { + return endNode; + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/AddNode.java b/src/org/jalgo/module/bfsdfs/controller/AddNode.java new file mode 100644 index 0000000..86d00e4 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/AddNode.java @@ -0,0 +1,88 @@ +package org.jalgo.module.bfsdfs.controller; + +import java.awt.Point; + +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; +/** + * A {@link Step} from undo package. It realized that a AddNode step can be undoable. + * Implements GraphObserver because it need to know what identifier has the added Node, + * to run undo. + * @author Johannes Siegert + */ +class AddNode extends DesignStep implements GraphObserver { + + private Point position = null; + private int nodeId = 0; + + /** + * @param observableGraph + * @param pos position of the node on the observableGraph + */ + public AddNode(ObservableGraph observableGraph, + Point pos,GraphController graphController) { + super(observableGraph); + graphController.addGraphObserver(this); + this.position = pos; + } + + public void execute() { + if (this.nodeId==0){ + this.getObservableGraph().addNode(this.position); + } + else{ + this.getObservableGraph(). + addNode(this.nodeId, this.position); + } + } + + public void undo() { + this.getObservableGraph().removeNodeWithAutomaticNodeIdAdaptation(this.nodeId); + } + + public void onNodeAdded(int node, Point pos){ + if (pos.equals(this.position)){ + this.nodeId = node; + this.position = pos; + } + } + + public void onNodeMoved(int node, Point pos) { + if (this.nodeId==node){ + this.position = pos; + } + } + + public void onNodeChanged(int oldNodeId, int newNodeId) { + if (this.nodeId==oldNodeId){ + this.nodeId=newNodeId; + } + } + + /** + * Non use method. + */ + public void onGraphLoaded() {} + + /** + * Non use method. + */ + public void onNodeRemoved(int node) {} + + /** + * Non use method. + */ + public void onEdgeAdded(int startNode, int endNode) {} + + /** + * Non use method. + */ + public void onEdgeRemoved(int startNode, int endNode) {} + + /** + * Non use method. + */ + public void onEdgeChanged(int oldStartNode, int oldEndNode, + int newStartNode, int newEndNode) {} +} diff --git a/src/org/jalgo/module/bfsdfs/controller/CVS/Entries b/src/org/jalgo/module/bfsdfs/controller/CVS/Entries new file mode 100644 index 0000000..2e10ee9 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/CVS/Entries @@ -0,0 +1,9 @@ +/AddDoubleEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/AddEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/AddNode.java/1.1/Wed Dec 8 13:47:54 2010// +/ComplexStep.java/1.1/Wed Dec 8 13:47:54 2010// +/DesignStep.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphController.java/1.1/Wed Dec 8 13:47:54 2010// +/RemoveDoubleEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/RemoveEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/RemoveNode.java/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/controller/CVS/Repository b/src/org/jalgo/module/bfsdfs/controller/CVS/Repository new file mode 100644 index 0000000..606b47f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/controller diff --git a/src/org/jalgo/module/bfsdfs/controller/CVS/Root b/src/org/jalgo/module/bfsdfs/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/controller/ComplexStep.java b/src/org/jalgo/module/bfsdfs/controller/ComplexStep.java new file mode 100644 index 0000000..2baaed0 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/ComplexStep.java @@ -0,0 +1,83 @@ +/** + * class: ComplexStep - offers the ability to merge a number of steps to one step, which can + * be undone and redone in common + * creation date: 28.05.09 + * completion date: 28.05.09 + * author: Ephraim Zimmer + */ + +package org.jalgo.module.bfsdfs.controller; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; + +public class ComplexStep extends DesignStep { + private List mySteps; + + public ComplexStep(ObservableGraph observableGraph, List steps) + throws NullPointerException { + super(observableGraph); + if (steps==null){ + throw new NullPointerException(); + } + this.mySteps = steps; + } + + public ComplexStep(ObservableGraph observableGraph) + throws IllegalArgumentException { + super(observableGraph); + this.mySteps = new ArrayList(); + } + + /** + * Adds a step to the List of steps which should be merged as one complex step. + * @param step + * @return Boolean + * @throws NullPointerException if step is null + */ + public boolean addStep(Step step) throws NullPointerException { + if (step == null) { + throw new NullPointerException(); + } + return mySteps.add(step); + } + + /** + * Removes a step from the List of steps which should be merged as one complex step. + * @param step + * @return Boolean + * @throws NullPointerException if step is null + */ + public boolean removeStep(Step step) throws NullPointerException { + if (step == null) { + throw new NullPointerException(); + } + return mySteps.remove(step); + } + + /** + * Executes all the steps represented by this complex step. + */ + public void execute() { + // the order of treatise is important; the first step in the list has to be executed first + // e.g. deletion of a node with edges: firstly the removal of the edges, than the removal of the node + for (Step s : mySteps) { + s.execute(); + } + } + + /** + * Undoes all the steps represented by this complex step. + */ + public void undo() { + // the order of treatise is important; the last step of the list has to be undone first + // e.g. undo of the deletion described above: firstly the recreation of the node, than the recreation of the edges + for (int i = mySteps.size()-1; i >= 0; i--) { + mySteps.get(i).undo(); + } + } + +} diff --git a/src/org/jalgo/module/bfsdfs/controller/DesignStep.java b/src/org/jalgo/module/bfsdfs/controller/DesignStep.java new file mode 100644 index 0000000..9f24338 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/DesignStep.java @@ -0,0 +1,29 @@ +package org.jalgo.module.bfsdfs.controller; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; + +/** + * DesignStep implements {@link Step} from from undo package. + * It represent a step in the design mode,which can do undo or redo. + * @author Johannes Siegert + */ +abstract class DesignStep implements Step{ + + private ObservableGraph observableGraph; + + /** + * @param observableGraph the observable graph on which the method will be called + * @throws NullPointerException if observableGraph is null + */ + public DesignStep(ObservableGraph observableGraph) throws NullPointerException{ + if(observableGraph==null){ + throw new NullPointerException(); + } + this.observableGraph = observableGraph; + } + + public ObservableGraph getObservableGraph() { + return observableGraph; + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/GraphController.java b/src/org/jalgo/module/bfsdfs/controller/GraphController.java new file mode 100644 index 0000000..e613f60 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/GraphController.java @@ -0,0 +1,317 @@ +package org.jalgo.module.bfsdfs.controller; + +import java.awt.Point; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.ModuleConnector; +import org.jalgo.module.bfsdfs.graph.Edge; +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.graph.Node; +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; +import org.jalgo.module.bfsdfs.undo.Undoable; + +/** + * This class controls the access to the {@link ObservableGraph}. + * @author Johannes Siegert + */ +public class GraphController extends Undoable{ + + /** + * The graph which is control by {@link GraphController}. + */ + private ObservableGraph observableGraph = null; + private ModuleConnector moduleConnector = null; + + public GraphController(){ + this.observableGraph = new ObservableGraph(); + } + + /** + * @param moduleConnector the moduleConnector which works together with the graph controller + */ + public GraphController(ModuleConnector moduleConnector){ + this.observableGraph = new ObservableGraph(); + this.moduleConnector = moduleConnector; + } + + /** + * Searches all direct predecessors of the specified node + * @author Thomas Görres + * @param node index of the node who's successors are searched + * @return indices of this node's direct successors. In case of an + * exception, an empty list is returned + */ + public List getPredecessors(int node) { + return observableGraph.getPredecessors(node); + } + + /** + * Searches all direct successors of the specified node + * @author Thomas Görres + * @param node index of the node who's successors are searched + * @return indices of this node's direct successors. In case of an + * exception, an empty list is returned + */ + public List getSuccessors(int node) { + return observableGraph.getSuccessors(node); + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. + * @param pos position on observable graph + */ + public void addNode(Point pos){ + this.makeUndoableStep(new AddNode(this.observableGraph,pos,this)); + } + + /** + * Add the start node, which isn't undoable to {@link ObservableGraph}. + * @param pos position on observable graph + */ + public void addStartNode(Point pos) throws IllegalArgumentException { + // just executes the step; no undoability + // important for loading a saved graph + this.makeStep(new AddNode(this.observableGraph,pos,this)); + } + + /** + * Remove {@link Node} from {@link ObservableGraph}. + * @param node identifier of the node which will be removed. + */ + public void removeNode(int node){ + /* + * Edges, which have the node as startNode or endNode must be deleted. + */ + ArrayList removeEdges = new ArrayList(); + for (Edge edge : this.getEdges()){ + if ((edge.getStartNode().equals(this.observableGraph.getNode(node))) + ||(edge.getEndNode().equals(this.observableGraph.getNode(node)))){ + removeEdges.add(edge); + } + } + + /* + * The removal of the node and the associated edges becomes a + * complex step + */ + ArrayList steps = new ArrayList(); + /* + * Firstly the creation of the instances "RemoveEdge" for + * each edge in the list "removeEdges". + */ + while (!(removeEdges.isEmpty())){ + steps.add(new RemoveEdge(this.observableGraph, + removeEdges.get(0).getStartNode().getId(), + removeEdges.get(0).getEndNode().getId())); + removeEdges.remove(removeEdges.get(0)); + } + /* + * Secondly the creation of the instance "RemoveNode" + * for the Node which has to be deleted. + */ + steps.add(new RemoveNode(this.observableGraph,node)); + this.makeUndoableStep(new ComplexStep(this.observableGraph, steps)); + } + + /** + * Add {@link Edge} to {@link ObservableGraph} if the node not exists on the {@link ObservableGraph}. + * @param startNode start node of the edge + * @param endNode end node of the edge + */ + public void addEdge(int startNode, int endNode){ + if (this.observableGraph.getEdge(startNode, endNode)==null){ + this.makeUndoableStep(new AddEdge(this.observableGraph,startNode,endNode)); + } + } + + /** + * Remove {@link Edge} from {@link ObservableGraph}. + * @param startNode start node of the edge + * @param endNode end node of the edge + */ + public void removeEdge(int startNode, int endNode){ + this.makeUndoableStep(new RemoveEdge(this.observableGraph,startNode,endNode)); + } + + /** + * Add two {@link Edge}'s to {@link ObservableGraph}. (startNode, endNode) and (endNode,startNode), + * if maximal one node exists on {@link ObservableGraph}. + * @param startNode start node of the edge + * @param endNode end node of the edge + */ + public void addDoubleEdge(int startNode, int endNode){ + if ((this.observableGraph.getEdge(startNode, endNode)!=null)&&((this.observableGraph.getEdge(endNode, startNode)!=null))){ + return; + } + this.makeUndoableStep(new AddDoubleEdge(this.observableGraph,startNode,endNode,this)); + } + + /** + * Remove two {@link Edge}'s to {@link ObservableGraph}. (startNode, endNode) and (endNode,startNode). + * @param startNode start node of the edge + * @param endNode end node of the edge + */ + public void removeDoubleEdge(int startNode, int endNode){ + this.makeUndoableStep(new RemoveDoubleEdge(this.observableGraph,startNode,endNode)); + } + + /** + * Add {@link GraphObserver} to {@link ObservableGraph}. + * @param graphObserver the graph observer which will be added + * @throws NullPointerException if graphObserver is null + */ + public void addGraphObserver(GraphObserver graphObserver) + throws NullPointerException{ + if (graphObserver==null){ + throw new NullPointerException(); + } + else{ + this.observableGraph.addGraphObserver(graphObserver); + } + } + + /** + * Remove {@link GraphObserver} from {@link ObservableGraph}. + * @param graphObserver the graph observer which will be removed + * @throws NullPointerException if graphObserver is null + */ + public void removeGraphObserver(GraphObserver graphObserver) + throws NullPointerException{ + if (graphObserver==null){ + throw new NullPointerException(); + } + else{ + this.observableGraph.removeGraphObserver(graphObserver); + } + } + + /** + * Update the position of the {@link Node} on {@link ObservableGraph}. + * @param node identifier of the node which will be moved + * @param pos new position of the node + */ + public void moveNode(int node,Point pos){ + this.observableGraph.moveNode(node, pos); + /* + * After moving a node the save button must be enabled. + */ + this.moduleConnector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + + /** + * @return collection of all nodes on observable graph + */ + public Collection getNodes(){ + return this.observableGraph.getNodesAsInteger(); + } + + /** + * @return collection of all edges on observable graph + */ + public Collection getEdges(){ + return this.observableGraph.getEdges(); + } + + /** + * @param node identifier from node which position is searched + * @return position on observable graph + */ + public Point getNodePosition(int node){ + return this.observableGraph.getNode(node).getPosition(); + } + + /** + * @return all positions of all nodes on observable graph + */ + public Map getNodePositions(){ + Map result = new TreeMap(); + for (Node node:this.observableGraph.getNodes()){ + result.put(node.getId(), node.getPosition()); + } + return result; + } + + /** + * This method set a ByteArrayOutputStream
          + * to save the actually {@link ObservableGraph} into a file. + * @return ByteArrayOutputStream + */ + public ByteArrayOutputStream getDataForFile(){ + ByteArrayOutputStream byteArrayOutputStream = + new ByteArrayOutputStream(); + try{ + ObjectOutputStream objectOutputStream = + new ObjectOutputStream(byteArrayOutputStream); + Collection nodes = this.observableGraph.getNodes(); + Collection edges = this.observableGraph.getEdges(); + List> result = + new LinkedList>(); + result.add(nodes); + result.add(edges); + objectOutputStream.writeObject(result); + objectOutputStream.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + return byteArrayOutputStream; + } + + /** + * Load the {@link ObservableGraph} from inputData. + * @param inputData the content which was read from file. + * @throws NullPointerException if inputData is null + */ + @SuppressWarnings("unchecked") + public void setDataFromFile(ByteArrayInputStream inputData) + throws NullPointerException{ + if (inputData==null){ + throw new NullPointerException(); + } + else{ + try { + ObjectInputStream objectInputStream = + new ObjectInputStream(inputData); + List> list = + ((List>)objectInputStream. + readObject()); + ModuleConnector.getGuiController().installStandardLayout(); + this.observableGraph.loadGraph(list); + } + catch (IOException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage + (Messages.getString( + "bfsdfs", "ModuleConnector.No_valid_BFSDFS_file")); + } + catch (ClassNotFoundException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage + (Messages.getString( + "bfsdfs", "ModuleConnector.Loading_error") + + System.getProperty("line.separator") + + Messages.getString("bfsdfs", "ModuleConnector.File_damaged")); + } + } + } + + /** + * @return next free node identifier to allocate + */ + public int getNextNodeId(){ + return this.observableGraph.getNextNodeId(); + } +} + diff --git a/src/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.java b/src/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.java new file mode 100644 index 0000000..b9dbe63 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/RemoveDoubleEdge.java @@ -0,0 +1,34 @@ +package org.jalgo.module.bfsdfs.controller; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; +/** + * A {@link Step} from undo package it realized that a + * RemoveDoubleEdge step can be undoable. + * @author Johannes Siegert + */ +class RemoveDoubleEdge extends DesignStep { + private int startNode = 0; + private int endNode = 0; + + /** + * @param observableGraph + * @param startNode the start node of the edge + * @param endNode the end node of the edge + */ + public RemoveDoubleEdge(ObservableGraph observableGraph, int startNode, int endNode) { + super(observableGraph); + this.startNode = startNode; + this.endNode = endNode; + } + + public void execute() { + this.getObservableGraph().removeEdge(this.startNode, this.endNode); + this.getObservableGraph().removeEdge(this.endNode, this.startNode); + } + + public void undo() { + this.getObservableGraph().addEdge(this.startNode, this.endNode); + this.getObservableGraph().addEdge(this.endNode, this.startNode); + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/RemoveEdge.java b/src/org/jalgo/module/bfsdfs/controller/RemoveEdge.java new file mode 100644 index 0000000..15e3687 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/RemoveEdge.java @@ -0,0 +1,32 @@ +package org.jalgo.module.bfsdfs.controller; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; +/** + * A {@link Step} from undo package it realized that a + * RemoveEdge step can be undoable. + * @author Johannes Siegert + */ +class RemoveEdge extends DesignStep { + private int startNode = 0; + private int endNode = 0; + + /** + * @param observableGraph + * @param startNode the start node of the edge + * @param endNode the end node of the edge + */ + public RemoveEdge(ObservableGraph observableGraph, int startNode, int endNode){ + super(observableGraph); + this.startNode = startNode; + this.endNode = endNode; + } + + public void execute() { + this.getObservableGraph().removeEdge(this.startNode, this.endNode); + } + + public void undo() { + this.getObservableGraph().addEdge(this.startNode, this.endNode); + } +} diff --git a/src/org/jalgo/module/bfsdfs/controller/RemoveNode.java b/src/org/jalgo/module/bfsdfs/controller/RemoveNode.java new file mode 100644 index 0000000..5578248 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/controller/RemoveNode.java @@ -0,0 +1,30 @@ +package org.jalgo.module.bfsdfs.controller; + +import java.awt.Point; + +import org.jalgo.module.bfsdfs.graph.ObservableGraph; +import org.jalgo.module.bfsdfs.undo.Step; +/** + * A {@link Step} from undo package it realized + * that a RemoveNode step can be undoable. + * @author Johannes Siegert + */ +class RemoveNode extends DesignStep{ + private int nodeId = 0; + private Point position = null; + + + public RemoveNode(ObservableGraph observableGraph,int node) { + super(observableGraph); + this.position = this.getObservableGraph().getNode(node).getPosition(); + this.nodeId = node; + } + + public void execute() { + this.getObservableGraph().removeNodeWithAutomaticNodeIdAdaptation(this.nodeId); + } + + public void undo() { + this.getObservableGraph().addNodeWithAutomaticNodeIdAdaptation(this.nodeId, this.position); + } +} diff --git a/src/org/jalgo/module/bfsdfs/de.properties b/src/org/jalgo/module/bfsdfs/de.properties new file mode 100644 index 0000000..8e649e2 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/de.properties @@ -0,0 +1,54 @@ +ModuleConnector.No_valid_BFSDFS_file=Keine gültige BFSDFS-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. + +ModuleInfo.description =Demonstriert Breiten- und Tiefensuche in Graphen. + +GUIController.warning=Warnung +GUIController.warning_desc=Achtung, ein Algorithmus läuft gerade! Wenn sie den Graphen bearbeiten wollen, setzen Sie alle Algorithmen zurück. +GUIController.warning_reset=Algorithmen jetzt zurücksetzen +GUIController.warning_abort=Abbrechen +WelcomeScreen.ioError=Datei konnte nicht gelesen werden. + +tab.designButton=Design +tab.bfsButton=Breitensuche +tab.dfsButton=Tiefensuche +tab.beamerButton=Beamermodus +tab.designButton_tooltip=Zeigt das Fenster für die Bearbeitung des Graphen an. +tab.bfsButton_tooltip=Zeigt das Fenster für den Breitensuche-Algorithmus an. +tab.dfsButton_tooltip=Zeigt das Fenster für den Tiefensuche-Algorithmus an. +tab.beamerButton_tooltip=Schaltet den Beamer-Modus an bzw. aus. (Taste: B) + +AlgoTab.startNodeLabel=Startknoten: +AlgoTab.startNodeChooserStatus=Wählen Sie hier den Startknoten aus. +AlgoTab.successorLabel=Nachfolger-Reihenfolge: +AlgoTab.successorChooserStatus=Hier können Sie die Reihenfolge der Nachfolger mittels Drag & Drop ändern. +AlgoTab.randomLabel=Zufall: +AlgoTab.randomBoxStatus=Schalten Sie hier den Nichtdeterminismus an bzw. aus. +AlgoTab.chooserPaneStatus=Hier können Sie den Algorithmus steuern. +AlgoTab.scrollPaneStatus=Hier wird der Graph visualisiert. + +GraphView.scrollPaneStatus=Hier können Sie einen Graphen erstellen oder bearbeiten. + +DFSTab.nodeViewLabel=Laufzeitkeller: +DFSTab.nodeViewStatus=Hier wird der vom Algorithmus benutzte Laufzeitkeller visualisiert. +BFSTab.nodeViewLabel=Warteschlange: +BFSTab.nodeViewStatus=Hier wird die vom Algorithmus benutzte Warteschlange visualisiert. + +ScrollArea.status = Bleiben Sie mit der Maus auf diesem Feld, um die Nachfolger zu scrollen. + +ResetAction.tooltip=Algorithmus zurücksetzen. (Taste: A) +StepBackAction.tooltip=Einen Schritt zurück. (Taste: S) +StepForwardAction.tooltip=Einen Schritt vor. (Taste: D) +PlayAction.tooltip=Algorithmus ablaufen lassen. (Taste: F) +CancelAction.tooltip=Derzeitige Animation abbrechen. (Taste: C) + +animationLabel.text =Animationen deaktivieren +AnimationAction.tooltip=Wählen Sie diese Option, um die Leistung zu erhöhen. + +UndoAction.tooltip=Letzten Schritt rückgängig machen. (Taste: Y) +RedoAction.tooltip=Letzten Schritt wiederholen. (Taste: X) +NodeAction.tooltip=Knoten hinzufügen und verschieben. (Taste: Q) +EdgeAction.tooltip=Gerichtete Kante hinzufügen. (Taste: W) +DoubleEdgeAction.tooltip=Ungerichtete Kante hinzufügen. (Taste: E) +EraserAction.tooltip=Strukturen löschen. (Taste: R) diff --git a/src/org/jalgo/module/bfsdfs/en.properties b/src/org/jalgo/module/bfsdfs/en.properties new file mode 100644 index 0000000..ab0ebdd --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/en.properties @@ -0,0 +1,54 @@ +ModuleConnector.No_valid_BFSDFS_file=No valid BFSDFS file. +ModuleConnector.Loading_error=An error occured while loading the file. +ModuleConnector.File_damaged=The file is possibly damaged. + +ModuleInfo.description = Demonstrates breadth first search and depth first search in graphs. + +GUIController.warning=Warning +GUIController.warning_desc=Attention, an algorithm is currently proceeding. If you want to change the graph, you have to reset all running algorithms. +GUIController.warning_reset=Reset algorithms now +GUIController.warning_abort=Cancel +WelcomeScreen.ioError=Could not read file. + +tab.designButton=Design +tab.bfsButton=Breadth First Search +tab.dfsButton=Depth First Search +tab.beamerButton=Beamer Mode +tab.designButton_tooltip=Shows the design window to work on the graph. +tab.bfsButton_tooltip=Shows the breadth first search window. +tab.dfsButton_tooltip=Shows the depth first search window. +tab.beamerButton_tooltip=Turns beamer mode on / off. (Key: B) + +AlgoTab.startNodeLabel=Start Node: +AlgoTab.startNodeChooserStatus=Here you can choose the start node. +AlgoTab.successorLabel=Successor Order: +AlgoTab.successorChooserStatus=Here you can change the order of the successors with Drag & Drop. +AlgoTab.randomLabel=Random: +AlgoTab.randomBoxStatus=Toggles the non-determinism. +AlgoTab.chooserPaneStatus=From here you can control the algorithm. +AlgoTab.scrollPaneStatus=Visualizes the graph. + +GraphView.scrollPaneStatus=From here you can create or edit the graph. + +DFSTab.nodeViewLabel=Stack: +DFSTab.nodeViewStatus=Visualizes the stack used by the algorithm. +BFSTab.nodeViewLabel=Queue: +BFSTab.nodeViewStatus=Visualizes the queue used by the algorithm. + +ScrollArea.status = Keep the mouse in this area to scroll the successors. + +ResetAction.tooltip=Reset the algorithm. (Key: A) +StepBackAction.tooltip=One step back. (Key: S) +StepForwardAction.tooltip=One step forward. (Key: D) +PlayAction.tooltip=Play the algorithm. (Key: F) +CancelAction.tooltip=Cancel the current animation. (Key: C) + +animationLabel.text =Disable Animations +AnimationAction.tooltip=Choose this option to increase the performance. + +UndoAction.tooltip=Undo the last step. (Key: Y) +RedoAction.tooltip=Redo the last step. (Key: X) +NodeAction.tooltip=Add or move a node. (Key: Q) +EdgeAction.tooltip=Add a directed edge. (Key: W) +DoubleEdgeAction.tooltip=Add a double edge. (Key: E) +EraserAction.tooltip=Erase structures. (Key: R) diff --git a/src/org/jalgo/module/bfsdfs/graph/AlgoGraph.java b/src/org/jalgo/module/bfsdfs/graph/AlgoGraph.java new file mode 100644 index 0000000..9716a74 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/AlgoGraph.java @@ -0,0 +1,107 @@ +package org.jalgo.module.bfsdfs.graph; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.TreeMap; + +/** + * This class represent the result graph of the algorithm. + * It extends {@link ObservableGraph} by methods to calculate the distance to startNode. + * @author Johannes Siegert + * + */ +public class AlgoGraph extends ObservableGraph { + + private static final long serialVersionUID = 1309990567480132436L; + + private Collection algoGraphObservers = null; + + /** + * This map save the distance from a node to the startNode. + * The key is the identifier of the node and the value is the distance to startNode. + */ + private Map distances = null; + + public AlgoGraph(){ + super(); + this.algoGraphObservers = new ArrayList(); + this.distances = new TreeMap(); + } + + /** + * @param node identifier of the node which distance will be set + * @param distance distance from node to startNode + * @throws IllegalArgumentException if node or distance is equal or smaller than 0 + * @throws NoSuchElementException if the node not exists on observeable graph + */ + public void setNodeDistance(int node,int distance) + throws IllegalArgumentException, NoSuchElementException{ + if((node<=0)||(distance<0)){ + throw new IllegalArgumentException(); + } + else if(this.getNode(node)==null){ + throw new NoSuchElementException(); + } + this.distances.put(node, distance); + for (AlgoGraphObserver aGO:this.algoGraphObservers){ + aGO.onDistanceChanged(node, distance); + } + } + + /** + * @param node identifier of the node which distance will be searched + * @return distance from node to startNode if distance is set, or infinite + * @throws IllegalArgumentException if node is equal or smaller than 0 + */ + public int getNodeDistance(int node) throws IllegalArgumentException{ + if (node<=0){ + throw new IllegalArgumentException(); + } + if ((distances == null) || (!(this.distances.containsKey(node)))) { + return Integer.MAX_VALUE; + } + else { + return this.distances.get(node); + } + } + + /** + * Add algoGraphObserver to algoGraphObservers. + @param algoGraphObserver the algoGraph observer which will be added. + * @throws NullPointerException if algoGraphObserver is null + */ + public void addAlgoGraphObserver(AlgoGraphObserver algoGraphObserver) + throws NullPointerException{ + if (algoGraphObserver==null){ + throw new NullPointerException(); + } + this.addGraphObserver(algoGraphObserver); + this.algoGraphObservers.add(algoGraphObserver); + } + + /** + * Remove algoGraphObserver to algoGraphObservers. + * @param algoGraphObserver the algoGraph observer which will be removed. + * @throws NullPointerException if algoGraphObserver is null + */ + public void removeAlgoGraphObserver(AlgoGraphObserver algoGraphObserver) + throws NullPointerException{ + if (algoGraphObserver==null){ + throw new NullPointerException(); + } + this.removeGraphObserver(algoGraphObserver); + this.algoGraphObservers.remove(algoGraphObserver); + } + + public void removeNode(int node){ + super.removeNode(node); + this.distances.remove(node); + } + + public void removeNodeWithAutomaticNodeIdAdaptation(int node){ + super.removeNodeWithAutomaticNodeIdAdaptation(node); + this.distances.remove(node); + } +} diff --git a/src/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.java b/src/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.java new file mode 100644 index 0000000..cf1431c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/AlgoGraphObserver.java @@ -0,0 +1,14 @@ +package org.jalgo.module.bfsdfs.graph; +/** + * Observer to observe {@link AlgoGraph}. + * @author Johannes Siegert + * + */ +public interface AlgoGraphObserver extends GraphObserver { + /** + * Is called if a node changed its distance to the start node. + * @param node identifier of the node which was changed its distance + * @param distance the new distance of the node + */ + public void onDistanceChanged(int node, int distance); +} diff --git a/src/org/jalgo/module/bfsdfs/graph/CVS/Entries b/src/org/jalgo/module/bfsdfs/graph/CVS/Entries new file mode 100644 index 0000000..8f242a1 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/CVS/Entries @@ -0,0 +1,7 @@ +/AlgoGraph.java/1.1/Wed Dec 8 13:47:54 2010// +/AlgoGraphObserver.java/1.1/Wed Dec 8 13:47:54 2010// +/Edge.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphObserver.java/1.1/Wed Dec 8 13:47:54 2010// +/Node.java/1.1/Wed Dec 8 13:47:54 2010// +/ObservableGraph.java/1.1/Wed Dec 8 13:47:54 2010// +/package.html/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/graph/CVS/Repository b/src/org/jalgo/module/bfsdfs/graph/CVS/Repository new file mode 100644 index 0000000..f5b41b9 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/graph diff --git a/src/org/jalgo/module/bfsdfs/graph/CVS/Root b/src/org/jalgo/module/bfsdfs/graph/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/graph/Edge.java b/src/org/jalgo/module/bfsdfs/graph/Edge.java new file mode 100644 index 0000000..93cd4be --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/Edge.java @@ -0,0 +1,86 @@ +package org.jalgo.module.bfsdfs.graph; + +import java.io.Serializable; + +/** + * This class represent an Edge on {@link ObservableGraph}. + * @author Johannes Siegert + * + */ +public class Edge implements Serializable { + + private static final long serialVersionUID = 540764027708479944L; + + private Node startNode = null; + private Node endNode = null; + + /** + * @param startNode start node of the new edge. + * @param endNode end node of the new edge. + * @throws NullPointerException if startNode or endNode is null + */ + public Edge (Node startNode, Node endNode) throws NullPointerException{ + if ((startNode==null)||(endNode==null)){ + throw new NullPointerException(); + } + this.startNode = startNode; + this.endNode = endNode; + } + + public Node getStartNode() { + return startNode; + } + + /** + * @param startNode node to set as start node. + * @throws NullPointerException if startNode is null + */ + public void setStartNode(Node startNode) throws NullPointerException{ + if (startNode==null){ + throw new NullPointerException(); + } + this.startNode = startNode; + } + + public Node getEndNode() { + return endNode; + } + + /** + * @param endNode node to set as end node. + * @throws NullPointerException if endNode is null + */ + public void setEndNode(Node endNode) throws NullPointerException { + if (endNode==null){ + throw new NullPointerException(); + } + this.endNode = endNode; + } + + /** + * @return true if start node identifier and end node identifier are equal + * @throws NullPointerException if obj is null + */ + @Override + public boolean equals(Object obj) throws IllegalArgumentException{ + if (obj==null){ + throw new IllegalArgumentException(); + } + else{ + Edge edge = (Edge) obj; + if ((edge.getStartNode().getId()==this.startNode.getId())&&(edge.getEndNode().getId()==this.endNode.getId())){ + return true; + } + else{ + return false; + } + } + } + + @Override + public String toString() { + return(startNode.getId() + "->"+endNode.getId()); + } + +} + diff --git a/src/org/jalgo/module/bfsdfs/graph/GraphObserver.java b/src/org/jalgo/module/bfsdfs/graph/GraphObserver.java new file mode 100644 index 0000000..8e7b44b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/GraphObserver.java @@ -0,0 +1,60 @@ +package org.jalgo.module.bfsdfs.graph; + +import java.awt.Point; + +/** + * Observer interface to observe {@link ObservableGraph}. + * @author Johannes Siegert + * + */ +public interface GraphObserver { + /** + * Is called if a node was added. + * @param node identifier of the node which was added + * @param pos position of the node which was added + */ + public void onNodeAdded(int node,Point pos); + + /** + * Is called if a node was removed. + * @param node identifier of the node which was removed + */ + public void onNodeRemoved(int node); + + /** + * Is called if an edge was added. + * @param startNode identifier of the start node + * @param endNode identifier of the end node + */ + public void onEdgeAdded(int startNode,int endNode); + + /** + * Is called if an edge was removed. + * @param startNode identifier of the start node + * @param endNode identifier of the end node + */ + public void onEdgeRemoved(int startNode,int endNode); + + /** + * Is called if a node was changed it's position. + * @param node identifier of the node which was moved + * @param pos new position of that node + */ + public void onNodeMoved(int node,Point pos); + + /** + * Is called if node identifier is changed. + * @param oldNodeId old identifier of the node + * @param newNodeId new identifier of the node + */ + public void onNodeChanged(int oldNodeId, int newNodeId); + + /** + * Is called if an edge changed. + * @param oldStartNode identifier of the old start node + * @param oldEndNode identifier of the old end node + * @param newStartNode identifier of the new start node + * @param newEndNode identifier of the new end node + */ + public void onEdgeChanged(int oldStartNode, int oldEndNode, int newStartNode, int newEndNode); +} diff --git a/src/org/jalgo/module/bfsdfs/graph/Node.java b/src/org/jalgo/module/bfsdfs/graph/Node.java new file mode 100644 index 0000000..c16cef8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/Node.java @@ -0,0 +1,121 @@ +package org.jalgo.module.bfsdfs.graph; + +import java.awt.Point; +import java.io.Serializable; + +/** + * This class represent a node on {@link ObservableGraph}. + * @author Johannes Siegert + * + */ +public class Node implements Serializable, Comparable { + + private static final long serialVersionUID = 7243160548381678774L; + /** + * The identifier of {@link Node}. + */ + private int id = 0; + /** + * The current position of {@link Node}. + */ + private Point position = null; + + /** + * @param id identifier of the new node + * @param pos position of the new node + * @throws NullPointerException if pos is null + * @throws IllegalArgumentException if the id equals or smaller than 0 + */ + public Node(int id,Point pos) throws NullPointerException,IllegalArgumentException{ + if(pos==null){ + throw new NullPointerException(); + } + else if (id<=0){ + throw new IllegalArgumentException(); + } + this.id = id; + this.position = pos; + } + + /** + * This constructor set the position to Point(0,0). + * @param id identifier of the new node + * @throws IllegalArgumentException if the id equals or smaller than 0 + */ + public Node(int id) throws IllegalArgumentException{ + if (id<=0){ + throw new IllegalArgumentException(); + } + this.id = id; + this.position = new Point(0,0); + } + + public int getId() { + return id; + } + + /** + * @param id new identifier for this node + * @throws IllegalArgumentException if the id equals or smaller than 0 + */ + public void setId(int id) throws IllegalArgumentException { + if(id<=0){ + throw new IllegalArgumentException(); + } + this.id = id; + } + + public Point getPosition() { + return position; + } + + /** + * @param position new position for this node + * @throws NullPointerException if the argument is null + */ + public void setPosition(Point position) throws NullPointerException{ + if (position==null){ + throw new NullPointerException(); + } + this.position = position; + } + + /* + * (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Node node) throws NullPointerException { + if(node==null){ + throw new NullPointerException(); + } + if (node.getId()==this.id){ + return 0; + } + else if (node.getId()>this.id){ + return -1; + } + else{ + return 1; + } + } + + /** + * @param obj object to compare + * @returns true if the specified object is equal to this {@link Node} with an identifier + * @throws NullPointerException if obj is null + */ + @Override + public boolean equals(Object obj) throws NullPointerException{ + if (obj==null){ + throw new NullPointerException(); + } + Node node = (Node)obj; + if (node.compareTo(this)==0){ + return true; + } + else{ + return false; + } + } +} + diff --git a/src/org/jalgo/module/bfsdfs/graph/ObservableGraph.java b/src/org/jalgo/module/bfsdfs/graph/ObservableGraph.java new file mode 100644 index 0000000..10d38ce --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/ObservableGraph.java @@ -0,0 +1,883 @@ +package org.jalgo.module.bfsdfs.graph; + +import java.awt.Point; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.TreeSet; + +/** + * This class represent the graph of the BFSDFS module. It is observable by {@link GraphObserver}. + * @author Johannes Siegert + */ +public class ObservableGraph implements Serializable{ + private static final long serialVersionUID = 6560484674663537319L; + + /** + * Saves the {@link GraphObserver}s of this {@link ObservableGraph}. + */ + private Collection graphObservers = null; + /** + * Saves the {@link Node}s of this {@link ObservableGraph}. + */ + private Collection nodes = null; + /** + * Saves the {@link Edge}s of this {@link ObservableGraph}. + */ + private Collection edges = null; + + /** + * Highest identifier which is currently assigned to a {@link Node}. + */ + private int highestNodeId = 0; + + public ObservableGraph(){ + this.graphObservers = new ArrayList(); + this.nodes = new TreeSet(); + this.edges = new ArrayList(); + } + + /** + * Checks whether this graph contains the specified {@link Node}. + * @author Thomas Görres + * @param nodeIndex index of the searched node + * @return true if this graph contains that node + */ + public boolean containsNode(int nodeIndex){ + return getNodesAsInteger().contains(nodeIndex); + } + + /** + * Searches all direct predecessors of the specified {@link Node}. + * @author Thomas Görres + * @param node index of the node who's successors are searched + * @return indices of this node's direct successors. In case of an + * exception, an empty list is returned + */ + public List getPredecessors(int node){ + // get all nodes of the graph + Collection allNodes = getNodesAsInteger(); + Collection allEdges = getEdges(); + if (null == allNodes) + return Collections.emptyList(); + + // search for edges that connect a predecessor with the specified node + List predecessors = new ArrayList(); + for (Edge edge: allEdges) + if (edge.getEndNode().getId() == node) + predecessors.add(edge.getStartNode().getId()); + + return predecessors; + } + + /** + * Searches all direct successors of the specified {@link Node}. + * @author Thomas Görres + * @param node index of the node who's successors are searched + * @return indices of this node's direct successors, sorted in ascending order. In case of an + * exception, an empty list is returned + */ + public List getSuccessors(int node) throws IllegalArgumentException{ + // get all nodes of the graph + Collection allNodes = getNodesAsInteger(); + Collection allEdges = getEdges(); + if (null == allNodes) + return Collections.emptyList(); + + // search for edges that connect the specified node with a successor + List successors = new ArrayList(); + for (Edge edge: allEdges) + if (edge.getStartNode().getId() == node) + successors.add(edge.getEndNode().getId()); + + Collections.sort(successors); + + return successors; + } + + /** + * Increments the identifier of the specified {@link Node}. + * @param node node which identifier is to be incremented + * @throws NullPointerException if node is null + */ + private void incrementNodeId(Node node) throws NullPointerException{ + if (node==null){ + throw new NullPointerException(); + } + /* + * Save old Node id. + */ + int oldNodeId = node.getId(); + /* + * Increments the id. + */ + node.setId(node.getId()+1); + /* + * Information to GraphObservers. + */ + for(GraphObserver graphObserver : this.graphObservers){ + graphObserver.onNodeChanged(oldNodeId,node.getId()); + } + } + + /** + * Decrement the identifier of the specified {@link Node}. + * @param node node which identifier is to be decremented + * @throws NullPointerException if node is null + */ + private void decrementNodeId(Node node) throws NullPointerException{ + if (node==null){ + throw new NullPointerException(); + } + /* + * Save old Node id. + */ + int oldNodeId = node.getId(); + /* + * Decrements the id. + */ + node.setId(node.getId()-1); + /* + * Information to GraphObservers. + */ + for(GraphObserver graphObserver : this.graphObservers){ + graphObserver.onNodeChanged(oldNodeId,node.getId()); + } + } + + /** + * Autoset the node identifier. + * @param node the node identifier of the node which produce the autoset + * @param if isNodeAdding it is true the nodes will be increment, otherwise decrement + * @throws IllegalArgumentException if node is equal or smaller than 0 + */ + private void autosetNodeIdAndEdges(int node, boolean isNodeAdding) + throws IllegalArgumentException{ + if ((node<=0)){ + throw new IllegalArgumentException(); + } + /* + * Create a temporary collection of Edge + */ + Collection tempEdges = this.edges; + + /* + * Save the old Edges + */ + Object[] edgesOldObject = this.edges.toArray(); + Integer[][] edgesOld = new Integer[this.edges.size()][2]; + for (int i = 0;i=node){ + for (Edge edge : tempEdges){ + if (edge.getStartNode().equals(nodeOnGraph)){ + edge.setStartNode(nodeOnGraph); + } + if (edge.getEndNode().equals(nodeOnGraph)){ + edge.setEndNode(nodeOnGraph); + } + } + } + } + + if (isNodeAdding){ + /* + * Increment backward until the list. + * At first the nodes which will be increment + * added to the array list nodesToIncrement, + * than all nodes in this list will be + * increment backward. + */ + ArrayList nodesToIncrement = new ArrayList(); + for (Node nodeOnGraph : this.nodes){ + if (nodeOnGraph.getId()>=node){ + nodesToIncrement.add(nodeOnGraph); + } + } + + for (int currentIndex = nodesToIncrement.size();currentIndex>0;currentIndex--){ + this.incrementNodeId(nodesToIncrement.get(currentIndex-1)); + } + } + else{ + /* + * Decrement until the list. + * At first the nodes which will be decrement + * added to the array list nodesToDecrement, + * than all nodes in this list will be + * decrement. + */ + ArrayList nodesToDecrement = new ArrayList(); + for (Node nodeOnGraph : this.nodes){ + if (nodeOnGraph.getId()>node){ + nodesToDecrement.add(nodeOnGraph); + } + } + + for (int currentIndex=0;currentIndex=0;i--){ + for (GraphObserver graphObserver : this.graphObservers){ + graphObserver.onEdgeChanged(edgesOld[i][0],edgesOld[i][1], + ((Edge)edgesNew[i]).getStartNode().getId(), + ((Edge)edgesNew[i]).getEndNode().getId()); + } + } + } + + /** + * Add the specified {@link GraphObserver} to {@link ObservableGraph}. + * @param graphObserver the graph observer which will be added + * @throws NullPointerException if graphObserver is null + */ + public void addGraphObserver(GraphObserver graphObserver) + throws NullPointerException{ + if(graphObserver==null){ + throw new NullPointerException(); + } + this.graphObservers.add(graphObserver); + } + + /** + * Remove the specified {@link GraphObserver} from {@link ObservableGraph}. + * @param graphObserver the graph observer which will be removed + * @throws NullPointerException if graphObserver is null + */ + public void removeGraphObserver(GraphObserver graphObserver) + throws NullPointerException{ + if(graphObserver==null){ + throw new NullPointerException(); + } + this.graphObservers.remove(graphObserver); + } + + /** + * Get all {@link GraphObserver} from {@link ObservableGraph}. + * @return the graph observers of observable graph. + */ + public Collection getGraphObservers(){ + return this.graphObservers; + } + + /** + * Get a {@link Collection} of {@link Node} from {@link ObservableGraph}. + * @return a collection of all nodes on the observable graph. + */ + public Collection getNodes() { + return this.nodes; + } + + /** + * Get a {@link Collection} of node identifiers from all nodes on {@link ObservableGraph}. + * @return a collection of node identifiers from all nodes on the observable graph + */ + public Collection getNodesAsInteger() { + /* + * Adapt the list of nodes to integer list + * with the ids of all nodes. + */ + Collection result = new TreeSet(); + for (Node node : this.getNodes()){ + result.add(node.getId()); + } + return result; + } + + /** + * Get a {@link Edge} from {@link ObservableGraph}. + * @param node the node identifier from the node which will be searched. + * @return if the node exist on the observable graph the node, otherwise null + * @throws IllegalArgumentException if node is equal or smaller than 0 + */ + public Node getNode(int node) throws IllegalArgumentException{ + if (node <= 0){ + throw new IllegalArgumentException(); + } + /* + * Search for the node with the right id and return it. + */ + for (Node nodeOnGraph: this.nodes){ + if (nodeOnGraph.getId()==node){ + return nodeOnGraph; + } + } + return null; + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. If the {@link Node} exists + * on {@link ObservableGraph}, only the position is changed. + * @param node the node identifier of node which will be added + * @param position the position on the observable graph + * @throws NullPointerException if position is null + * @throws IllegalArgumentException if node is equal or smaller than 0 + */ + public void addNode(int node, Point position) throws NullPointerException, IllegalArgumentException{ + if(position==null){ + throw new NullPointerException(); + } + else if (node<=0){ + throw new IllegalArgumentException(); + } + + /* + * Add the Node. + */ + if (this.getNode(node)!=null){ + this.getNode(node).setPosition(position); + } + else{ + this.nodes.add(new Node(node, position)); + /* + * If the node is adding after the last Node + * idCounter must incremented + */ + if ((this.highestNodeId+1) == node){ + this.highestNodeId++; + } + } + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeAdded(node, position); + } + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. + * If a {@link Node} with the same node identifier already + * exists on {@link ObservableGraph}, the node identifier + * of this {@link Node} and all {@link Node}s with greater + * identifier will be increment. + * @param node the node identifier of the node which will be added + * @param position the position on the observable graph + * @throws NullPointerException if position is null + * @throws IllegalArgumentException if node is equal or smaller than 0 + */ + public void addNodeWithAutomaticNodeIdAdaptation(int node, Point position) + throws NullPointerException, IllegalArgumentException { + if(position == null){ + throw new NullPointerException(); + } + else if (node<=0){ + throw new IllegalArgumentException(); + } + + if (this.getNode(node)!=null){ + this.autosetNodeIdAndEdges(node, true); + } + /* + * Add the Node. + */ + this.nodes.add(new Node(node, position)); + + this.highestNodeId++; + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeAdded(node, position); + } + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. + * The node identifier will be publish + * by {@link GraphObserver} method onNodeAdded. + * @param position the position of the new node on observable graph + * @throws NullPointerException if position is null + */ + public void addNode(Point position) throws NullPointerException { + if (position==null){ + throw new NullPointerException(); + } + /* + * Node id save in node. + */ + this.highestNodeId++; + + int node = this.highestNodeId; + + /* + * Adding the node. + */ + this.nodes.add(new Node(node, position)); + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeAdded(node, position); + } + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. If the {@link Node} exists + * on {@link ObservableGraph}, only the position is changed. + * @param node the node which will be added to the observable graph + * @throws NullPointerException if node is null + */ + public void addNode(Node node) throws NullPointerException{ + if (node==null){ + throw new NullPointerException(); + } + /* + * Add the Node. + */ + if (this.getNode(node.getId())!=null){ + this.getNode(node.getId()).setPosition(node.getPosition()); + } + else{ + this.nodes.add(node); + /* + * If the node is adding after the last Node idCounter must + * incremented + */ + if ((this.highestNodeId+1) == node.getId()){ + this.highestNodeId++; + } + } + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeAdded(node.getId(), node.getPosition()); + } + } + + /** + * Add a {@link Node} to {@link ObservableGraph}. + * If a {@link Node} with the same node identifier already + * exists on {@link ObservableGraph}, the node identifier + * of this {@link Node} and all {@link Node}s with greater + * identifier will be increment. + * @param node the node which will be added to the observable graph + * @throws NullPointerException if node is null + */ + public void addNodeWithAutomaticNodeIdAdaptation(Node node) + throws NullPointerException{ + if (node==null){ + throw new NullPointerException(); + } + /* + * Increment the nodes which have a equal or + * greater id and chance the edges according to this. + */ + if (this.getNode(node.getId())!=null){ + this.autosetNodeIdAndEdges(node.getId(), true); + } + + /* + * Add the Node. + */ + this.nodes.add(node); + + this.highestNodeId++; + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeAdded(node.getId(), node.getPosition()); + } + } + /** + * Delete the edges which have the node identifier as start node or as end node. + */ + private void removeEdges(int node)throws IllegalArgumentException{ + if (node<=0){ + throw new IllegalArgumentException(); + } + ArrayList edgesToDelete = new ArrayList(); + for (Edge edge : this.edges){ + if ((edge.getStartNode().getId()==node)||(edge.getEndNode().getId()==node)){ + edgesToDelete.add(edge); + } + } + for (Edge edge : edgesToDelete){ + this.removeEdge(edge); + } + } + + /** + * Remove a {@link Node} from {@link ObservableGraph}. + * @param node the node identifier from the node which will be removed + * @throws IllegalArgumentException if node is equal or smaller than 0 + * @throws NoSuchElementException if node not exists on observeable graph + */ + public void removeNode(int node) throws IllegalArgumentException, NoSuchElementException{ + if (node <= 0){ + throw new IllegalArgumentException(); + } + else if(this.getNode(node)==null){ + throw new NoSuchElementException(); + } + + this.removeEdges(node); + + Node nodeToDelete = this.getNode(node); + this.nodes.remove(nodeToDelete); + /* + * Information to GraphObservers + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeRemoved(node); + } + } + + + /** + * Remove a {@link Node} from {@link ObservableGraph} and + * increment the node identifier of {@link Node}s on + * {@link ObservableGraph}, which has greather node identifier. + * @param node the node identifier from the node which will be removed + * @throws IllegalArgumentException if node is equal or smaller than 0 + * @throws NoSuchElementException if node not exists on observeable graph + */ + public void removeNodeWithAutomaticNodeIdAdaptation(int node) + throws IllegalArgumentException, NoSuchElementException{ + if (node <= 0){ + throw new IllegalArgumentException(); + } + else if (this.getNode(node)==null){ + throw new NoSuchElementException(); + } + + this.removeEdges(node); + + /* + * Delete the Node if the Node was the Node with the highest Id, + * it can be only removed. Else all Nodes, which have an greater Id, + * their Id must decremented after removing the Node. + */ + Node nodeToDelete = this.getNode(node); + this.nodes.remove(nodeToDelete); + + /* + * Information to GraphObservers + */ + for (GraphObserver graphObserver: this.graphObservers){ + graphObserver.onNodeRemoved(node); + } + /* + * Chance the greater nodes and edges. + */ + if (node < this.highestNodeId + 1){ + this.autosetNodeIdAndEdges(node, false); + } + this.highestNodeId--; + } + + + /** + * Move position of a {@link Node} on {@link ObservableGraph}. + * @param node the node identifier of node to move + * @param position the new position on the observable graph + * @throws NullPointerException if position is null + * @throws IllegalArgumentException if node is equal or smaller than 0 + * @throws NoSuchElementException if node not exists on observable graph + */ + public void moveNode(int node, Point position) + throws NullPointerException, IllegalArgumentException, NoSuchElementException{ + if (position==null){ + throw new NullPointerException(); + } + else if (node <= 0){ + throw new IllegalArgumentException(); + } + else if (this.getNode(node)==null){ + throw new NoSuchElementException(); + } + /* + * Move the position. + */ + this.getNode(node).setPosition(position); + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver : this.graphObservers){ + graphObserver.onNodeMoved(node, this.getNode(node).getPosition()); + } + } + + /** + * Get a {@link Collection} of {@link Edge} from {@link ObservableGraph}. + * @return collection of all edges on the observable graph + */ + public Collection getEdges(){ + return this.edges; + } + + + /** + * Get an {@link Edge} from {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @return if the edge exist on the observable graph the edge, otherwise null + * @throws IllegalArgumentException if startNode or endNode is equal or smaller than 0 + */ + public Edge getEdge(int startNode, int endNode) + throws IllegalArgumentException{ + if ((startNode<=0)||(endNode<=0)){ + throw new IllegalArgumentException(); + } + for (Edge edge:this.edges){ + if ((edge.getStartNode().equals(this.getNode(startNode))) + &&(edge.getEndNode().equals(this.getNode(endNode)))){ + return edge; + } + } + return null; + } + + + /** + * Get an {@link Edge} from {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @return if the edge exist on the observable graph the edge, otherwise null + * @throws NullPointerException if startNode or endNode is null + */ + public Edge getEdge(Node startNode, Node endNode) + throws NullPointerException{ + if ((startNode==null)||(endNode==null)){ + throw new NullPointerException(); + } + for(Edge edge: this.edges){ + if ((edge.getStartNode().equals(startNode))&& + (edge.getEndNode().equals(endNode))){ + return edge; + } + } + return null; + } + + + /** + * Add an {@link Edge} to {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @throws IllegalArgumentException if startNode or endNode is equal or smaller than 0 + * @throws NoSuchElementException if startNode or endNode not exist on the observable graph + */ + public void addEdge(int startNode, int endNode) + throws IllegalArgumentException, NoSuchElementException{ + if ((startNode<=0)||(endNode<=0)){ + throw new IllegalArgumentException(); + } + else if (((this.getNode(startNode)==null)||(this.getNode(endNode)==null))){ + throw new NoSuchElementException(); + } + + if(this.getEdge(startNode, endNode)==null){ + this.edges.add(new Edge(this.getNode(startNode),this.getNode(endNode))); + /* + * Information to GraphObservers + */ + for (GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeAdded(startNode, endNode); + } + } + } + + + /** + * Add an {@link Edge} to {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @throws NullPointerException if startNode or endNode is null + * @throws NoSuchElementException if startNode or endNode not exist on the observable graph + */ + public void addEdge(Node startNode, Node endNode) + throws NullPointerException, NoSuchElementException{ + if (((startNode==null)||(endNode==null))){ + throw new NullPointerException(); + } + else if((!this.nodes.contains(endNode))||(!(this.nodes.contains(startNode)))){ + throw new NoSuchElementException(); + } + if(this.getEdge(startNode, endNode)==null){ + this.edges.add(new Edge(startNode,endNode)); + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeAdded(startNode.getId(), endNode.getId()); + } + } + } + + + /** + * Add an {@link Edge} to {@link ObservableGraph}. + * @param edge the edge which will be added + * @throws NullPointerException if edge is null + * @throws NoSuchElementException if the start node or the end node not exist on the observable graph + */ + public void addEdge(Edge edge)throws NullPointerException, NoSuchElementException{ + if(edge==null){ + throw new NullPointerException(); + } + else if (((this.getNode(edge.getStartNode().getId())==null)|| + (this.getNode(edge.getEndNode().getId())==null))){ + throw new NoSuchElementException(); + } + if (this.getEdge(edge.getStartNode(),edge.getEndNode())==null){ + this.edges.add(edge); + /* + * Information to GraphObservers. + */ + for (GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeAdded(edge.getStartNode().getId(), + edge.getEndNode().getId()); + } + } + } + + + /** + * Remove an {@link Edge} from {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @throws IllegalArgumentException if startNode or endNode is equal or smaller than 0 + * @throws NoSuchElementException if the edge, startNode or endNode not exist on the observable graph + */ + public void removeEdge(int startNode,int endNode) + throws IllegalArgumentException, NoSuchElementException{ + if ((startNode<=0)||(endNode<=0)){ + throw new IllegalArgumentException(); + } + else if((this.getNode(startNode)==null)||(this.getNode(endNode)==null)|| + (this.getEdge(startNode, endNode)==null)){ + throw new NoSuchElementException(); + } + this.edges.remove(this.getEdge(startNode, endNode)); + /* + * Information to GraphObservers. + */ + for(GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeRemoved(startNode, endNode); + } + } + + + /** + * Remove an {@link Edge} from {@link ObservableGraph}. + * @param startNode the start node of the edge + * @param endNode the end node of the edge + * @throws NullPointerException if startNode or endNode is null + * @throws NoSuchElementException if the edge, startNode or endNode not exist on the observable graph + */ + public void removeEdge(Node startNode,Node endNode) + throws NullPointerException, NoSuchElementException{ + if(((startNode==null)||(endNode==null))){ + throw new NullPointerException(); + } + else if (((!(this.nodes.contains(startNode)))|| + ((!(this.nodes.contains(endNode)))))|| + (this.getEdge(startNode, endNode)==null)){ + throw new NoSuchElementException(); + } + this.edges.remove(this.getEdge(startNode, endNode)); + /* + * Information to GraphObservers + */ + for(GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeRemoved(startNode.getId(), endNode.getId()); + } + } + + + /** + * Remove an {@link Edge} from {@link ObservableGraph}. + * @param edge an edge which will be removed + * @throws NullPointerException if edge is null + * @throws NoSuchElementException if edge , the start node or the end node not exist on the observable graph + */ + public void removeEdge(Edge edge)throws NullPointerException, NoSuchElementException{ + if ((edge==null)){ + throw new NullPointerException(); + } + else if (((!(this.nodes.contains(edge.getStartNode())))|| + ((!(this.nodes.contains(edge.getEndNode())))))|| + (!(this.edges.contains(edge)))){ + throw new NoSuchElementException(); + } + this.edges.remove(edge); + /* + * Information to GraphObservers. + */ + for(GraphObserver graphObserver:this.graphObservers){ + graphObserver.onEdgeRemoved(edge.getStartNode().getId(), + edge.getEndNode().getId()); + } + } + + + /** + * Load the structure of {@link ObservableGraph}. + * @param list a list which contain a collection of node and a collection of edge + * @throws NullPointerException if list is null + */ + @SuppressWarnings("unchecked") + public void loadGraph(List list) + throws NullPointerException{ + if (list == null){ + throw new NullPointerException(); + } + + for (int i = 1; i<=this.highestNodeId;i++){ + this.removeNode(i); + } + + Collection nodes= (Collection)list.get(0); + Collection edges= (Collection)list.get(1); + + /* + * Add the nodes. + */ + for (Node node : nodes){ + this.addNode(node); + } + /* + * Add the edges. + */ + for (Edge edge : edges){ + this.addEdge(edge); + } + } + + + /** + * @return next free node identifier + */ + public int getNextNodeId(){ + return this.highestNodeId +1; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/graph/package.html b/src/org/jalgo/module/bfsdfs/graph/package.html new file mode 100644 index 0000000..01467d3 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/graph/package.html @@ -0,0 +1,10 @@ + + + + +

          The graph package provide the class ObservableGraph, the graph which BFS / DFS algorithm works on. +It also contains the class AlgoGraph, with represents the result tree for the BFS / DFS algorithm. +The both graph are observable. The observer interface for the class ObservableGraph is GraphObserver and +for the class AlgoGraph AlgoGraphObserver. Class Node and Class Edge represents the basic datatyps of the both graph.

          + + \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.java b/src/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.java new file mode 100644 index 0000000..aaa6c0d --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/AddNodeAnimation.java @@ -0,0 +1,93 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.components.NodeStackView; + +/** + * This class is used to animate nodes that were recently added to the stack in + * {@linkplain NodeStackView}.
          + * The animation fades in the nodes in a certain time specified in + * {@linkplain GUIConstants#NODE_ANIMATION_TIME}.
          + * It handles an own thread which calculates the appropriate alpha value of the + * nodes. + * @author Florian Dornbusch + */ +public class AddNodeAnimation implements GUIConstants, Runnable { + + /** The used thread. */ + private Thread animation = null; + + /** The start time of the animation */ + private long time; + + /** The current time of the animation */ + private long currentTime; + + /** + * The used instance of {@linkplain NodeStackView} which started the + * animation. + */ + private NodeStackView n; + + /** + * Constructor. Stores the used instance of {@linkplain NodeStackView} + * which started the animation to send information when the animation + * stops. + * @author Florian Dornbusch + */ + public AddNodeAnimation(NodeStackView n) { + this.n=n; + } + + /** + * Starts the animation. Also sets the current time and start time. + * @author Florian Dornbusch + */ + public void start() { + if ( animation == null ) { + animation = new Thread( this ); + animation.start(); + time = Calendar.getInstance().getTimeInMillis(); + currentTime = time; + } + } + + /** + * Stops the animation. Also removes the recently added nodes from the + * list in {@linkplain NodeStackView}. + * @author Florian Dornbusch + */ + public void stop() { + if ( animation != null && animation.isAlive() ) + animation.interrupt(); + animation = null; + n.clearAddedNodes(); + } + + /** + * Runs the animation. Calculates the alpha value according to the + * percentage of time passed and repaints the {@linkplain NodeStackView}. + * @author Florian Dornbusch + */ + public void run() { + int alpha = 0; + n.setAlphaAdd(0); + n.repaint(); + while(currentTime-time<=NODE_ANIMATION_TIME && animation != null) { + try {Thread.sleep(ANIMATION_REPAINT_DELAY);} + catch (InterruptedException e) {} + double a = (double)(currentTime-time); + double b = (double)NODE_ANIMATION_TIME; + double factor = a / b; + alpha = (int)(ALPHA_100_PERCENT * factor); + n.setAlphaAdd(alpha); + n.repaint(); + currentTime = Calendar.getInstance().getTimeInMillis(); + while(currentTime == Calendar.getInstance().getTimeInMillis()); + } + n.setAlphaAdd(ALPHA_100_PERCENT); + n.repaint(); + stop(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/CVS/Entries b/src/org/jalgo/module/bfsdfs/gui/CVS/Entries new file mode 100644 index 0000000..40c6754 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/CVS/Entries @@ -0,0 +1,15 @@ +/AddNodeAnimation.java/1.1/Wed Dec 8 13:47:54 2010// +/ComponentUtility.java/1.1/Wed Dec 8 13:47:54 2010// +/GUIConstants.java/1.1/Wed Dec 8 13:47:54 2010// +/GUIController.java/1.1/Wed Dec 8 13:47:54 2010// +/GUITest.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphAnimations.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphCalculation.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphDrawing.java/1.1/Wed Dec 8 13:47:54 2010// +/PlayAnimation.java/1.1/Wed Dec 8 13:47:54 2010// +/RemoveNodeAnimation.java/1.1/Wed Dec 8 13:47:54 2010// +/StatusMouseAdapter.java/1.1/Wed Dec 8 13:47:54 2010// +D/components//// +D/event//// +D/graphview//// +/package.html/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/gui/CVS/Repository b/src/org/jalgo/module/bfsdfs/gui/CVS/Repository new file mode 100644 index 0000000..59e48e5 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/gui diff --git a/src/org/jalgo/module/bfsdfs/gui/CVS/Root b/src/org/jalgo/module/bfsdfs/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/gui/ComponentUtility.java b/src/org/jalgo/module/bfsdfs/gui/ComponentUtility.java new file mode 100644 index 0000000..eb42e53 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/ComponentUtility.java @@ -0,0 +1,130 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Point; + +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JToggleButton; + +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; + +/** + * abstract class that contains methods which are used in multiple GUI classes. + * @author Florian Dornbusch + */ +public abstract class ComponentUtility implements GUIConstants { + + /** if true, changes all attributes from normal sizes and fonts to bigger + * beamer mode sizes and fonts. + */ + public static boolean BEAMER_MODE = false; + + /** + * Draws a node at certain coordinates. A node is a circle with a border + * and a label inside. Uses {@linkplain GraphDrawing} utility method. + * @param g the used Graphics + * @param x x-coordinate of the node + * @param y y-coordinate of the node + * @param label the label that is drawn on the node + * @param status the NodeStatus which decides how the node is drawn + * @param nodeSize determines how large the node is. this value is twice + * the radius of the node + * @param nodeBorderSize the size of the border in pixel + * @param font the used font + * @param alpha the used alpha value that determines the transparency + * @author Florian Dornbusch + * @author Anselm Schmidt + */ + public static void drawNode(Graphics g, int x, int y, + int label, NodeStatus status, int nodeSize, + int nodeBorderSize, Font font, int alpha) { + Color topColor = NODE_COLOR_TOP; + Color bottomColor = NODE_COLOR_BOTTOM; + Color labelColor = NODE_LABEL_COLOR; + + switch(status) { + case UNTOUCHED: + topColor = NODE_COLOR_UNTOUCHED_TOP; + bottomColor = NODE_COLOR_UNTOUCHED_BOTTOM; + break; + + case WAITING: + topColor = NODE_COLOR_WAITING_TOP; + bottomColor = NODE_COLOR_WAITING_BOTTOM; + break; + + case FINISHED: + topColor = NODE_COLOR_FINISHED_TOP; + bottomColor = NODE_COLOR_FINISHED_BOTTOM; + labelColor = NODE_LABEL_COLOR_FINISHED; + break; + } + + int radius = (int) Math.round((double) nodeSize / 2); + + GraphDrawing.drawNode(g, Integer.toString(label), + new Point(x + radius, y + radius), + font, nodeSize, nodeBorderSize, + NODE_BORDER_COLOR, labelColor, topColor, + bottomColor, alpha, NODE_GRADIENT_HEIGHT); + } + + + /** + * Utility method to create a {@linkplain JToolbarButton}. + * @param a The action for this button. + * @return The created Button. + * @author Florian Dornbusch + */ + public static JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton( + (Icon)a.getValue(Action.SMALL_ICON), + null, null); + button.setAction(a); + button.setText(""); + button.setFocusable(false); + String status = button.getAction().getClass().getSimpleName() + +".tooltip"; + button.addMouseListener(new StatusMouseAdapter(status)); + return button; + } + + /** + * Utility method to create a {@linkplain JButton}. + * @param a The action for this button. + * @return The created Button. + * @author Florian Dornbusch + */ + public static JButton createButton(Action a) { + JButton button = new JButton(); + button.setAction(a); + button.setText(""); + button.setFocusable(false); + String status = button.getAction().getClass().getSimpleName() + +".tooltip"; + button.addMouseListener(new StatusMouseAdapter(status)); + return button; + } + + + /** + * Utility method to create a {@linkplain JToggleButton}. + * @param a The action for this button. + * @return The created Button. + * @author Florian Dornbusch + */ + public static JToggleButton createToolbarToggleButton(Action a) { + JToggleButton button = new JToggleButton(); + button.setAction(a); + button.setText(""); + button.setFocusable(false); + String status = button.getAction().getClass().getSimpleName()+".tooltip"; + button.addMouseListener(new StatusMouseAdapter(status)); + return button; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/GUIConstants.java b/src/org/jalgo/module/bfsdfs/gui/GUIConstants.java new file mode 100644 index 0000000..ae08a7e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GUIConstants.java @@ -0,0 +1,215 @@ +package org.jalgo.module.bfsdfs.gui; +import java.awt.Color; +import java.awt.Font; + +/** + * The interface GUIConstants is a collection of several constant + * values used by various GUI classes. + * + * @author Anselm Schmidt + * @author Florian Dornbusch + */ +public interface GUIConstants { + /*------------------------------colors----------------------------*/ + /** The background color of the welcome screen. */ + public static final Color WELCOME_SCREEN_BACKGROUND = + new Color(51, 102, 153); + /** The background color of the graph view. */ + public static final Color GRAPH_VIEW_BACKGROUND = Color.white; + + /** The standard color of a node. */ + public static final Color NODE_COLOR = Color.white; + /** The color of the node cursor. */ + public static final Color NODE_CURSOR_COLOR = new Color(192, 37, 0); + /** The color at the top of a node. */ + public static final Color NODE_COLOR_TOP = new Color(255, 255, 255); + /** The color at the bottom of a node. */ + public static final Color NODE_COLOR_BOTTOM = new Color(218, 221, 225); + /** The color at the top of a waiting node. */ + public static final Color NODE_COLOR_WAITING_TOP = + new Color(150, 180, 226); + /** The color at the bottom of a waiting node. */ + public static final Color NODE_COLOR_WAITING_BOTTOM = + new Color(78, 136, 202); + /** The color at the top of a finished node. */ + public static final Color NODE_COLOR_FINISHED_TOP = new Color(27, 56, 89); + /** The color at the bottom of a finished node. */ + public static final Color NODE_COLOR_FINISHED_BOTTOM = Color.black; + + /** The color of a node icon. */ + public static final Color NODE_ICON_COLOR = Color.white; + /** The border color of a node. */ + public static final Color NODE_BORDER_COLOR = new Color(50,57,62); + /** The border color of a focused node in erase mode. */ + public static final Color NODE_BORDER_COLOR_FOCUSED = + new Color(192, 37, 0); + /** The border color of a node icon. */ + public static final Color NODE_ICON_BORDER_COLOR = Color.black; + + /** The label color of a node. */ + public static final Color NODE_LABEL_COLOR = Color.black; + /** The label color of a focused node in erase mode. */ + public static final Color NODE_LABEL_COLOR_FOCUSED = + NODE_BORDER_COLOR_FOCUSED; + /** The label color of a finished node. */ + public static final Color NODE_LABEL_COLOR_FINISHED = Color.white; + /** The label color of a node icon. */ + public static final Color NODE_ICON_LABEL_COLOR = Color.black; + + /** The color of the node distance. */ + public static final Color NODE_DISTANCE_COLOR = new Color(192, 37, 0); + + /** The color at the top of an untouched node. */ + public static final Color NODE_COLOR_UNTOUCHED_TOP = NODE_COLOR_TOP; + /** The color at the bottom of a untouched node. */ + public static final Color NODE_COLOR_UNTOUCHED_BOTTOM = NODE_COLOR_BOTTOM; + /** The border color of an untouched node. */ + public static final Color NODE_UNTOUCHED_BORDER_COLOR = + new Color(31, 34, 35); + /** The border color of a waiting node. */ + public static final Color NODE_WAITING_BORDER_COLOR = + NODE_COLOR_FINISHED_TOP; + /** The border color of a finished node. */ + public static final Color NODE_FINISHED_BORDER_COLOR = + new Color(0, 0, 0); + /** The label color of a untouched node. */ + public static final Color NODE_LABEL_COLOR_UNTOUCHED = + NODE_UNTOUCHED_BORDER_COLOR; + /** The label color of a waiting node. */ + public static final Color NODE_LABEL_COLOR_WAITING = Color.black; + + /** The color of an edge. */ + public static final Color EDGE_COLOR = new Color(0, 0, 0); + /** The color of a focused edge. */ + public static final Color EDGE_COLOR_FOCUSED = new Color(192, 37, 0); + + /** The color of the NodeStackView background. */ + public static final Color NODESTACKVIEW_BACKGROUND_COLOR = Color.white; + /** The top color of the highlighted first column in NodeStackView. */ + public static final Color NODESTACKVIEW_OWNER_COLOR_LEFT = + new Color(114,118,146); + /** The bottom color of the highlighted first column in NodeStackView. */ + public static final Color NODESTACKVIEW_OWNER_COLOR_RIGHT = + new Color(30,31,38); + + /*------------------------------alpha values----------------------*/ + /** The alpha value of a temporary element. */ + public static final int TEMP_ALPHA_VALUE = 100; + /** The alpha value of the white rectangle the TreeView uses to paint + * on top of the graph. */ + public static final int TREEVIEW_ALPHA_VALUE = 180; + /** The alpha value of the white rectangle for a disabled interactive + * GraphView. */ + public static final int GRAPHVIEW_ALPHA_VALUE = 180; + /** 100% alpha value. */ + public static final int ALPHA_100_PERCENT = 255; + + /*------------------------------fonts-----------------------------*/ + /** The standard font family. */ + public static final String FONT_NAME = "Verdana"; + /** The standard writing font. */ + public static final Font WRITING_FONT = new Font(FONT_NAME, Font.BOLD, 12); + /** The beamer writing font. */ + public static final Font BEAMER_WRITING_FONT = + new Font(FONT_NAME, Font.BOLD, 15); + /** The font of the text in a node. */ + public static final Font NODE_FONT = new Font(FONT_NAME, Font.BOLD, 18); + /** The beamer font of the text in a node. */ + public static final Font NODE_BEAMER_FONT = + new Font(FONT_NAME, Font.BOLD, 30); + /** The font of the text in a node icon. */ + public static final Font NODE_ICON_FONT = + new Font(FONT_NAME, Font.BOLD, 18); + /** The beamer font of the text in a node icon. */ + public static final Font NODE_BEAMER_ICON_FONT = + new Font(FONT_NAME, Font.BOLD, 20); + /** The font for the node distance in a TreeView. */ + public static final Font NODE_DISTANCE_FONT = + new Font(FONT_NAME, Font.BOLD, 14); + /** The font for the node distance in a TreeView. */ + public static final Font NODE_BEAMER_DISTANCE_FONT = + new Font(FONT_NAME, 0, 20); + /** The font for the node distance in a TreeView. */ + + /*--------------------------constant sizes------------------------*/ + /** The maximal row count of the start node chooser in + * AlgoTab. */ + public static final Integer MAX_ROW_COUNT = 5; + + /** The number of pixel scrolled in SuccessorChooser. */ + public static final Integer SCROLL_FACTOR = 7; + + /** The diameter of a node. */ + public static final Integer NODE_SIZE = 30; + /** The diameter of a beamer node. */ + public static final Integer NODE_BEAMER_SIZE = 50; + /** The diameter of a node icon. */ + public static final Integer NODE_ICON_SIZE = 30; + /** The diameter of a beamer node icon. */ + public static final Integer NODE_BEAMER_ICON_SIZE = 36; + /** The size of a node border. */ + public static final Integer NODE_BORDER_SIZE = 2; + /** The size of a beamer node border. */ + public static final Integer NODE_BEAMER_BORDER_SIZE = 3; + /** The size of a node icon border. */ + public static final Integer NODE_ICON_BORDER_SIZE = 2; + /** The size of a beamer node icon border. */ + public static final Integer NODE_BEAMER_ICON_BORDER_SIZE = 2; + /** The height of the color gradient at the top of the inner circle of + * a node. */ + public static final Integer NODE_GRADIENT_HEIGHT = 25; + + /** [size of the node cursor] = + * [size of a node] * NODE_CURSOR_SCALE_FACTOR*/ + public static final float NODE_CURSOR_SCALE_FACTOR = 1.2f; + + /** The width of an edge. */ + public static final Integer EDGE_WIDTH = 4; + /** The width of an edge arrow. */ + public static final Integer EDGE_ARROW_WIDTH = 12; + /** The length of an edge arrow. */ + public static final Integer EDGE_ARROW_LENGTH = 15; + /** The diameter of an edge circle. */ + public static final Integer EDGE_CIRCLE_SIZE = 60; + /** The width of the boundaries of an edge. */ + public static final Integer EDGE_BOUNDARIES = 20; + /** The width of a tree edge. */ + public static final int EDGE_TREE_WIDTH = 5; + /** The percentage of the tree edges to be clipped on each side + * (1 is 100%). */ + public static final double EDGE_TREE_CLIPPING = 0.2; + /** The maximum clipping size of the tree edges on each side */ + public static final int EDGE_TREE_MAXCLIP = 25; + /** The width of a tree edge arrow. */ + public static final Integer EDGE_TREE_ARROW_WIDTH = 7; + /** The length of a tree edge arrow. */ + public static final Integer EDGE_TREE_ARROW_LENGTH = 15; + + + /** A big space between nodes. */ + public static final Integer SPACE_BIG = 30; + /** A small space between nodes. */ + public static final Integer SPACE_SMALL = 5; + + /** The number of successors in the NodeStackView. */ + public static final Integer NODESTACKVIEW_NUMBER_SUCCESSORS = 5; + + /** The width of the accessible graph area. */ + public static final Integer MAX_GRAPH_WIDTH = 2000; + /** The height of the accessible graph area. */ + public static final Integer MAX_GRAPH_HEIGHT = 1000; + + /*--------------------------animation times-----------------------*/ + /** The animation speed of playing the algorithm in milliseconds. */ + public static final Integer PLAY_ANIMATION = 1500; + /** The duration of a tree edge animation in milliseconds. */ + public static final Integer EDGE_ANIMATION = 500; + /** The duration of a tree node animation in milliseconds. */ + public static final Integer NODE_ANIMATION_TIME = 1000; + /** The duration of the node cursor's blinking animation in milliseconds.*/ + public static final Integer NODE_CURSOR_ANIMATION_TIME = 2000; + /** The duration of the node cursor's hiding animation in milliseconds. */ + public static final Integer NODE_CURSOR_HIDING_ANIMATION_TIME = 500; + /** The repaint delay during animations in milliseconds. */ + public static final Integer ANIMATION_REPAINT_DELAY = 30; +} diff --git a/src/org/jalgo/module/bfsdfs/gui/GUIController.java b/src/org/jalgo/module/bfsdfs/gui/GUIController.java new file mode 100644 index 0000000..6c020e0 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GUIController.java @@ -0,0 +1,1324 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.Point; +import java.awt.event.KeyEvent; +import java.io.IOException; +import java.util.List; + +import javax.swing.AbstractAction; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JToggleButton; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.JAlgoWindow; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.ModuleConnector; +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.algorithms.BFS; +import org.jalgo.module.bfsdfs.algorithms.DFS; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.algorithms.stack.StackObserver; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.graph.AlgoGraphObserver; +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.gui.components.AlgoTab; +import org.jalgo.module.bfsdfs.gui.components.BFSTab; +import org.jalgo.module.bfsdfs.gui.components.DFSTab; +import org.jalgo.module.bfsdfs.gui.components.DesignTab; +import org.jalgo.module.bfsdfs.gui.components.TabContainer; +import org.jalgo.module.bfsdfs.gui.components.WelcomeScreen; +import org.jalgo.module.bfsdfs.gui.event.AnimationAction; +import org.jalgo.module.bfsdfs.gui.event.CancelAction; +import org.jalgo.module.bfsdfs.gui.event.DoubleEdgeAction; +import org.jalgo.module.bfsdfs.gui.event.EdgeAction; +import org.jalgo.module.bfsdfs.gui.event.EraserAction; +import org.jalgo.module.bfsdfs.gui.event.NodeAction; +import org.jalgo.module.bfsdfs.gui.event.PlayAction; +import org.jalgo.module.bfsdfs.gui.event.RedoAction; +import org.jalgo.module.bfsdfs.gui.event.ResetAction; +import org.jalgo.module.bfsdfs.gui.event.StepBackAction; +import org.jalgo.module.bfsdfs.gui.event.StepForwardAction; +import org.jalgo.module.bfsdfs.gui.event.UndoAction; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; +import org.jalgo.module.bfsdfs.gui.graphview.InteractiveGraphView; +import org.jalgo.module.bfsdfs.undo.UndoableObserver; + +/** + * The GUIController manages all visualization e.g. the + * {@linkplain WelcomeScreen}, the three tabs {@linkplain DesignTab}, + * {@linkplain BFSTab} and {@linkplain DFSTab}, the toolbar and the + * {@linkplain InteractiveGraphView} and sends actions to the current + * {@linkplain Algo}, the {@linkplain GraphController} and the + * {@linkplain ModuleConnector}. + * It owns one algorithm at a time and can switch between them when a new + * window is selected by the user. + * @author Florian Dornbusch + */ +public class GUIController implements GUIConstants { + + // general references + private ModuleConnector connector; + private GraphController controller; + private Algo algo = null; + private BFS bfs; + private DFS dfs; + private WelcomeScreen welcomeScreen; + private TabContainer tabContainer; + private DesignTab designTab; + private BFSTab bfsTab; + private DFSTab dfsTab; + private InteractiveGraphView graphView; + private EditMode graphViewEditMode = EditMode.PUT_NODE; + + // actions + private AbstractAction animationToggleAction; + private AbstractAction resetAction; + private AbstractAction stepBackAction; + private AbstractAction stepForwardAction; + private AbstractAction playAction; + private AbstractAction cancelAction; + private AbstractAction undoAction; + private AbstractAction redoAction; + private AbstractAction nodeAction; + private AbstractAction edgeAction; + private AbstractAction doubleEdgeAction; + private AbstractAction eraserAction; + + // components + private JPanel contentPane; + private JComponent rootPane; + + // all toolbar items that are further used + private JToggleButton nodeButton; + private JToggleButton edgeButton; + private JToggleButton doubleEdgeButton; + private JToggleButton eraserButton; + private JLabel animationLabel; + private JCheckBox animationBox; + + // saved states for enabling the tool bar buttons + private boolean design = true; + private boolean designUndo = false; + private boolean designRedo = false; + private boolean bfsReset = false; + private boolean bfsStepBack = false; + private boolean bfsStepForward = true; + private boolean bfsPlay = true; + private boolean bfsCancel = false; + private boolean dfsReset = false; + private boolean dfsStepBack = false; + private boolean dfsStepForward = true; + private boolean dfsPlay = true; + private boolean dfsCancel = false; + + /** The saved center position of the viewport in all three tabs. */ + private Point graphViewPosition; + + /** The used animation for playing the algorithm. */ + private PlayAnimation bfsAnimation, dfsAnimation; + + /** The current frame state if not in beamer mode. */ + private int frameState = Frame.NORMAL; + + /** + * Constructor. Initializes the inner class observers, the + * contentPane, the {@linkplain WelcomeScreen}, the + * {@linkplain TabContainer}, the animations and the + * {@linkplain InteractiveGraphView}. + * Installs the tool bar and creates shortcuts. + * @author Florian Dornbusch + */ + public GUIController(ModuleConnector connector, BFS bfs, DFS dfs, + GraphController controller) { + this.connector = connector; + this.bfs = bfs; + this.dfs = dfs; + this.controller = controller; + + // install the main panel + rootPane = + JAlgoGUIConnector.getInstance().getModuleComponent(connector); + rootPane.setLayout(new BorderLayout()); + contentPane = new JPanel(); + rootPane.add(contentPane, BorderLayout.CENTER); + + // install the toolbar + installToolbar(); + + // create the tab container + tabContainer = new TabContainer(this, bfs, dfs, this.controller); + designTab = tabContainer.getDesignTab(); + bfsTab = tabContainer.getBFSTab(); + dfsTab = tabContainer.getDFSTab(); + graphView = designTab.getGraphView(); + + // create the animations + bfsAnimation = new PlayAnimation(bfsTab.getNodeStackView(), bfs); + dfsAnimation = new PlayAnimation(dfsTab.getNodeStackView(), dfs); + + // internal classes that are used to observe other parts of the program + new MyBFSObserver(); + new MyDFSObserver(); + new MyGraphObserver(); + + welcomeScreen = new WelcomeScreen(this); + + // create the shortcuts + createShortcuts(); + } + + + /** + * Loads the graph from the specified file. + * @param filename full name of the file containing the graph + * @author Thomas Görres + */ + public void loadGraph(String filename) throws IOException { + ModuleConnector.loadFromFile(filename); + } + + + /** + * Loads the graph from the last loaded file. + * @author Thomas Görres + */ + public void loadLastGraph() throws IOException { + ModuleConnector.loadFromLastFile(); + } + + + /** + * Returns the used {@linkplain ResetAction}. + * @author Florian Dornbusch + */ + public AbstractAction getResetAction() { + return resetAction; + } + + + /** + * Returns the used {@linkplain StepBackAction}. + * @author Florian Dornbusch + */ + public AbstractAction getStepBackAction() { + return stepBackAction; + } + + + /** + * Returns the used {@linkplain StepForwardAction}. + * @author Florian Dornbusch + */ + public AbstractAction getStepForwardAction() { + return stepForwardAction; + } + + + /** + * Returns the used {@linkplain PlayAction}. + * @author Florian Dornbusch + */ + public AbstractAction getPlayAction() { + return playAction; + } + + + /** + * Returns the used {@linkplain CancelAction}. + * @author Florian Dornbusch + */ + public AbstractAction getCancelAction() { + return cancelAction; + } + + + /** + * Returns the used {@linkplain UndoAction}. + * @author Florian Dornbusch + */ + public AbstractAction getUndoAction() { + return undoAction; + } + + + /** + * Returns the used {@linkplain RedoAction}. + * @author Florian Dornbusch + */ + public AbstractAction getRedoAction() { + return redoAction; + } + + + /** + * Returns the used {@linkplain NodeAction}. + * @author Florian Dornbusch + */ + public AbstractAction getNodeAction() { + return nodeAction; + } + + + /** + * Returns the used {@linkplain EdgeAction}. + * @author Florian Dornbusch + */ + public AbstractAction getEdgeAction() { + return edgeAction; + } + + + /** + * Returns the used {@linkplain DoubleEdgeAction}. + * @author Florian Dornbusch + */ + public AbstractAction getDoubleEdgeAction() { + return doubleEdgeAction; + } + + + /** + * Returns the used {@linkplain EraserAction}. + * @author Florian Dornbusch + */ + public AbstractAction getEraserAction() { + return eraserAction; + } + + + /** + * Shows the {@linkplain WelcomeScreen} and changes the + * {@linkplain SaveStatus} to NOTHING_TO_SAVE. + * @author Florian Dornbusch + */ + public void installWelcomeScreen() { + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(welcomeScreen, BorderLayout.CENTER); + welcomeScreen.setVisible(true); + connector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + } + + + /** + * Hides the {@linkplain WelcomeScreen} and switches to design mode. + * @author Florian Dornbusch + */ + public void installStandardLayout() { + contentPane.add(tabContainer, BorderLayout.CENTER); + welcomeScreen.setVisible(false); + graphView.addStartNode(); + animationToggleAction.setEnabled(true); + animationLabel.setEnabled(true); + switchToDesign(); + setGraphView(EditMode.PUT_NODE); + } + + + /** + * Shows the design buttons and hides the algorithm buttons. If the boolean + * values of the design buttons are false, at least one algorithm is + * currently running. If so, shows a window where the user can reset them. + * @author Florian Dornbusch + */ + public void switchToDesign() { + // stop possibly running animations + stopBFSAnimation(); + stopDFSAnimation(); + + // show the design buttons + undoAction.setEnabled(designUndo && design); + redoAction.setEnabled(designRedo && design); + nodeAction.setEnabled(design); + edgeAction.setEnabled(design); + doubleEdgeAction.setEnabled(design); + eraserAction.setEnabled(design); + + // hide the algorithm buttons + resetAction.setEnabled(false); + stepBackAction.setEnabled(false); + stepForwardAction.setEnabled(false); + playAction.setEnabled(false); + cancelAction.setEnabled(false); + + // activate the saved edit mode for the graph view + graphView.setEditMode(graphViewEditMode); + + // set animations to Design + animationBox.setActionCommand("Design"); + toggleAnimation(); + + // if the design buttons are disabled set the GraphView to algorithm + if(!design) { + setGraphView(EditMode.ALGORITHM); + + // show a warning window that an algorithm is running + Object[] options = { + Messages.getString("bfsdfs", "GUIController.warning_reset"), + Messages.getString("bfsdfs", "GUIController.warning_abort"), + }; + int n = JOptionPane.showOptionDialog( + rootPane, + Messages.getString("bfsdfs", "GUIController.warning_desc") + + System.getProperty("line.separator") + + System.getProperty("line.separator"), + Messages.getString("bfsdfs", "GUIController.warning"), + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + options, + options[1]); + + // if the user choice is to reset the algorithm + if(n == 0) { + // reset both algorithms + Algo temp = algo; + algo = bfs; + resetAlgo(); + algo = dfs; + resetAlgo(); + algo = temp; + switchToDesign(); + } + } + } + + + /** + * Changes the {@linkplain Algo} to {@linkplain DFS}, hides the design + * buttons and shows the algorithm buttons. + * @author Florian Dornbusch + */ + public void switchToDFS() { + // toggle algo to BFS + algo = dfs; + + // stop possibly running DFS animation + stopBFSAnimation(); + + // disable all design buttons + undoAction.setEnabled(false); + redoAction.setEnabled(false); + nodeAction.setEnabled(false); + edgeAction.setEnabled(false); + doubleEdgeAction.setEnabled(false); + eraserAction.setEnabled(false); + + // enable the algorithm buttons according to their boolean values + resetAction.setEnabled(dfsReset); + stepBackAction.setEnabled(dfsStepBack); + stepForwardAction.setEnabled(dfsStepForward + && !dfsTab.startNodeChooserEmpty()); + playAction.setEnabled(dfsPlay + && !bfsTab.startNodeChooserEmpty()); + cancelAction.setEnabled(dfsCancel); + + // set animations to DFS + animationBox.setActionCommand("DFS"); + toggleAnimation(); + } + + + /** + * Changes the {@linkplain Algo} to {@linkplain BFS}, hides the design + * buttons and shows the algorithm buttons. + * @author Florian Dornbusch + */ + public void switchToBFS() { + // toggle algo to BFS + algo = bfs; + + // stop possibly running DFS animation + stopDFSAnimation(); + + // disable all design buttons + undoAction.setEnabled(false); + redoAction.setEnabled(false); + nodeAction.setEnabled(false); + edgeAction.setEnabled(false); + doubleEdgeAction.setEnabled(false); + eraserAction.setEnabled(false); + + // enable the algorithm buttons according to their boolean values + resetAction.setEnabled(bfsReset); + stepBackAction.setEnabled(bfsStepBack); + stepForwardAction.setEnabled(bfsStepForward + && !bfsTab.startNodeChooserEmpty()); + playAction.setEnabled(bfsPlay + && !bfsTab.startNodeChooserEmpty()); + cancelAction.setEnabled(bfsCancel); + + // set animations to BFS + animationBox.setActionCommand("BFS"); + toggleAnimation(); + } + + + /** + * This method is called, if the user sets a new start node with the use + * of the start node chooser in an {@linkplain AlgoTab}.
          + * The current algorithm is informed about the new start node.
          + * If the algorithm is not yet chosen, which means the user has not yet + * changed the tabs, both algorithms are informed of the new start node. + * @param id the identifier of the node + * @author Florian Dornbusch + */ + public void setStartNode(int id) { + if(algo == null) { + bfs.setStartNode(id); + dfs.setStartNode(id); + } + else { + algo.setStartNode(id); + } + } + + + /** + * Sends the successor order to the current algorithm. + * @param list the successor order chosen in {@link SuccessorChooser}. + * @author Florian Dornbusch + */ + public void setSuccessorOrder(List list) { + if(list == null || list.isEmpty()) return; + if(algo == null) { + bfs.setSuccessorOrder(list); + dfs.setSuccessorOrder(list); + } + else { + algo.setSuccessorOrder(list); + } + } + + + /** + * Resets the current algorithm. + * @author Florian Dornbusch + */ + public void resetAlgo() { + AlgoTab tab; + if(algo instanceof BFS) tab = bfsTab; + else tab = dfsTab; + tab.getNodeStackView().stopAnimation(); + algo.undoAll(); + tab.getNodeStackView().clearStack(); + } + + + /** + * Undoes the last step in the algorithm. + * @author Florian Dornbusch + */ + public void previousAlgoStep() { + AlgoTab tab; + if(algo instanceof BFS) tab = bfsTab; + else tab = dfsTab; + tab.getNodeStackView().stopAnimation(); + algo.undo(); + tab.getNodeStackView().startAnimation(); + + stepForwardAction.setEnabled(true); + playAction.setEnabled(true); + if(algo instanceof BFS) { + bfsStepForward = true; + bfsPlay = true; + } + else { + dfsStepForward = true; + dfsPlay = true; + } + } + + + /** + * Executes the next step in the algorithm. If the check box, which + * determines if the algorithm is deterministic or not, is enabled, + * a random permutation of the possible successors is sent before + * the step is executed. + * @author Florian Dornbusch + */ + public void nextAlgoStep() { + AlgoTab tab; + if(algo instanceof BFS) tab = bfsTab; + else tab = dfsTab; + + tab.getNodeStackView().stopAnimation(); + algo.step(); + tab.getNodeStackView().startAnimation(); + + resetAction.setEnabled(true); + stepBackAction.setEnabled(true); + if(algo instanceof BFS) { + bfsReset = true; + bfsStepBack = true; + } + else { + dfsReset = true; + dfsStepBack = true; + } + } + + + /** + * Plays the current algorithm. + * @author Florian Dornbusch + */ + public void playAlgo() { + if(algo instanceof BFS) { + bfsAnimation.start(); + bfsReset = false; + bfsStepBack = false; + bfsStepForward = false; + bfsPlay = false; + bfsCancel = true; + } + else { + dfsAnimation.start(); + dfsReset = false; + dfsStepBack = false; + dfsStepForward = false; + dfsPlay = false; + dfsCancel = true; + } + resetAction.setEnabled(false); + stepBackAction.setEnabled(false); + stepForwardAction.setEnabled(false); + playAction.setEnabled(false); + cancelAction.setEnabled(true); + } + + + /** + * Cancels the current animation. + * @author Florian Dornbusch + */ + public void cancel() { + if(algo instanceof BFS) stopBFSAnimation(); + else stopDFSAnimation(); + } + + + /** + * Undoes the last step in the graph (e.g. adding a node). + * @author Florian Dornbusch + */ + public void undo() { + controller.undo(); + } + + + /** + * Redoes the last step in the graph (e.g. adding a node). + * @author Florian Dornbusch + */ + public void redo() { + controller.redo(); + } + + + /** + * Sets the {@linkplain InteractiveGraphView} to the according mode, + * saves the mode and toggles the appropriate buttons. + * @author Florian Dornbusch + */ + public void setGraphView(EditMode mode) { + graphViewEditMode = mode; + + nodeButton.setSelected(mode == EditMode.PUT_NODE); + edgeButton.setSelected(mode == EditMode.START_EDGE); + doubleEdgeButton.setSelected(mode == EditMode.START_DOUBLE_EDGE); + eraserButton.setSelected(mode == EditMode.ERASE); + designTab.switchTo(mode); + + if(mode == EditMode.ALGORITHM) { + graphViewEditMode = graphView.getEditMode(); + } + + graphView.setEditMode(mode); + } + + + /** + * Returns the saved position of the Viewport used in the + * JScrollPane in all three tabs. + * @author Florian Dornbusch + */ + public Point getGraphViewPosition() { + return graphViewPosition; + } + + + /** + * Saves the position of the Viewport used in the + * JScrollPane in all three tabs. + * @author Florian Dornbusch + */ + public void setGraphViewPosition(Point p) { + graphViewPosition = p; + } + + + /** + * Adds a {@linkplain StackObserver} to {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void addBFSStackObserver(StackObserver observer) { + bfs.addStackObserver(observer); + } + + + /** + * Removes a {@linkplain StackObserver} from {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void removeBFSStackObserver(StackObserver observer) { + bfs.removeStackObserver(observer); + } + + + /** + * Adds a {@linkplain StackObserver} to {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void addDFSStackObserver(StackObserver observer) { + dfs.addStackObserver(observer); + } + + + /** + * Removes a {@linkplain StackObserver} from {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void removeDFSStackObserver(StackObserver observer) { + dfs.removeStackObserver(observer); + } + + + /** + * Adds an {@linkplain UndoableObserver} to {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void addBFSUndoableObserver(UndoableObserver observer) { + bfs.addUndoableObserver(observer); + } + + + /** + * Removes an {@linkplain UndoableObserver} from {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void removeBFSUndoableObserver(UndoableObserver observer) { + bfs.removeUndoableObserver(observer); + } + + + /** + * Adds an {@linkplain UndoableObserver} to {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void addDFSUndoableObserver(UndoableObserver observer) { + dfs.addUndoableObserver(observer); + } + + + /** + * Removes an {@linkplain UndoableObserver} from {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void removeDFSUndoableObserver(UndoableObserver observer) { + dfs.removeUndoableObserver(observer); + } + + + /** + * Adds an {@linkplain AlgoGraphObserver} to {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void addBFSTreeObserver(AlgoGraphObserver observer) { + bfs.addTreeObserver(observer); + } + + + /** + * Removes an {@linkplain AlgoGraphObserver} from {@linkplain BFS}. + * @author Florian Dornbusch + */ + public void removeBFSTreeObserver(AlgoGraphObserver observer) { + bfs.removeTreeObserver(observer); + } + + + /** + * Adds an {@linkplain AlgoGraphObserver} to {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void addDFSTreeObserver(AlgoGraphObserver observer) { + dfs.addTreeObserver(observer); + } + + + /** + * Removes an {@linkplain AlgoGraphObserver} from {@linkplain DFS}. + * @author Florian Dornbusch + */ + public void removeDFSTreeObserver(AlgoGraphObserver observer) { + dfs.removeTreeObserver(observer); + } + + + /** + * Adds a {@linkplain GraphObserver} to the {@linkplain GraphController}. + * @author Florian Dornbusch + */ + public void addGraphObserver(GraphObserver observer) { + controller.addGraphObserver(observer); + } + + + /** + * Removes a {@linkplain GraphObserver} from the + * {@linkplain GraphController}. + * @author Florian Dornbusch + */ + public void removeGraphObserver(GraphObserver observer) { + controller.addGraphObserver(observer); + } + + + /** + * Adds an {@linkplain UndoableController} to the + * {@linkplain GraphController}. + * @author Florian Dornbusch + */ + public void addGraphUndoableObserver(UndoableObserver observer) { + controller.addUndoableObserver(observer); + } + + + /** + * Removes an {@linkplain UndoableController} from the + * {@linkplain GraphController}. + * @author Florian Dornbusch + */ + public void removeGraphUndoableObserver(UndoableObserver observer) { + controller.removeUndoableObserver(observer); + } + + + /** + * This method changes the content of all major components depending on + * {@linkplain ComponentUtility#BEAMER_MODE}. + * @author Florian Dornbusch + */ + public void toggleBeamerMode() { + // maximize / minimize window depending on beamer mode + Frame[] frames = JAlgoWindow.getFrames(); + // get the JAlgoWindow + for(Frame f:frames) { + if(f instanceof JAlgoWindow) { + if(ComponentUtility.BEAMER_MODE) { + // save state and then maximize + frameState = f.getExtendedState(); + f.setExtendedState(Frame.MAXIMIZED_BOTH); + } + else { + // load state + if(f.getExtendedState() == Frame.MAXIMIZED_BOTH)f.setExtendedState(frameState); + } + } + } + + if (tabContainer != null) + tabContainer.toggleBeamerMode(); + + if (bfsTab != null) { + bfsTab.toggleBeamerMode(); + bfsTab.getNodeStackView().toggleBeamerMode(); + } + + if (dfsTab != null) { + dfsTab.toggleBeamerMode(); + dfsTab.getNodeStackView().toggleBeamerMode(); + } + } + + + /** + * Enables or disables the main animation for the three tabs + * {@linkplain BFSTab}, {@linkplain DFSTab} and {@linkplain DesignTab}.
          + * If the checkbox "Animation" is selected, the animations for the + * three tabs are set according to their boolean values.
          + * Otherwise all animations are disabled. + * @author Ephraim Zimmer + */ + public void toggleAnimation() { + if (!animationBox.isSelected()){ + graphView.setAnimationsEnabled( + animationBox.getActionCommand().equals("Design")); + bfsTab.getTreeView().setAnimationsEnabled( + animationBox.getActionCommand().equals("BFS")); + dfsTab.getTreeView().setAnimationsEnabled( + animationBox.getActionCommand().equals("DFS")); + + bfsTab.getNodeStackView().setAnimationsEnabled(true); + dfsTab.getNodeStackView().setAnimationsEnabled(true); + } else { + graphView.setAnimationsEnabled(false); + bfsTab.getTreeView().setAnimationsEnabled(false); + dfsTab.getTreeView().setAnimationsEnabled(false); + + bfsTab.getNodeStackView().setAnimationsEnabled(false); + dfsTab.getNodeStackView().setAnimationsEnabled(false); + } + } + + + /** + * Inner class to observe the graph. + * @author Florian Dornbusch + */ + private class MyGraphObserver implements UndoableObserver { + + public MyGraphObserver() { + addGraphUndoableObserver(this); + } + + + /** + * If undo is enabled in the graph, the appropriate button + * is shown and the save status is updated. + * @author Florian Dornbusch + */ + public void onUndoEnabled() { + undoAction.setEnabled(true); + designUndo = true; + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + + + /** + * If undo is disabled in the graph, the appropriate button + * is hid and the save status is updated. + * @author Florian Dornbusch + */ + public void onUndoDisabled() { + undoAction.setEnabled(false); + designUndo = false; + connector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + } + + + /** + * If redo is enabled in the graph, the appropriate button + * is shown. + * @author Florian Dornbusch + */ + public void onRedoEnabled() { + redoAction.setEnabled(true); + designRedo = true; + } + + + /** + * If redo is disabled in the graph, the appropriate button is hid. + * @author Florian Dornbusch + */ + public void onRedoDisabled() { + redoAction.setEnabled(false); + designRedo = false; + } + } + + /** + * Inner class to observe the BFS algorithm. + * @author Florian Dornbusch + */ + private class MyBFSObserver implements UndoableObserver, StackObserver { + + public MyBFSObserver() { + addBFSUndoableObserver(this); + addBFSStackObserver(this); + } + + + /** + * If undo is disabled in the algorithm, the appropriate buttons + * are hid. + * @author Florian Dornbusch + */ + public void onUndoDisabled() { + resetAction.setEnabled(false); + stepBackAction.setEnabled(false); + stepForwardAction.setEnabled(true); + playAction.setEnabled(true); + bfsReset = false; + bfsStepBack = false; + bfsStepForward = true; + bfsPlay = true; + + design = !dfs.isUndoPossible(); + } + + + public void onUndoEnabled() { + design = false; + } + + + /** unused observer method */ + public void onRedoEnabled() {} + + + /** unused observer method */ + public void onRedoDisabled() {} + + + /** + * If the algorithm is finished, the appropriate buttons are hid. + * @author Florian Dornbusch + */ + public void onAllNodesFinished() { + bfsAnimation.stop(); + bfsReset = true; + bfsStepBack = true; + bfsStepForward = false; + bfsPlay = false; + bfsCancel = false; + resetAction.setEnabled(true); + stepBackAction.setEnabled(true); + stepForwardAction.setEnabled(false); + playAction.setEnabled(false); + cancelAction.setEnabled(false); + } + + + /** unused observer method */ + public void onStatusChanged(int node, NodeStatus newStatus) {} + + + /** unused observer method */ + public void onFirstQueueAdded(int owner) {} + + + /** unused observer method */ + public void onQueueAdded(int owner) {} + + + /** unused observer method */ + public void onNodesAdded(List nodes) {} + + + /** unused observer method */ + public void onUntouchedReplaced(List o, List n) {} + + + /** unused observer method */ + public void onTopQueueRemoved() {} + + + /** unused observer method */ + public void onAllQueuesRemoved() {} + + + /** unused observer method */ + public void onCurrentNodeChanged(int lastWaitingNode) {} + } + + + /** + * Inner class to observe the DFS algorithm. + * @author Florian Dornbusch + */ + private class MyDFSObserver implements UndoableObserver, StackObserver { + + public MyDFSObserver() { + addDFSUndoableObserver(this); + addDFSStackObserver(this); + } + + + /** + * If undo is disabled in the algorithm, the appropriate buttons + * are hid. + * @author Florian Dornbusch + */ + public void onUndoDisabled() { + resetAction.setEnabled(false); + stepBackAction.setEnabled(false); + stepForwardAction.setEnabled(true); + playAction.setEnabled(true); + dfsReset = false; + dfsStepBack = false; + dfsStepForward = true; + dfsPlay = true; + + design = !bfs.isUndoPossible(); + } + + + public void onUndoEnabled() { + design = false; + } + + + /** unused observer method */ + public void onRedoEnabled() {} + + + /** unused observer method */ + public void onRedoDisabled() {} + + + /** unused observer method */ + public void onAllNodesFinished() {} + + + /** unused observer method */ + public void onStatusChanged(int node, NodeStatus newStatus) {} + + + /** unused observer method */ + public void onFirstQueueAdded(int owner) {} + + + /** unused observer method */ + public void onQueueAdded(int owner) {} + + + /** unused observer method */ + public void onNodesAdded(List nodes) {} + + + /** unused observer method */ + public void onUntouchedReplaced(List o, List n) {} + + + /** unused observer method */ + public void onTopQueueRemoved() {} + + + /** + * If the algorithm is finished, the appropriate buttons are hid. + * @author Florian Dornbusch + */ + public void onAllQueuesRemoved() { + dfsAnimation.stop(); + dfsReset = true; + dfsStepBack = true; + dfsStepForward = false; + dfsPlay = false; + dfsCancel = false; + resetAction.setEnabled(true); + stepBackAction.setEnabled(true); + stepForwardAction.setEnabled(false); + playAction.setEnabled(false); + cancelAction.setEnabled(false);} + + + /** unused observer method */ + public void onCurrentNodeChanged(int lastWaitingNode) {} + } + + + /** + * Creates the buttons in the tool bar and saves all buttons, which are + * further used (either to toggle them or to set them as standard). + * @author Florian Dornbusch + */ + private void installToolbar() { + JToolBar toolBar = + JAlgoGUIConnector.getInstance().getModuleToolbar(connector); + + + resetAction = new ResetAction(this); + toolBar.add(ComponentUtility.createToolbarButton(resetAction)); + + stepBackAction = new StepBackAction(this); + toolBar.add(ComponentUtility.createToolbarButton(stepBackAction)); + + stepForwardAction = new StepForwardAction(this); + toolBar.add(ComponentUtility. + createToolbarButton(stepForwardAction)); + + playAction = new PlayAction(this); + toolBar.add(ComponentUtility.createToolbarButton(playAction)); + + cancelAction = new CancelAction(this); + toolBar.add(ComponentUtility.createToolbarButton(cancelAction)); + + toolBar.addSeparator(); + + undoAction = new UndoAction(this); + toolBar.add(ComponentUtility.createToolbarButton(undoAction)); + + redoAction = new RedoAction(this); + toolBar.add(ComponentUtility.createToolbarButton(redoAction)); + + nodeAction = new NodeAction(this); + nodeButton = ComponentUtility.createToolbarToggleButton(nodeAction); + nodeButton.setFocusable(false); + toolBar.add(nodeButton); + + edgeAction = new EdgeAction(this); + edgeButton = ComponentUtility.createToolbarToggleButton(edgeAction); + edgeButton.setFocusable(false); + toolBar.add(edgeButton); + + doubleEdgeAction = new DoubleEdgeAction(this); + doubleEdgeButton = ComponentUtility. + createToolbarToggleButton(doubleEdgeAction); + doubleEdgeButton.setFocusable(false); + toolBar.add(doubleEdgeButton); + + eraserAction = new EraserAction(this); + eraserButton = ComponentUtility. + createToolbarToggleButton(eraserAction); + eraserButton.setFocusable(false); + toolBar.add(eraserButton); + + toolBar.addSeparator(); + + animationToggleAction = new AnimationAction(this); + animationLabel = new JLabel(); + animationLabel.setText(Messages.getString("bfsdfs", + "animationLabel.text")); + animationLabel.setEnabled(false); + animationBox = new JCheckBox(animationToggleAction); + animationBox.addMouseListener(new StatusMouseAdapter( + "AnimationAction.tooltip")); + toolBar.add(animationLabel); + toolBar.add(animationBox); + } + + + /** + * Creates shortcuts for all important operations. + * @author Ephraim Zimmer + * @author Florian Dornbusch + */ + private void createShortcuts() { + // y for undo + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_Y, 0), "undo"); + contentPane.getActionMap().put("undo", undoAction); + + // x for redo + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_X, 0),"redo"); + contentPane.getActionMap().put("redo", redoAction); + + // q for node + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_Q, 0), "node"); + contentPane.getActionMap().put("node", nodeAction); + + // w for edge + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_W, 0), "edge"); + contentPane.getActionMap().put("edge", edgeAction); + + // e for double edge + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_E, 0), "doubleEdge"); + contentPane.getActionMap().put("doubleEdge", doubleEdgeAction); + + // r for eraser + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_R, 0), "eraser"); + contentPane.getActionMap().put("eraser", eraserAction); + + // a for reset + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_A, 0), "reset"); + contentPane.getActionMap().put("reset", resetAction); + + // s for step back + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_S, 0), "stepBack"); + contentPane.getActionMap().put("stepBack", stepBackAction); + + // d for step forward + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_D, 0), "stepForward"); + contentPane.getActionMap().put("stepForward", stepForwardAction); + + // f for play + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_F, 0), "play"); + contentPane.getActionMap().put("play", playAction); + + // c for cancel + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_C, 0), "cancel"); + contentPane.getActionMap().put("cancel", cancelAction); + + // b for beamer + contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). + put(KeyStroke.getKeyStroke( + KeyEvent.VK_B, 0), "beamer"); + contentPane.getActionMap().put("beamer", + tabContainer.getBeamerAction()); + } + + + /** + * Stops the current BFS Animation if it is running. + * @author Florian Dornbusch + */ + private void stopBFSAnimation() { + if(bfsAnimation.isRunning()) { + bfsAnimation.stop(); + bfsReset = true; + bfsStepBack = true; + bfsStepForward = true; + bfsPlay = true; + bfsCancel = false; + resetAction.setEnabled(true); + stepBackAction.setEnabled(true); + stepForwardAction.setEnabled(true); + playAction.setEnabled(true); + cancelAction.setEnabled(false); + } + } + + + /** + * Stops the current DFS Animation if it is running. + * @author Florian Dornbusch + */ + private void stopDFSAnimation() { + if(dfsAnimation.isRunning()) { + dfsAnimation.stop(); + dfsReset = true; + dfsStepBack = true; + dfsStepForward = true; + dfsPlay = true; + dfsCancel = false; + resetAction.setEnabled(true); + stepBackAction.setEnabled(true); + stepForwardAction.setEnabled(true); + playAction.setEnabled(true); + cancelAction.setEnabled(false); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/GUITest.java b/src/org/jalgo/module/bfsdfs/gui/GUITest.java new file mode 100644 index 0000000..ca318ea --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GUITest.java @@ -0,0 +1,72 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.util.Collection; + +import javax.swing.JOptionPane; + +import org.jalgo.module.bfsdfs.gui.graphview.VisualEdge; +import org.jalgo.module.bfsdfs.gui.graphview.VisualGraphElement; +import org.jalgo.module.bfsdfs.gui.graphview.VisualNode; + +/** + * Interface with GUI test methods. + * Can be removed later. + * @author Anselm Schmidt + * + */ +public abstract class GUITest { + /** + * Show a simple message box with a simple message. + * @param string Message to show. + * @author Anselm Schmidt + */ + public static void msgBox(String string) { + JOptionPane.showMessageDialog(null, string, "GUITest", JOptionPane.INFORMATION_MESSAGE); + } + + /** + * Write a line into System.out or System.err. + * @param string Text to write. + * @param err If it is True, + * the line will be written into System.err. + * Otherwise, it will be written into System.out. + * @author Anselm Schmidt + */ + public static void write(String string, boolean err) { + if(err) { + System.err.println(string); + } + else { + System.out.println(string); + } + } + + /** + * Write a collection of VisualGraphElement into System.out or + * System.err. + * @param collection Collection to write. + * @param err If it is True, + * the line will be written into System.err. + * Otherwise, it will be written into System.out. + * @author Anselm Schmidt + */ + public static void write(Collection collection, boolean err) { + for(VisualGraphElement element : collection) { + String string = ""; + + if(element instanceof VisualNode) { + string = ((VisualNode) element).toString(); + } + else if(element instanceof VisualEdge) { + string = ((VisualEdge) element).toString(); + } + + if(err) { + System.err.println(string); + } + else { + System.out.println(string); + } + } + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/GraphAnimations.java b/src/org/jalgo/module/bfsdfs/gui/GraphAnimations.java new file mode 100644 index 0000000..c0bceb4 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GraphAnimations.java @@ -0,0 +1,132 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.Point; + +/** + * Collection of helper methods to animate different graph elements. + * @author Anselm Schmidt + */ +public abstract class GraphAnimations { + /** + * Animate an edge. Get the size of the edge depending on the animation time. + * @param start Start point of the edge. + * @param end End point of the edge. + * @param clipping Size of the edge part which will be removed due to clipping. + * @param time The time since the animation started, in milliseconds. + * @param totalTime The length of the animation, in milliseconds. + * @return The new end point of the edge. + * @author Anselm Schmidt + */ + public static Point animateEdge(Point start, Point end, int clipping, long time, + long totalTime) { + if(time == 0) { + // no animation yet + return end; + } + + if(time > totalTime) { + // animation already finished + return end; + } + + // calculate animation length factor + double factor = (double) time / (double) totalTime; + + // calculate length of the edge + double length = Math.sqrt(GraphCalculation.calcPointPointDistSqr(start.x, + start.y, end.x, end.y)); + + // calculate edge length after clipping + double lengthAfterClipping = length - clipping; + + // change this length using the animation length factor + lengthAfterClipping = factor * lengthAfterClipping; + + // calculate unit vector of the edge + double unitX = (end.x - start.x) / length; + double unitY = (end.y - start.y) / length; + + // calculate new length + length = lengthAfterClipping + clipping; + + // calculate new end point + return new Point(start.x + (int) Math.round(unitX * length), start.y + (int) + Math.round(unitY * length)); + } + + /** + * Animate a node. Get the alpha value of the node depending on the animation time. + * @param alpha The full alpha value of the node. + * @param time The time since the animation started, in milliseconds. + * @param totalTime The length of the animation, in milliseconds. + * @return The new alpha value of the node. + * @author Anselm Schmidt + */ + public static int animateNode(int alpha, long time, long totalTime) { + if(time == 0) { + // no animation yet + return 0; + } + + if(time > totalTime) { + // animation already finished + return alpha; + } + + // calculate animation alpha factor + double factor = (double) time / (double) totalTime; + + // return the new alpha value + return (int) Math.round(factor * alpha); + } + + /** + * Animate the node cursor. Get the alpha value of the cursor depending on the time. + * Will use cosinus to perform a cyclic animation, so time can be as + * large as you want. + * @param alpha The full alpha value of the node cursor. + * Use GUIConstants.ALPHA_100_PERCENT as default value. + * @param time The time since the animation started. + * @param totalTime The time for one blinking animation cyclus. + * This includes one blending in and one blending out animation. + */ + public static int animateNodeCursor(int alpha, long time, long totalTime) { + if(time == 0) { + // no animation yet + return 0; + } + + // calculate animation factor by using cosinus + double factor = (-Math.cos((double) time / totalTime * 2 * Math.PI) + 1) / 2; + + // return the new alpha value + return (int) Math.round(factor * alpha); + } + + /** + * Hide an element. Get the alpha value of the element depending on the time. + * @param alpha The full alpha value of the node. + * @param time The time since the animation started, in milliseconds. + * @param totalTime The length of the animation, in milliseconds. + * @return The new alpha value of the node or 0, + * if totalTime is smaller than time. + * @author Anselm Schmidt + */ + public static int hide(int alpha, long time, long totalTime) { + if(time == 0) { + // no animation yet + return alpha; + } + + if(time >= totalTime) { + // animation already finished + return 0; + } + + // calculate animation alpha factor + double factor = (double) time / (double) totalTime; + + // return the new alpha value + return alpha - (int) Math.round(factor * alpha); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/GraphCalculation.java b/src/org/jalgo/module/bfsdfs/gui/GraphCalculation.java new file mode 100644 index 0000000..4dce04a --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GraphCalculation.java @@ -0,0 +1,194 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.geom.Rectangle2D; + +/** + * Collection of helper methods to solve different graph calculations. + * @author Anselm Schmidt + * + */ +public abstract class GraphCalculation { + /** + * Calculate the distance between the intersections of two circles. + * @param x1 X coordinate of the first circle center. + * @param y1 Y coordinate of the first circle center. + * @param r1 Radius of the first circle. + * @param x2 X coordinate of the second circle center. + * @param y2 Y coordinate of the second circle center. + * @param r2 Radius of the second circle. + * @author Anselm Schmidt + */ + public static double calcCircleCircleIntersecDist(double x1, double y1, + double r1, double x2, double y2, double r2) { + // calculate distance between circles + double dx = x2 - x1; + double dy = y2 - y1; + double d = Math.sqrt(dx * dx + dy * dy); + + // calculate distance between first circle center and intersections line + double a = (r1 * r1 - r2 * r2 + d * d) / (2 * d); + + // calculate distance between intersections + return 2 * Math.sqrt(r1 * r1 - a * a); + } + + /** + * Calculate the center point of a text. + * @param g Used Graphics instance. + * @param label Used text. + * @return Correct coordinates to write the text. + * @author Florian Dornbusch + */ + public static Point calcTextCenter(Graphics g, String label, Font font, + int size) { + Integer textHeight, textWidth, x, y; + Rectangle2D rect; + + FontMetrics fm = g.getFontMetrics(font); + rect = fm.getStringBounds(label, g); + textHeight = (int) (rect.getHeight()); + textWidth = (int) (rect.getWidth()); + x = (size - textWidth) / 2; + y = (size - textHeight) / 2 + fm.getAscent(); + + return new Point(x, y); + } + + /** + * Calculate the size of a text. + * @param g Used Graphics instance. + * @param label Used text. + * @return Correct coordinates to write the text. + * @author Florian Dornbusch + */ + public static int calcTextWidth(Graphics g, String label, Font font) { + Rectangle2D rect; + + FontMetrics fm = g.getFontMetrics(font); + rect = fm.getStringBounds(label, g); + + return (int) rect.getWidth(); + } + + /** + * Calculate the squared distance between two points + * + * @param x1 + * X coordinate of the first point. + * @param y1 + * Y coordinate of the first point. + * @param x2 + * Y coordinate of the second point. + * @param y2 + * Y coordinate of the second point. + * @result The squared distance between the two points. + * @author Anselm Schmidt + */ + public static double calcPointPointDistSqr(double x1, double y1, double x2, + double y2) { + // calculate distance vector + double distX = x2 - x1; + double distY = y2 - y1; + + // return size of the distance vector + return distX * distX + distY * distY; + } + + /** + * Calculate the squared distance between two points + * + * @param p1 First point. + * @param p2 Second point. + * @result The squared distance between the two points. + * @author Anselm Schmidt + */ + public static double calcPointPointDistSqr(Point p1, Point p2) { + return calcPointPointDistSqr(p1.x, p1.y, p2.x, p2.y); + } + + /** + * Calculate the squared distance between a point and a line. + * + * @param x1 + * The x coordinate of the first point on the line. + * @param y1 + * The y coordinate of the first point on the line. + * @param x2 + * The x coordinate of the second point on the line. + * @param y2 + * The y coordinate of the second point on the line. + * @param x3 + * The x coordinate of the point. + * @param y3 + * The y coordinate of the point. + * @result The squared distance between the specified point and the line. + * @author Anselm Schmidt + */ + public static double calcPointLineDistSqr(int x1, int y1, int x2, int y2, int x3, + int y3) { + // calculate the squared length of the line vector + double sqrLength = calcPointPointDistSqr(x1, y1, x2, y2); + + // calculate factor of the direction vector + double u = (double) ((x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1)) + / sqrLength; + + // calculate point of intersection of the tangent + double x = (double) x1 + u * (x2 - x1); + double y = (double) y1 + u * (y2 - y1); + + // calculate the distance from there to p3 + return calcPointPointDistSqr(x, y, x3, y3); + } + + /** + * Check, which part of a bidirectional edge has been hit by a mouse click. + * + * @param x1 + * The x coordinate of one end of the edge. + * @param y1 + * The y coordinate of one end of the edge. + * @param x2 + * The x coordinate of the other end of the edge. + * @param y2 + * The y coordinate of the other end of the edge. + * @param hit + * Position of the mouse click. + * @return 1, if the edge has been hit at the first end. + * 2, if the edge has been hit at the other end. + * 0 if the edge has been hit somewhere else. + * @author Anselm Schmidt + */ + public static short getBidirectionalEdgeHitArea(int x1, int y1, int x2, int y2, + Point hit, int arrowLength, int nodeSize) { + // calculate the squared distance between point and line + double sqrDistance = calcPointLineDistSqr(x1, y1, x2, y2, hit.x, hit.y); + + // calculate the squared distances between edge ends and hitting point + double sqrHitDist1 = calcPointPointDistSqr(x1, y1, hit.x, hit.y); + double sqrHitDist2 = calcPointPointDistSqr(x2, y2, hit.x, hit.y); + + // calculate the distances between edge ends and line hitting point + double dist1 = Math.sqrt(sqrHitDist1 - sqrDistance); + double dist2 = Math.sqrt(sqrHitDist2 - sqrDistance); + + // check the shortest distance + if (dist1 < dist2) { + if (dist1 < 2 * arrowLength + nodeSize / 2) { + // edge 1 has been hit + return 1; + } + } else { + if (dist2 < 2 * arrowLength + nodeSize / 2) { + // edge 2 has been hit + return 2; + } + } + + return 0; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/GraphDrawing.java b/src/org/jalgo/module/bfsdfs/gui/GraphDrawing.java new file mode 100644 index 0000000..c9df877 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/GraphDrawing.java @@ -0,0 +1,482 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Font; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Paint; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; + +/** + * Collection of helper methods to draw different graph elements. + * @author Anselm Schmidt + * + */ +public abstract class GraphDrawing { + /** + * Draw an arrowhead at the specified point with the specified direction. + * NOTE: The arrowhead direction vector has to be an unit vector. + * Color and alpha values have to be set already. + * @param g Used Graphics instance. + * @param position The position of the arrowhead. + * @param directionX The x coordinate of the arrowhead direction vector. + * @param directionY The y coordinate of the arrowhead direction vector. + * @param width The width of the arrowhead. + * Use GUIConstants.EDGE_WIDTH as default value. + * @param length The length of the arrowhead. + * Use GUIConstants.EDGE_LENGTH as default value. + * @param drawMiddle True, if the arrow middle has to be drawn, too. + * For example, if the arrow has another color than the rest of the edge. + * False, otherwise. NOTE: If alpha is lower than + * 255, it should be set to False to keep the right + * transparency. + * @author Anselm Schmidt + */ + private static void drawArrowhead(Graphics g, Point position, + double directionX, double directionY, int width, int length) { + // calculate vector with arrow length and direction + double lengthX = directionX * length; + double lengthY = directionY * length; + + // calculate position back from arrow end by arrow length + double backX = (double) position.x - lengthX; + double backY = (double) position.y - lengthY; + + // calculate right-handed normal by rotating the direction vector + double normalRightX = directionY; + double normalRightY = - directionX; + + // calculate left-handed normal by rotating the direction vector + double normalLeftX = - directionY; + double normalLeftY = directionX; + + // calculate right side point by sizing the right-handed normal + double rightX = backX + normalRightX * width; + double rightY = backY + normalRightY * width; + + // calculate left side point by sizing the right-handed normal + double leftX = backX + normalLeftX * width; + double leftY = backY + normalLeftY * width; + + // draw right side line of arrow + g.drawLine(position.x, position.y, (int) Math.round(rightX), + (int) Math.round(rightY)); + + // draw left side line of arrow + g.drawLine(position.x, position.y, (int) Math.round(leftX), + (int) Math.round(leftY)); + } + + /** + * Draw a clipped circle edge with one arrowhead. + * Circular clipping will be performed at the begin and end of the circle edge. + * If clippingRadius is set to 0, + * no clipping will be performed. + * The circle edge will always be drawn above the position. + * @param g Used Graphics instance. + * @param position Begin and end of the circle edge. + * @param lineWidth The line width of the circle edge. + * @param clippingRadius The radius of the clipping circle. + * @param color The color of the circle edge. + * @param arrowWidth The width of the arrowhead. + * Use GUIConstants.EDGE_WIDTH as default value. + * @param arrowLength The length of the arrowhead. + * Use GUIConstants.EDGE_LENGTH as default value. + * @param circleEdgeSize The diameter of the circle edge. + * Use GUIConstants.EDGE_CIRCLE_SIZE as default value. + * @param alpha Alpha value for drawing. + * Use 255 as default value. + * @author Anselm Schmidt + */ + private static void drawClippedCircleEdge(Graphics g, Point position, + int lineWidth, int clippingRadius, Color color, int arrowWidth, + int arrowLength, int circleEdgeSize, int alpha) { + if(alpha == 0) { + return; + } + + // set transparency + color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + + // calculate circle edge radius + int radius = (int) Math.round((float) circleEdgeSize / 2f); + + // calculate circle edge center + Point center = new Point(position.x, position.y - radius); + + // calculate distance between circle intersections + double intersectionDist = + GraphCalculation.calcCircleCircleIntersecDist(position.x, position.y, + clippingRadius, center.x, center.y, radius); + + // calculate angle between circle intersections, + // relative to circle edge center + double intersectionAngle = Math.acos(1 - + (intersectionDist * intersectionDist) / (2 * radius * radius)); + + // convert angle from radians to degrees and round it to int + int angle = (int) Math.round(Math.toDegrees(intersectionAngle)); + + // set color + g.setColor(color); + + // set line width + ((Graphics2D) g).setStroke(new BasicStroke(lineWidth)); + + // draw arc of circle edge + g.drawArc(center.x - radius, center.y - radius, circleEdgeSize, + circleEdgeSize, 270 + (int) Math.round((float) angle / 2f), 360 - + angle); + + // calculate arrowhead position, relative to circle edge center + Point arrowPos = new Point((int) Math.round(Math.sin(intersectionAngle / + 2d) * radius), (int) Math.round(Math.cos(intersectionAngle / 2d) * + radius)); + + // convert the arrowhead position vector into unit vector + double length = Math.sqrt(arrowPos.x * arrowPos.x + arrowPos.y * arrowPos.y); + double unitX = (double) arrowPos.x / length; + double unitY = (double) arrowPos.y / length; + + // create unit arrow direction vector by rotating this unit vector by alpha + double angleAlpha = Math.toRadians(70d); + double arrowDirX = unitX * Math.cos(angleAlpha) - unitY * + Math.sin(angleAlpha); + double arrowDirY = unitX * Math.sin(angleAlpha) + unitY * + Math.cos(angleAlpha); + + // draw arrowhead + drawArrowhead(g, new Point(center.x + arrowPos.x, center.y + arrowPos.y), + arrowDirX, arrowDirY, arrowWidth, arrowLength); + } + + /** + * Enable Anti-Aliasing for specified Graphics instance. + * @param g The used Graphics instance. + * @author Anselm Schmidt + */ + public static void enableAntiAliasing(Graphics g) { + ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + } + + /** + * Draw a node. + * @param g Used Graphics instance. + * @param label Text that will be shown in the center of the node. + * This should be the id of the node. + * If it is null, no label will be shown. + * @param position The position of the node. + * @param font The font that will be used for the text in the center of the node. + * Use GUIConstants.NODE_FONT as default value. + * @param size The diameter of the node. + * Use GUIConstants.NODE_SIZE as default value. + * @param borderSize The width of the node border. + * Use GUIConstants.NODE_BORDER_SIZE as default value. + * @param borderColor The color of the node border. + * Use GUIConstants.NODE_BORDER_COLOR as default value. + * @param labelColor The color of the text in the center of the node. + * Use GUIConstants.NODE_LABEL_COLOR as default value. + * @param topColor The background color at the top of the node. + * Use GUIConstants.NODE_COLOR_TOP as default value. + * @param bottomColor The background color at the bottom of the node. + * Use GUIConstants.NODE_COLOR_BOTTOM as default value. + * @param gradientHeight Height of the color gradient at the top of the inner circle + * Use GUIConstants.NODE_GRADIENT_HEIGHT as default value. + * @param alpha Alpha value for drawing. + * @param numberFont Used font for the number near the node. + * Will be ignored, if number is 0. + * @param numberColor Used color for the number near the node. + * Will be ignored, if number is 0. + * @param number Number to write near the node. + * Will be ignored, if it is 0. + * Integer.MAX_VALUE will be interpreted as infinite. + * @author Anselm Schmidt + */ + public static void drawNode(Graphics g, String label, Point position, + Font font, int size, int borderSize, Color borderColor, + Color labelColor, Color topColor, Color bottomColor, int alpha, + int gradientHeight, Font numberFont, Color numberColor, int number) { + if(alpha == 0) { + return; + } + + Graphics2D g2 = (Graphics2D) g; + + // set transparency + topColor = new Color(topColor.getRed(), topColor.getGreen(), topColor.getBlue(), + alpha); + bottomColor = new Color(bottomColor.getRed(), bottomColor.getGreen(), + bottomColor.getBlue(), alpha); + borderColor = new Color(borderColor.getRed(), borderColor.getGreen(), + borderColor.getBlue(), alpha); + if(labelColor != null) { + labelColor = new Color(labelColor.getRed(), labelColor.getGreen(), + labelColor.getBlue(), alpha); + } + if(numberColor != null) { + numberColor = new Color(numberColor.getRed(), numberColor.getGreen(), + numberColor.getBlue(), alpha); + } + + // calculate the node radius + int radius = (int) Math.round((float) size / 2f); + + // calculate the coordinates of the top left node rectangle corner + int topLeftX = position.x - radius; + int topLeftY = position.y - radius; + + // calculate inner circle attributes + int circleX = topLeftX + borderSize - 2; + int circleY = topLeftY + borderSize - 2; + int circleWidth = size - 2 * borderSize + 4; + int circleHeight = size - 2 * borderSize + 4; + + // save old paint settings + Paint oldPaint = g2.getPaint(); + + // draw color gradient + Paint gradPaint = new GradientPaint(circleX, circleY, topColor, circleX, + circleY + gradientHeight, bottomColor); + g2.setPaint(gradPaint); + g.fillOval(circleX, circleY, circleWidth, circleHeight); + + // set color and stroke of the border + g2.setPaint(oldPaint); + g.setColor(borderColor); + g2.setStroke(new BasicStroke(borderSize)); + + // draw the border + g.drawOval(topLeftX, topLeftY, size - borderSize / 2, size - borderSize / 2); + + if(label != null && label.length() > 0) { + // set font and color + g.setFont(font); + g.setColor(labelColor); + + // finally write the label on the node + g.drawString(label, topLeftX + GraphCalculation.calcTextCenter(g, label, + font, size).x, topLeftY + GraphCalculation.calcTextCenter(g, label, + font, size).y); + } + + if(number > 0) { + // get string to write + String string = String.valueOf(number); + + if(number == Integer.MAX_VALUE) { + string = "inf"; + } + + // calc text position + Point pos = new Point(position.x + radius, position.y - radius); + + // set font and color + g.setFont(numberFont); + g.setColor(numberColor); + + // draw number + g.drawString(string, pos.x, pos.y); + } + } + + /** + * Draw a node without small number next to it. + * @param g Used Graphics instance. + * @param label Text that will be shown in the center of the node. + * This should be the id of the node. + * If it is null, no label will be shown. + * @param position The position of the node. + * @param font The font that will be used for the text in the center of the node. + * Use GUIConstants.NODE_FONT as default value. + * @param size The diameter of the node. + * Use GUIConstants.NODE_SIZE as default value. + * @param borderSize The width of the node border. + * Use GUIConstants.NODE_BORDER_SIZE as default value. + * @param borderColor The color of the node border. + * Use GUIConstants.NODE_BORDER_COLOR as default value. + * @param labelColor The color of the text in the center of the node. + * Use GUIConstants.NODE_LABEL_COLOR as default value. + * @param topColor The background color at the top of the node. + * Use GUIConstants.NODE_COLOR_TOP as default value. + * @param bottomColor The background color at the bottom of the node. + * Use GUIConstants.NODE_COLOR_BOTTOM as default value. + * @param alpha Alpha value for drawing. + * @param gradientHeight Height of the color gradient at the top of the inner circle + * Use GUIConstants.NODE_GRADIENT_HEIGHT as default value. + * @author Anselm Schmidt + */ + public static void drawNode(Graphics g, String label, Point position, + Font font, int size, int borderSize, Color borderColor, + Color labelColor, Color topColor, Color bottomColor, int alpha, + int gradientHeight) { + // draw a node without small number next to it + drawNode(g, label, position, font, size, borderSize, borderColor, labelColor, + topColor, bottomColor, alpha, gradientHeight, null, null, 0); + } + + /** + * Draw a clipped edge. + * Clipping will be performed at the begin and the end of the edge. + * The clipping values can be set separately. + * If a clipping value is 0, no clipping will be performed at + * this position. + * The position of the arrows will be changed by the performed clipping. + * If the edge ends at the same position as it starts, + * a circle edge will be drawn. + * NOTE: The edge has to be long enough for the clipping to be performed! + * @param g Used Graphics instance. + * @param start Start point of the edge. Clipping of the begin will start here. + * @param end End point of the edge. Clipping of the end will end here. + * @param width The width of the edge line. + * Use GUIConstants.EDGE_WIDTH as default value. + * @param bidirectional If True, arrows will be drawn on both sides. + * If False, only one arrow will be drawn at the end of the edge. + * @param clipBegin Number of pixels that will be removed at the begin of the + * edge line. + * @param clipEnd Number of pixels that will be removed at the end of the edge + * line. + * @param startColor The color of the edge start. + * Use GUIConstants.EDGE_COLOR as default value. + * Will be ignored, when bidirectional is False. + * @param endColor The color of the edge end. + * Use GUIConstants.EDGE_COLOR as default value. + * @param edgeColor The color of the edge middle. + * Use GUIConstants.EDGE_COLOR as default value. + * @param arrowWidth Width of the arrow(s) of the edge. + * Use GUIConstants.EDGE_ARROW_WIDTH as default value. + * @param arrowLength Length of the arrow(s) of the edge. + * Use GUIConstants.EDGE_ARROW_LENGTH as default value. + * @param circleEdgeSize The diameter of a circle edge. + * Use GUIConstants.EDGE_CIRCLE_SIZE as default value. + * @param alpha Alpha value for drawing. + * Use 255 as default value. + * @author Anselm Schmidt + */ + public static void drawClippedEdge(Graphics g, Point start, Point end, + int width, boolean bidirectional, int clipBegin, int clipEnd, + Color startColor, Color endColor, Color edgeColor, int arrowWidth, + int arrowLength, int circleEdgeSize, int alpha) { + if(alpha == 0) { + return; + } + + // check if edge is a circle + if(start.equals(end)) { + // draw circle edge instead of line edge + drawClippedCircleEdge(g, start, width, clipBegin, edgeColor, arrowWidth, + arrowLength, circleEdgeSize, alpha); + } + else { + // set transparency + startColor = new Color(startColor.getRed(), startColor.getGreen(), + startColor.getBlue(), alpha); + endColor = new Color(endColor.getRed(), endColor.getGreen(), + endColor.getBlue(), alpha); + edgeColor = new Color(edgeColor.getRed(), edgeColor.getGreen(), + edgeColor.getBlue(), alpha); + + // set line width + ((Graphics2D) g).setStroke(new BasicStroke(width)); + + // calculate edge vector + double edgeVectorX = end.x - start.x; + double edgeVectorY = end.y - start.y; + double edgeVectorLength = Math.sqrt(edgeVectorX * edgeVectorX + + edgeVectorY * edgeVectorY); + + // create unit vector from edge vector + double unitVectorX = edgeVectorX / edgeVectorLength; + double unitVectorY = edgeVectorY / edgeVectorLength; + + // edge length is okay: change length of edge vector into clipping size + edgeVectorX = unitVectorX * clipBegin; + edgeVectorY = unitVectorY * clipBegin; + + // calculate the coordinates of the line start point + Point newStart = new Point(start.x + (int) Math.round(edgeVectorX), + start.y + (int) Math.round(edgeVectorY)); + + // change length of edge vector into end clipping size + edgeVectorX = unitVectorX * clipEnd; + edgeVectorY = unitVectorY * clipEnd; + + // calculate the coordinates of the line end point + Point newEnd = new Point(end.x - (int) Math.round(edgeVectorX), + end.y - (int) Math.round(edgeVectorY)); + + // draw edge end with specified color + g.setColor(endColor); + drawArrowhead(g, newEnd, unitVectorX, unitVectorY, arrowWidth, + arrowLength); + + if(bidirectional) { + // edge is bidirectional: draw edge start with specified color + g.setColor(startColor); + drawArrowhead(g, newStart, -unitVectorX, -unitVectorY, arrowWidth, + arrowLength); + + newStart.x += (int) Math.round(unitVectorX * width); + newStart.y += (int) Math.round(unitVectorY * width); + } + + // correct end position + newEnd.x -= (int) Math.round(unitVectorX * width); + newEnd.y -= (int) Math.round(unitVectorY * width); + + // set color to edge line color + g.setColor(edgeColor); + + // draw edge line + g.drawLine(newStart.x, newStart.y, newEnd.x, newEnd.y); + } + } + + /** + * Draw a node cursor over the border of a node. + * @param position The position of the selected node. + * @param nodeSize The size of the node. + * Use GUIConstants.NODE_SIZE as default value. + * @param sizeFactor + * The size of the cursor will be sizeFactor times the size of a node. + * @param borderSize The size of the border. + * Use GUIConstants.NODE_BORDER_SIZE as default value. + * @param color The color of the node cursor. + * Use GUIConstants.NODE_CURSOR_COLOR as default value. + * @param alpha The alpha value of the node cursor. + * @return The rectangle around the node cursor. + * @author Anselm Schmidt + */ + public static Rectangle drawNodeCursor(Graphics g, Point position, int nodeSize, + float sizeFactor, int borderSize, Color color, int alpha) { + // scale node size + int scaledNodeSize = (int) Math.round((double) nodeSize * sizeFactor); + + // calculate node cursor radius + int radius = (int) Math.round((double) scaledNodeSize / 2); + + // calculate the coordinates of the top left node cursor rectangle corner + int topLeftX = position.x - radius; + int topLeftY = position.y - radius; + + if(alpha > 0) { + // set transparency + color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + + // set color and stroke of the node cursor + g.setColor(color); + ((Graphics2D) g).setStroke(new BasicStroke(borderSize)); + + // draw node cursor circle + g.drawOval(topLeftX, topLeftY, scaledNodeSize - borderSize / 2, + scaledNodeSize - borderSize / 2); + } + + return new Rectangle(topLeftX - 1, topLeftY - 1, scaledNodeSize + 2, + scaledNodeSize + 2); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/PlayAnimation.java b/src/org/jalgo/module/bfsdfs/gui/PlayAnimation.java new file mode 100644 index 0000000..5a06e4b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/PlayAnimation.java @@ -0,0 +1,86 @@ +package org.jalgo.module.bfsdfs.gui; + +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.gui.components.NodeStackView; +import org.jalgo.module.bfsdfs.gui.components.TabContainer; + +/** + * This class is used to play the algorithm. It executed a new step after the + * {@linkplain GUIConstants#ANIMATION_SPEED} has expired. This is done in an + * own thread. + * @author Florian Dornbusch + */ +public class PlayAnimation implements GUIConstants, Runnable { + + /** The used thread. */ + private Thread animation = null; + + /** The {@linkplain TabContainer} */ + + /** The algorithm from which the animation was started. */ + private Algo algo; + + /** + * The used instance of {@linkplain NodeStackView} which started the + * animation. + */ + private NodeStackView n; + + /** + * Constructor. Stores the used instance of {@linkplain NodeStackView}, + * {@linkplain Algo} and {@linkplain TabContainer} from which the animation + * is started to send information while animating. + */ + public PlayAnimation(NodeStackView n, Algo algo) { + this.n = n; + this.algo = algo; + } + + /** + * Starts the animation. + */ + public void start() { + if ( animation == null ) { + animation = new Thread( this ); + animation.start(); + } + } + + /** + * Stops the animation. + */ + public void stop() { + if ( animation != null && animation.isAlive() ) + animation.interrupt(); + animation = null; + } + + /** + * Runs the animation. In every cycle, checks if the random check box is + * active and sends a random permutation to the algorithm, stops possibly + * running animations in the {@linkplain NodeStackView}, executes a new + * step and starts new animations. + */ + public void run() { + while(animation != null && !algo.isFinished()) { + + n.stopAnimation(); + algo.step(); + n.startAnimation(); + + n.repaint(); + + try {Thread.sleep(PLAY_ANIMATION);} + catch (InterruptedException e) {} + } + stop(); + } + + /** + * Returns true, if this animation is currently running. + * @author Florian Dornbusch + */ + public boolean isRunning() { + return animation != null; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.java b/src/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.java new file mode 100644 index 0000000..1a61371 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/RemoveNodeAnimation.java @@ -0,0 +1,98 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.components.NodeStackView; + +/** + * This class is used to animate nodes that were recently removed from the + * stack in {@linkplain NodeStackView}.
          + * The animation fades out the nodes in a certain time specified in + * {@linkplain GUIConstants#NODE_ANIMATION_TIME}.
          + * It handles an own thread which calculates the appropriate alpha value of the + * nodes. + * @author Florian Dornbusch + */ +public class RemoveNodeAnimation +implements GUIConstants, Runnable { + + /** The used thread. */ + private Thread animation = null; + + /** The start time of the animation */ + private long time; + + /** The current time of the animation */ + private long currentTime; + + /** + * The used instance of {@linkplain NodeStackView} which started the + * animation. + */ + private NodeStackView n; + + /** + * Constructor. Stores the used instance of {@linkplain NodeStackView} + * which started the animation to send information when the animation + * stops. + * @author Florian Dornbusch + */ + public RemoveNodeAnimation(NodeStackView n) { + this.n=n; + } + + /** + * Starts the animation. Also sets the current time and start time. + * @author Florian Dornbusch + */ + public void start() { + if ( animation == null ) { + animation = new Thread( this ); + animation.start(); + time = Calendar.getInstance().getTimeInMillis(); + currentTime = time; + } + } + + /** + * Stops the animation and removes the recently removed nodes from the + * list in {@linkplain NodeStackView}.
          + * If a queue was declared to be removed, this is executed now.
          + * If the {@linkplain NodeStackView} represents a queue, the first visible + * node is removed. + * @author Florian Dornbusch + */ + public void stop() { + if ( animation != null && animation.isAlive() ) + animation.interrupt(); + animation = null; + n.clearRemovedNodes(); + if(n.getQueueRemoved()) n.removeQueue(); + if(!n.getSuccessorsVisible()) n.removeFirstQueueNode(); + } + + /** + * Runs the animation. Calculates the alpha value according to the + * percentage of time passed and repaints the {@linkplain NodeStackView}. + * @author Florian Dornbusch + */ + public void run() { + int alpha; + n.setAlphaRemove(ALPHA_100_PERCENT); + n.repaint(); + while(currentTime-time<=NODE_ANIMATION_TIME && animation != null) { + try {Thread.sleep(ANIMATION_REPAINT_DELAY);} + catch (InterruptedException e) {} + double a = (double)(currentTime-time); + double b = (double)NODE_ANIMATION_TIME; + double factor = 1 - a / b; + alpha = (int)(ALPHA_100_PERCENT * factor); + n.setAlphaRemove(alpha); + n.repaint(); + currentTime = Calendar.getInstance().getTimeInMillis(); + while(currentTime == Calendar.getInstance().getTimeInMillis()); + } + n.repaint(); + stop(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.java b/src/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.java new file mode 100644 index 0000000..183645c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/StatusMouseAdapter.java @@ -0,0 +1,33 @@ +package org.jalgo.module.bfsdfs.gui; + +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; + +/** + * Utility class that extends {@linkplain MouseAdapter}. In this class, an + * additional string can be stored.
          The methods + * {@link #mouseExited(MouseEvent)} and {@link #mouseEntered(MouseEvent)} are + * preset to hide or show the status message in the status bar, respectively. + * + * @param status : The stored string. Note that the string is not the string + * of the status message, but the location where the actual string is stored + * in the properties files. + * @author Florian Dornbusch + */ +public class StatusMouseAdapter extends MouseAdapter { + private String status; + + public StatusMouseAdapter(String status) { + this.status = status; + } + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("bfsdfs", status)); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/components/AlgoTab.java b/src/org/jalgo/module/bfsdfs/gui/components/AlgoTab.java new file mode 100644 index 0000000..0511e8f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/AlgoTab.java @@ -0,0 +1,801 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.ComponentOrientation; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.image.BufferedImage; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.AbstractAction; +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.algorithms.stack.StackObserver; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; +import org.jalgo.module.bfsdfs.gui.StatusMouseAdapter; +import org.jalgo.module.bfsdfs.gui.event.RandomAction; +import org.jalgo.module.bfsdfs.gui.graphview.GraphView; +import org.jalgo.module.bfsdfs.gui.graphview.InteractiveGraphView; +import org.jalgo.module.bfsdfs.gui.graphview.TreeView; +import org.jalgo.module.bfsdfs.undo.UndoableObserver; + +/** + * AlgoTab is the abstract super class of {@linkplain DFSTab} and + * {@linkplain BFSTab}. It contains every component both tabs have in common. + *
          + * The main components are: + *
            + *
          • chooserPane : The panel where the user can choose the start node, + * the order of the successors of the current node and + * if the algorithm is or is not deterministic therefore + * lets you choose the successor order or not.
          • + *
          • nodeViewPane : The panel where the queue respectively the stack is + * shown.
          • + *
          • scrollPane : The panel where the {@linkplain GraphView} is embedded. + * Actually {@linkplain TreeView} is drawn above the + * the {@linkplain InteractiveGraphView}, which is grayed + * out.
          • + *
          + * + * @author Florian Dornbusch + * @author Anselm Schmidt + */ +public abstract class AlgoTab +extends JPanel +implements ComponentListener, MouseListener, GraphObserver, +UndoableObserver, StackObserver, GUIConstants { + private static final long serialVersionUID = 7334524852619774015L; + + // general references + protected GUIController gui; + private GraphController graph = null; + private GraphView graphView; + private TreeView treeView; + + // main components + protected JScrollPane scrollPane; + protected JScrollPane stackScrollPane; + protected JPanel controlPane; + protected JPanel chooserPane; + protected JPanel nodeViewPane; + private JPanel scrollPanel; + + // components of chooserPane + private JLabel startNodeLabel; + private JLabel successorLabel; + private JLabel randomLabel; + private JComboBox startNodeChooser; + private JPanel successorPane; + private SuccessorChooser successorChooser; + private JScrollPane successorScrollPane; + private JCheckBox randomBox; + private ScrollArea leftScrollArea; + private ScrollArea rightScrollArea; + + // components of nodeViewPane + protected NodeStackView nodeStackView; + private JLabel nodeViewLabel; + + // actions + private AbstractAction resetAction; + private AbstractAction stepBackAction; + private AbstractAction stepForwardAction; + private AbstractAction playAction; + private AbstractAction cancelAction; + private AbstractAction randomAction; + + /** Determines if the successorChooser is enabled or not. */ + private boolean successorsAvailable = false; + + /** + * Stores the current successors incoming from + * {@linkplain #onNodesAdded(List)}. + */ + private List currentSuccessors; + + /** The diameter of a node. */ + protected int nodeSize; + + /** + * Constructor. + * @author Florian Dornbusch + */ + public AlgoTab(GUIController gui, GraphController graph, Algo algo) { + this.graph=graph; + this.gui = gui; + + currentSuccessors = new LinkedList(); + + gui.addGraphObserver(this); + + this.setLayout(new BorderLayout()); + + // create components + treeView = new TreeView(algo, graph); + + startNodeLabel = new JLabel( + Messages.getString("bfsdfs", "AlgoTab.startNodeLabel")); + + startNodeChooser = new JComboBox(); + startNodeChooser.setRenderer(new NodeListRenderer()); + startNodeChooser.setMaximumRowCount(MAX_ROW_COUNT); + startNodeChooser.setToolTipText(Messages.getString("bfsdfs", + "AlgoTab.startNodeChooserStatus")); + + successorLabel = new JLabel( + Messages.getString("bfsdfs", "AlgoTab.successorLabel")); + + successorChooser = new SuccessorChooser(gui, this); + + successorScrollPane = new JScrollPane(successorChooser, + ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + leftScrollArea = new ScrollArea( + successorScrollPane.getHorizontalScrollBar(), true, this); + rightScrollArea = new ScrollArea( + successorScrollPane.getHorizontalScrollBar(), false, this); + + successorPane = new JPanel(); + successorPane.setLayout(new BorderLayout()); + successorPane.add(leftScrollArea, BorderLayout.WEST); + successorPane.add(rightScrollArea, BorderLayout.EAST); + successorPane.add(successorScrollPane, BorderLayout.CENTER); + + randomLabel = new JLabel( + Messages.getString("bfsdfs", "AlgoTab.randomLabel")); + + randomAction = new RandomAction(this, gui); + + randomBox = new JCheckBox(); + randomBox.setAction(randomAction); + + nodeViewLabel = new JLabel(Messages.getString("bfsdfs", + this.getClass().getSimpleName()+".nodeViewLabel")); + + nodeStackView = new NodeStackView(); + + stackScrollPane = new JScrollPane(nodeStackView, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + stackScrollPane.setPreferredSize(new Dimension(0, 0)); + + nodeViewPane = new JPanel(); + nodeViewPane.setLayout(new BorderLayout()); + nodeViewPane.setBorder(BorderFactory.createEtchedBorder()); + nodeViewPane.add(nodeViewLabel, BorderLayout.NORTH); + nodeViewPane.add(stackScrollPane, BorderLayout.CENTER); + + controlPane = new JPanel(); + + setupChooserPane(); + setupScrollArea(); + handleEvents(); + adjustLayout(); + toggleBeamerMode(); + } + + /** + * Hook method that adjusts all additional content of the window. + * @author Florian Dornbusch + */ + protected abstract void adjustLayout(); + + /** + * Additionally adjusts the size of the start node chooser because the size + * of the drop down button differentiates in different layouts. + * @author Florian Dornbusch + */ + @Override + public void setVisible(boolean aFlag) { + super.setVisible(aFlag); + if(aFlag) { + int width = startNodeChooser.getComponents()[0].getWidth() + 50; + startNodeChooser.setSize(new Dimension(width,50)); + startNodeChooser.setPreferredSize(new Dimension(width,50)); + } + } + + /** + * Returns {@linkplain #successorsAvailable}. + * @author Florian Dornbusch + */ + public boolean getSuccessorsAvailable() { + return successorsAvailable; + } + + /** + * Returns the used check box to toggle the non-determinism. + * @author Florian Dornbusch + */ + public JCheckBox getRandomBox() { + return randomBox; + } + + /** + * Returns the used {@linkplain SuccessorChooser}. + * @author Florian Dornbusch + */ + public SuccessorChooser getSuccessorChooser() { + return successorChooser; + } + + /** + * Returns the left {@linkplain ScrollArea} of the + * {@linkplain SuccessorChooser}. + * @author Florian Dornbusch + */ + public ScrollArea getLeftScrollArea() { + return leftScrollArea; + } + + /** + * Returns the right {@linkplain ScrollArea} of the + * {@linkplain SuccessorChooser}. + * @author Florian Dornbusch + */ + public ScrollArea getRightScrollArea() { + return rightScrollArea; + } + + /** + * Returns true if the check box, which toggles the non-determinism, is + * selected. + * @author Florian Dornbusch + */ + public boolean isRandomActive() { + return successorsAvailable && randomBox.isSelected(); + } + + /** + * Returns a random permutation of the current available successors. + * @author Florian Dornbusch + */ + public List getRandomPermutation() { + List result = new LinkedList(); + // copy the currentSuccessors list to a new list + List s = new LinkedList(); + s.addAll(currentSuccessors); + + while(!s.isEmpty()) { + // calculate a random entry, add it to the result and remove it + // from the copied list + int random = (int)(Math.random()*s.size()); + result.add(s.get(random)); + s.remove(random); + } + return result; + } + + /** + * Returns the {@linkplain GraphController}. + * @author Florian Dornbusch + */ + public GraphController getGraphController() { + return graph; + } + + /** + * Returns the used {@linkplain TreeView}. + * @author Florian Dornbusch + */ + public TreeView getTreeView() { + return treeView; + } + + /** + * Saves the viewport position of the scroll pane. + * @author Florian Dornbusch + */ + public void saveViewportPosition() { + mouseReleased(null); + } + + /** + * Loads the viewport position of the scroll pane. + * @author Florian Dornbusch + */ + public void loadViewportPosition() { + componentResized(null); + } + + /** + * Returns true if there is no available start node. + * @author Florian Dornbusch + */ + public boolean startNodeChooserEmpty() { + return startNodeChooser.getItemCount() == 0; + } + + /** + * Returns the {@linkplain NodeStackView}. + * @author Florian Dornbusch + */ + public NodeStackView getNodeStackView() { + return nodeStackView; + } + + /** + * This method changes the content of this component depending on + * {@linkplain ComponentUtility#BEAMER_MODE}. + * @author Florian Dornbusch + */ + public void toggleBeamerMode() { + int nodeStackWidth; + Font font; + if(ComponentUtility.BEAMER_MODE) { + font = BEAMER_WRITING_FONT; + nodeSize = NODE_BEAMER_SIZE; + } + else { + font = WRITING_FONT; + nodeSize = NODE_SIZE; + } + + nodeStackWidth = + SPACE_SMALL + nodeSize + SPACE_BIG + + NODESTACKVIEW_NUMBER_SUCCESSORS * + (nodeSize + SPACE_SMALL)+ 25; + + nodeViewLabel.setFont(font); + startNodeLabel.setFont(font); + successorLabel.setFont(font); + randomLabel.setFont(font); + successorChooser.setFont(font); + chooserPane.setPreferredSize(new Dimension(nodeStackWidth,160)); + } + + /** + * ScrollArea has been resized. The viewport is set with coordinates that + * keeps the current content centered. The current viewport position is + * loaded from the {@linkplain GUIController}. + * @author Florian Dornbusch + * @author Anselm Schmidt + */ + public void componentResized(ComponentEvent arg0) { + // change the position in a way, that the new content is at the + // same place where the old was. + Point p = gui.getGraphViewPosition(); + if(p==null) return; + int x = p.x - scrollPane.getViewport().getWidth() / 2; + int y = p.y - scrollPane.getViewport().getHeight() / 2; + scrollPane.getViewport().setViewPosition(new Point(x,y)); + } + + /** Unused observer method. */ + public void componentHidden(ComponentEvent arg0) {} + + /** Unused observer method. */ + public void componentMoved(ComponentEvent arg0) {} + + /** Unused observer method. */ + public void componentShown(ComponentEvent arg0) {} + + + /** + * This method is invoked, when the mouse is released from one of the + * scroll bars of the viewport indicating that resizing has finished. + * The new center of the viewport is calculated and saved in the + * {@linkplain GUIController}. + * @author Florian Dornbusch + */ + public void mouseReleased(MouseEvent e) { + Point p = scrollPane.getViewport().getViewPosition(); + int x = p.x + scrollPane.getViewport().getWidth() / 2; + int y = p.y + scrollPane.getViewport().getHeight() / 2; + gui.setGraphViewPosition(new Point(x,y)); + } + + /** unused mouse events */ + public void mouseClicked(MouseEvent e) {} + + /** unused mouse events */ + public void mouseEntered(MouseEvent e) {} + + /** unused mouse events */ + public void mouseExited(MouseEvent e) {} + + /** unused mouse events */ + public void mousePressed(MouseEvent e) {} + + + /** + * If a new node was added to the graph, it has to be + * inserted in the start node chooser. + * @author Florian Dornbusch + */ + public void onNodeAdded(int id, Point point) { + List list = new LinkedList(); + list.add(id); + startNodeChooser.addItem(createEntry(list)); + startNodeChooser.setEnabled(true); + } + /** + * If a node was removed from the graph it also has to be + * removed from the startNodeChooser. + * @author Florian Dornbusch + */ + @SuppressWarnings("unchecked") + public void onNodeRemoved(int id) { + for(int i=0; io3 = (List)o2[1]; + if(o3.get(0) == id) { + startNodeChooser.removeItem(o); + if(this.startNodeChooserEmpty()) { + startNodeChooser.setEnabled(false); + } + } + } + } + } + } + + /** + * If the id of a node has changed, delete the old + * id and add the new one. + * @author Florian Dornbusch + */ + public void onNodeChanged(int oldNode, int newNode) { + this.onNodeRemoved(oldNode); + this.onNodeAdded(newNode, null); + } + + /** unused observer method */ + public void onNodeMoved(int id, Point point) {} + + /** unused observer method */ + public void onEdgeAdded(int id1, int id2) {} + + /** unused observer method */ + public void onEdgeRemoved(int id1, int id2) {} + + /** unused observer method */ + public void onEdgeChanged(int oldStart, int oldEnd, int newStart, + int newEnd) {} + + /** + * This method removes all entries in {@linkplain SuccessorChooser}, + * saves the current successors and displays the standard permutation. + * @author Florian Dornbusch + */ + public void onNodesAdded(List nodes) { + if(nodes == null || nodes.isEmpty()) return; + successorsAvailable = true; + + currentSuccessors = nodes; + + successorChooser.setEnabled(true); + + if(randomBox.isSelected()) { + List random = getRandomPermutation(); + successorChooser.fill(random); + gui.setSuccessorOrder(random); + } + else { + successorChooser.fill(nodes); + } + } + + /** + * Enables or disables the {@linkplain SuccessorChooser} depending on + * the changed {@linkplain NodeStatus}. + * @author Florian Dornbusch + */ + public void onStatusChanged(int node, NodeStatus status) { + successorsAvailable = false; + successorChooser.setEnabled(false); + leftScrollArea.setEnabled(false); + rightScrollArea.setEnabled(false); + } + + /** + * Removes all items from {@linkplain SuccessorChooser} if the algorithm + * has finished. + * @author Florian Dornbusch + */ + public void onAllNodesFinished() { + successorChooser.setEnabled(false); + leftScrollArea.setEnabled(false); + rightScrollArea.setEnabled(false); + } + + /** Unused observer method. */ + public void onFirstQueueAdded(int owner) {} + + /** Unused observer method. */ + public void onQueueAdded(int owner) {} + + /** Unused observer method. */ + public void onTopQueueRemoved() {} + + /** Unused observer method. */ + public void onAllQueuesRemoved() {} + + /** Unused observer method. */ + public void onUntouchedReplaced(List o, List n) {} + + /** Unused observer method. */ + public void onCurrentNodeChanged(int i) {} + + /** + * If undo is enabled meaning the algorithm is running, + * the start node chooser has to be disabled. + * @author Florian Dornbusch + */ + public void onUndoEnabled() { + startNodeChooser.setEnabled(false); + } + + /** + * If undo is disabled meaning the algorithm is not running, + * the start node chooser has to be enabled. + * Also, the {@linkplain SuccessorChooser} has to be disabled. + * @author Florian Dornbusch + */ + public void onUndoDisabled() { + startNodeChooser.setEnabled(true); + successorChooser.setEnabled(false); + leftScrollArea.setEnabled(false); + rightScrollArea.setEnabled(false); + } + + /** Unused observer method. */ + public void onRedoEnabled() {} + + /** Unused observer method. */ + public void onRedoDisabled() {} + + /** + * Fills chooserPane with 4 rows and 2 columns. The utility + * class {@linkplain FormUtility} is used to create the + * {@linkplain GridBagLayout}. + * @author Florian Dornbusch + */ + private void setupChooserPane() { + chooserPane = new JPanel(); + chooserPane.setLayout(new GridBagLayout()); + int nodeStackWidth = + SPACE_SMALL + NODE_SIZE + SPACE_BIG + SPACE_BIG + SPACE_BIG + + NODESTACKVIEW_NUMBER_SUCCESSORS * (NODE_SIZE+SPACE_SMALL)+ + SPACE_SMALL+20; + chooserPane.setPreferredSize(new Dimension(nodeStackWidth,160)); + chooserPane.setBorder(BorderFactory.createEtchedBorder()); + + FormUtility formUtility = new FormUtility(); + // The following comments use (row, column) to identify the cells. + + // (1,1) set the startNodeLabel and add it to chooserPane + JPanel startLabelPanel = new JPanel(); + startLabelPanel.setLayout(new BorderLayout()); + startLabelPanel.setPreferredSize(new Dimension(120,25)); + startLabelPanel.add(startNodeLabel, BorderLayout.CENTER); + formUtility.addLabel(startLabelPanel, chooserPane); + + // (1,2) set the randomPane and add it to chooserPane + JPanel randomPane = new JPanel(); + randomPane.setLayout(new BoxLayout(randomPane, BoxLayout.LINE_AXIS)); + randomPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + randomPane.add(randomBox); + randomPane.add(randomLabel); + formUtility.addLastField(randomPane, chooserPane); + + // (2,1) set the startNodeChooser and add it to chooserPane + JPanel startChooserPanel = new JPanel(); + startChooserPanel.setLayout(new BorderLayout()); + startChooserPanel.add(startNodeChooser, BorderLayout.WEST); + startNodeChooser.setPreferredSize(new Dimension (65,50)); + formUtility.addLabel(startChooserPanel, chooserPane); + + // (2,2) add the buttons to handle the algorithm BFSTab and DFSTab + JPanel buttonPane = new JPanel(); + buttonPane.setPreferredSize(new Dimension(50,25)); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + cancelAction = gui.getCancelAction(); + buttonPane.add(ComponentUtility.createToolbarButton(cancelAction)); + playAction = gui.getPlayAction(); + buttonPane.add(ComponentUtility.createToolbarButton(playAction)); + stepForwardAction = gui.getStepForwardAction(); + buttonPane.add(ComponentUtility. + createToolbarButton(stepForwardAction)); + stepBackAction = gui.getStepBackAction(); + buttonPane.add(ComponentUtility.createToolbarButton(stepBackAction)); + resetAction = gui.getResetAction(); + buttonPane.add(ComponentUtility.createToolbarButton(resetAction)); + formUtility.addLastField(buttonPane, chooserPane); + + // (3,1) set the successorLabel and add it to chooserPane + JPanel succLabelPanel = new JPanel(); + succLabelPanel.setLayout(new BorderLayout()); + succLabelPanel.setPreferredSize(new Dimension(0,25)); + succLabelPanel.add(successorLabel, BorderLayout.CENTER); + formUtility.addLastField(succLabelPanel, chooserPane); + + // (4,1) set the successorChooser and add it to chooserPane + JPanel succChooserPanel = new JPanel(); + succChooserPanel.setLayout(new BorderLayout()); + succChooserPanel.add(successorPane, BorderLayout.CENTER); + succChooserPanel.setPreferredSize(new Dimension(0,50)); + formUtility.addLastField(succChooserPanel, chooserPane); + } + + /** + * This utility method adds {@linkplain ActionListener}s and + * {@linkplain MouseListener}s to all components that need it. + * @author Florian Dornbusch + */ + @SuppressWarnings("unchecked") + private void handleEvents() { + + startNodeChooser.addActionListener(new ActionListener() { + /** + * If a start node is selected by the user, the algorithm + * and the tree view have to know it. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent arg0) { + Object o = startNodeChooser.getSelectedItem(); + if(o instanceof Object[]) { + Object[] oa = (Object[])o; + if(oa[1] instanceof List) { + List list = (List)oa[1]; + gui.setStartNode(list.get(0)); + treeView.onCurrentNodeChanged(list.get(0)); + } + } + } + }); + + + // add MouseListeners to the following components that update + // the status bar according to their status text + + for(Component c:startNodeChooser.getComponents()) { + c.addMouseListener(new StatusMouseAdapter( + "AlgoTab.startNodeChooserStatus")); + } + + startNodeChooser.addMouseListener(new StatusMouseAdapter( + "AlgoTab.startNodeChooserStatus")); + + successorChooser.addMouseListener(new StatusMouseAdapter( + "AlgoTab.successorChooserStatus")); + + randomBox.addMouseListener(new StatusMouseAdapter( + "AlgoTab.randomBoxStatus")); + + nodeViewPane.addMouseListener(new StatusMouseAdapter( + this.getClass().getSimpleName()+".nodeViewStatus")); + + nodeStackView.addMouseListener(new StatusMouseAdapter( + this.getClass().getSimpleName()+".nodeViewStatus")); + + chooserPane.addMouseListener(new StatusMouseAdapter( + "AlgoTab.chooserPaneStatus")); + + scrollPane.addMouseListener(new StatusMouseAdapter( + "AlgoTab.scrollPaneStatus")); + } + + /** + * Creates the scrollPane and the scrollPanel + * including {@linkplain GraphView} and {@linkplain TreeView} + * and adds itself as {@linkplain ComponentListener} to itself. + * @author Anselm Schmidt + */ + private void setupScrollArea() { + // create components + graphView = new GraphView(this.graph); + gui.addGraphObserver(graphView); + scrollPanel = new JPanel(); + scrollPane = new JScrollPane(scrollPanel, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + + // adds itself as ComponentListener to the scrollArea + scrollPane.addComponentListener(this); + scrollPane.getVerticalScrollBar().addMouseListener(this); + scrollPane.getHorizontalScrollBar().addMouseListener(this); + + // set up scroll area + scrollPanel.setLayout(null); + scrollPanel.add(treeView); + scrollPanel.add(graphView); + + // set sizes + Dimension size = new Dimension(MAX_GRAPH_WIDTH, MAX_GRAPH_HEIGHT); + scrollPanel.setSize(size); + scrollPanel.setPreferredSize(size); + graphView.setSize(size); + graphView.setPreferredSize(size); + treeView.setSize(size); + treeView.setPreferredSize(size); + + // show the center of the scroll area + int viewportWidth = scrollPane.getViewport().getWidth(); + int viewportHeight = scrollPane.getViewport().getHeight(); + int x = MAX_GRAPH_WIDTH / 2 - viewportWidth / 2; + int y = MAX_GRAPH_HEIGHT / 2 - viewportHeight / 2; + scrollPane.getViewport().setViewPosition(new Point(x, y)); + mouseReleased(null); + } + + /** + * This method draws a horizontal line of node icons and creates an image + * of it. It is used to render the nodes in startNodeChooser. + * @param i the position of a node in the current line. + * i=0 is the first node after the owner + * @author Florian Dornbusch + */ + private BufferedImage createImageIcon(List list) { + Integer i=0; + + //initiate the image + BufferedImage p = new BufferedImage(NODE_ICON_SIZE * list.size(), + NODE_ICON_SIZE, BufferedImage.TYPE_4BYTE_ABGR); + Graphics2D g = p.createGraphics(); + + // turn on anti-aliasing + GraphDrawing.enableAntiAliasing(g); + + // turn background transparent + g.setColor(new Color(0, 0, 0, 0)); + g.fillRect(0, 0, NODE_ICON_SIZE * list.size(), NODE_ICON_SIZE); + g.setColor(Color.BLACK); + for (Integer e : list) { + ComponentUtility.drawNode(g, i * NODE_ICON_SIZE, 0, e, + NodeStatus.UNTOUCHED, NODE_ICON_SIZE, + NODE_ICON_BORDER_SIZE, NODE_ICON_FONT, ALPHA_100_PERCENT); + i++; + } + return p; + } + + /** + * Utility method to create entries for the start node chooser because each + * entry contains an {@linkplain ImageIcon} and the underlying integer + * list. + * @param list : The list from which the image icons are created. + * It is read in the according action events. + * @return : an object array with two elements - the icon and the list + * @author Florian Dornbusch + */ + private Object[] createEntry(List list) { + Object[] o = new Object[2]; + o[0] = new ImageIcon(createImageIcon(list)); + o[1] = list; + return o; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/BFSTab.java b/src/org/jalgo/module/bfsdfs/gui/components/BFSTab.java new file mode 100644 index 0000000..ebee57f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/BFSTab.java @@ -0,0 +1,72 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.BorderLayout; +import java.awt.Dimension; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.GraphView; + +/** + * BFSTab manages the breadth first search algorithm. The user can + * click through it step by step (forward and backward), reset, run and cancel + * it.
          + * The resulting graph is directly shown in the top end of the window, the + * {@linkplain GraphView}.
          + * Furthermore the user can choose the start node and the successor order if + * multiple successors are available.
          + * The queue that is used by the algorithm is visualized by the use of + * {@linkplain NodeStackView}. + * + * @author Florian Dornbusch + */ + +public class BFSTab +extends AlgoTab { + private static final long serialVersionUID = -218770648365873881L; + + public BFSTab(GUIController gui, GraphController graph, Algo algo) { + super(gui, graph, algo); + } + + @Override + protected void adjustLayout() { + // add observers + gui.addBFSUndoableObserver(this); + gui.addBFSStackObserver(this); + gui.addBFSStackObserver(nodeStackView); + + // adjust components + nodeStackView.setSuccessorsVisible(false); + stackScrollPane.setHorizontalScrollBarPolicy( + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + stackScrollPane.setVerticalScrollBarPolicy( + ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); + + JPanel blubb = new JPanel(); + blubb.setLayout(new BoxLayout(blubb, BoxLayout.PAGE_AXIS)); + blubb.add(Box.createVerticalGlue()); + blubb.add(stackScrollPane); + blubb.add(Box.createVerticalGlue()); + nodeViewPane.add(blubb, BorderLayout.CENTER); + + controlPane.setLayout(new BorderLayout()); + controlPane.add(nodeViewPane, BorderLayout.CENTER); + controlPane.add(chooserPane, BorderLayout.EAST); + + // add main components to the content pane + add(scrollPane, BorderLayout.CENTER); + add(controlPane, BorderLayout.SOUTH); + } + + public void toggleBeamerMode() { + super.toggleBeamerMode(); + stackScrollPane.setPreferredSize(new Dimension(0,nodeSize)); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/CVS/Entries b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Entries new file mode 100644 index 0000000..168bfa9 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Entries @@ -0,0 +1,13 @@ +/AlgoTab.java/1.1/Wed Dec 8 13:47:54 2010// +/BFSTab.java/1.1/Wed Dec 8 13:47:54 2010// +/DFSTab.java/1.1/Wed Dec 8 13:47:54 2010// +/DesignTab.java/1.1/Wed Dec 8 13:47:54 2010// +/FormUtility.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeListRenderer.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeStackView.java/1.1/Wed Dec 8 13:47:54 2010// +/ScrollArea.java/1.1/Wed Dec 8 13:47:54 2010// +/SuccessorChooser.java/1.1/Wed Dec 8 13:47:54 2010// +/TabContainer.java/1.1/Wed Dec 8 13:47:54 2010// +/WelcomeButton.java/1.1/Wed Dec 8 13:47:54 2010// +/WelcomeScreen.java/1.1/Wed Dec 8 13:47:54 2010// +/package.html/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/gui/components/CVS/Repository b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Repository new file mode 100644 index 0000000..667d50c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/gui/components diff --git a/src/org/jalgo/module/bfsdfs/gui/components/CVS/Root b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/gui/components/DFSTab.java b/src/org/jalgo/module/bfsdfs/gui/components/DFSTab.java new file mode 100644 index 0000000..415e218 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/DFSTab.java @@ -0,0 +1,49 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.BorderLayout; + +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.GraphView; + +/** + * DFSTab manages the depth first search algorithm. The user can + * click through it step by step (forward and backward), run it, and reset it. + *
          + * The resulting graph is directly shown in the left end of the window, the + * {@linkplain GraphView}.
          + * Furthermore the user can choose the start node and the successor order if + * multiple successors are available.
          + * The stack that is used by the algorithm is visualized by the use of + * {@linkplain NodeStackView}. + * + * @author Florian Dornbusch + */ + +public class DFSTab +extends AlgoTab { + private static final long serialVersionUID = -4710478217401676189L; + + public DFSTab(GUIController gui, GraphController graph, Algo algo) { + super(gui, graph, algo); + } + + @Override + protected void adjustLayout() { + // add observers + gui.addDFSUndoableObserver(this); + gui.addDFSStackObserver(this); + gui.addDFSStackObserver(nodeStackView); + + //adjust components + nodeStackView.setSuccessorsVisible(true); + controlPane.setLayout(new BorderLayout()); + controlPane.add(nodeViewPane, BorderLayout.CENTER); + controlPane.add(chooserPane, BorderLayout.SOUTH); + + // add main components to the content pane + add(scrollPane, BorderLayout.CENTER); + add(controlPane, BorderLayout.EAST); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/DesignTab.java b/src/org/jalgo/module/bfsdfs/gui/components/DesignTab.java new file mode 100644 index 0000000..e173173 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/DesignTab.java @@ -0,0 +1,261 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JToggleButton; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; +import org.jalgo.module.bfsdfs.gui.graphview.InteractiveGraphView; + +/** + * DesignTab represents a design mode to configure the graph. It + * consists of a scrollPane, where the Graph is drawn, and 6 + * Buttons to handle it: + *
            + *
          • Undo
          • + *
          • Redo
          • + *
          • Node
          • + *
          • Edge
          • + *
          • DoubleEdge
          • + *
          • Eraser
          • + *
          + * + * @author Florian Dornbusch + * @author Anselm Schmidt + */ +public class DesignTab +extends JPanel +implements ComponentListener, MouseListener, GUIConstants { + private static final long serialVersionUID = 2662482559820040502L; + + // general references + private GUIController gui; + private GraphController graphController = null; + private InteractiveGraphView graphView; + + // main components + private JPanel scrollArea; + private JPanel buttonPane; + private JScrollPane scrollPane; + + // buttons + private JButton undoButton; + private JButton redoButton; + private JToggleButton nodeButton; + private JToggleButton edgeButton; + private JToggleButton doubleEdgeButton; + private JToggleButton eraserButton; + + // actions + private AbstractAction undoAction; + private AbstractAction redoAction; + private AbstractAction nodeAction; + private AbstractAction edgeAction; + private AbstractAction doubleEdgeAction; + private AbstractAction eraserAction; + + /** + * Constructor. + * @author Florian Dornbusch + */ + public DesignTab(GUIController guiController, + GraphController graphController) { + + this.graphController = graphController; + this.gui = guiController; + + setLayout(new BorderLayout()); + + setupButtons(); + setupScrollArea(); + + JPanel south = new JPanel(); + south.setPreferredSize(new Dimension(0,35)); + south.add(buttonPane); + + // add components to pane + add(scrollPane, BorderLayout.CENTER); + add(south, BorderLayout.SOUTH); + } + + /** + * Toggles the buttons so that the button according to the given + * {@linkplain EditMode} is the only selected button. + * @author Florian Dornbusch + */ + public void switchTo(EditMode mode) { + nodeButton.setSelected(mode == EditMode.PUT_NODE); + edgeButton.setSelected(mode == EditMode.START_EDGE); + doubleEdgeButton.setSelected(mode == EditMode.START_DOUBLE_EDGE); + eraserButton.setSelected(mode == EditMode.ERASE); + } + + /** + * Returns the {@linkplain InteractiveGraphView}. + * @author Florian Dornbusch + */ + public InteractiveGraphView getGraphView() { + return graphView; + } + + /** + * Saves the view port position of the scroll pane. + * @author Florian Dornbusch + */ + public void saveViewportPosition() { + mouseReleased(null); + } + + /** + * Loads the view port position of the scroll pane. + * @author Florian Dornbusch + */ + public void loadViewportPosition() { + componentResized(null); + } + + /** Unused observer method. */ + public void componentHidden(ComponentEvent arg0) {} + + /** Unused observer method. */ + public void componentMoved(ComponentEvent arg0) {} + + /** Unused observer method. */ + public void componentShown(ComponentEvent arg0) {} + + /** + * ScrollArea has been resized. The view port is set with coordinates that + * keeps the current content centered. The current viewport position is + * loaded from the {@linkplain GUIController}. + * @author Florian Dornbusch + * @author Anselm Schmidt + */ + public void componentResized(ComponentEvent arg0) { + // change the position in a way, that the new content is at the + // same place where the old was. + Point p = gui.getGraphViewPosition(); + if(p==null) return; + int x = p.x - scrollPane.getViewport().getWidth() / 2; + int y = p.y - scrollPane.getViewport().getHeight() / 2; + scrollPane.getViewport().setViewPosition(new Point(x,y)); + } + + /** + * This method is invoked, when the mouse is released from one of the + * scroll bars of the viewport indicating that resizing has finished. + * The new center of the viewport is calculated and saved in the + * {@linkplain GUIController}. + * @author Florian Dornbusch + */ + public void mouseReleased(MouseEvent e) { + Point p = scrollPane.getViewport().getViewPosition(); + int x = p.x + scrollPane.getViewport().getWidth() / 2; + int y = p.y + scrollPane.getViewport().getHeight() / 2; + gui.setGraphViewPosition(new Point(x,y)); + } + + /** Unused observer method. */ + public void mouseClicked(MouseEvent e) {} + + /** Unused observer method. */ + public void mouseEntered(MouseEvent e) {} + + /** Unused observer method. */ + public void mouseExited(MouseEvent e) {} + + /** Unused observer method. */ + public void mousePressed(MouseEvent e) {} + + /** + * Creates the design buttons and sets them up with the same action as the + * design buttons in the toolbar. + * @author Florian Dornbusch + */ + private void setupButtons() { + buttonPane = new JPanel(); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + + undoAction = gui.getUndoAction(); + undoButton = ComponentUtility.createButton(undoAction); + buttonPane.add(undoButton); + + redoAction = gui.getRedoAction(); + redoButton = ComponentUtility.createButton(redoAction); + buttonPane.add(redoButton); + + buttonPane.add(Box.createRigidArea(new Dimension(50, 0))); + + nodeAction = gui.getNodeAction(); + nodeButton = ComponentUtility.createToolbarToggleButton(nodeAction); + nodeButton.setSelected(true); + + buttonPane.add(nodeButton); + edgeAction = gui.getEdgeAction(); + edgeButton = ComponentUtility.createToolbarToggleButton(edgeAction); + buttonPane.add(edgeButton); + + doubleEdgeAction = gui.getDoubleEdgeAction(); + doubleEdgeButton = ComponentUtility. + createToolbarToggleButton(doubleEdgeAction); + buttonPane.add(doubleEdgeButton); + + eraserAction = gui.getEraserAction(); + eraserButton = ComponentUtility. + createToolbarToggleButton(eraserAction); + buttonPane.add(eraserButton); + } + + /** + * Creates the scroll pane and the scroll area including the + * {@linkplain InteractiveGraphView} and adds itself as + * {@linkplain ComponentListener} to the scroll area. + * + * @author Anselm Schmidt + */ + private void setupScrollArea() { + // create components + graphView = new InteractiveGraphView(this.graphController); + graphController.addGraphObserver(graphView); + scrollArea = new JPanel(); + scrollPane = new JScrollPane(scrollArea, + ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollPane.addComponentListener(this); + scrollPane.getVerticalScrollBar().addMouseListener(this); + scrollPane.getHorizontalScrollBar().addMouseListener(this); + + // set up scroll area + scrollArea.setLayout(new BorderLayout()); + scrollArea.add(graphView, BorderLayout.CENTER); + + // set sizes + graphView.setPreferredSize(new Dimension( + MAX_GRAPH_WIDTH, MAX_GRAPH_HEIGHT)); + + // show the center of the scroll area + int viewportWidth = scrollPane.getViewport().getWidth(); + int viewportHeight = scrollPane.getViewport().getHeight(); + int x = MAX_GRAPH_WIDTH / 2 - viewportWidth / 2; + int y = MAX_GRAPH_HEIGHT / 2 - viewportHeight / 2; + scrollPane.getViewport().setViewPosition(new Point(x, y)); + gui.setGraphViewPosition(new Point(x,y)); + mouseReleased(null); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/FormUtility.java b/src/org/jalgo/module/bfsdfs/gui/components/FormUtility.java new file mode 100644 index 0000000..c3faca8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/FormUtility.java @@ -0,0 +1,112 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Component; +import java.awt.Container; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +import javax.swing.JLabel; + +/** + * Simple utility class for creating forms that have a column + * of labels and a column of fields. All of the labels have the + * same width, determined by the width of the widest label + * component. + *

          + * Philip Isenhour - 060628 - http://javatechniques.com/ + */ +class FormUtility { + /** + * Grid bag constraints for fields and labels + */ + private GridBagConstraints lastConstraints = null; + private GridBagConstraints middleConstraints = null; + private GridBagConstraints labelConstraints = null; + + public FormUtility() { + // Set up the constraints for the "last" field in each + // row first, then copy and modify those constraints. + + // weightx is 1.0 for fields, 0.0 for labels + // gridwidth is REMAINDER for fields, 1 for labels + lastConstraints = new GridBagConstraints(); + + // Stretch components horizontally (but not vertically) + lastConstraints.fill = GridBagConstraints.HORIZONTAL; + + // Components that are too short or narrow for their space + // Should be pinned to the northwest (upper left) corner + lastConstraints.anchor = GridBagConstraints.NORTHWEST; + + // Give the "last" component as much space as possible + lastConstraints.weightx = 1.0; + + // Give the "last" component the remainder of the row + lastConstraints.gridwidth = GridBagConstraints.REMAINDER; + + // Add a little padding + lastConstraints.insets = new Insets(0, 0, 0, 0); + + // Now for the "middle" field components + middleConstraints = + (GridBagConstraints) lastConstraints.clone(); + + // These still get as much space as possible, but do + // not close out a row + middleConstraints.gridwidth = GridBagConstraints.RELATIVE; + + // And finally the "label" constrains, typically to be + // used for the first component on each row + labelConstraints = + (GridBagConstraints) lastConstraints.clone(); + + // Give these as little space as necessary + labelConstraints.weightx = 0.0; + labelConstraints.gridwidth = 1; + } + + /** + * Adds a field component. Any component may be used. The + * component will be stretched to take the remainder of + * the current row. + */ + public void addLastField(Component c, Container parent) { + GridBagLayout gbl = (GridBagLayout) parent.getLayout(); + gbl.setConstraints(c, lastConstraints); + parent.add(c); + } + + /** + * Adds an arbitrary label component, starting a new row + * if appropriate. The width of the component will be set + * to the minimum width of the widest component on the + * form. + */ + public void addLabel(Component c, Container parent) { + GridBagLayout gbl = (GridBagLayout) parent.getLayout(); + gbl.setConstraints(c, labelConstraints); + parent.add(c); + } + + /** + * Adds a JLabel with the given string to the label column. + */ + public JLabel addLabel(String s, Container parent) { + JLabel c = new JLabel(s); + addLabel(c, parent); + return c; + } + + /** + * Adds a "middle" field component. Any component may be + * used. The component will be stretched to take all of + * the space between the label and the "last" field. All + * "middle" fields in the layout will be the same width. + */ + public void addMiddleField(Component c, Container parent) { + GridBagLayout gbl = (GridBagLayout) parent.getLayout(); + gbl.setConstraints(c, middleConstraints); + parent.add(c); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.java b/src/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.java new file mode 100644 index 0000000..bc3c797 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/NodeListRenderer.java @@ -0,0 +1,60 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Font; +import java.util.List; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.ListCellRenderer; + +/** + * This class renders the content of the comboBox startNodeChooser + * used in {@linkplain AlgoTab}. Each entry contains an {@linkplain ImageIcon} + * which is displayed, and the underlying integer. + * + * @author Florian Dornbusch + */ +@SuppressWarnings(value={"unchecked", "unused"}) +class NodeListRenderer +implements ListCellRenderer{ + /** + * This list contains the original integers of the nodes. + * Other classes need this list to read the entries of the + * comboBoxes because they cannot read the image icon. + */ + List theIntList; + + protected DefaultListCellRenderer defaultRenderer = + new DefaultListCellRenderer(); + + public Component getListCellRendererComponent(JList list, Object value, + int index, boolean isSelected, boolean cellHasFocus) { + ImageIcon theIcon = null; + + JLabel renderer = + (JLabel) defaultRenderer.getListCellRendererComponent( + list, value, index, isSelected,cellHasFocus); + + // data conversion + if (value instanceof Object[]) { + Object values[] = (Object[]) value; + if(values[0] instanceof ImageIcon){ + theIcon = (ImageIcon) values[0]; + } + if(values[1] instanceof List) { + theIntList = (List)values[1]; + } + } + + if (theIcon != null) { + renderer.setIcon(theIcon); + } + //eliminate the text + renderer.setText(null); + return renderer; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/NodeStackView.java b/src/org/jalgo/module/bfsdfs/gui/components/NodeStackView.java new file mode 100644 index 0000000..9dfda8d --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/NodeStackView.java @@ -0,0 +1,591 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Font; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Paint; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.module.bfsdfs.algorithms.BFS; +import org.jalgo.module.bfsdfs.algorithms.DFS; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.algorithms.stack.StackObserver; +import org.jalgo.module.bfsdfs.gui.AddNodeAnimation; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; +import org.jalgo.module.bfsdfs.gui.RemoveNodeAnimation; + +/** + * This class represents a Stack with list elements. These lists contain + * integers representing the nodes.
          + * NodeStackView is needed to visualize the queue in + * {@linkplain BFS} and the Stack in {@linkplain DFS}, whereas the queue + * is a special stack with one element list. + * + * @author Florian Dornbusch + */ +public class NodeStackView +extends JPanel +implements GUIConstants, StackObserver { + private static final long serialVersionUID = 7442575235221720865L; + + // general references + private AddNodeAnimation addNodeAnimation = null; + private RemoveNodeAnimation removeNodeAnimation = null; + + /** True for DFS, false for BFS. */ + private boolean successorsVisible; + + /** + * True if a queue was recently removed from the stack and currently + * fades out. + */ + private boolean queueRemoved = false; + + /** True if animations are enabled meaning the nodes fade in and out. */ + private boolean animationsEnabled = true; + + /** + * A size that changes depending on the + * {@linkplain ComponentUtility#BEAMER_MODE}. + * */ + private int nodeSize = NODE_SIZE, borderSize = NODE_BORDER_SIZE; + + /** Alpha value that changes during animations. */ + private int alphaAdd, alphaRemove; + + /** + * Index of the node which was recently removed from the queue and + * currently fades out. if it is -1, no node was removed. + */ + private int removedNodeIndex=-1; + + /** + * The used font. Changes depending on the + * {@linkplain ComponentUtility#BEAMER_MODE}. + */ + private Font font = NODE_FONT; + + /** The used stack data type. */ + private Stack> stack; + + /** + * In this map, every node in the stack gets an own + * {@linkplain NodeStatus}. + * */ + private HashMap map; + + /** Contains nodes that are currently animated. */ + private List addedNodes, removedNodes; + + /** + * Constructor. Creates the stack and a map that matches each node with a + * certain {@linkplain NodeStatus}. Depending on the status, the node is + * drawn differently.
          + * Also creates lists that contain nodes that are currently added to + * or removed from the stack, respectively.
          + * Lastly creates an {@linkplain AddNodeAnimation}and a + * {@linkplain RemoveNodeAnimation}. + * @author Florian Dornbusch + */ + public NodeStackView() { + setBackground(NODESTACKVIEW_BACKGROUND_COLOR); + + stack = new Stack>(); + map = new HashMap(); + + addedNodes = new LinkedList(); + removedNodes = new LinkedList(); + + addNodeAnimation = new AddNodeAnimation(this); + removeNodeAnimation = new RemoveNodeAnimation(this); + } + + /** + * Draws the data as a stack or as a queue depending on + * the boolean value {@link #successorsVisible}. + * @author Florian Dornbusch + */ + @Override + public void paint(Graphics g) { + super.paint(g); + GraphDrawing.enableAntiAliasing(g); + if(successorsVisible) { + try {drawStack(g);} + catch(ConcurrentModificationException e){} + catch( NullPointerException a){} + } + else { + try{drawQueue(g);} + catch(ConcurrentModificationException e){} + } + } + + /** + * Basically, this method is used to decide if this class draws a queue + * or a stack. In a queue the possible successors of a node are not shown. + * @author Florian Dornbusch + */ + public void setSuccessorsVisible(boolean successorsVisible) { + this.successorsVisible = successorsVisible; + } + + /** + * Sets the alpha value of the currently added nodes. + * @author Florian Dornbusch + */ + public void setAlphaAdd(int alpha) { + alphaAdd = alpha; + } + + /** + * Sets the alpha value of the currently removed nodes. + * @author Florian Dornbusch + */ + public void setAlphaRemove(int alpha) { + alphaRemove = alpha; + } + + /** + * This method is invoked when a {@linkplain RemoveNodeAnimation} in the + * queue has finished. It updates the status of the removed node to + * {@linkplain NodeStatus}.FINISHED.
          + * Note: Technically the removed node is not the first element, it + * is just the first that is visible because the prior finished + * nodes stay in the stack but are not drawn. + * @author Florian Dornbusch + */ + public void removeFirstQueueNode() { + if(stack.isEmpty() || removedNodeIndex == -1 || + stack.peek().size() <= removedNodeIndex) return; + map.put(stack.peek().get(removedNodeIndex), NodeStatus.FINISHED); + removedNodeIndex = -1; + } + + /** + * Returns {@linkplain #successorsVisible} indicating whether this is a + * stack or a queue. + * @author Florian Dornbusch + */ + public boolean getSuccessorsVisible() { + return successorsVisible; + } + + /** + * Starts new {@linkplain AddNodeAnimation} and + * {@linkplain RemoveNodeAnimation}. + * @author Florian Dornbusch + */ + public void startAnimation() { + if(!addedNodes.isEmpty()) addNodeAnimation.start(); + if(!animationsEnabled) addNodeAnimation.stop(); + + if(!removedNodes.isEmpty()) removeNodeAnimation.start(); + if(!animationsEnabled) removeNodeAnimation.stop(); + } + + /** + * Stops the current {@linkplain AddNodeAnimation} and + * {@linkplain RemoveNodeAnimation}. + * @author Florian Dornbusch + */ + public void stopAnimation() { + addNodeAnimation.stop(); + removeNodeAnimation.stop(); + } + + /** + * This method is invoked after the {@linkplain RemoveNodeAnimation} of a + * list has finished. It removes the list from the stack.
          + * Also scrolls to the current list. + * @author Florian Dornbusch + */ + public void removeQueue() { + if(!stack.isEmpty()) { + stack.pop(); + queueRemoved = false; + + JScrollPane sp = (JScrollPane)(getParent().getParent()); + int posY = getHeight()-((nodeSize+SPACE_SMALL)*(stack.size()-1)); + sp.getVerticalScrollBar().setValue(posY); + + repaint(); + } + } + + /** + * This method clears the stack. + * @author Florian Dornbusch + */ + public void clearStack() { + if(!stack.isEmpty())stack.clear(); + queueRemoved = false; + repaint(); + } + + /** + * This method is invoked after an {@linkplain AddNodeAnimation} has + * finished. It removes the animated nodes from its list. + * @author Florian Dornbusch + */ + public void clearAddedNodes() { + addedNodes.clear(); + repaint(); + } + + /** + * This method is invoked after an {@linkplain RemoveNodeAnimation} has + * finished. It removes the animated nodes from its list. + * @author Florian Dornbusch + */ + public void clearRemovedNodes() { + removedNodes.clear(); + repaint(); + } + + /** + * Returns if a queue was recently removed and fades out. + * @author Florian Dornbusch + */ + public boolean getQueueRemoved() { + return queueRemoved; + } + + public void setAnimationsEnabled(boolean enabled) { + animationsEnabled = enabled; + } + + /** + * Adjusts the content of this component depending on the + * BEAMER_MODE. + * @author Florian Dornbusch + */ + public void toggleBeamerMode() { + if(ComponentUtility.BEAMER_MODE) { + font = NODE_BEAMER_FONT; + nodeSize = NODE_BEAMER_SIZE; + borderSize = NODE_BEAMER_BORDER_SIZE; + } + else { + font = NODE_FONT; + nodeSize = NODE_SIZE; + borderSize = NODE_BORDER_SIZE; + } + } + + /** + * When a queue is added to the stack, this method checks if the related + * owner is already in the stack.
          + * If not, a new list is created and added to the stack.
          + * Also scrolls to the current list. + * @author Florian Dornbusch + */ + public void onQueueAdded(int owner) { + // search the node + boolean nodeFound = false; + for(List l:stack) { + if(l.get(0) == owner) nodeFound = true; + } + + // if it was not found, a new stack line is added + if(!nodeFound){ + List list = new LinkedList(); + if(successorsVisible) list.add(owner); + stack.push(list); + + // scroll to the current stack line + JScrollPane sp = (JScrollPane)(getParent().getParent()); + int posY = getHeight()-((nodeSize+SPACE_SMALL)*(stack.size()-1)); + sp.getVerticalScrollBar().setValue(posY); + } + + repaint(); + } + + /** + * Apart from invoking {@linkplain #onQueueAdded(int)} this method also + * clears the stack. + * @author Florian Dornbusch + */ + public void onFirstQueueAdded(int owner) { + stack.clear(); + onQueueAdded(owner); + } + + /** + * If the status of a node changes, the node is searched in the stack. If + * the node is not found, it will be added to the topmost stack line.
          + * Regardless of whether the node was found or not, the changed status + * is saved. + * @author Florian Dornbusch + */ + public void onStatusChanged(int node, NodeStatus status) { + if(stack.isEmpty()) return; + + // search the node + boolean nodeFound = false; + for(List l:stack) { + if(l.contains(node)) nodeFound = true; + } + + // if it was not found, add the node to the topmost stack line + List list = stack.peek(); + if(!nodeFound){ + list.add(node); + } + + // if a node was set finished in the queue it has to be animated + if(status == NodeStatus.FINISHED && !successorsVisible) { + // calculate the index of this node + for(int i=0; iUNTOUCHED
          . + * @author Florian Dornbusch + */ + public void onNodesAdded(List nodes){ + if(nodes == null || nodes.isEmpty()) return; + if(stack.isEmpty()) return; + if(queueRemoved) return; + if(stack.peek().containsAll(nodes)) return; + + stack.peek().addAll(nodes); + for(int i:nodes) { + map.put(i, NodeStatus.UNTOUCHED); + addedNodes.add(i); + } + + repaint(); + } + + /** + * This method is invoked when the successor order of the current node has + * changed.
          + * Provided that these successors are in the topmost stack line, + * the old ones are removed and the new ones are added. + * @author Florian Dornbusch + */ + public void onUntouchedReplaced(List o, List n) { + if(o == null || o.isEmpty()) return; + if(n != null && o.equals(n)) return; + if(n != null && o.size() != n.size()) return; + + List list = stack.peek(); + + stopAnimation(); + + list.removeAll(o); + if(n!=null){ + list.addAll(n); + for(int i:n) { + map.put(i, NodeStatus.UNTOUCHED); + } + addedNodes.addAll(n); + } + + startAnimation(); + } + + /** + * Adds all nodes that are to be removed to the corresponding list to fade + * them out. Also declares that a queue was removed. + * @author Florian Dornbusch + */ + public void onTopQueueRemoved() { + if(stack.isEmpty()) return; + + removedNodes.addAll(stack.peek()); + queueRemoved = true; + repaint(); + } + + /** Unused method from {@linkplain StackObserver}. */ + public void onAllQueuesRemoved() {} + + /** Unused method from {@linkplain StackObserver}. */ + public void onAllNodesFinished() {} + + /** Unused method from {@linkplain StackObserver}. */ + public void onCurrentNodeChanged(int i) {} + + /** + * If the nodes are too large to be fully drawn, + * the size of this panel is matched dynamically. + * @param posX : The x-coordinate of the current drawn node + * @param posY : The y-coordinate of the current drawn node. + * @author Florian Dornbusch + */ + private void matchSize(int posX, int posY) { + if(posY<0) { + setSize(getWidth(), getHeight()- posY); + setPreferredSize(getSize()); + } + + int x = posX+nodeSize+SPACE_SMALL; + if(x>getWidth() || !successorsVisible) { + setSize(x, getHeight()); + setPreferredSize(getSize()); + } + } + + /** + * Draws a successor in the current stack line. + * @param g : The used Graphics. + * @param e : The number / label of the node. + * @param posX : The x-coordinate of the current drawn node + * @param posY : The y-coordinate of the current drawn node. + * @author Florian Dornbusch + */ + private void drawSuccessor(Graphics g, int e, int posX, int posY) { + int alphaSuccessor = ALPHA_100_PERCENT; + + // decide which alpha value this node gets + boolean b = removedNodes.contains(e); + // if this is a stack, animate only the nodes in topmost line with a + // remove animation + if(successorsVisible) b = b + && (posY == getHeight()-((nodeSize+SPACE_SMALL)*(stack.size()-1))); + if(b && animationsEnabled) alphaSuccessor = alphaRemove; + if(addedNodes.contains(e) && animationsEnabled) + alphaSuccessor = alphaAdd; + + try { + // draw the node + ComponentUtility.drawNode(g, posX, posY, e, + map.get(e), nodeSize, borderSize, + font, alphaSuccessor); + } + catch (IllegalArgumentException exc) {} + } + + /** + * This method draws the stack in a vertical style. The first element in + * each line is the owner. It is separated from the possible successors + * through a border. + * @param i : The position of a node in the stack. i=1 is the lowest point. + * @param posY : The actual height in pixel of the node in pixel. + * @param j : The position of a node in the current line. j=0 is the first + * node after the owner. + * @author Florian Dornbusch + */ + private void drawStack(Graphics g) { + int i=1, j=-1, posY=getHeight(); + + // highlight the owner column + Graphics2D g2 = (Graphics2D)g; + Paint gp = new GradientPaint(25, 0, NODESTACKVIEW_OWNER_COLOR_LEFT, + SPACE_SMALL + nodeSize + SPACE_BIG / 2, 0, + NODESTACKVIEW_OWNER_COLOR_RIGHT); + g2.setPaint(gp); + g2.fillRect(0, 0, SPACE_SMALL + nodeSize + SPACE_BIG / 2, + posY+nodeSize+SPACE_SMALL); + + // in every cycle of the loop one line is drawn + // a line represents the owner, its possible successors and a border + for(List list:stack) { + // draw not the first line because it is only used for + // initialization + if(list.get(0)!=0) { + // calculate the y-coordinate of the current line + posY = getHeight()-((nodeSize+SPACE_SMALL)*(i)); + + // match the new size + matchSize(0, posY); + + // check the alpha value of the owner + int alphaOwner = ALPHA_100_PERCENT; + if(addedNodes.contains(list.get(0)) && animationsEnabled) + alphaOwner = alphaAdd; + if(removedNodes.contains(list.get(0)) && animationsEnabled + && alphaRemove > 0 && queueRemoved) { + alphaOwner = alphaRemove; + } + + // draw the owner + ComponentUtility.drawNode(g,SPACE_SMALL, posY, list.get(0), + NodeStatus.WAITING, nodeSize, borderSize, + font, alphaOwner); + + // in every cycle of this loop, one successor is drawn + for(Integer e:list) { + // leave out the owner because it is already drawn + if(j>-1) { + // calculate the x-coordinate of the node + int posX = SPACE_SMALL + nodeSize + SPACE_BIG + +j*(nodeSize+SPACE_SMALL); + + // match the new size + matchSize(posX, posY); + + // draw the node + drawSuccessor(g, e, posX, posY); + } + j++; + } + i++; + j=-1; + } + } + } + + /** + * This method draws the queue in a horizontal style. + * @param i : the position of a node in the stack. + * i=1 is the lowest point + * @param posY : is the actual height of the node in pixel + * @param j : the position of a node in the current line + * j=0 is the first node after the owner + * @author Florian Dornbusch + */ + private void drawQueue(Graphics g) { + Integer i=0; + + // calculate the height of the nodes, so that they are centered + int posY = getHeight() / 2 - nodeSize / 2; + + if(!stack.isEmpty()) { + // draw only the top line (this should be the only line in the + // stack). in every cycle, one node is drawn. + for(Integer e:stack.peek()) { + // calculate the x-coordinate of the node + int posX = SPACE_SMALL + i*(nodeSize+SPACE_SMALL); + + // match the new size + matchSize(posX,posY); + + // do not draw nodes that are already finished + if(map.get(e) != NodeStatus.FINISHED) { + // draw the node + drawSuccessor(g,e,posX,posY); + i++; + } + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/ScrollArea.java b/src/org/jalgo/module/bfsdfs/gui/components/ScrollArea.java new file mode 100644 index 0000000..1af6c66 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/ScrollArea.java @@ -0,0 +1,240 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Cursor; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Paint; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.JPanel; +import javax.swing.JScrollBar; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * This class represents an area to scroll the {@linkplain SuccessorChooser}. + * There is a scroll area to scroll to the left and to the right. As long as + * the mouse is inside this area, the scrolling is done automatically. + * @author Florian Dornbusch + */ +public class ScrollArea +extends JPanel +implements MouseListener, GUIConstants { + private static final long serialVersionUID = 134960763689527085L; + + /** The used Thread that scrolls the {@linkplain SuccessorChooser}. */ + private ScrollThread st; + + /** The used {@linkplain AlgoTab}. */ + private AlgoTab algoTab; + + /** Determines if this class scrolls to the left or to the right. */ + private boolean left; + + /** + * The horizontal scroll bar that is used to scroll the + * {@linkplain SuccessorChooser} but is invisble because these two scroll + * areas scroll it. + */ + private JScrollBar sb; + + /** + * Constructor. Adds a {@linkplain MouseListener} to itself to enable and + * disable scrolling. + * @author Florian Dornusch + */ + public ScrollArea(JScrollBar sb, boolean left, AlgoTab algoTab) { + setEnabled(false); + addMouseListener(this); + + this.left = left; + this.algoTab = algoTab; + this.sb = sb; + + st = new ScrollThread(); + } + + /** + * If the mouse is inside this component, it updates the cursor and the + * status message and starts the scrolling thread. + * @author Florian Dornbusch + */ + public void mouseEntered(MouseEvent e) { + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + JAlgoGUIConnector.getInstance().setStatusMessage( + Messages.getString("bfsdfs", "ScrollArea.status")); + + st.start(); + algoTab.getLeftScrollArea().repaint(); + algoTab.getRightScrollArea().repaint(); + } + + /** + * If the mouse is outside this component, this method resets the status + * message and stops the current scrolling thread. + * @author Florian Dornbusch + */ + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + + st.stop(); + algoTab.getLeftScrollArea().repaint(); + algoTab.getRightScrollArea().repaint(); + } + + /** Unused observer method. */ + public void mouseClicked(MouseEvent e) {} + + /** Unused observer method. */ + public void mousePressed(MouseEvent e) {} + + /** Unused observer method. */ + public void mouseReleased(MouseEvent e) {} + + /** + * Paints only if this panel is enabled and paints differently dependent + * on {@linkplain #left}. + * @author Florian Dornbusch + */ + @Override + public void paint(Graphics gr) { + super.paint(gr); + Graphics2D g = (Graphics2D) gr; + if(!this.isEnabled()) return; + GraphDrawing.enableAntiAliasing(g); + if(left) drawLeft(g); + else drawRight(g); + } + + /** + * Draws a triangle which points to the left with a gradient. + * @author Florian Dornbusch + */ + private void drawLeft(Graphics2D g) { + Paint gp = new GradientPaint(0, 0, NODESTACKVIEW_OWNER_COLOR_RIGHT, + getWidth(), 0, NODESTACKVIEW_OWNER_COLOR_LEFT); + g.setPaint(gp); + int xpoints[] = {getWidth(), 0, getWidth()}; + int ypoints[] = {0, getHeight() / 2, getHeight()}; + g.fillPolygon(xpoints, ypoints, 3); + } + + /** + * Draws a triangle which points to the right with a gradient. + * @author Florian Dornbusch + */ + private void drawRight(Graphics2D g) { + Paint gp = new GradientPaint(0, 0, NODESTACKVIEW_OWNER_COLOR_LEFT, + getWidth(), 0, NODESTACKVIEW_OWNER_COLOR_RIGHT); + g.setPaint(gp); + int xpoints[] = {0, getWidth(), 0}; + int ypoints[] = {0, getHeight() / 2, getHeight()}; + g.fillPolygon(xpoints, ypoints, 3); + } + + + /** + * Inner class of {@linkplain ScrollArea} that handles the scrolling. + * @author Florian Dornbusch + */ + private class ScrollThread implements Runnable, GUIConstants { + + /** The used thread. */ + private Thread runner=null; + + /** + * Starts the thread and enables the other scroll area. + * @author Florian Dornbusch + */ + public void start() { + if ( runner == null ) { + runner = new Thread( this ); + + ScrollArea other; + if(left) other = algoTab.getRightScrollArea(); + else other = algoTab.getLeftScrollArea(); + + if(isEnabled()) { + other.setEnabled(true); + runner.start(); + } + } + } + + /** + * Stops the current thread and repaints both {@linkplain ScrollArea}s. + * @author Florian Dornbusch + */ + public void stop() { + if ( runner != null && runner.isAlive() ) + runner.interrupt(); + runner = null; + algoTab.getLeftScrollArea().repaint(); + algoTab.getRightScrollArea().repaint(); + } + + /** + * Runs the thread. This method computes the actual scrolling. + * Scrolling differs dependent on {@linkplain ScrollArea#left}. + * @author Florian Dornbusch + */ + public void run() { + if(left) runleft(); + else runright(); + } + + /** + * While the invisible scroll bar of the {@linkplain SuccessorChooser} + * is not leftmost, this method moves the scroll bar an amount of pixel + * in every loop.
          + * Disables itself if it is finished to be no longer drawn. + * @author Florian Dornbusch + */ + private void runleft() { + int value = sb.getValue(); + + while(value > 0 && runner != null) { + value -= SCROLL_FACTOR; + sb.setValue(value); + try { + Thread.sleep(ANIMATION_REPAINT_DELAY); + } + catch ( InterruptedException ex ) {} + } + if(runner != null) setEnabled(false); + stop(); + } + + /** + * While the invisible scroll bar of the {@linkplain SuccessorChooser} + * is not rightmost, this method moves the scroll bar an amount of + * pixel in every loop.
          + * Disables itself if it is finished to be no longer drawn. + * @author Florian Dornbusch + */ + private void runright() { + int value = sb.getValue(); + int maximum = value + SCROLL_FACTOR; + + while(value < maximum && runner != null) { + sb.setValue(maximum); + if(sb.getValue() > value) { + maximum += SCROLL_FACTOR; + } + value += SCROLL_FACTOR; + + try { + Thread.sleep(ANIMATION_REPAINT_DELAY); + } + catch ( InterruptedException ex ) {} + } + if(runner != null) setEnabled(false); + stop(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.java b/src/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.java new file mode 100644 index 0000000..63f7b0e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/SuccessorChooser.java @@ -0,0 +1,381 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * This class represents a panel where the current successors are drawn. + * One can change the order of the successors by using drag & drop.
          + * Once a new order is set, it is sent to the {@linkplain GUIController}. + * + * @author Florian Dornbusch + */ +public class SuccessorChooser +extends JPanel +implements GUIConstants, MouseListener, MouseMotionListener { + private static final long serialVersionUID = -4310412523478515344L; + + /** The {@linkplain GUIController}. */ + private GUIController gui; + + /** The current cursor position */ + private Point cursorPosition; + + /** + * The id of the node that is currently dragged.
          + * This attribute is 0 if no node is dragged. + */ + private int cursorNode = 0; + + /** True if the mouse is inside this component. */ + private boolean mouseInside; + + /** True if the mouse button is currently pressed. */ + private boolean mousePressed; + + /** True if this component was resized due to too much */ + private boolean resized = false; + + /** This list contains all currently available successors. */ + private List nodes; + + /** + * Maps properties to every node. The first entry in this array holds the + * coordinates and the second indicate if the node is highlighted. + */ + private Map properties; + + /** + * The {@linkplain AlgoTab}. It is used by this class to update the two + * {@linkplain ScrollArea}s. + */ + private AlgoTab algoTab; + + /** + * Constructor. + * @author Florian Dornbusch + */ + public SuccessorChooser(GUIController gui, AlgoTab algoTab) { + this.gui = gui; + this.algoTab = algoTab; + + cursorPosition = new Point(); + nodes = new LinkedList(); + properties = new HashMap(); + + this.addMouseListener(this); + this.addMouseMotionListener(this); + } + + /** + * Additionally changes the background color of this component. + * @author Florian Dornbusch + */ + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if(enabled) setBackground(Color.white); + else setBackground(getParent().getBackground()); + } + + /** + * Paints the current successors in a horizontal style. + * @author Florian Dornbusch + */ + @Override + public void paint(Graphics g) { + super.paint(g); + if(!isEnabled() || nodes == null || nodes.isEmpty()) return; + GraphDrawing.enableAntiAliasing(g); + + // in each cycle of the loop one node is drawn + for(int n:nodes) { + // set a new size if necessary + matchSize(n); + + // if this node is highlighted, it is drawn with a different color + Color b; + Color l; + if((Boolean)properties.get(n)[1]) { + b = NODE_BORDER_COLOR_FOCUSED; + l = NODE_LABEL_COLOR_FOCUSED; + } else { + b = NODE_BORDER_COLOR; + l = NODE_LABEL_COLOR; + } + + // draw the node + if(n != cursorNode || !mousePressed) { + GraphDrawing.drawNode(g, Integer.toString(n), + (Point)properties.get(n)[0], + NODE_FONT, NODE_SIZE, NODE_BORDER_SIZE, b, + l, NODE_COLOR, NODE_COLOR, + ALPHA_100_PERCENT, 0); + } + } + + // draw the cursor if a dragging is currently performed + if(mouseInside && mousePressed && cursorNode != 0) { + GraphDrawing.drawNode(g, Integer.toString(cursorNode), + cursorPosition, + NODE_FONT, NODE_SIZE, NODE_BORDER_SIZE,NODE_BORDER_COLOR, + NODE_LABEL_COLOR, NODE_COLOR, NODE_COLOR, + 160, 0); + } + } + + /** + * This method is invoked if new successors are available. It clears all + * current data, sets the new nodes and maps coordinates to them. + * @author Florian Dornbusch + */ + public void fill(List nodes) { + + resized = false; + + this.nodes.clear(); + properties.clear(); + + cursorNode = 0; + + this.nodes.addAll(nodes); + + for(int i = 0; i < nodes.size(); i++) { + int x = SPACE_SMALL + i*(NODE_SIZE + SPACE_SMALL)+ NODE_SIZE / 2; + int y = getHeight() / 2; + Object[] p = {new Point(x,y), false}; + properties.put(nodes.get(i), p); + } + + repaint(); + } + + /** Unused observer method. */ + public void mouseClicked(MouseEvent e) {} + + /** + * If the mouse enters this component, this state is saved. + * @author Florian Dornbusch + */ + public void mouseEntered(MouseEvent e) { + mouseInside = true; + repaint(); + } + + /** + * If the mouse exits this component, no node is highlighted. + * @author Florian Dornbusch + */ + public void mouseExited(MouseEvent e) { + mouseInside = false; + clearHighlighted(); + repaint(); + } + + /** + * If a mouse button is pressed, this state is saved and the rest of + * this method is similar to {@linkplain #mouseMoved(MouseEvent)}. + * @author Florian Dornbusch + */ + public void mousePressed(MouseEvent e) { + if(mousePressed) return; + mousePressed = true; + + mouseMoved(e); + matchCoords(); + } + + /** + * If a mouse button is released, a new successor order is set and is sent + * to the {@linkplain GUIController}. + * @author Florian Dornbusch + */ + public void mouseReleased(MouseEvent e) { + mousePressed = false; + if(cursorNode != 0 && mouseInside) { + validateSuccessors(); + gui.setSuccessorOrder(nodes); + } else { + // readjust the coordinates of the nodes + List temp = new LinkedList(); + temp.addAll(nodes); + fill(temp); + temp = null; + } + repaint(); + } + + /** + * If the mouse is dragged, the new position of the mouse cursor is saved. + * @author Florian Dornbusch + */ + public void mouseDragged(MouseEvent e) { + cursorPosition = e.getPoint(); + + repaint(); + } + + /** + * If the mouse is moved, this method sets the highlighted property for + * the node that is under the mouse and changes the mouse cursor if the + * mouse is over a node. + * @author Florian Dornbusch + */ + public void mouseMoved(MouseEvent e) { + cursorPosition = e.getPoint(); + + boolean hitAnything = false; + + for (Entry entry : properties.entrySet()) { + if(isCursorInsideNode((Point)entry.getValue()[0])) { + cursorNode = entry.getKey(); + hitAnything = true; + + Object[] p = {(Point)entry.getValue()[0], true}; + properties.put(entry.getKey(), p); + } else { + Object[] p = {(Point)entry.getValue()[0], false}; + properties.put(entry.getKey(), p); + } + } + + if(!hitAnything) { + cursorNode = 0; + setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } else { + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + + repaint(); + } + + /** + * This method checks the mouse cursor is over a given node represented by + * its center position. + * @author Florian Dornbusch + */ + private boolean isCursorInsideNode(Point node) { + + int x = Math.abs(cursorPosition.x- node.x); + int y = Math.abs(cursorPosition.y- node.y); + + double distance = Math.sqrt(x * x + y * y); + + if(distance > NODE_SIZE / 2) return false; + return true; + } + + /** + * This method checks if a node is at the right side of the currently + * dragged node and changes sets its new position one to the left. + * @author Florian Dornbusch + */ + private void matchCoords() { + int cursorX = ((Point)properties.get(cursorNode)[0]).x; + for (Entry entry : properties.entrySet()) { + int x = ((Point)entry.getValue()[0]).x; + if(x > cursorX) { + Point newPoint = ((Point)entry.getValue()[0]); + newPoint.x -= NODE_SIZE + SPACE_SMALL; + Object[] p = {newPoint, ((Boolean)entry.getValue()[1])}; + properties.put(entry.getKey(), p); + } + } + } + + /** + * This method sets the size of this component according to the amount of + * successors. + * @param n : The id of the node that is currently checked. + * @author Florian Dornbusch + */ + private void matchSize(int n) { + + int x = ((Point)properties.get(n)[0]).x; + // if there are too many successors + if(x > getWidth()) { + // set the new size + setSize(x + NODE_SIZE / 2 + SPACE_SMALL,getHeight()); + setPreferredSize(getSize()); + + // sets the new values for the two scroll areas. the left one + // is only shown if the invisible scroll bar is not leftmost. + boolean b = ((JScrollPane)getParent().getParent()). + getHorizontalScrollBar().getValue() != 0; + algoTab.getLeftScrollArea().setEnabled(b); + algoTab.getRightScrollArea().setEnabled(true); + + resized = true; + } + if(!resized) { + // set the normal size + setSize(getParent().getParent().getWidth(),getHeight()); + setPreferredSize(getSize()); + + // disable the scroll areas + algoTab.getLeftScrollArea().setEnabled(false); + algoTab.getRightScrollArea().setEnabled(false); + } + } + + /** + * This method creates a list of all nodes and inserts the currently + * dragged node at the right position. + * @author Florian Dornbusch + */ + private void validateSuccessors() { + List result = new LinkedList(); + + int leftNeighborX=0, leftNeighbor=0; + + for (Entry entry : properties.entrySet()) { + if(entry.getKey() != cursorNode) { + // get the left neighbor of the mouse + int x = ((Point)entry.getValue()[0]).x; + if(leftNeighborX <= x && x <= cursorPosition.x) { + leftNeighborX = x; + leftNeighbor = entry.getKey(); + } + } + } + + // if the dragged node is the most left one + if(leftNeighbor == 0) result.add(cursorNode); + + for(int i=0;i entry : properties.entrySet()) { + Object[] p = {((Point)entry.getValue()[0]), false}; + properties.put(entry.getKey(), p); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/TabContainer.java b/src/org/jalgo/module/bfsdfs/gui/components/TabContainer.java new file mode 100644 index 0000000..69cbbac --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/TabContainer.java @@ -0,0 +1,260 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Action; +import javax.swing.ImageIcon; +import javax.swing.JPanel; +import javax.swing.JToggleButton; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.algorithms.BFS; +import org.jalgo.module.bfsdfs.algorithms.DFS; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.StatusMouseAdapter; +import org.jalgo.module.bfsdfs.gui.event.BeamerAction; + +/** + * This class represents a container. It consists of three windows which can be + * shown by clicking on their corresponding buttons. The three windows are: + *

            + *
          • {@linkplain DesignTab}: design and edit a graph
          • + *
          • {@linkplain BFSTab}: visualize the breadth first search algorithm
          • + *
          • {@linkplain DFSTab}: visualize the depth first search algorithm
          • + *
          + * There is also a beamer mode button available. + * + * @author Anselm Schmidt, + * @author Florian Dornbusch + */ +public class TabContainer +extends JPanel +implements GUIConstants { + private static final long serialVersionUID = -5942603844775439386L; + + // general references + private GUIController gui; + private DesignTab designTab; + private BFSTab bfsTab; + private DFSTab dfsTab; + + // components + private JPanel tabArea; + private JPanel buttonArea; + private JPanel leftButtons; + private JPanel rightButtons; + private JToggleButton designButton; + private JToggleButton bfsButton; + private JToggleButton dfsButton; + private JToggleButton beamerButton; + private CardLayout layout; + private Action beamerAction; + + /** + * Creates the Tab Container and its components. + * @author Florian Dornbusch + * @author Anselm Schmidt + */ + public TabContainer(GUIController gui, BFS bfs, DFS dfs, + GraphController graphController) { + + this.gui = gui; + + // create the tabs + designTab = new DesignTab(gui, graphController); + dfsTab = new DFSTab(gui, graphController, dfs); + bfsTab = new BFSTab(gui, graphController, bfs); + + // create Panels + buttonArea = new JPanel(); + tabArea = new JPanel(); + leftButtons = new JPanel(); + rightButtons = new JPanel(); + + // create the buttons + designButton = setupButton("designButton"); + designButton.setSelected(true); + bfsButton = setupButton("bfsButton"); + dfsButton = setupButton("dfsButton"); + beamerAction = new BeamerAction(gui); + beamerButton = setupButton("beamerButton"); + + // add the tab buttons to the left + leftButtons.add(designButton); + leftButtons.add(dfsButton); + leftButtons.add(bfsButton); + + // add the beamer button to the right + rightButtons.add(beamerButton); + + // add buttons to the area + buttonArea.setLayout(new BorderLayout()); + buttonArea.setPreferredSize(new Dimension(0,40)); + buttonArea.add(leftButtons, BorderLayout.WEST); + buttonArea.add(rightButtons, BorderLayout.EAST); + + // set up the tab area + layout = new CardLayout(); + tabArea.setLayout(layout); + tabArea.add(designTab, "designTab"); + tabArea.add(bfsTab, "bfsTab"); + tabArea.add(dfsTab, "dfsTab"); + + // add the areas to the container + setLayout(new BorderLayout()); + add(buttonArea, BorderLayout.NORTH); + add(tabArea, BorderLayout.CENTER); + + toggleBeamerMode(); + + handleEvents(); + } + + /** + * Returns the {@linkplain DesignTab}. + * @author Florian Dornbusch + */ + public DesignTab getDesignTab() { + return designTab; + } + + /** + * Returns the {@linkplain BFSTab}. + * @author Florian Dornbusch + */ + public BFSTab getBFSTab() { + return bfsTab; + } + + /** + * Returns the {@linkplain DFSTab}. + * @author Florian Dornbusch + */ + public DFSTab getDFSTab() { + return dfsTab; + } + + /** + * Returns the used {@linkplain BeamerAction}. + * @author Florian Dornbusch + */ + public Action getBeamerAction() { + return beamerAction; + } + + /** + * This method changes the content of this component depending on + * {@linkplain ComponentUtility#BEAMER_MODE} + * @author Florian Dornbusch + */ + public void toggleBeamerMode() { + Font font; + if(ComponentUtility.BEAMER_MODE) font = BEAMER_WRITING_FONT; + else font = WRITING_FONT; + designButton.setFont(font); + bfsButton.setFont(font); + dfsButton.setFont(font); + beamerButton.setFont(font); + } + + + private void handleEvents() { + designButton.addActionListener(new ActionListener() { + /** + * This method is invoked if the user clicks on the design button. + * The position of the viewport in the old tab is used to set the + * new viewport properly. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent event) { + layout.show(tabArea, "designTab"); + + if(bfsButton.isSelected()) + bfsTab.saveViewportPosition(); + else dfsTab.saveViewportPosition(); + designTab.loadViewportPosition(); + + designButton.setSelected(true); + dfsButton.setSelected(false); + bfsButton.setSelected(false); + + gui.switchToDesign(); + } + }); + + dfsButton.addActionListener(new ActionListener() { + /** + * This method is called if the user clicks on the DFS button. + * The position of the viewport of the old tab is used to set the + * new viewport properly. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent event) { + layout.show(tabArea, "dfsTab"); + + if(designButton.isSelected()) + designTab.saveViewportPosition(); + else bfsTab.saveViewportPosition(); + dfsTab.loadViewportPosition(); + + designButton.setSelected(false); + dfsButton.setSelected(true); + bfsButton.setSelected(false); + + gui.switchToDFS(); + } + }); + + bfsButton.addActionListener(new ActionListener() { + /** + * This method is called if the user clicks on the BFS button. + * The position of the viewport of the old tab is used to set the + * new viewport properly. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent event) { + layout.show(tabArea, "bfsTab"); + + if(designButton.isSelected()) + designTab.saveViewportPosition(); + else dfsTab.saveViewportPosition(); + bfsTab.loadViewportPosition(); + + designButton.setSelected(false); + dfsButton.setSelected(false); + bfsButton.setSelected(true); + + gui.switchToBFS(); + } + }); + } + + /** + * Creates a new button for the TabContainer. + * @param name : The name of the corresponding entry in the properties + * files. + * @return The created button. + * @author Florian Dornbusch + */ + private JToggleButton setupButton(String name) { + JToggleButton b = new JToggleButton(); + if(name == "beamerButton") b.setAction(beamerAction); + b.setText(Messages.getString("bfsdfs", + "tab."+name)); + b.addMouseListener(new StatusMouseAdapter( + "tab."+name+"_tooltip")); + b.setToolTipText(Messages.getString("bfsdfs", + "tab."+name+"_tooltip")); + b.setIcon(new ImageIcon(Messages.getResourceURL("bfsdfs", + "tab."+name))); + return b; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.java b/src/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.java new file mode 100644 index 0000000..3e453fc --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/WelcomeButton.java @@ -0,0 +1,55 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; + +import org.jalgo.module.bfsdfs.gui.event.WelcomeScreenActionHandler; + +/** + * This class represents one of three buttons in {@linkplain WelcomeScreen}. + * It is a roll over enabled graphical button. + * + * @author Florian Dornbusch + */ +public class WelcomeButton +extends JToggleButton { + private static final long serialVersionUID = -1924541401853204950L; + + private final ImageIcon desc; + + public WelcomeButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + ImageIcon description, String actionCommand, + WelcomeScreenActionHandler action) { + + desc = description; + this.setFocusable(false); + + // set the icons + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + // set the size of the button to the size of the icon + setMinimumSize(new Dimension( + defaultIcon.getIconWidth(), + defaultIcon.getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + // set up the action command and the listeners + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(action); + } + + /** + * Returns the description of this button. + * @author Florian Dornbusch + */ + public ImageIcon getDescription() { + return desc; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.java b/src/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.java new file mode 100644 index 0000000..12b0572 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/WelcomeScreen.java @@ -0,0 +1,111 @@ +package org.jalgo.module.bfsdfs.gui.components; + +import java.awt.Component; +import java.awt.Dimension; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.bfsdfs.ModuleConnector; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.event.WelcomeScreenActionHandler; + +/** + * This class represents the welcome screen of this module. It contains three + * buttons to create a new graph, load a graph from an existing file and load + * the last opened graph. Furthermore it contains a description label that + * indicated the use of every button. + * + * @author Florian Dornbusch + */ +public class WelcomeScreen +extends JPanel +implements GUIConstants { + private static final long serialVersionUID = 8620144727183351679L; + + + private WelcomeScreenActionHandler action; + + // components + private WelcomeButton newButton; + private WelcomeButton loadButton; + private WelcomeButton lastButton; + private JLabel descriptionLabel; + private JPanel buttonPane; + + public WelcomeScreen(GUIController guiController) { + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBackground(WELCOME_SCREEN_BACKGROUND); + + action = new WelcomeScreenActionHandler(this, guiController); + + // create buttons + String lang = Settings.getString("main", "Language"); + if (!lang.equals("de")) lang = "en"; + newButton = new WelcomeButton( + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.newButton")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.newButton_over")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.newButton_descr_"+lang)), + "new", action); + loadButton = new WelcomeButton( + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.loadButton")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.loadButton_over")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.loadButton_descr_"+lang)), + "load", action); + lastButton = new WelcomeButton( + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.lastButton")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.lastButton_over")), + new ImageIcon(Messages.getResourceURL("bfsdfs", + "WelcomeScreen.lastButton_descr_"+lang)), + "last", action); + + // set up the button pane + buttonPane = new JPanel(); + buttonPane.setBackground(WELCOME_SCREEN_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(newButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(loadButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(lastButton); + + // hide "lastButton" if it is not needed + lastButton.setVisible(ModuleConnector.islastOpenedFileKnown()); + + // set up the description label + descriptionLabel = new JLabel(); + descriptionLabel.setPreferredSize(new Dimension(0,25)); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + // add the main components to the welcome screen + add(Box.createVerticalGlue()); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + add(Box.createVerticalGlue()); + } + + /** + * Changes the description of each button dynamically. + * @author Florian Dornbusch + */ + public void setDescription(Icon desc) { + descriptionLabel.setIcon(desc); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/components/package.html b/src/org/jalgo/module/bfsdfs/gui/components/package.html new file mode 100644 index 0000000..a4fc6b9 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/components/package.html @@ -0,0 +1,30 @@ + + + + +

          +This package contains every component that is visible in the module except the GraphViews. There +are: +

            +
          • The WelcomeScreen with its three WelcomeButtons. Here you can create a new +graph, load an existing graph from file or load the last opened graph.
          • +
          • The TabContainer which represents a simple container class with a card layout that switches +its content by pressing the according button. It handles the three windows DesignTab, +BFSTab and DFSTab. Also, there is a beamer mode button that switches the sizes and +fonts of the components.
          • +
          • The DesignTab which is used to work with the graph. It is possible to add / move nodes, +add edges and erase structures and also undo / redo these steps.
          • +
          • The AlgoTab which is the super class of the other two windows BFSTab and +DFSTab. Here it is possible to control the according algorithm meaning the commands reset, step +back, step forward, play and cancel. Furthermore one can choose the start node, the order of the possible +successors and toggle the non-determinism.
            +They also contain the NodeStackView that visualizes the stack / queue used by the algorithm.
          • +
          • The SuccessorChooser from where the user can change the order of the current successors +per Drag & Drop. It is associated with its two ScrollAreas which are necessary to scroll it.
          • +
          • Some utility classes, such as FormUtility to create a nice GridBagLayout and the +NodeListRenderer that renders the nodes in the start node chooser, so that it contains icons +instead of numbers.
          • +
          +

          + + \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/AnimationAction.java b/src/org/jalgo/module/bfsdfs/gui/event/AnimationAction.java new file mode 100644 index 0000000..214f8d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/AnimationAction.java @@ -0,0 +1,31 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to turn the animations on and off. + * + * @author Ephraim Zimmer + */ +public class AnimationAction +extends AbstractAction { + private static final long serialVersionUID = -5649219591514335869L; + + private GUIController gui; + + public AnimationAction(GUIController gui) { + this.gui = gui; + setEnabled(false); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "AnimationAction.tooltip")); + } + + public void actionPerformed(ActionEvent e) { + gui.toggleAnimation(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/BeamerAction.java b/src/org/jalgo/module/bfsdfs/gui/event/BeamerAction.java new file mode 100644 index 0000000..914f4a0 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/BeamerAction.java @@ -0,0 +1,29 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; + +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to toggle the beamer mode. + * + * @author Florian Dornbusch + */ +public class BeamerAction +extends AbstractAction { + private static final long serialVersionUID = 2372809553068441995L; + + private GUIController gui; + + public BeamerAction(GUIController guiController) { + this.gui = guiController; + } + + public void actionPerformed(ActionEvent event) { + ComponentUtility.BEAMER_MODE = !ComponentUtility.BEAMER_MODE; + gui.toggleBeamerMode(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/CVS/Entries b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Entries new file mode 100644 index 0000000..915c9f1 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Entries @@ -0,0 +1,16 @@ +/AnimationAction.java/1.1/Wed Dec 8 13:47:54 2010// +/BeamerAction.java/1.1/Wed Dec 8 13:47:54 2010// +/CancelAction.java/1.1/Wed Dec 8 13:47:54 2010// +/DoubleEdgeAction.java/1.1/Wed Dec 8 13:47:54 2010// +/EdgeAction.java/1.1/Wed Dec 8 13:47:54 2010// +/EraserAction.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeAction.java/1.1/Wed Dec 8 13:47:54 2010// +/PlayAction.java/1.1/Wed Dec 8 13:47:54 2010// +/RandomAction.java/1.1/Wed Dec 8 13:47:54 2010// +/RedoAction.java/1.1/Wed Dec 8 13:47:54 2010// +/ResetAction.java/1.1/Wed Dec 8 13:47:54 2010// +/StepBackAction.java/1.1/Wed Dec 8 13:47:54 2010// +/StepForwardAction.java/1.1/Wed Dec 8 13:47:54 2010// +/UndoAction.java/1.1/Wed Dec 8 13:47:54 2010// +/WelcomeScreenActionHandler.java/1.1/Wed Dec 8 13:47:54 2010// +/package.html/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/gui/event/CVS/Repository b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Repository new file mode 100644 index 0000000..bff25f2 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/gui/event diff --git a/src/org/jalgo/module/bfsdfs/gui/event/CVS/Root b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/gui/event/CancelAction.java b/src/org/jalgo/module/bfsdfs/gui/event/CancelAction.java new file mode 100644 index 0000000..577430f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/CancelAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to cancel the animation to play the current + * algorithm. + * + * @author Florian Dornbusch + */ +public class CancelAction +extends AbstractAction { + private static final long serialVersionUID = -4022448418439840518L; + + private GUIController gui; + + public CancelAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "CancelAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "CancelAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Abort_algorithm"))); + } + + public void actionPerformed(ActionEvent e) { + gui.cancel(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.java b/src/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.java new file mode 100644 index 0000000..719d353 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/DoubleEdgeAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; + +/** + * This class represents an action to change to the double-edge mode. + * + * @author Florian Dornbusch + */ +public class DoubleEdgeAction +extends AbstractAction { + private static final long serialVersionUID = -5920832848188996554L; + + private GUIController gui; + + public DoubleEdgeAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "DoubleEdgeAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "DoubleEdgeAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("bfsdfs", "icon_doubleedges"))); + } + + public void actionPerformed(ActionEvent e) { + gui.setGraphView(EditMode.START_DOUBLE_EDGE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/EdgeAction.java b/src/org/jalgo/module/bfsdfs/gui/event/EdgeAction.java new file mode 100644 index 0000000..b8ae31c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/EdgeAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; + +/** + * This class represents an action to change to the edge mode. + * + * @author Florian Dornbusch + */ +public class EdgeAction +extends AbstractAction { + private static final long serialVersionUID = -8933041027480952255L; + + private GUIController gui; + + public EdgeAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "EdgeAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "EdgeAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("bfsdfs", "icon_edges"))); + } + + public void actionPerformed(ActionEvent e) { + gui.setGraphView(EditMode.START_EDGE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/EraserAction.java b/src/org/jalgo/module/bfsdfs/gui/event/EraserAction.java new file mode 100644 index 0000000..bd2e10c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/EraserAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; + +/** + * This class represents an action to change to the eraser mode. + * + * @author Florian Dornbusch + */ +public class EraserAction +extends AbstractAction { + private static final long serialVersionUID = -6440908155733393663L; + + private GUIController gui; + + public EraserAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "EraserAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "EraserAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("main", "Icon.Clear"))); + } + + public void actionPerformed(ActionEvent e) { + gui.setGraphView(EditMode.ERASE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/NodeAction.java b/src/org/jalgo/module/bfsdfs/gui/event/NodeAction.java new file mode 100644 index 0000000..26cc2a6 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/NodeAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.graphview.EditMode; + +/** + * This class represents an action to change to the node mode. + * + * @author Florian Dornbusch + */ +public class NodeAction +extends AbstractAction { + private static final long serialVersionUID = -6899288668914760000L; + + private GUIController gui; + + public NodeAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "NodeAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "NodeAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("bfsdfs", "icon_nodeEdit"))); + } + + public void actionPerformed(ActionEvent e) { + gui.setGraphView(EditMode.PUT_NODE); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/PlayAction.java b/src/org/jalgo/module/bfsdfs/gui/event/PlayAction.java new file mode 100644 index 0000000..4a81d2c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/PlayAction.java @@ -0,0 +1,35 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to play the current algorithm. + * + * @author Florian Dornbusch + */ +public class PlayAction +extends AbstractAction { + private static final long serialVersionUID = -7156200255850126725L; + + private GUIController gui; + + public PlayAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "PlayAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "PlayAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("main", "Icon.Perform_all"))); + } + + public void actionPerformed(ActionEvent e) { + gui.playAlgo(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/RandomAction.java b/src/org/jalgo/module/bfsdfs/gui/event/RandomAction.java new file mode 100644 index 0000000..916a34c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/RandomAction.java @@ -0,0 +1,48 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; +import java.util.List; + +import javax.swing.AbstractAction; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.components.AlgoTab; + +/** + * This class represents an action to toggle the random check box. + * + * @author Florian Dornbusch + */ +public class RandomAction +extends AbstractAction { + private static final long serialVersionUID = 2372809553068441995L; + + private AlgoTab algoTab; + + private GUIController gui; + + public RandomAction(AlgoTab algoTab, GUIController gui) { + this.algoTab = algoTab; + this.gui = gui; + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "AlgoTab.randomBoxStatus")); + } + + /** + * If the check box is selected, the permutations must not be chosen + * to ensure the non-determinism of the algorithm. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent arg0) { + + boolean b = algoTab.getSuccessorsAvailable(); + algoTab.getSuccessorChooser().setEnabled(b); + + if(algoTab.getRandomBox().isSelected()) { + List random = algoTab.getRandomPermutation(); + algoTab.getSuccessorChooser().fill(random); + gui.setSuccessorOrder(random); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/RedoAction.java b/src/org/jalgo/module/bfsdfs/gui/event/RedoAction.java new file mode 100644 index 0000000..8fda901 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/RedoAction.java @@ -0,0 +1,35 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to redo a design step (e.g. add a node). + * + * @author Florian Dornbusch + */ +public class RedoAction +extends AbstractAction { + private static final long serialVersionUID = 7006845531760056982L; + + private GUIController gui; + + public RedoAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "RedoAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "RedoAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("main", "Icon.Redo"))); + } + + public void actionPerformed(ActionEvent e) { + gui.redo(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/ResetAction.java b/src/org/jalgo/module/bfsdfs/gui/event/ResetAction.java new file mode 100644 index 0000000..6ea61bf --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/ResetAction.java @@ -0,0 +1,35 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to reset the current algorithm. + * + * @author Florian Dornbusch + */ +public class ResetAction +extends AbstractAction { + private static final long serialVersionUID = -8467509629339786748L; + + private GUIController gui; + + public ResetAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "ResetAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "ResetAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_all"))); + } + + public void actionPerformed(ActionEvent e) { + gui.resetAlgo(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/StepBackAction.java b/src/org/jalgo/module/bfsdfs/gui/event/StepBackAction.java new file mode 100644 index 0000000..bfe2916 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/StepBackAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to do a step in the current algorithm + * in backwards direction. + * + * @author Florian Dornbusch + */ +public class StepBackAction +extends AbstractAction { + private static final long serialVersionUID = -8007372505949383154L; + + private GUIController gui; + + public StepBackAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "StepBackAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "StepBackAction.tooltip")); + putValue(SMALL_ICON, + new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_step"))); + } + + public void actionPerformed(ActionEvent e) { + gui.previousAlgoStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.java b/src/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.java new file mode 100644 index 0000000..5ca320b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/StepForwardAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to do a step in the current algorithm + * in forward direction. + * + * @author Florian Dornbusch + */ +public class StepForwardAction +extends AbstractAction { + private static final long serialVersionUID = -106333707156892106L; + + private GUIController gui; + + public StepForwardAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "StepForwardAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "StepForwardAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Perform_step"))); + } + + public void actionPerformed(ActionEvent e) { + gui.nextAlgoStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/UndoAction.java b/src/org/jalgo/module/bfsdfs/gui/event/UndoAction.java new file mode 100644 index 0000000..a329cdb --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/UndoAction.java @@ -0,0 +1,35 @@ +package org.jalgo.module.bfsdfs.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; + +/** + * This class represents an action to undo a design step (e.g. add a node). + * + * @author Florian Dornbusch + */ +public class UndoAction +extends AbstractAction { + private static final long serialVersionUID = -4212789064786233606L; + + private GUIController gui; + + public UndoAction(GUIController guiController) { + this.gui = guiController; + setEnabled(false); + putValue(NAME, Messages.getString("bfsdfs", "UndoAction.tooltip")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "bfsdfs", "UndoAction.tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("main", "Icon.Undo"))); + } + + public void actionPerformed(ActionEvent e) { + gui.undo(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.java b/src/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.java new file mode 100644 index 0000000..c2cde0a --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/WelcomeScreenActionHandler.java @@ -0,0 +1,99 @@ +package org.jalgo.module.bfsdfs.gui.event; + + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.io.IOException; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.gui.GUIController; +import org.jalgo.module.bfsdfs.gui.components.WelcomeButton; +import org.jalgo.module.bfsdfs.gui.components.WelcomeScreen; + +/** + * This class handles the actions of the three welcome buttons to create a new + * graph, load an existing graph and load the last opened graph. + * + * @author Florian Dornbusch + */ +public class WelcomeScreenActionHandler +implements ActionListener, MouseListener { + + private GUIController gui; + private WelcomeScreen screen; + + + public WelcomeScreenActionHandler(WelcomeScreen screen, + GUIController gui) { + this.gui = gui; + this.screen = screen; + } + + /** + * Execute the actions according to the three welcome buttons. + * @author Florian Dornbusch + */ + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("new")) + gui.installStandardLayout(); + else if (e.getActionCommand().equals("load")) { + String filename = + JAlgoGUIConnector.getInstance().showOpenDialog(false,false); + if (filename != null) { + try { + gui.loadGraph(filename); + } catch (IOException io) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("bfsdfs", + "WelcomeScreen.ioError")); + } + } + } + else if (e.getActionCommand().equals("last")) { + try { + gui.loadLastGraph(); + } catch (IOException io) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("bfsdfs", + "WelcomeScreen.ioError")); + } + } + + ((WelcomeButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** + * Change to the highlighted version of the button and display + * its description. + * @author Florian Dornbusch + */ + public void mouseEntered(MouseEvent e) { + WelcomeButton source = (WelcomeButton)e.getSource(); + if (!source.isEnabled()) return; + source.setSelected(true); + screen.setDescription(source.getDescription()); + } + + /** + * Change to the normal version of the button and display no + * description. + * @author Florian Dornbusch + */ + public void mouseExited(MouseEvent e) { + ((WelcomeButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** unused observer method */ + public void mouseClicked(MouseEvent e) {} + + /** unused observer method */ + public void mousePressed(MouseEvent e) {} + + /** unused observer method */ + public void mouseReleased(MouseEvent e) {} +} diff --git a/src/org/jalgo/module/bfsdfs/gui/event/package.html b/src/org/jalgo/module/bfsdfs/gui/event/package.html new file mode 100644 index 0000000..90a8df3 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/event/package.html @@ -0,0 +1,17 @@ + + + + +

          +This package contains actions to control: +

            +
          • the graph (Undo, Redo, Node, Edge, DoubleEdge, Eraser) +
          • the algorithm (Reset, StepBack, StepForward, Play, Cancel) +
          • and the animations (AnimationToggleAction) +
          +They extend AbstractAction and set a name, a short description +and a small icon. It is easier controlling the actions than controlling the +buttons because there are multiple buttons for each action. +

          + + \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.java new file mode 100644 index 0000000..e67999f --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoEdgeStrategy.java @@ -0,0 +1,116 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphCalculation; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +public class AlgoEdgeStrategy implements EdgeDrawingStrategy, GUIConstants { + /** + * Drawing method. Draws the edge of a tree. + * @param g Used Graphics instance. + * @param start Start point of the edge. + * @param end End point of the edge. + * @param bidirectional True, if the edge is bidirectional, + * False otherwise. + * @param focusedStart True, if the start arrow of the edge is focused, + * False otherwise. + * @param focusedEnd True, if the end arrow of the edge is focused, + * False otherwise. + * @param focusedEdge True, if the edge is focused, + * False otherwise. + * @param alpha Alpha value of the drawed edge. + * @param type The animation type of the edge. + * AnimationType.NONE if no animation will be performed. + * @param time The start time of the edge's animation. + * @param beamerMode Not used. + * @return True, if a repaint is needed because of animations, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, Point start, Point end, boolean bidirectional, + boolean focusedStart, boolean focusedEnd, boolean focusedEdge, + int alpha, AnimationType type, long time, boolean beamerMode) { + int radius = (int) Math.round((float) NODE_BEAMER_SIZE / 2f); + boolean repaint = false; + + // check, if animated + if(time > 0) { + // calculate animation time + long animation = Calendar.getInstance().getTimeInMillis() - time; + + // check animation + if(type == AnimationType.DELETE) { + // get current alpha value of deleted edge + alpha = GraphAnimations.hide(alpha, animation, EDGE_ANIMATION); + + // repaint until invisibility is reached + repaint = alpha > 1; + } + else if(animation < EDGE_ANIMATION && type == AnimationType.CREATE) { + // calculate distance + int edgeLength = (int) + Math.round(Math.sqrt(GraphCalculation.calcPointPointDistSqr(start, + end))); + int distance = (int) Math.round((edgeLength - 2 * radius) * + EDGE_TREE_CLIPPING); + + // check max distance + if(distance > EDGE_TREE_MAXCLIP) { + distance = EDGE_TREE_MAXCLIP; + } + + // get current end position of the edge + end = GraphAnimations.animateEdge(start, end, 2 * + (radius + distance), animation, EDGE_ANIMATION); + + // repaint because of animation + repaint = true; + } + } + + // select the right colors depending on the focus + Color edgeColor = EDGE_COLOR; + Color startColor = EDGE_COLOR; + Color endColor = EDGE_COLOR; + + if(focusedEdge) { + startColor = EDGE_COLOR_FOCUSED; + endColor = EDGE_COLOR_FOCUSED; + edgeColor = EDGE_COLOR_FOCUSED; + } + else { + if(focusedStart) { + startColor = EDGE_COLOR_FOCUSED; + } + + if(focusedEnd) { + endColor = EDGE_COLOR_FOCUSED; + } + } + + // calculate distance + int edgeLength = (int) + Math.round(Math.sqrt(GraphCalculation.calcPointPointDistSqr(start, end))); + int distance = (int) Math.round((edgeLength - 2 * radius) * EDGE_TREE_CLIPPING); + + // check max distance + if(distance > EDGE_TREE_MAXCLIP) { + distance = EDGE_TREE_MAXCLIP; + } + + // draw clipped edge + GraphDrawing.drawClippedEdge((Graphics2D) g, start, end, EDGE_TREE_WIDTH, + bidirectional, radius + distance, radius + distance, startColor, + endColor, edgeColor, EDGE_TREE_ARROW_WIDTH, EDGE_TREE_ARROW_LENGTH, + EDGE_CIRCLE_SIZE, alpha); + + return repaint; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.java new file mode 100644 index 0000000..34bcbbb --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoFinishedNodeStrategy.java @@ -0,0 +1,65 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +public class AlgoFinishedNodeStrategy implements NodeDrawingStrategy, GUIConstants { + /** + * Drawing method. Draws the finished node of a tree. + * @param g Used Graphics instance. + * @param id Id of the node. + * @param position Position of the node. + * @param focused True, if the node is focused, + * False otherwise. + * @param alpha Alpha value of the drawed edge. + * @param distance The distance of the node, which will be drawn next to the node. + * 0, if no distance should be drawn. + * @param type The animation type of the edge. + * AnimationType.NONE if no animation will be performed. + * @param time The creation time of the edge. Can be used for animations. + * @param beamerMode True, if the beamer mode has been activated. + * False otherwise. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, int id, Point position, boolean focused, + int alpha, int distance, AnimationType type, long time, boolean beamerMode) { + boolean repaint = false; + Font distanceFont = NODE_DISTANCE_FONT; + + // check, if beamer mode is activated + if(beamerMode) { + distanceFont = NODE_BEAMER_DISTANCE_FONT; + } + + // calculate animation time + long animation = Calendar.getInstance().getTimeInMillis() - time; + + // check animation + if(type == AnimationType.DELETE) { + // animate deleted node: calculate new alpha value and repaint + alpha = GraphAnimations.hide(alpha, animation, NODE_ANIMATION_TIME); + repaint = true; + } + else if(animation < NODE_ANIMATION_TIME && type != AnimationType.NONE) { + // animate node: calculate new alpha value and repaint + alpha = GraphAnimations.animateNode(alpha, animation, NODE_ANIMATION_TIME); + repaint = true; + } + + GraphDrawing.drawNode((Graphics2D) g, String.valueOf(id), position, + NODE_BEAMER_FONT, NODE_BEAMER_SIZE, NODE_BORDER_SIZE, + NODE_FINISHED_BORDER_COLOR, NODE_LABEL_COLOR_FINISHED, + NODE_COLOR_FINISHED_TOP, NODE_COLOR_FINISHED_BOTTOM, alpha, + NODE_GRADIENT_HEIGHT, distanceFont, NODE_DISTANCE_COLOR, distance); + + // repaint if needed + return repaint; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.java new file mode 100644 index 0000000..e7f44ff --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/AlgoNodeStrategy.java @@ -0,0 +1,79 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +public class AlgoNodeStrategy implements NodeDrawingStrategy, GUIConstants { + /** + * Drawing method. Draws the untouched or focused node of a tree. + * @param g Used Graphics instance. + * @param id Id of the node. + * @param position Position of the node. + * @param focused True, if the node is focused, + * False otherwise. + * @param alpha Alpha value of the drawed edge. + * @param distance The distance of the node, which will be drawn next to the node. + * 0, if no distance should be drawn. + * @param type The animation type of the edge. + * AnimationType.NONE if no animation will be performed. + * @param beamerMode True, if the beamer mode has been activated. + * False otherwise. + * @param time The animation time of the edge. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, int id, Point position, boolean focused, + int alpha, int distance, AnimationType type, long time, boolean beamerMode) { + boolean repaint = false; + Font distanceFont = NODE_DISTANCE_FONT; + + // check, if beamer mode is activated + if(beamerMode) { + distanceFont = NODE_BEAMER_DISTANCE_FONT; + } + + // calculate animation time + long animation = Calendar.getInstance().getTimeInMillis() - time; + + // check animation + if(type == AnimationType.DELETE) { + // animate deleted node: calculate new alpha value and repaint + alpha = GraphAnimations.hide(alpha, animation, NODE_ANIMATION_TIME); + + // repaint until invisibility is reached + repaint = alpha > 1; + } + else if(animation < NODE_ANIMATION_TIME && type != AnimationType.NONE) { + // animate node: calculate new alpha value and repaint + alpha = GraphAnimations.animateNode(alpha, animation, NODE_ANIMATION_TIME); + repaint = true; + } + + if(focused) { + // draw waiting node including the distance (if distance > 0) + GraphDrawing.drawNode((Graphics2D) g, String.valueOf(id), position, + NODE_BEAMER_FONT, NODE_BEAMER_SIZE, NODE_BEAMER_BORDER_SIZE, + NODE_WAITING_BORDER_COLOR, NODE_LABEL_COLOR_WAITING, + NODE_COLOR_WAITING_TOP, NODE_COLOR_WAITING_BOTTOM, alpha, + NODE_GRADIENT_HEIGHT, distanceFont, NODE_DISTANCE_COLOR, + distance); + } + else { + // draw untouched node + GraphDrawing.drawNode((Graphics2D) g, String.valueOf(id), position, + NODE_BEAMER_FONT, NODE_BEAMER_SIZE, NODE_BEAMER_BORDER_SIZE, + NODE_UNTOUCHED_BORDER_COLOR, NODE_LABEL_COLOR_UNTOUCHED, + NODE_COLOR_UNTOUCHED_TOP, NODE_COLOR_UNTOUCHED_BOTTOM, alpha, + NODE_GRADIENT_HEIGHT); + } + + // repaint if needed + return repaint; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.java b/src/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.java new file mode 100644 index 0000000..506d88e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/AnimationType.java @@ -0,0 +1,34 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +/** + * This enumeration represents the current animation type of a + * VisualGraphElement. + * @author Anselm Schmidt + */ +public enum AnimationType { + /** + * Creation animation. + */ + CREATE, + + /** + * Focus animation. + */ + FOCUS, + + /** + * Unfocus animation. + */ + UNFOCUS, + + /** + * Delete animation. + */ + DELETE, + + /** + * No animation. + */ + NONE, +} + diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Entries b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Entries new file mode 100644 index 0000000..73db026 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Entries @@ -0,0 +1,21 @@ +/AlgoEdgeStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/AlgoFinishedNodeStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/AlgoNodeStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/AnimationType.java/1.1/Wed Dec 8 13:47:54 2010// +/DeletedEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/DeletedNode.java/1.1/Wed Dec 8 13:47:54 2010// +/EdgeDrawingStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/EditMode.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphEdgeStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphNodeStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/GraphView.java/1.1/Wed Dec 8 13:47:54 2010// +/InteractiveGraphView.java/1.1/Wed Dec 8 13:47:54 2010// +/NodeDrawingStrategy.java/1.1/Wed Dec 8 13:47:54 2010// +/Repainter.java/1.1/Wed Dec 8 13:47:54 2010// +/TreeView.java/1.1/Wed Dec 8 13:47:54 2010// +/VisualEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/VisualGraphElement.java/1.1/Wed Dec 8 13:47:54 2010// +/VisualNode.java/1.1/Wed Dec 8 13:47:54 2010// +/VisualTempEdge.java/1.1/Wed Dec 8 13:47:54 2010// +/VisualTempNode.java/1.1/Wed Dec 8 13:47:54 2010// +/package.html/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Repository b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Repository new file mode 100644 index 0000000..f68a342 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/gui/graphview diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Root b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.java b/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.java new file mode 100644 index 0000000..8ada84c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedEdge.java @@ -0,0 +1,143 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; + +public class DeletedEdge extends VisualGraphElement { + /** + * The start position of the edge. + */ + private Point start; + + /** + * The end position of the edge. + */ + private Point end; + + /** + * True, if edge is bidirectional, False otherwise. + */ + private boolean bidirectional; + + /** + * The time of the deletion. + */ + private long time; + + /** + * Drawing strategy. + */ + private EdgeDrawingStrategy drawingStrategy; + + /** + * Constructor. + * @param edge The edge. + * @param graphController The used GraphController instance. + * @author Anselm Schmidt + */ + public DeletedEdge(VisualEdge edge, GraphController graphController) { + super(graphController); + + start = graphController.getNodePosition(edge.getStartNode()); + end = graphController.getNodePosition(edge.getEndNode()); + focused = edge.isFocused(); + drawingStrategy = edge.getDrawingStrategy(); + bidirectional = edge.isBidirectional(); + + time = Calendar.getInstance().getTimeInMillis(); + } + + /** + * Constructor for single direction. + * @param edge The edge. + * @param startNode The id of the direction's start node. + * @param endNode The id of the direction's end node. + * @param graphController The used GraphController instance. + * @author Anselm Schmidt + */ + public DeletedEdge(VisualEdge edge, int startNode, int endNode, + GraphController graphController) { + super(graphController); + + start = graphController.getNodePosition(startNode); + end = graphController.getNodePosition(endNode); + focused = edge.isFocused(endNode); + drawingStrategy = edge.getDrawingStrategy(); + bidirectional = false; + + time = Calendar.getInstance().getTimeInMillis(); + } + + @Override + /** + * Not used. + */ + public boolean hitBoundaries(Point point) { + return false; + } + + @Override + /** + * Drawing method. Draws the deleted edge. + * @param g Used Graphics interface. + * @param animated True, if animations are enabled. + * False otherwise. + */ + public boolean paint(Graphics g, boolean animated) { + if(animated) { + return drawingStrategy.paint(g, start, end, bidirectional, focused, focused, + focused, ALPHA_100_PERCENT, AnimationType.DELETE, time, + ComponentUtility.BEAMER_MODE); + } + + return false; + } + + @Override + /** + * Not used. A deleted edge cannot be hit. + */ + public boolean wasHit(Point point) { + return false; + } + + @Override + /** + * Get the rectangle around the edge. + * @param g Not used. + * @return The rectangle around the edge. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // get the start and the end point + Point start = new Point(this.start); + Point end = new Point(this.end); + int space = EDGE_WIDTH + EDGE_ARROW_WIDTH; + + // correct coordinates + if(start.x > end.x) { + int swap = start.x; + start.x = end.x; + end.x = swap; + } + if(start.y > end.y) { + int swap = start.y; + start.y = end.y; + end.y = swap; + } + + start.x -= space; + start.y -= space; + end.x += space; + end.y += space; + + // return rectangle around edge + return new Rectangle(start.x, start.y, end.x - start.x, end.y - start.y); + } + +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.java b/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.java new file mode 100644 index 0000000..ab3f2cf --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/DeletedNode.java @@ -0,0 +1,104 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.graphview.AnimationType;; + +public class DeletedNode extends VisualGraphElement { + /** + * The position of the deleted node. + */ + private Point position; + + /** + * Distance of the node. Only used by tree nodes. + */ + protected int distance; + + /** + * The time of the deletion. + */ + private long time; + + /** + * The id of the node + */ + private int id; + + /** + * Drawing strategy. + */ + private NodeDrawingStrategy drawingStrategy; + + /** + * Constructor. + * @param node The node. + * @param graphController The used GraphController instance. + * @author Anselm Schmidt + */ + public DeletedNode(VisualNode node, GraphController graphController) { + super(graphController); + + id = node.getId(); + distance = node.getDistance(); + position = node.getPosition(); + focused = node.isFocused(); + drawingStrategy = node.getDrawingStrategy(); + + time = Calendar.getInstance().getTimeInMillis(); + } + + @Override + /** + * Not used. + */ + public boolean hitBoundaries(Point point) { + return false; + } + + @Override + /** + * Drawing method. Draws the deleted node. + * @param g Used Graphics instance. + * @param animated True, if animations are enabled. + * False otherwise. + */ + public boolean paint(Graphics g, boolean animated) { + if(animated) { + return drawingStrategy.paint(g, id, position, focused, ALPHA_100_PERCENT, + distance, AnimationType.DELETE, time, ComponentUtility.BEAMER_MODE); + } + + return false; + } + + @Override + /** + * Not used. A deleted node cannot be hit. + */ + public boolean wasHit(Point point) { + return false; + } + + @Override + /** + * Get the rectangle around the node. + * @param g Not used. + * @return The rectangle around the node. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // calculate the radius of the node + int radius = (int) Math.round((double) NODE_BEAMER_SIZE / 2) + + NODE_BEAMER_BORDER_SIZE; + + // return rectangle around node + return new Rectangle(position.x - radius, position.y - radius, + 2 * radius, 2 * radius); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.java new file mode 100644 index 0000000..50efa1c --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/EdgeDrawingStrategy.java @@ -0,0 +1,39 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; + +/** + * Interface for the drawing strategy of an edge + * @author Anselm Schmidt + * + */ +interface EdgeDrawingStrategy { + /** + * Drawing method. Draws the edge of a graph or tree. + * @param g Used Graphics instance. + * @param start Start point of the edge. + * @param end End point of the edge. + * @param bidirectional True, if the edge is bidirectional, + * False otherwise. + * @param focusedStart True, if the start arrow of the edge is focused, + * False otherwise. + * @param focusedEnd True, if the end arrow of the edge is focused, + * False otherwise. + * @param focusedEdge True, if the edge is focused, + * False otherwise. + * @param alpha Alpha value of the drawed edge. + * @param type The animation type of the edge. + * AnimationType.NONE if no animation will be performed. + * @param time The animation start time of the edge. + * @param beamerMode True, if the beamer mode has been activated. + * False otherwise. + * @return True, if a repaint is needed because of animations, + * False otherwise. + * @author Anselm Schmidt + * @param animationType + */ + public boolean paint(Graphics g, Point start, Point end, boolean bidirectional, + boolean focusedStart, boolean focusedEnd, boolean focusedEdge, + int alpha, AnimationType type, long time, boolean beamerMode); +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/EditMode.java b/src/org/jalgo/module/bfsdfs/gui/graphview/EditMode.java new file mode 100644 index 0000000..d6cd8da --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/EditMode.java @@ -0,0 +1,53 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +/** + * This enumeration represents the current mode of the InteractiveGraphView + * @author Anselm Schmidt + * + */ +public enum EditMode { + /** + * A mouse click will start a new edge. + */ + START_EDGE, + /** + * A mouse click will start a new bidirectional edge. + */ + START_DOUBLE_EDGE, + /** + * Elements can be removed with the mouse. + */ + ERASE, + /** + * A mouse click will create a new graph node. + */ + PUT_NODE, + /** + * A node is moved by the user. + */ + MOVE_NODE, + /** + * A node is moved by the user using drag and drop. + */ + DRAG_NODE, + /** + * An edge is drawn by the user. + */ + DRAW_EDGE, + /** + * An edge is drawn by the user using mouse drag & drop. + */ + DRAG_EDGE, + /** + * A bidirectional edge is drawn by the user. + */ + DRAW_DOUBLE_EDGE, + /** + * A bidirectional edge is drawn by the user using drag & drop. + */ + DRAG_DOUBLE_EDGE, + /** + * Algorithm is active. No interactivity. + */ + ALGORITHM +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.java new file mode 100644 index 0000000..f71f0b5 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphEdgeStrategy.java @@ -0,0 +1,82 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * Strategy class to draw a simple graph edge. + * @author Anselm Schmidt + */ +public class GraphEdgeStrategy implements EdgeDrawingStrategy, GUIConstants { + /** + * Drawing method. Draws the edge of a graph. + * @param g Used Graphics instance. + * @param start Start point of the edge. + * @param end End point of the edge. + * @param bidirectional True, if the edge is bidirectional, + * False otherwise. + * @param focusedStart True, if the start arrow of the edge is focused, + * False otherwise. + * @param focusedEnd True, if the end arrow of the edge is focused, + * False otherwise. + * @param focusedEdge True, if the edge is focused, + * False otherwise. + * @param alpha Alpha value of the drawed edge. + * @param type The animation type of the edge. + * AnimationType.NONE if no animation will be performed. + * @param time The start time of the edge's animation. + * @param beamerMode Not used. + * @return True, if a repaint is needed because of animations, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, Point start, Point end, boolean bidirectional, + boolean focusedStart, boolean focusedEnd, boolean focusedEdge, int alpha, + AnimationType type, long time, boolean beamerMode) { + boolean repaint = false; + + // calculate node radius + int radius = (int) Math.round((float) NODE_BEAMER_SIZE / 2f); + + // calculate animation time + long animation = Calendar.getInstance().getTimeInMillis() - time; + + // check animation + if(type == AnimationType.DELETE) { + // animate node: calculate new alpha value and repaint + alpha = GraphAnimations.hide(alpha, animation, NODE_ANIMATION_TIME); + repaint = true; + } + + // select the right colors depending on the focus + Color edgeColor = EDGE_COLOR; + Color startColor = EDGE_COLOR; + Color endColor = EDGE_COLOR; + + if(focusedEdge) { + edgeColor = EDGE_COLOR_FOCUSED; + } + if(focusedStart) { + startColor = EDGE_COLOR_FOCUSED; + } + + if(focusedEnd) { + endColor = EDGE_COLOR_FOCUSED; + } + + // draw clipped edge + GraphDrawing.drawClippedEdge((Graphics2D) g, start, end, EDGE_WIDTH, + bidirectional, radius, radius, startColor, endColor, edgeColor, + EDGE_ARROW_WIDTH, EDGE_ARROW_LENGTH, EDGE_CIRCLE_SIZE, alpha); + + // repaint if needed + return repaint; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.java new file mode 100644 index 0000000..796b6fe --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphNodeStrategy.java @@ -0,0 +1,66 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * Strategy class to draw a simple graph node. + * @author Anselm Schmidt + * + */ +public class GraphNodeStrategy implements NodeDrawingStrategy, GUIConstants { + /** + * Drawing method. Draws the node of a graph. + * @param g Used Graphics instance. + * @param id Id of the node. + * @param position Position of the node. + * @param focused True, if the node is focused, + * False otherwise. + * @param alpha Alpha value of the drawed node. + * @param distance The distance of the node, which will be drawn next to the node. + * 0, if no distance should be drawn. + * @param type The animation type of the node. + * AnimationType.NONE if no animation will be performed. + * @param time The start time of the node's animation. + * @param beamerMode Not used. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, int id, Point position, boolean focused, + int alpha, int distance, AnimationType type, long time, boolean beamerMode) { + boolean repaint = false; + + // calculate animation time + long animation = Calendar.getInstance().getTimeInMillis() - time; + + // check animation + if(type == AnimationType.DELETE) { + // animate node: calculate new alpha value and repaint + alpha = GraphAnimations.hide(alpha, animation, NODE_ANIMATION_TIME); + repaint = true; + } + + if(focused) { + // draw focused node + GraphDrawing.drawNode((Graphics2D) g, String.valueOf(id), position, + NODE_BEAMER_FONT, NODE_BEAMER_SIZE, NODE_BEAMER_BORDER_SIZE, + NODE_BORDER_COLOR_FOCUSED, NODE_LABEL_COLOR_FOCUSED, + NODE_COLOR_TOP, NODE_COLOR_BOTTOM, alpha, NODE_GRADIENT_HEIGHT); + } + else { + // draw non-focused node + GraphDrawing.drawNode((Graphics2D) g, String.valueOf(id), position, + NODE_BEAMER_FONT, NODE_BEAMER_SIZE, NODE_BEAMER_BORDER_SIZE, + NODE_BORDER_COLOR, NODE_LABEL_COLOR, NODE_COLOR_TOP, + NODE_COLOR_BOTTOM, alpha, NODE_GRADIENT_HEIGHT); + } + + // repaint if needed + return repaint; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/GraphView.java b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphView.java new file mode 100644 index 0000000..a04d383 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/GraphView.java @@ -0,0 +1,599 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; + +import javax.swing.JComponent; +import javax.swing.Timer; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.gui.GUIConstants; +import org.jalgo.module.bfsdfs.gui.GUITest; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * GraphView represents an area where a graph will be drawn + * + * @author Anselm Schmidt + * + */ +public class GraphView extends JComponent implements GraphObserver, + GUIConstants { + private static final long serialVersionUID = 1L; + + /** + * Save the actual graphController. + */ + private GraphController graphController = null; + + /** + * Return the graphController. + */ + protected GraphController getGraphController() { + return graphController; + } + + /** + * Collection for drawing the graph elements. + */ + protected Collection elements; + + /** + * Collection for drawing deleted elements. Needed for delete animations. + */ + protected Collection deletedElements; + + /** + * Used drawing strategy for the nodes. + */ + private GraphNodeStrategy nodeStrategy; + + /** + * Used drawing strategy for the edges. + */ + private EdgeDrawingStrategy edgeStrategy; + + /** + * True, if animations are enabled, False + * otherwise. + */ + protected boolean animated; + + /** + * Draw all edges. + * + * @param g + * Used Graphics instance. + * @return True, if the edges have to be redrawn due to + * animations, False otherwise. + * @author Anselm Schmidt + */ + protected void drawEdges(Graphics g) { + try { + // draw deleted edges + for(VisualGraphElement element : deletedElements) { + if(element instanceof DeletedEdge) { + if(element.paint(g, animated)) { + // repaint deleted edge after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + } + + // draw edges + for(VisualGraphElement element : elements) { + if(element instanceof VisualEdge) { + if(element.paint(g, animated)) { + // repaint deleted edge after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + } + } + catch(ConcurrentModificationException e) { + // This can occure because of multi-threading - can be ignored. + } + } + + /** + * Draw all nodes. + * + * @param g + * Used Graphics instance. + * @return True, if the nodes have to be redrawn due to + * animations, False otherwise. + * @author Anselm Schmidt + */ + protected void drawNodes(Graphics g) { + // draw deleted nodes + for (VisualGraphElement element : deletedElements) { + if (element instanceof DeletedNode) { + if (element.paint(g, animated)) { + // repaint deleted node after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + } + + // draw nodes + for (VisualGraphElement element : elements) { + if (element instanceof VisualNode) { + if (element.paint(g, animated)) { + // repaint node after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + } + } + + /** + * Remove edge with the specified start end end nodes. Should only be used when + * the egde has already been removed by the GraphController. + * + * @param start + * Id of the start node. + * @param end + * Id of the end node. + * @author Anselm Schmidt + */ + protected void removeEdge(int start, int end) { + VisualEdge edge = null; + + // look for existing edges + for (VisualGraphElement element : elements) { + if (element instanceof VisualEdge) { + edge = (VisualEdge) element; + + // check start and end nodes + if (edge.getStartNode() == start && edge.getEndNode() == end) { + // specified edge found: remove it + deletedElements.add(new DeletedEdge(edge, graphController)); + elements.remove(element); + break; + } + } + } + } + + /** + * Removes one direction of an edge. Should only be used when + * the direction has already been removed by the GraphController. + * @param edge The edge. + * @param start Id of the direction's start node. + * @param end Id of the direction's end node. + * @author Anselm Schmidt + */ + protected void removeDirection(VisualEdge edge, int start, int end) { + deletedElements.add(new DeletedEdge(edge, start, end, graphController)); + edge.removeDirection(start, end); + } + + /** + * Return the node with the specified id. + * + * @param id + * Id of the node. + * @return The node, if it will be found, null otherwise. + */ + protected VisualNode findNode(int id) { + VisualNode node = null; + + // look for node elements + for (VisualGraphElement element : elements) { + if (element instanceof VisualNode) { + node = (VisualNode) element; + + // check the id of the found node + if (node.getId() == id) { + // node found! + return node; + } + } + } + + // no node with the specified id exists + return null; + } + + /** + * Return the edge with the specified start and end nodes. + * + * @param from + * Id of the start node of the edge. + * @param to + * Id of the end node of the edge. + * @return The edge, if it will be found, null otherwise. + */ + protected VisualEdge findEdge(int from, int to) { + VisualEdge edge = null; + + // look for edge elements + for (VisualGraphElement element : elements) { + if (element instanceof VisualEdge) { + edge = (VisualEdge) element; + + // check the start and end nodes of the found edge + if (edge.getStartNode() == from && edge.getEndNode() == to) { + // edge found! + return edge; + } + + // is edge bidirectional? + if (edge.isBidirectional()) { + // check other direction, too + if (edge.getEndNode() == from && edge.getStartNode() == to) { + // edge found! + return edge; + } + } + } + } + + // no edge with the specified start and end nodes exists + return null; + } + + /** + * Return the bidirectional edge with the specified start and end nodes. + * + * @param end1 + * Id of the node at one end of the bidirectional edge. + * @param end2 + * Id of the node at the other end of the bidirectional edge. + * @return The bidirectional edge, if it will be found, null + * otherwise. + */ + protected VisualEdge findBidirectionalEdge(int end1, int end2) { + VisualEdge edge = null; + + // look for bidirectional edges + for (VisualGraphElement element : elements) { + if (element instanceof VisualEdge) { + edge = (VisualEdge) element; + + if (edge.isBidirectional()) { + // check the start and end nodes of the found bidirectional + // edge + if ((edge.getStartNode() == end1 && edge.getEndNode() == end2) + || edge.getStartNode() == end2 + && edge.getEndNode() == end1) { + // bidirectional edge found + return edge; + } + } + } + } + + // no bidirectional edge with the specified nodes exists + return null; + } + + /** + * Constructor. Creates elements collection and drawing strategies. Disables + * animations. + * + * @author Anselm Schmidt + */ + public GraphView(GraphController graphController) { + this.graphController = graphController; + // create arrays for graph elements + elements = new ArrayList(); + deletedElements = new ArrayList(); + + // create drawing strategies + nodeStrategy = new GraphNodeStrategy(); + edgeStrategy = new GraphEdgeStrategy(); + + // disable animations in the beginning + animated = false; + } + + /** + * Drawing method. Draws all graph elements with anti-aliasing. + * + * @author Anselm Schmidt + */ + @Override + public void paint(Graphics g) { + // fill white + g.setColor(GRAPH_VIEW_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + + // enable anti-aliasing + GraphDrawing.enableAntiAliasing(g); + + // draw edges first, nodes last + drawEdges(g); + drawNodes(g); + } + + /** + * Enables or disables animation + * + * @param enabled + * true enables animation, false + * disables it + * @author Anselm Schmidt + */ + public void setAnimationsEnabled(boolean enabled) { + // clear deleted elements + deletedElements.clear(); + + // set animations enabled or disabled + animated = enabled; + } + + /** + * Adds the VisualGraphElement for an edge or double edge + * when a new edge was added to the graph. + * + * @param startNode + * Id of the start node of the edge. + * @param endNode + * Id of the end node of the edge. + * @author Anselm Schmidt + */ + public void onEdgeAdded(int startNode, int endNode) { + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onEdgeAdded(" + startNode + ", " + endNode + + ")", true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onEdgeAdded(" + startNode + ", " + endNode + + ")", true); + } + + // stop deleting animations + deletedElements.clear(); + + // look for similar edge in the other direction + VisualEdge otherDirection = findEdge(endNode, startNode); + + if (otherDirection == null) { + // no bidirectional edge: add new edge + elements.add(new VisualEdge(startNode, endNode, false, + edgeStrategy, this.graphController)); + + } else { + // bidirectional edge: make old edge bidirectional + otherDirection.makeBidirectional(); + } + + // repaint to show changes + repaint(); + } + + /** + * Removes an edge or double edge VisualGraphElement and repaints when + * an edge was deleted from the graph. + * + * @param startNode + * Id of the start node of the edge. + * @param endNode + * Id of the end node of the edge. + * @author Anselm Schmidt + */ + public void onEdgeRemoved(int startNode, int endNode) { + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onEdgeRemoved(" + startNode + ", " + + endNode + ")", true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onEdgeRemoved(" + startNode + ", " + + endNode + ")", true); + } + + // look for bidirectional edge + VisualEdge edge = findBidirectionalEdge(startNode, endNode); + + if (edge == null) { + // no bidirectional edge: remove edge + removeEdge(startNode, endNode); + } else { + // bidirectional edge: make old edge bidirectional + removeDirection(edge, startNode, endNode); + } + + // repaint to show changes + repaint(); + } + + /** + * Clears the graph if it was reloaded + * + * @author Anselm Schmidt + */ + public void onGraphLoaded() { + elements.clear(); + } + + /** + * Removes the corresponding VisualGraphElement and repaints when a + * node was removed from the graph + * + * @param node + * Id of the changed node. + * @author Anselm Schmidt + */ + public void onNodeRemoved(int node) { + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onNodeRemoved(" + node + ")", true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onNodeRemoved(" + node + ")", true); + } + + // remove node + VisualNode deletedNode = findNode(node); + + if(deletedNode != null) { + deletedElements.add(new DeletedNode(deletedNode, graphController)); + elements.remove(deletedNode); + + // repaint to show changes + repaint(); + } + } + + /** + * Adds a node VisualGraphElement and repaints when a + * node was added to the graph + * + * @param node + * Id of the new node. + * @param pos + * Position of the new node. + * @author Anselm Schmidt + */ + public void onNodeAdded(int node, Point pos) { + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onNodeAdded(" + node + ", " + pos + ")", + true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onNodeAdded(" + node + ", " + pos + ")", + true); + } + + // stop deleting animations + deletedElements.clear(); + + // add node + elements.add(new VisualNode(node, (Point) pos, nodeStrategy, + this.graphController)); + + // repaint + repaint(); + } + + /** + * Moves the corresponding node VisualGraphElement and repaints when a + * node moved in the graph + * + * @param node + * Id of the changed node. + * @param pos + * New position of the node. + * @author Anselm Schmidt + */ + public void onNodeMoved(int node, Point pos) { + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onNodeMoved(" + node + ", " + pos + ")", + true); + } else if (this instanceof InteractiveGraphView) { + GUITest.write("[ALGO] > onNodeMoved(" + node + ", " + pos + ")", + true); + } + + findNode(node).setPosition(pos); + repaint(); + } + + /** + * Implemented GraphObserver method. The id of a node has been changed, + * reset corresponding element and repaint. Throws an + * IllegalArgumentException if the node wasn't found. + * + * @param node + * Id of the changed node. + * @param pos + * New position of the node. + * @author Anselm Schmidt + */ + public void onNodeChanged(int oldId, int newId) { + // find node + VisualNode node = findNode(oldId); + + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onNodeChanged(" + oldId + ", " + newId + + ")", true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onNodeChanged(" + oldId + ", " + newId + + ")", true); + } + + if (node == null) { + GUITest.write("FATAL ERROR: node " + oldId + " hasn't been found!", + true); + throw new IllegalArgumentException(); + } + + // change node and repaint + node.changeId(newId); + repaint(); + } + + /** + * Implemented GraphObserver method. The id of an edge has been changed, + * reset corresponding element and repaint. Throws an + * IllegalArgumentException if the edge wasn't found. + * + * @param oldStart + * Old id of the start node. + * @param oldEnd + * Old id of the end node. + * @param newStart + * New id of the start node. + * @param newEnd + * New id of the end node. + * @author Anselm Schmidt + */ + public void onEdgeChanged(int oldStart, int oldEnd, int newStart, int newEnd) { + // find edge + VisualEdge edge = findEdge(oldStart, oldEnd); + + if (this instanceof InteractiveGraphView) { + GUITest.write("[GRAPH] > onEdgeChanged(" + oldStart + ", " + oldEnd + + ", " + newStart + ", " + newEnd + ")", true); + } else if (this instanceof TreeView) { + GUITest.write("[ALGO] > onEdgeChanged(" + oldStart + ", " + oldEnd + + ", " + newStart + ", " + newEnd + ")", true); + } + + if (edge == null) { + GUITest.write("FATAL ERROR: edge " + oldStart + "=>" + oldEnd + + " hasn't been found!", true); + throw new IllegalArgumentException(); + } + + // check for a bidirectional edge + if (edge.isBidirectional()) { + // bidirectional edge: change only once per two calls + edge.changeBidirectionalEdgeOnce(newStart, newEnd); + } else { + // no bidirectional edge: just change the edge + edge.changeEdge(newStart, newEnd); + } + repaint(); + } + + /** + * Convert graph elements into string. + * + * @result A string with one element per line. For detailed information look + * at the toString methods of the element classes. + * @author Anselm Schmidt + */ + @Override + public String toString() { + String string = ""; + + for (VisualGraphElement element : elements) { + string += element.toString() + "\n"; + } + + return string; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.java b/src/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.java new file mode 100644 index 0000000..5891338 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/InteractiveGraphView.java @@ -0,0 +1,993 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.MouseInfo; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GUITest; +import org.jalgo.module.bfsdfs.gui.GraphCalculation; + +/** + * InteractiveGraphView represents an area where a graph will be + * drawn and the user can edit this graph. There are different edit modes which + * influence the handling of mouse events and motions + * + * @author Anselm Schmidt + * + */ +public class InteractiveGraphView extends GraphView implements MouseListener, + MouseMotionListener { + private static final long serialVersionUID = 1L; + + /** + * The current edit mode. + */ + protected EditMode mode; + + /** + * The erase cursor + */ + protected Cursor eraseCursor; + + /** + * The default cursor + */ + protected Cursor defaultCursor; + + /** + * Selected node. In edit mode MOVE_NODE the node that is being moved + * around. In the edit modes DRAW_EDGE, DRAG_EDGE, DRAW_DOUBLE_EDGE and + * DRAG_DOUBLE_EDGE, it is the start node of the new edge. + */ + protected VisualNode selectedNode; + + /** + * Current mouse position. Will be used in the edit modes DRAW_EDGE, + * DRAW_DOUBLE_EDGE, DRAG_EDGE and DRAG_DOUBLE_EDGE to draw a temporary edge + * that shows the edge that will be created as soon as the user clicks or + * drops at the position of an existing node. In the edit mode PUT_NODE it + * will be used to draw a temporary node where a new node will be added as + * soon as the user clicks at the current position. + */ + protected Point mousePosition; + + /** + * Is dragging still possible? Will be True, if the user + * pressed, but didn't release the mouse, False otherwise. + */ + protected boolean isDraggingPossible; + + /** + * Will be True, if the mouse pointer is inside the component, + * False otherwise. + */ + protected boolean isMouseIn; + + /** + * Remove an edge or a direction of a bidirectional edge from the graph. + * If edge is bidirectional, it depends on the hitting area, whether + * the whole edge or just one direction will be removed. + * + * @param edge + * Edge to change. + * @param hitAt + * Point, the edge has been hit at. + * @author Anselm Schmidt + */ + protected void removeEdgeOrDirection(VisualEdge edge, Point hitAt) { + // check, if it is a bidirectional edge + if (edge.isBidirectional()) { + // bidirectional edge: get start end end node id and position + int id1 = edge.getStartNode(); + int id2 = edge.getEndNode(); + + Point end1 = this.getGraphController().getNodePosition(id1); + Point end2 = this.getGraphController().getNodePosition(id2); + + // get the hit area of the bidirectional edge + short hitArea = GraphCalculation.getBidirectionalEdgeHitArea(end1.x, + end1.y, end2.x, end2.y, mousePosition, EDGE_ARROW_LENGTH, + NODE_SIZE); + + // remove edge or directions depending on the hit area + switch (hitArea) { + case 1: + // remove first direction + this.getGraphController().removeEdge(id2, id1); + break; + + case 2: + // remove second direction + this.getGraphController().removeEdge(id1, id2); + break; + + default: + // remove both directions + this.getGraphController().removeEdge(id1, id2); + this.getGraphController().removeEdge(id2, id1); + } + } + else { + // remove edge + this.getGraphController().removeEdge(edge.getStartNode(), + edge.getEndNode()); + } + } + + /** + * Add a node to the graph using the GraphController singleton. + * + * @param position + * Position of the new node. + * @author Anselm Schmidt + */ + protected void addNode(Point position) { + if(!hitNode(null, position)) { + GUITest.write("[GRAPH] addNode([" + position.x + ";" + position.y + "])", + true); + + // add node by using the graph controller + this.getGraphController().addNode(position); + } + } + + /** + * Add an edge to the graph using the GraphController singleton. + * + * @param start Id of the start node. + * @param end Id of the end node. + * @author Anselm Schmidt + */ + protected void addEdge(int start, int end) { + GUITest.write("[GRAPH] addEdge(" + start + ", " + end + ")", true); + this.getGraphController().addEdge(start, end); + } + + /** + * Add a bidirectional edge to the graph using the GraphController + * singleton. + * + * @param start Id of the start node. + * @param end Id of the end node. + * @author Anselm Schmidt + */ + protected void addDoubleEdge(int start, int end) { + GUITest.write("[GRAPH] addDoubleEdge(" + start + ", " + end + ")", true); + this.getGraphController().addDoubleEdge(start, end); + } + + /** + * Start moving a node around. + * + * @param node + * The node object. + * @author Anselm Schmidt + */ + protected void startMovingNode(VisualNode node) { + // select node and enter edit mode MOVE_NODE + selectedNode = node; + setEditMode(EditMode.MOVE_NODE); + + // dragging is possible + isDraggingPossible = true; + } + + /** + * Start drawing a new edge. + * + * @param startNode + * The start node of the new edge. + * @author Anselm Schmidt + */ + protected void startNewEdge(VisualNode startNode) { + // select node and enter edit mode DRAW_EDGE + selectedNode = startNode; + setEditMode(EditMode.DRAW_EDGE); + + // dragging is possible + isDraggingPossible = true; + } + + /** + * Start drawing a new bidirectional edge. + * + * @param startNode + * The start node of the new bidirectional edge. + * @author Anselm Schmidt + */ + protected void startNewDoubleEdge(VisualNode startNode) { + // select node and enter edit mode DRAW_DOUBLE_EDGE + selectedNode = startNode; + setEditMode(EditMode.DRAW_DOUBLE_EDGE); + + // dragging is possible + isDraggingPossible = true; + } + + /** + * End edge drawing at specified position. If a node exists at this + * position, the edge will be drawn. Otherwise, it will be cancelled. + * + * @param at + * The position where the drawing ends. + * @author Anselm Schmidt + */ + protected void endNewEdge(Point at) { + // check, if a node has been hit + VisualNode node = getNodeAt(at); + + if (node == null) { + // no node has been hit: cancel the drawing + cancelDrawingEdge(); + } else { + // node has been hit: finish new edge + finishNewEdge(node.getId()); + } + } + + /** + * End bidirectional edge drawing at specified position. If a node exists at + * this position, the bidirectional edge will be drawn. Otherwise, it will + * be cancelled. + * + * @param at + * The position where the drawing ends. + * @author Anselm Schmidt + */ + protected void endNewDoubleEdge(Point at) { + // check, if a node has been hit + VisualNode node = getNodeAt(at); + + if (node == null) { + // no node has been hit: cancel the drawing + cancelDrawingDoubleEdge(); + } else { + // node has been hit: finish new bidirectional edge + finishNewDoubleEdge(node.getId()); + } + } + + /** + * Finish the moving of a node. The moved node will stay at the last valid + * position. + * + * @author Anselm Schmidt + */ + protected void finishMovingNode() { + // leave edit mode MOVE_NODE or DRAG_NODE + setEditMode(EditMode.PUT_NODE); + + // set node focused + selectedNode.setFocused(true); + + // remove selection + selectedNode = null; + + // repaint to show changes + repaint(); + + // reset mouse cursor + setCursor(new Cursor(Cursor.HAND_CURSOR)); + } + + /** + * Finish a new edge. + * + * @param endNode + * Id of the end node of the new edge. + * @author Anselm Schmidt + */ + protected void finishNewEdge(int endNode) { + // add edge + addEdge(selectedNode.getId(), endNode); + + // remove selection and leave edit mode DRAW_EDGE + selectedNode = null; + setEditMode(EditMode.START_EDGE); + } + + /** + * Finish a new bidirectional edge. + * + * @param endNode + * ID of the end node of the new edge. + * @author Anselm Schmidt + */ + protected void finishNewDoubleEdge(int endNode) { + // check if it is a circle edge + if(selectedNode.getId() == endNode) { + // there are no bidirectional circle edges, add a simple circle edge + addEdge(endNode, endNode); + } + else { + // add bidirectional edge + addDoubleEdge(selectedNode.getId(), endNode); + } + + // remove selection and leave edit mode DRAW_DOUBLE_EDGE + selectedNode = null; + setEditMode(EditMode.START_DOUBLE_EDGE); + } + + /** + * Cancel drawing a new edge. + * + * @author Anselm Schmidt + */ + protected void cancelDrawingEdge() { + // remove selection and leave edit mode DRAW_EDGE + selectedNode = null; + setEditMode(EditMode.START_EDGE); + } + + /** + * Cancel drawing a new bidirectional edge. + * + * @author Anselm Schmidt + */ + protected void cancelDrawingDoubleEdge() { + // remove selection and leave edit mode DRAW_DOUBLE_EDGE + selectedNode = null; + setEditMode(EditMode.START_DOUBLE_EDGE); + } + + /** + * Try to move the current node to the specified position. If anything is + * already there, the node will not be moved. + * + * @param point + * Position the node will be moved to. + * @author Anselm Schmidt + */ + protected void moveNodeTo(Point point) { + // check if anything else has been hit + if (!hitNode(selectedNode, point)) { + // no hit: move node to new position and repaint + this.getGraphController().moveNode(selectedNode.getId(), point); + } + } + + protected void dragNodeTo(Point point) { + // move node to new position + moveNodeTo(point); + + // repaint + repaint(); + } + + /** + * Set all graph elements to unfocused and repaint. + * + * @author Anselm Schmidt + */ + protected void unfocusAll() { + // unfocus all elements + for (VisualGraphElement element : elements) { + element.setFocused(false); + + // check, if the found element is an edge + if (element instanceof VisualEdge) { + VisualEdge edge = (VisualEdge) element; + + // edge found: unfocus edge endings, too + edge.setStartFocused(false); + edge.setEndFocused(false); + } + } + + // repaint to show changed + repaint(); + } + + /** + * Check, if the boundaries of any element have been hit. + * + * @param point + * Point to check. + * @return True, if the boundaries of an element have been hit, + * False otherwise. + * @author Anselm Schmidt + */ + protected boolean hitAnything(Point point) { + // check all elements + for (VisualGraphElement element : elements) { + // check boundaries of current element + if (element.hitBoundaries(point)) { + // boundaries have been hit + return true; + } + } + + // nothing has been hit + return false; + } + + /** + * Check, if the boundaries of any node have been hit. If + * except is not null, this node will be ignored. + * + * @param except + * Node that will be ignored while checking or null, + * if all nodes will be checked. + * @param point + * Point to check. + * @return True, if the boundaries of a node have been hit, + * False otherwise. + * @author Anselm Schmidt + */ + protected boolean hitNode(VisualNode except, Point point) { + // check all other elements + for (VisualGraphElement element : elements) { + // checking for nodes only + if (element instanceof VisualNode) { + // if nodes are equal, return false + if (except == null || !except.equals(element)) { + // check boundaries of current other node + if (element.hitBoundaries(point)) { + // other node boundaries have been hit + return true; + } + } + } + } + + // nothing else been hit + return false; + } + + /** + * Return the element at a specified position. + * + * @param point + * Position of the element. + * @result The hit element or null if no element has been hit. + * @author Anselm Schmidt + */ + protected VisualGraphElement getElementNear(Point point) { + // check all elements + for (VisualGraphElement element : elements) { + // check, if the element boundaires have been hit + if (element.hitBoundaries(point)) { + // return element + return element; + } + } + + return null; + } + + /** + * Return the node at a specified position. + * + * @param point + * Position of the node. + * @result The hit node or null if no node has been hit. + * @author Anselm Schmidt + */ + protected VisualNode getNodeAt(Point point) { + // check all elements + for (VisualGraphElement element : elements) { + // check, if the current element is a node + if (element instanceof VisualNode) { + // check, if the node has been hit + if (element.wasHit(point)) { + // return node + return (VisualNode) element; + } + } + } + + return null; + } + + /** + * Return the node near a specified position using the node boundaries. + * + * @param point + * Position of the node. + * @result The hit node or null if no node has been hit. + * @author Anselm Schmidt + */ + protected VisualNode getNodeNear(Point point) { + // check all elements + for (VisualGraphElement element : elements) { + // check, if the current element is a node + if (element instanceof VisualNode) { + // check, if the node boundaries have been hit + if (element.hitBoundaries(point)) { + // return node + return (VisualNode) element; + } + } + } + + return null; + } + + /** + * Return the edge near a specified position. + * + * @param point + * Position of the edge. + * @result The hit edge or null if no edge has been hit. + * @author Anselm Schmidt + */ + protected VisualEdge getEdgeNear(Point point) { + // check all elements + for (VisualGraphElement element : elements) { + // check, if the current element is a node + if (element instanceof VisualEdge) { + // check, if the node boundaries have been hit + if (element.hitBoundaries(point)) { + // return node + return (VisualEdge) element; + } + } + } + + return null; + } + + /** + * Perform a mouse move in erase mode. Highlights nodes, edges and edge + * arrows. + * + * @author Anselm Schmidt + */ + protected void eraserMouseMove() { + // set all elements to unfocussed + unfocusAll(); + + // check, if the mouse is over a node + VisualNode node = getNodeAt(mousePosition); + + if (node == null) { + // check, if the mouse is over an edge + VisualEdge edge = getEdgeNear(mousePosition); + + if (edge != null) { + // handle mouse over edge: check if it is a bidirectional edge + if (edge.isBidirectional()) { + // bidirectional edge: check hitting area + Point end1 = this.getGraphController().getNodePosition( + edge.getStartNode()); + Point end2 = this.getGraphController().getNodePosition( + edge.getEndNode()); + + short hitArea = GraphCalculation.getBidirectionalEdgeHitArea(end1.x, + end1.y, end2.x, end2.y, mousePosition, EDGE_ARROW_LENGTH, + NODE_SIZE); + + // set focus of a bidirectional edge part or the whole edge + // depending on hitting area + switch (hitArea) { + case 1: + edge.setStartFocused(true); + break; + + case 2: + edge.setEndFocused(true); + break; + + default: + // focus whole edge + edge.setStartFocused(true); + edge.setEndFocused(true); + edge.setFocused(true); + } + } + else { + // simple edge: focus it + edge.setFocused(true); + edge.setEndFocused(true); + } + } + } else { + // handle mouse over node: focus node + node.setFocused(true); + } + + // repaint to show changes + repaint(); + } + + /** + * Perform a mouse click in erase mode. Removes nodes, edges and directions of + * bidirectional edges. + * @param position Position of the mouse click. + * @author Anselm Schmidt + */ + protected void eraserMouseClick(Point position) { + // check, if node has been hit + VisualNode node = getNodeAt(position); + + if(node != null) { + // node has been hit: remove it + GUITest.write("[GRAPH] removeNode(" + node.getId() + ")", true); + this.getGraphController().removeNode(node.getId()); + } + else { + // check, if edge has been hit + VisualEdge edge = getEdgeNear(position); + + if(edge != null) { + // edge has been hit: remove it (or a direction of it) + removeEdgeOrDirection(edge, position); + } + } + } + + /** + * Constructor. Sets edit mode to the default value PUT_NODE and adds itself + * as MouseListener and as MouseMotionListener to itself. Creates the + * different cursors. + * + * @author Anselm Schmidt + */ + public InteractiveGraphView(GraphController graphController) { + super(graphController); + // set default edit mode + mode = EditMode.PUT_NODE; + + // dragging is not possible in the beginning + isDraggingPossible = false; + + // add mouse and mouse motion listeners + addMouseListener(this); + addMouseMotionListener(this); + + // create cursors + eraseCursor = Toolkit.getDefaultToolkit().createCustomCursor( + (new ImageIcon(Messages.getResourceURL("main", "Icon.Clear"))) + .getImage(), new Point(0, 15), "ERASER"); + defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); + + // get mouse position and transform it into GraphView coordinates + mousePosition = MouseInfo.getPointerInfo().getLocation(); + mousePosition.x -= getX(); + mousePosition.y -= getY(); + } + + /** + * Create a start node in the middle of the InteractiveGraphView. + * @author Anselm Schmidt + */ + public void addStartNode() { + this.getGraphController().addStartNode(new Point(MAX_GRAPH_WIDTH / 2, MAX_GRAPH_HEIGHT / 2)); + } + + /** + * Set the edit mode. NOTE: All elements will be unfocused. + * + * @param mode + * New edit mode. Use GUIConstants.PUT_NODE as + * default value. + * @author Anselm Schmidt + */ + public void setEditMode(EditMode mode) { + // set new edit mode + this.mode = mode; + + // set all elements to unfocused + unfocusAll(); + + // set cursor depending on edit mode + switch (mode) { + case ERASE: + this.setCursor(eraseCursor); + break; + + default: + this.setCursor(defaultCursor); + } + } + + //gets the current edit mode + public EditMode getEditMode() { + return mode; + } + + /** + * Drawing method. Uses the drawing method of GraphView to paint the graph. + * Draws a temporary node or edge, if necessary. + * + * @param g + * Used instance of Graphics. + * @author Anselm Schmidt + */ + public void paint(Graphics g) { + VisualTempEdge tempEdge = null; + VisualTempNode tempNode = null; + VisualNode endNode = null; + + // paint GraphView + super.paint(g); + + // check edit mode + switch (mode) { + case ALGORITHM: + // draw semi-transparent white rectangle over + g.setColor(new Color(255, 255, 255, GRAPHVIEW_ALPHA_VALUE)); + g.fillRect(0, 0, getWidth(), getHeight()); + break; + + case PUT_NODE: + // check, if mouse position hits an existing node + if (isMouseIn && !hitNode(null, mousePosition)) { + // no node has been hit: create and paint a temporary node + tempNode = new VisualTempNode(mousePosition, this.getGraphController()); + tempNode.paint(g); + } + break; + + case DRAW_EDGE: + case DRAG_EDGE: + // get the end node + endNode = getNodeAt(mousePosition); + + // create and paint a temporary edge + tempEdge = new VisualTempEdge(selectedNode, endNode, mousePosition, + false, this.getGraphController()); + tempEdge.paint(g); + break; + + case DRAW_DOUBLE_EDGE: + case DRAG_DOUBLE_EDGE: + // get the end node + endNode = getNodeAt(mousePosition); + + // create and paint temporary bidirectional edge + tempEdge = new VisualTempEdge(selectedNode, endNode, mousePosition, + true, this.getGraphController()); + tempEdge.paint(g); + break; + } + } + + /** + * Event handler for mouse movements. Will be used to focus elements. + * + * @param e + * Mouse event. + * @author Anselm Schmidt + */ + public void mouseMoved(MouseEvent e) { + // refresh mouse position + mousePosition = e.getPoint(); + + // check edit mode + switch (mode) { + case ALGORITHM: + // no interactivity during algorithm + return; + + case MOVE_NODE: + // move node to mouse position if possible + moveNodeTo(mousePosition); + return; + + case ERASE: + eraserMouseMove(); + return; + } + + // set all elements to unfocussed + unfocusAll(); + + // check, if the mouse is on a node + VisualNode node = getNodeAt(mousePosition); + + if (node != null) { + // handle mouse on node: focus node + node.setFocused(true); + + if(mode == EditMode.PUT_NODE) { + setCursor(new Cursor(Cursor.HAND_CURSOR)); + } + } + else if(mode == EditMode.PUT_NODE){ + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + } + + // repaint GraphView to show changes + repaint(); + } + + /** + * Mouse click handler. The performed action depends on the current edit + * mode. + * + * @param e + * Mouse event. + * @author Anselm Schmidt + */ + public void mousePressed(MouseEvent e) { + VisualNode node = null; + + // perform actions depending on edit mode + switch (mode) { + case MOVE_NODE: + // finish node moving + finishMovingNode(); + break; + + case PUT_NODE: + // check, if a node has been hit + node = getNodeAt(e.getPoint()); + + if (node == null) { + // no node has been hit: add new node + addNode(e.getPoint()); + } else { + // node hit: start to move node + startMovingNode(node); + setCursor(new Cursor(Cursor.HAND_CURSOR)); + } + break; + + case START_EDGE: + // check, if a node has been hit + node = getNodeAt(e.getPoint()); + + if (node != null) { + // node has been hit: start drawing a new edge + startNewEdge(node); + } + break; + + case START_DOUBLE_EDGE: + // check, if a node has been hit + node = getNodeAt(e.getPoint()); + + if (node != null) { + // node has been hit: start drawing a new edge + startNewDoubleEdge(node); + } + break; + + case DRAW_EDGE: + // user set end point of new edge + endNewEdge(e.getPoint()); + break; + + case DRAW_DOUBLE_EDGE: + // check, if a node has been hit + endNewDoubleEdge(e.getPoint()); + break; + + case ERASE: + eraserMouseClick(e.getPoint()); + break; + } + + } + + /** + * Mouse drag handler. Allows the user to draw edges by using drag and drop. + * If we are in DRAW_EDGE or DRAW_DOUBLE_EDGE mode and dragging is possible, + * mode will be changed to DRAG_EDGE or DRAG_DOUBLE_EDGE. + * + * @param e + * Mouse event. + * @author Anselm Schmidt + */ + public void mouseDragged(MouseEvent e) { + // refresh mouse position + mousePosition = e.getPoint(); + + if (isDraggingPossible) { + // check edit mode + switch (mode) { + case DRAW_EDGE: + // draw edge by drag & drop + setEditMode(EditMode.DRAG_EDGE); + break; + case DRAG_NODE: + // move node by drag & drop + dragNodeTo(mousePosition); + return; + case DRAW_DOUBLE_EDGE: + // draw bidirectional edge by drag & drop + setEditMode(EditMode.DRAG_DOUBLE_EDGE); + break; + case MOVE_NODE: + // move node by drag & drop + setEditMode(EditMode.DRAG_NODE); + setCursor(new Cursor(Cursor.HAND_CURSOR)); + return; + case DRAG_EDGE: + case DRAG_DOUBLE_EDGE: + // perform mouse moving actions below + break; + default: + // no drag & drop: do not perform any further actions here + return; + } + + // set all elements to unfocussed + unfocusAll(); + + // check, if the mouse is over a node + VisualNode node = getNodeAt(mousePosition); + + if (node != null) { + // handle mouse over node: focus node + node.setFocused(true); + } + + // repaint to show changes + repaint(); + } + } + + /** + * Mouse release handler. If we are in DRAG_EDGE or DRAG_DOUBLE_EDGE mode, a + * new edge will be drawn. No new edge will be drawn if the mouse doesn't + * point at a node. + * + * @param e + * Mouse event. + * @author Anselm Schmidt + */ + public void mouseReleased(MouseEvent e) { + // dragging is not longer possible + isDraggingPossible = false; + + // check, if drag & drop has been performed + switch (mode) { + case DRAG_EDGE: + // new edge by drag & drop + endNewEdge(e.getPoint()); + break; + + case DRAG_DOUBLE_EDGE: + // new bidirectional edge by drag & drop + endNewDoubleEdge(e.getPoint()); + break; + + case DRAG_NODE: + // finish moving node by drag & drop + finishMovingNode(); + break; + } + } + + /** unused mouse event */ + public void mouseClicked(MouseEvent e) { + } + + /** + * Implemented interface method. + * Sets the status text and shows the temporary node when the mouse pointer enters + * the component. + * @author Anselm Schmidt + */ + public void mouseEntered(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(Messages.getString("bfsdfs", + "GraphView.scrollPaneStatus")); + isMouseIn = true; + repaint(); + } + + /** + * Implemented interface method. + * Removes the status text and hides the temporary node when the mouse pointer leaves + * the component. + * @author Anselm Schmidt + */ + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + isMouseIn = false; + repaint(); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.java b/src/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.java new file mode 100644 index 0000000..80ec89d --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/NodeDrawingStrategy.java @@ -0,0 +1,32 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; + +/** + * Interface for the drawing strategy of a node. + * @author Anselm Schmidt + */ +interface NodeDrawingStrategy { + /** + * Drawing method. Draws the node of a graph or tree. + * @param g Used Graphics instance. + * @param id Id of the node. + * @param position Position of the node. + * @param focused True, if the node is focused, + * False otherwise. + * @param alpha Alpha value of the drawed node. + * @param distance The distance of the node, which will be drawn next to the node. + * 0, if no distance should be drawn. + * @param type The type of the current animation. + * AnimationType.NONE if no animation will be performed. + * @param time The start time of the current animation. + * @param beamerMode True, if the beamer mode has been activated. + * False otherwise. + * @return True, if the element has to be redrawn due to animations, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, int id, Point position, boolean focused, + int alpha, int distance, AnimationType type, long time, boolean beamerMode); +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/Repainter.java b/src/org/jalgo/module/bfsdfs/gui/graphview/Repainter.java new file mode 100644 index 0000000..2520b68 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/Repainter.java @@ -0,0 +1,40 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Component; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * Helper class for delayed repainting of a specific component and rectangle. + * @author Anselm Schmidt + * + */ +public class Repainter implements ActionListener { + /** The component that will be repainted. */ + Component component; + + /** The rectangle to repaint. */ + Rectangle rect; + + /** + * Constructor. + * @param component Component that will be repainted. + * @param rect Rectangle that will be repainted. + * @author Anselm Schmidt + */ + public Repainter(Component component, Rectangle rect) { + this.component = component; + this.rect = rect; + } + + /** + * Implemented interface method. Will be called when it's time to repaint. + * @param arg0 Not used. + * @author Anselm Schmidt + */ + public void actionPerformed(ActionEvent arg0) { + component.repaint(rect.x, rect.y, rect.width, rect.height); + } + +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/TreeView.java b/src/org/jalgo/module/bfsdfs/gui/graphview/TreeView.java new file mode 100644 index 0000000..b9443a2 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/TreeView.java @@ -0,0 +1,400 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.Calendar; +import java.util.ConcurrentModificationException; +import java.util.List; + +import javax.swing.Timer; + +import org.jalgo.module.bfsdfs.algorithms.Algo; +import org.jalgo.module.bfsdfs.algorithms.stack.NodeStatus; +import org.jalgo.module.bfsdfs.algorithms.stack.StackObserver; +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.graph.AlgoGraphObserver; +import org.jalgo.module.bfsdfs.graph.GraphObserver; +import org.jalgo.module.bfsdfs.gui.GUITest; +import org.jalgo.module.bfsdfs.gui.GraphAnimations; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * TreeView extends GraphView and paints the result + * tree over the already drawn graph using transparency. + * + * @author Anselm Schmidt + * + */ +public class TreeView extends GraphView implements StackObserver, AlgoGraphObserver { + private static final long serialVersionUID = 1L; + + /** + * Used drawing strategy for the tree nodes. + */ + protected AlgoNodeStrategy nodeStrategy; + + /** + * Used drawing strategy for the finished tree nodes. + */ + protected AlgoFinishedNodeStrategy finishedStrategy; + + /** + * Used drawing strategy for the tree edges. + */ + protected AlgoEdgeStrategy edgeStrategy; + + /** + * Id of the current node. Will be shown animated. + */ + protected int currentNode; + + /** + * Start time of the node cursor animation. + * Will be used to perform the hiding animation of the last node, too. + */ + protected long cursorAnimationTime; + + /** + * Alpha value of the last node when it changed to the current node. + */ + protected int lastAlphaValue; + + /** + * Position of the current node. + */ + protected Point currentNodePos; + + /** + * Position of the last node. + */ + protected Point lastNodePos; + + /** + * Used GraphController instance. + */ + GraphController graphController; + + /** + * Constructor. Creates the element array and the drawing strategy. Adds + * itself as AlgoGraphObserver and StackObserver + * to the corresponding algorithm. Disables animations. + * + * @param agorithm + * Algorithm to show in the view. + * @author Anselm Schmidt + */ + public TreeView(Algo algorithm, GraphController graphController) { + super(graphController); + + // create drawing strategies + nodeStrategy = new AlgoNodeStrategy(); + edgeStrategy = new AlgoEdgeStrategy(); + finishedStrategy = new AlgoFinishedNodeStrategy(); + + // disable animations in the beginning + animated = false; + + // add observers + algorithm.addTreeObserver(this); + algorithm.addStackObserver(this); + graphController.addGraphObserver(new InputGraphObserver()); + + // save graph controller instance + this.graphController = graphController; + } + + @Override + /** Drawing method. Draws the result tree over the graph using transparency. + * @param g Used Graphics instance. + * @author Anselm Schmidt + */ + public void paint(Graphics g) { + // draw semi-transparent white rectangle + g.setColor(new Color(255, 255, 255, TREEVIEW_ALPHA_VALUE)); + g.fillRect(0, 0, getWidth(), getHeight()); + + // enable anti-aliasing + GraphDrawing.enableAntiAliasing(g); + + try { + // draw deleted tree elements + for(VisualGraphElement element : deletedElements) { + if(element.paint(g, animated)) { + // repaint element after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + + // draw tree elements + for (VisualGraphElement element : elements) { + if(element.paint(g, animated)) { + // repaint element after a short while + Repainter repainter = new Repainter(this, element.getRect(g)); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + } + } + catch(ConcurrentModificationException e) { + // This can be happen because of multi-threading - can be ignored. + } + + if(currentNode > 0) { + // draw and animate the current node cursor + if(animated) { + int alpha = GraphAnimations.animateNodeCursor(ALPHA_100_PERCENT, + Calendar.getInstance().getTimeInMillis() - cursorAnimationTime, + NODE_CURSOR_ANIMATION_TIME); + + Rectangle rect = GraphDrawing.drawNodeCursor(g, currentNodePos, + NODE_BEAMER_SIZE, NODE_CURSOR_SCALE_FACTOR, + NODE_BEAMER_BORDER_SIZE, NODE_CURSOR_COLOR, alpha); + + // repaint node cursor after a short while + Repainter repainter = new Repainter(this, rect); + Timer timer = new Timer(ANIMATION_REPAINT_DELAY, repainter); + timer.setRepeats(false); + timer.start(); + } + else { + GraphDrawing.drawNodeCursor(g, currentNodePos, + NODE_BEAMER_SIZE, NODE_CURSOR_SCALE_FACTOR, + NODE_BEAMER_BORDER_SIZE, NODE_CURSOR_COLOR, 255); + } + } + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onAllNodesFinished() { + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onAllQueuesRemoved() { + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onFirstQueueAdded(int owner) { + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onNodesAdded(List nodes) { + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onQueueAdded(int owner) { + } + + /** + * Observer method. Changes status of a node. + * + * @param node + * Id of the node. + * @param newStatus + * New status of the node. + * @author Anselm Schmidt + */ + public void onStatusChanged(int node, NodeStatus newStatus) { + // logging + GUITest.write("[ALGO] onStatusChanged(" + node + ", " + newStatus + ")", true); + + // find node in the tree + VisualNode visualNode = findNode(node); + + if (visualNode != null) { + // focus and finish node depending on new node status + switch (newStatus) { + case UNTOUCHED: + // untouched node: unfocus and unfinish node + visualNode.setFocused(false); + visualNode.changeDrawingStrategy(nodeStrategy); + break; + + case WAITING: + // waiting node: focus node and unfinish node + visualNode.setFocused(true); + visualNode.changeDrawingStrategy(nodeStrategy); + break; + + case FINISHED: + // finished node: unfocus node and finish node + visualNode.setFocused(false); + visualNode.changeDrawingStrategy(finishedStrategy); + break; + } + + repaint(visualNode.getRect(getGraphics())); + } + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onTopQueueRemoved() { + } + + /** + * Observer method. Not used. + * + * @author Anselm Schmidt + */ + public void onUntouchedReplaced(List oldNodes, + List newNodes) { + } + + /** + * Implemented observer method. Changes the distance of a tree node. + * + * @param node + * Id of the node. + * @author Anselm Schmidt + */ + public void onDistanceChanged(int node, int newDistance) { + // logging + GUITest.write("[ALGO] > onDistanceChanged(" + node + ", " + newDistance + + ")", true); + + // find node in the tree + VisualNode visualNode = findNode(node); + + if (visualNode != null) { + // change distance + visualNode.changeDistance(newDistance); + } + } + + /** + * Implemented observer method. Node has been added. Use the corresponding + * GraphView method, but change the drawing strategy. + * + * @param node + * Id of the new node.- + * @param pos + * Position of the new node. + * @author Anselm Schmidt + */ + @Override + public void onNodeAdded(int node, Point pos) { + // add node + super.onNodeAdded(node, pos); + + // change drawing strategy if the node has been added + VisualNode visualNode = findNode(node); + + if (visualNode != null) { + visualNode.changeDrawingStrategy(nodeStrategy); + } + } + + /** + * Implemented observer method. Edge has been added. Use the corresponding + * GraphView method, but change the drawing strategy. + * + * @param startNode + * Id of the start node.- + * @param endNode + * Id of the end node. + * @author Anselm Schmidt + */ + @Override + public void onEdgeAdded(int startNode, int endNode) { + // add edge + super.onEdgeAdded(startNode, endNode); + + // change drawing strategy if the edge has been added + VisualEdge edge = findEdge(startNode, endNode); + + if (edge != null) { + edge.changeDrawingStrategy(edgeStrategy); + } + } + + /** + * Implemented observer method. Changes the current node. + * @param newCurrentNode New id of the current node. + * @author Anselm Schmidt + */ + public void onCurrentNodeChanged(int newCurrentNode) { + if (!graphController.getNodes().contains(newCurrentNode)) + return; + + // save the current alpha value of the old cursor to perform the hiding animation + if (graphController.getNodes().contains(currentNode)) { + lastAlphaValue = GraphAnimations.animateNodeCursor(ALPHA_100_PERCENT, + System.currentTimeMillis(), NODE_CURSOR_ANIMATION_TIME); + lastNodePos = graphController.getNodePosition(currentNode); + } + + // change ids + currentNode = newCurrentNode; + + // start animation of the new node's cursor + currentNodePos = graphController.getNodePosition(currentNode); + cursorAnimationTime = Calendar.getInstance().getTimeInMillis(); + } + + /** + * Observer for the original graph (not for the tree the algorithm generates) + * @author Thomas Görres + * + */ + private class InputGraphObserver implements GraphObserver { + /** + * Corrects the node cursor's position if a node was moved + * @author Thomas Görres + */ + public void onNodeMoved(int node, Point pos) { + if (node == currentNode) + currentNodePos = pos; + } + + /** + * Hides the node cursor if the last node was removed + */ + public void onNodeRemoved(int node) { + if (1 == node) + currentNode = 0; + } + + /** + * Shows the node cursor if the first node was added + */ + public void onNodeAdded(int node, Point pos) { + if (1 == node) + currentNode = 1; + + } + + public void onEdgeAdded(int startNode, int endNode) {} + public void onEdgeChanged(int oldStartNode, int oldEndNode, int newStartNode, int newEndNode) {} + public void onEdgeRemoved(int startNode, int endNode) {} + public void onNodeChanged(int oldNodeId, int newNodeId) {} + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.java b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.java new file mode 100644 index 0000000..6c4bb23 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualEdge.java @@ -0,0 +1,400 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.geom.Line2D; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GraphCalculation; + +/** + * VisualEdge represents an animated edge which will be drawn by a + * GraphView or TreeView element. + * @author Anselm Schmidt + * + */ +public class VisualEdge extends VisualGraphElement { + + /** + * Start node of the edge. + */ + private int startNode; + + /** + * End node of the edge. + */ + private int endNode; + + /** + * True, if edge is bidirectional, False otherwise. + */ + private boolean bidirectional; + + /** + * True, if the start of the edge is focused, + * False otherwise. + */ + private boolean startFocused; + + /** + * True, if the end of the edge is focused, + * False otherwise. + */ + private boolean endFocused; + + /** + * Drawing strategy for the edge. + */ + private EdgeDrawingStrategy drawingStrategy; + + /** + * True if the method changeBidirectionalEdgeOnce has + * already been called. False otherwise. If True, the + * bidirectional edge will be changed on the next call of this method. + */ + private boolean changing; + + /** + * Constructor. Creates a new VisualEdge instance. + * @param startNode ID of the start node. + * @param endNode ID of the end node. + * @param bidirectional True, if the edge is bidirectional, + * False otherwise. + * @param drawingStrategy Used drawing strategy. + * @param graphController Used GraphController instance. + * @author Anselm Schmidt + */ + public VisualEdge(int startNode, int endNode, boolean bidirectional, + EdgeDrawingStrategy drawingStrategy, GraphController graphController) { + super(graphController); + this.startNode = startNode; + this.endNode = endNode; + this.bidirectional = bidirectional; + this.drawingStrategy = drawingStrategy; + + startFocused = false; + endFocused = false; + changing = false; + + // start creation animation + animationStartTime = Calendar.getInstance().getTimeInMillis(); + animationType = AnimationType.CREATE; + } + + /** + * Get the start node of the edge. + * @return Id of the start node. + * @author Anselm Schmidt + */ + public int getStartNode() { + return startNode; + } + + /** + * Get the end node of the edge. + * @return Id of the start node. + * @author Anselm Schmidt + */ + public int getEndNode() { + return endNode; + } + + /** + * Change the drawing strategy of the edge. + * @param strategy New drawing strategy. + * @author Anselm Schmidt + */ + public void changeDrawingStrategy(EdgeDrawingStrategy strategy) { + drawingStrategy = strategy; + } + + @Override + /** + * Check, if the specified point is in the boundaries of the edge. + * @param point The point to check. + * @return True, if the point is in the boundaries, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean hitBoundaries(Point point) { + // checks, if it is a circle edge + if(startNode == endNode) { + // circle edge: get node position + Point pos = this.getGraphController().getNodePosition(startNode); + + // calculate center of the circle + int centerX = pos.x; + int centerY = pos.y - EDGE_CIRCLE_SIZE / 2; + + // calculate squared mininmal and maximal distance + int sqrMin = (EDGE_CIRCLE_SIZE / 2 - EDGE_BOUNDARIES) * + (EDGE_CIRCLE_SIZE / 2 - EDGE_BOUNDARIES); + int sqrMax = (EDGE_CIRCLE_SIZE / 2 + EDGE_BOUNDARIES) * + (EDGE_CIRCLE_SIZE / 2 + EDGE_BOUNDARIES); + + // calculate and round squared distance between hitting point and center + int sqrDist = (int) + Math.round(GraphCalculation.calcPointPointDistSqr(point.x, point.y, + centerX, centerY)); + + // if distance is between min and max, the circle edge has been hit + return sqrMin <= sqrDist && sqrDist <= sqrMax; + } + + // no circle edge: get node positions + Point startPos = this.getGraphController().getNodePosition(startNode); + Point endPos = this.getGraphController().getNodePosition(endNode); + + // create instance of Line2D object + Line2D line = new Line2D.Float(startPos, endPos); + + // calculate distance between line and point + long distance = Math.round(line.ptSegDist(point)); + + // checks the size of the distance + return distance <= EDGE_BOUNDARIES; + } + + @Override + /** + * Drawing method. + * Let the current EdgeDrawingStrategy paint the edge. + * @param g Used Graphics instance. + * @param animated True, if the element is animated, + * False otherwise. + * @return True, if the element has to be redrawn due to animations, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, boolean animated) { + // get node positions + Point startPos = this.getGraphController().getNodePosition(startNode); + Point endPos = this.getGraphController().getNodePosition(endNode); + + if(!animated) { + // stop animation + animationType = AnimationType.NONE; + } + + // draw edge + return drawingStrategy.paint(g, startPos, endPos, bidirectional, startFocused, + endFocused, focused, alpha, animationType, animationStartTime, + ComponentUtility.BEAMER_MODE); + } + + @Override + /** + * Checks, if the specified point is on the edge. + * @param point The point to check. + * @return True, if the point is on the edge, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean wasHit(Point point) { + // checks, if it is a circle edge + if(startNode == endNode) { + // circle edge: get node position + Point pos = this.getGraphController().getNodePosition(startNode); + + // calculate center of the circle + int centerX = pos.x; + int centerY = pos.y - EDGE_CIRCLE_SIZE / 2; + + // calculate squared mininmal and maximal distance + int sqrMin = (EDGE_CIRCLE_SIZE / 2 - EDGE_WIDTH / 2) * + (EDGE_CIRCLE_SIZE / 2 - EDGE_WIDTH / 2); + int sqrMax = (EDGE_CIRCLE_SIZE / 2 + EDGE_WIDTH / 2) * + (EDGE_CIRCLE_SIZE / 2 + EDGE_WIDTH / 2); + + // calculate and round squared distance between hitting point and center + int sqrDist = (int) + Math.round(GraphCalculation.calcPointPointDistSqr(point.x, point.y, + centerX, centerY)); + + // if distance is between min and max, the circle edge has been hit + return sqrMin <= sqrDist && sqrDist <= sqrMax; + } + + // no circle edge: get node positions + Point startPos = this.getGraphController().getNodePosition(startNode); + Point endPos = this.getGraphController().getNodePosition(endNode); + + // create instance of Line2D object + Line2D line = new Line2D.Float(startPos, endPos); + + // calculate distance between line and point + long distance = Math.round(line.ptSegDist(point)); + + // checks the size of the distance + return distance <= EDGE_WIDTH; + } + + /** + * Make the edge bidirectional. + * @author Anselm Schmidt + */ + public void makeBidirectional() { + bidirectional = true; + } + + /** + * Remove one direction of a bidirectional edge + * @param startPos The id of the start node. + * @param endPos The id of the end node. + * @author Anselm Schmidt + */ + public void removeDirection(int startNode, int endNode) { + if(this.startNode == startNode && this.endNode == endNode) { + this.startNode = endNode; + this.endNode = startNode; + } + + bidirectional = false; + } + + /** + * Check, if the edge is bidirectional. + * @return True, if the edge is bidirectional, + * False otherwise. + * @author Anselm Schmidt + */ + public boolean isBidirectional() { + return bidirectional; + } + + /** + * Set, if the the start of the edge is focused. + * @param focused True, if the start of the edge is focused, + * False otherwise. + * @author Anselm Schmidt + */ + public void setStartFocused(boolean focused) { + startFocused = focused; + } + + /** + * Set, if the the end of the edge is focused. + * @param focused True, if the end of the edge is focused, + * False otherwise. + * @author Anselm Schmidt + */ + public void setEndFocused(boolean focused) { + endFocused = focused; + } + + /** + * Change the ids of start and end node. + * @param start New id of the start node. + * @param end New id of the end node. + * @author Anselm Schmidt + */ + public void changeEdge(int start, int end) { + startNode = start; + endNode = end; + } + + /** + * Changes the ids of bidirectional edge nodes. + * The method has to be called twice to take effect. + * Throws an IllegalArgumentException if the edge isn't bidirectional. + * @param start New id of the first node. + * @param end New id of the other node. + * @author Anselm Schmidt + */ + public void changeBidirectionalEdgeOnce(int start, int end) { + if(bidirectional) { + if(changing) { + // second call: change edge + startNode = start; + endNode = end; + changing = false; + } + else { + // first call: remember call + changing = true; + } + } + else { + // edge isn't bidirectional + throw new IllegalArgumentException(); + } + } + + /** + * Converting node to string. + * @return A string "edge a=>b" with the start node + * id instead of a and the end node if instead of + * b. + * @author Anselm Schmidt + */ + @Override + public String toString() { + if(bidirectional) { + return "edge " + startNode + "<=>" + endNode; + } + + return "edge " + startNode + "=>" + endNode; + } + + /** + * Get the drawing strategy of the edge. + * @return Drawing strategy. + * @author Anselm Schmidt + */ + public EdgeDrawingStrategy getDrawingStrategy() { + return drawingStrategy; + } + + @Override + /** + * Get the rectangle around the edge. + * @param g Not used. + * @return The rectangle around the edge. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // get start and end coordinates + Point start = new Point(getGraphController().getNodePosition(startNode)); + Point end = new Point(getGraphController().getNodePosition(endNode)); + int space = EDGE_WIDTH + EDGE_ARROW_WIDTH; + + // correct coordinates + if(start.x > end.x) { + int swap = start.x; + start.x = end.x; + end.x = swap; + } + if(start.y > end.y) { + int swap = start.y; + start.y = end.y; + end.y = swap; + } + + start.x -= space; + start.y -= space; + end.x += space; + end.y += space; + + // return rectangle around edge + return new Rectangle(start.x, start.y, end.x - start.x, end.y - start.y); + } + + /** + * Returns, if an arrow has been focused. + * @param endNode The id of the end node (where the arrow is). + * @author Ans + */ + public boolean isFocused(int endNode) { + if(this.startNode == endNode) { + return this.startFocused; + } + else if(this.endNode == endNode) { + return this.endFocused; + } + + return false; + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.java b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.java new file mode 100644 index 0000000..37b739a --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualGraphElement.java @@ -0,0 +1,137 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GUIConstants; + +/** + * VisualGraphElement represents a drawn element of a graph or tree + * @author Anselm Schmidt + * + */ +public abstract class VisualGraphElement implements GUIConstants { + + private GraphController graphController = null; + + public GraphController getGraphController() { + return graphController; + } + + public VisualGraphElement(GraphController graphController){ + this.graphController = graphController; + } + + /** + * position of the element + */ + protected Point position; + + /** + * True, if the node is focused. False otherwise. + */ + protected boolean focused; + + /** + * Alpha value of the element. + */ + protected short alpha = 255; + + /** + * The time of the animation start. + */ + protected long animationStartTime; + + /** + * The type of the current animation. + */ + protected AnimationType animationType; + + /** + * Get the position of the element. + * @return Position of the center of the element. + * @author Anselm Schmidt + */ + public Point getPosition() { + return position; + } + + /** + * Check, if the current coordinates hit the element. + * @param point The coordinates to be checked. + * @return True if the coordinates hit the element, + * False otherwise. + * @author Anselm Schmidt + */ + public abstract boolean wasHit(Point point); + + /** + * Check, if the current coordinates hit the protected area around the element. + * @param point The coordinates to be checked. + * @return True if the coordinates hit the protected area, + * False otherwise. + * @author Anselm Schmidt + */ + public abstract boolean hitBoundaries(Point point); + + /** + * Drawing method. Draws the element without animation. + * @param g Used Graphics instance. + * @author Anselm Schmidt + */ + public void paint(Graphics g) { + paint(g, false); + } + + /** + * Drawing method. Draws the element. + * @param g Used Graphics instance. + * @param animated True, if the element is animated, + * False otherwise. + * @return True, if the element has to be redrawn due to animations, + * False otherwise. + * @author Anselm Schmidt + */ + public abstract boolean paint(Graphics g, boolean animated); + + /** + * Set focus of the node. + * @ + * @author Anselm Schmidt + */ + public void setFocused(boolean focused) { + // reset animation time + animationStartTime = Calendar.getInstance().getTimeInMillis(); + + // set animation type + if(focused) { + animationType = AnimationType.FOCUS; + } + else { + animationType = AnimationType.UNFOCUS; + } + + // set focus + this.focused = focused; + } + + /** + * Check, if the element is focussed. + * @return True if the element is focussed, False + * otherwise. + * @author Anselm Schmidt + */ + public boolean isFocused() { + return focused; + } + + /** + * Get the rectangle of the element. Can be used to repaint this area only. + * @param g Used Graphics interface. + * @return Rectangle around the element. + */ + public abstract Rectangle getRect(Graphics g); +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.java b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.java new file mode 100644 index 0000000..06ce06a --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualNode.java @@ -0,0 +1,235 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.util.Calendar; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.ComponentUtility; +import org.jalgo.module.bfsdfs.gui.GraphCalculation; + +/** + * VisualNode represents an animated graph or tree node which will be + * drawn in a GraphView or TreeView element. + * @author Anselm Schmidt + * + */ +public class VisualNode extends VisualGraphElement { + /** + * Id of the node. + */ + protected int id; + + /** + * Distance of the node. Only used by tree nodes. + */ + protected int distance; + + /** + * Drawing strategy for the edge. + */ + protected NodeDrawingStrategy drawingStrategy; + + /** + * Constructor. Creates a new VisualNode instance. + * @param id Number of the new node. + * @param position Position of the new node. + * @param drawingStrategy Used drawing strategy. + * @param graphController Used GraphController instance. + * @author Anselm Schmidt + */ + public VisualNode(int id, Point position, NodeDrawingStrategy drawingStrategy, + GraphController graphController) { + super(graphController); + this.id = id; + this.position = position; + this.drawingStrategy = drawingStrategy; + + // start creation animation + animationStartTime = Calendar.getInstance().getTimeInMillis(); + animationType = AnimationType.CREATE; + } + + /** + * Copy constructor. + * Creates a clone of an existing VisualNode instance. + * @param node Existing node. + * @param graphController Used GraphController instance. + * @author Anselm Schmidt + */ + public VisualNode(VisualNode node, GraphController graphController) { + super(graphController); + id = node.getId(); + position = node.getPosition(); + distance = node.getDistance(); + drawingStrategy = node.getDrawingStrategy(); + + // start creation animation + animationStartTime = Calendar.getInstance().getTimeInMillis(); + animationType = AnimationType.CREATE; + } + + /** + * Check, if the current coordinates hit the node. + * @param point The coordinates to be checked. + * @return True if the coordinates hit the node, + * False otherwise. + * @author Anselm Schmidt + */ + @Override + public boolean wasHit(Point point) { + // checks if the distance between point and position is smaller than the radius + return point.distance(position) <= Math.round(NODE_BEAMER_SIZE / 2); + } + + /** + * Check, if the current coordinates hit the boundaries of the node. + * @param point The coordinates to be checked. + * @return True if the coordinates hit the node boundaries, + * False otherwise. + * @author Anselm Schmidt + */ + @Override + public boolean hitBoundaries(Point point) { + // create rectangle for the boundaries of the node + Rectangle boundaries = new Rectangle(); + + // calculate top left corner + boundaries.x = position.x - NODE_SIZE; + boundaries.y = position.y - NODE_SIZE; + + // calculate size + boundaries.width = 2 * NODE_SIZE; + boundaries.height = 2 * NODE_SIZE; + + // check if the point lays in the boundaries + return boundaries.contains(point); + } + + /** + * Set a new node position. + * @param position The new position of the node. + * @author Anselm Schmidt + */ + public void setPosition(Point position) { + this.position = position; + } + + /** + * Change the node id. + * @param id The new id of the node. + * @author Anselm Schmidt + */ + public void changeId(int id) { + this.id = id; + } + + /** + * Get the id of the node. + * @return Id of the node. + * @author Anselm Schmidt + */ + public int getId() { + return id; + } + + /** + * Get the drawing strategy of the node. + * @return Drawing strategy. + * @author Anselm Schmidt + */ + public NodeDrawingStrategy getDrawingStrategy() { + return drawingStrategy; + } + + /** + * Change the drawing strategy of the node. + * @param strategy New drawing strategy. + * @author Anselm Schmidt + */ + public void changeDrawingStrategy(NodeDrawingStrategy strategy) { + drawingStrategy = strategy; + } + + /** + * Drawing method. + * Let the current NodeDrawingStrategy paint the node. + * @param g Used Graphics instance. + * @param animated True, if the element is animated, + * False otherwise. + * @return True, if the element has to be redrawn due to animations, + * False otherwise. + * @author Anselm Schmidt + */ + @Override + public boolean paint(Graphics g, boolean animated) { + if(!animated) { + // stop animation + animationType = AnimationType.NONE; + } + + // draw node + return drawingStrategy.paint(g, id, position, focused, alpha, distance, + animationType, animationStartTime, ComponentUtility.BEAMER_MODE); + } + + /** + * Convert node to string. + * @return A string "node i at [x;y]" with the + * node id instead of i, the x coordinate of the node + * instead of x and the y coordinate of the node instead of + * y. + * @author Anselm Schmidt + */ + @Override + public String toString() { + return "node " + id + " at [" + position.x + ";" + position.y + "]"; + } + + /** + * Change distance of the node. + * @param distance New distance. + * @author Anselm Schmidt + */ + public void changeDistance(int distance) { + this.distance = distance; + } + + /** + * Get the distance of the node. Only used by tree nodes. + * @return The distance of the node. + * @author Anselm Schmidt + */ + public int getDistance() { + return distance; + } + + @Override + /** + * Get the rectangle around the node. + * @param g Used Graphics interface. + * @return The rectangle around the node. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // get coordinates and calculate the radius of the node + Point center = this.getGraphController().getNodePosition(id); + int radius = (int) Math.round((double) NODE_BEAMER_SIZE / 2) + + NODE_BEAMER_BORDER_SIZE; + Font distanceFont = NODE_DISTANCE_FONT; + + if(ComponentUtility.BEAMER_MODE) { + distanceFont = NODE_BEAMER_DISTANCE_FONT; + } + + int distanceHeight = distanceFont.getSize(); + int distanceWidth = GraphCalculation.calcTextWidth(g, String.valueOf(distance), + distanceFont); + + // return rectangle around node + return new Rectangle(center.x - radius, center.y - radius - distanceHeight, 2 * + radius + distanceWidth, 2 * radius + distanceHeight); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.java b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.java new file mode 100644 index 0000000..dc355d5 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempEdge.java @@ -0,0 +1,143 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * Represents an edge that has not been created yet. + * This class is used when the user is drawing a new edge. + * @author Anselm Schmidt + */ +public class VisualTempEdge extends VisualGraphElement { + /** + * Start node. + */ + protected VisualNode startNode; + + /** + * End node or null, if no end node is used. + */ + protected VisualNode endNode; + + /** + * Position of the end point, if no end node is used. + */ + protected Point endPoint; + + /** + * Is temporary edge bidirectional? + */ + protected boolean bidirectional; + + /** + * Constructor. Creates a temporary edge. + * @param startNode Start node of the temporary edge. + * @param endNode End node of the temporary edge or null + * if no end node is used. + * @param endPoint End point of the temporary edge. + * Will be ignored if an end node is used. + * @param bidirectional True if the temporary edge bidirectional, + * False otherwise. + * @param graphController Used GraphController instance. + * @author Anselm Schmidt + */ + public VisualTempEdge(VisualNode startNode, VisualNode endNode, Point endPoint, + boolean bidirectional, GraphController graphController) { + super(graphController); + this.startNode = startNode; + this.endNode = endNode; + this.bidirectional = bidirectional; + + if(endNode == null) { + // no end node used: use end point + this.endPoint = endPoint; + } + } + + @Override + /** + * Unused method. A temporary edge cannot be hit. + * @author Anselm Schmidt + */ + public boolean hitBoundaries(Point point) { + return false; + } + + @Override + /** + * Drawing method. Draws the temporary edge. + * @param g Used Graphics instance. + * @param animated Not used. + * Temporary graph elements don't have any animations. + * @author Anselm Schmidt + */ + public boolean paint(Graphics g, boolean animated) { + if(startNode != null && (endNode != null || endPoint != null)) { + int radius = (int) Math.round((float) NODE_BEAMER_SIZE / 2f); + + if(endNode == null) { + // no end node is used: draw semi-clipped edge + GraphDrawing.drawClippedEdge(g, startNode.getPosition(), endPoint, + EDGE_WIDTH, bidirectional, radius, 0, EDGE_COLOR, EDGE_COLOR, + EDGE_COLOR, EDGE_ARROW_WIDTH, EDGE_ARROW_LENGTH, + EDGE_CIRCLE_SIZE, TEMP_ALPHA_VALUE); + } + else { + // end node is used: draw fully clipped edge + GraphDrawing.drawClippedEdge(g, startNode.getPosition(), + endNode.getPosition(), EDGE_WIDTH, bidirectional, radius, + radius, EDGE_COLOR, EDGE_COLOR, EDGE_COLOR, EDGE_ARROW_WIDTH, + EDGE_ARROW_LENGTH, EDGE_CIRCLE_SIZE, TEMP_ALPHA_VALUE); + } + } + + // no repaint needed + return false; + } + + @Override + /** + * Unused method. A temporary edge cannot be hit. + * @author Anselm Schmidt + */ + public boolean wasHit(Point point) { + return false; + } + + @Override + /** + * Get the rectangle around the edge. + * @param g Not used. + * @return The rectangle around the edge. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // get start and end coordinates + Point start = new + Point(this.getGraphController().getNodePosition(startNode.getId())); + Point end = new Point(endPoint); + + if(endNode != null) { + end = this.getGraphController().getNodePosition(endNode.getId()); + } + + // correct coordinates + if(start.x > end.x) { + int swap = start.x; + start.x = end.x; + end.x = swap; + } + if(start.y > end.y) { + int swap = start.y; + start.y = end.y; + end.y = swap; + } + + // return rectangle around edge + return new Rectangle(start.x, start.y, end.x - start.x, end.y - start.y); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.java b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.java new file mode 100644 index 0000000..a246856 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/VisualTempNode.java @@ -0,0 +1,89 @@ +package org.jalgo.module.bfsdfs.gui.graphview; + +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Rectangle; + +import org.jalgo.module.bfsdfs.controller.GraphController; +import org.jalgo.module.bfsdfs.gui.GraphDrawing; + +/** + * Represents a node that has not been created yet. + * This class is used when the user is putting a new node. + * @author Anselm Schmidt + */ +public class VisualTempNode extends VisualGraphElement { + + /** + * Position of the temporary node. + */ + protected Point position; + + /** + * Constructor. Creates a temporary node. + * @param position The position of the temporary node. + * @param graphController Used GraphController instance. + * @author Anselm Schmidt + */ + public VisualTempNode(Point position, GraphController graphController) { + super(graphController); + this.position = position; + } + + @Override + /** + * Unused method. A temporary node cannot be hit. + * @author Anselm Schmidt + */ + public boolean hitBoundaries(Point point) { + return false; + } + + /** + * Drawing method. Draws the temporary node. + * @param g Used Graphics instance. + * @param animated Not used. + * Temporary graph elements don't have any animations. + * @author Anselm Schmidt + */ + @Override + public boolean paint(Graphics g, boolean animated) { + // ask GraphController for the if of the next node + int id = this.getGraphController().getNextNodeId(); + + // draw temporary node + GraphDrawing.drawNode(g, String.valueOf(id), position, NODE_BEAMER_FONT, + NODE_BEAMER_SIZE, NODE_BEAMER_BORDER_SIZE, NODE_BORDER_COLOR, + NODE_LABEL_COLOR, NODE_COLOR_TOP, NODE_COLOR_BOTTOM, TEMP_ALPHA_VALUE, + NODE_GRADIENT_HEIGHT); + + // no repaint needed + return false; + } + + /** + * Unused method. A temporary edge cannot be hit. + * @author Anselm Schmidt + */ + @Override + public boolean wasHit(Point point) { + return false; + } + + @Override + /** + * Get the rectangle around the node. + * @param g Not used. + * @return The rectangle around the edge. + * @author Anselm Schmidt + */ + public Rectangle getRect(Graphics g) { + // calculate the radius of the node + int radius = (int) Math.round((double) NODE_BEAMER_SIZE / 2) + + NODE_BEAMER_BORDER_SIZE; + + // return rectangle around node + return new Rectangle(position.x - radius, position.y - radius, + 2 * radius, 2 * radius); + } +} diff --git a/src/org/jalgo/module/bfsdfs/gui/graphview/package.html b/src/org/jalgo/module/bfsdfs/gui/graphview/package.html new file mode 100644 index 0000000..56cfdca --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/graphview/package.html @@ -0,0 +1,11 @@ + + + + +

          This package contains the GraphView, which is a component to show a graph or a tree. InteractiveGraphView and TreeView are child classes from this component, used to create interactivity for creating a graph and to show the result tree of an algorithm.

          +

          To draw the elements of a graph or tree, the abstract class VisualGraphElement is used. There are different child classes like VisualEdge and VisualNode to draw edges and nodes. The child classes DeletedEdge and DeletedNode are used for the remove animation of this elements only. The classes VisualTempNode and VisualTempEdge are used for drawing a temporary graph element that is not created yet.

          +

          This classes use the Strategy design pattern to enable different drawing styles. The abstract classes for this strategies are EdgeDrawingStrategy and NodeDrawingStrategy. The implementations are GraphEdgeStrategy and GraphNodeStrategy for drawing the graph elements and AlgoEdgeStrategy, AlgoNodeStrategy and AlgoFinishedNodeStrategy for drawing the different tree elements.

          +

          For the edit modes of InteractiveGraphView and the animation types for graph or tree elements, there also are two enumerations, called EditMode and AnimationType.

          +

          Finally, the class Repainter is used for the creation of timers, that repaint specified rectangles of different components after a short while. This is used for animations.

          + + \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/gui/package.html b/src/org/jalgo/module/bfsdfs/gui/package.html new file mode 100644 index 0000000..f2f618e --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/gui/package.html @@ -0,0 +1,24 @@ + + + + +

          +This package contains the GUIController which represents an interface between the GUI and the rest of +the program. It controls user actions and observes the graph and the algorithm. Furthermore there are a few +utility classes: +

            +
          • AddNodeAnimation and RemoveNodeAnimation are used in the NodeStackView to fade the +recently added / removed nodes in / out. They use a separate thread.
          • +
          • PlayAnimation is similar to the two above, but is used to play the algorithm.
          • +
          • GraphAnimations is used to calculate values that are needed to animate the GraphView
          • +
          • ComponentUtlility, GraphCalculation and GraphDrawing contain methods that are used +by classes from various gui packages.
          • +
          • GUIConstants contains all constant values, e.g. constant sizes and fonts.
          • +
          • StatusMouseAdapter is an extended MouseAdapter that is used to easily add a mouseover effect to +various components that updates the status bar of J-Algo
          • +
          • GUITest is used to test the classes. One can write values to the error log or popup a new window +etc.
          • +
          +

          + + \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/res.properties b/src/org/jalgo/module/bfsdfs/res.properties new file mode 100644 index 0000000..e29429b --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/res.properties @@ -0,0 +1,24 @@ +ui.Logo_small = /bfsdfs_pix/logo.png +HelpSet_Name = /help/jhelp/bfsdfs_help.hs + +WelcomeScreen.newButton = /bfsdfs_pix/ws_new.png +WelcomeScreen.newButton_over = /bfsdfs_pix/ws_new_over.png +WelcomeScreen.newButton_descr_de = /bfsdfs_pix/ws_new_descr_de.png +WelcomeScreen.newButton_descr_en = /bfsdfs_pix/ws_new_descr_en.png +WelcomeScreen.loadButton = /bfsdfs_pix/ws_load.png +WelcomeScreen.loadButton_over = /bfsdfs_pix/ws_load_over.png +WelcomeScreen.loadButton_descr_de = /bfsdfs_pix/ws_load_descr_de.png +WelcomeScreen.loadButton_descr_en = /bfsdfs_pix/ws_load_descr_en.png +WelcomeScreen.lastButton = /bfsdfs_pix/ws_last.png +WelcomeScreen.lastButton_over = /bfsdfs_pix/ws_last_over.png +WelcomeScreen.lastButton_descr_de = /bfsdfs_pix/ws_last_descr_de.png +WelcomeScreen.lastButton_descr_en = /bfsdfs_pix/ws_last_descr_en.png + +icon_doubleedges = /bfsdfs_pix/edit_double_edges.png +icon_edges = /bfsdfs_pix/edit_edges.png +icon_nodeEdit = /bfsdfs_pix/edit_nodes.png + +tab.designButton = /bfsdfs_pix/tab_design.png +tab.bfsButton = /bfsdfs_pix/tab_bfs.png +tab.dfsButton = /bfsdfs_pix/tab_dfs.png +tab.beamerButton = /bfsdfs_pix/beamermode_button.gif \ No newline at end of file diff --git a/src/org/jalgo/module/bfsdfs/undo/CVS/Entries b/src/org/jalgo/module/bfsdfs/undo/CVS/Entries new file mode 100644 index 0000000..4e2eeb9 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/CVS/Entries @@ -0,0 +1,3 @@ +/Step.java/1.1/Wed Dec 8 13:47:54 2010// +/Undoable.java/1.1/Wed Dec 8 13:47:54 2010// +/UndoableObserver.java/1.1/Wed Dec 8 13:47:54 2010// diff --git a/src/org/jalgo/module/bfsdfs/undo/CVS/Repository b/src/org/jalgo/module/bfsdfs/undo/CVS/Repository new file mode 100644 index 0000000..1cf081d --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/bfsdfs/undo diff --git a/src/org/jalgo/module/bfsdfs/undo/CVS/Root b/src/org/jalgo/module/bfsdfs/undo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/bfsdfs/undo/Step.java b/src/org/jalgo/module/bfsdfs/undo/Step.java new file mode 100644 index 0000000..dd9afda --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/Step.java @@ -0,0 +1,23 @@ +/** + * interface: Step - declares methods to represent a step within the algorithm for + * some kind of a history (undo-redo) + * creation date: 08.05.09 + * completion date: 20.05.09 + * author: Ephraim Zimmer + */ + +package org.jalgo.module.bfsdfs.undo; + +public interface Step { + + /** + * Executes the step represented by the implementation of this interface + */ + public void execute(); + + /** + * Revokes the step represented by the implementation of this interface with the + * possibility to execute the revoked step again + */ + public void undo(); +} diff --git a/src/org/jalgo/module/bfsdfs/undo/Undoable.java b/src/org/jalgo/module/bfsdfs/undo/Undoable.java new file mode 100644 index 0000000..5eec808 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/Undoable.java @@ -0,0 +1,243 @@ +/** + * class: Undoable - an abstract class to make the undo-redo functionality possible + * for the classes "Algo" and "GraphController" + * creation date: 08.05.09 + * completion date: 26.05.09 + * author: Ephraim Zimmer + */ + +package org.jalgo.module.bfsdfs.undo; + +import java.util.ArrayList; +import java.util.LinkedList; + +public abstract class Undoable { + // LinedList as implementation of the interface Queue + private LinkedList undoableSteps; + // ArrayList to have index-assisted access + private ArrayList myUndoableObservers; + // If a step is revoked, it should not be removed from the list "undoableSteps" to + // make a redo possible, but the next step has to be available to be revoked. + private int actualStepIndex; + + //private Logger logger; + + public Undoable() { + // initialize the attributes + + this.undoableSteps = new LinkedList(); + this.myUndoableObservers = new ArrayList(); + // as there is no actual step available + this.actualStepIndex = -1; + + //logger = Logger.getLogger(this.getClass().getName()); + } + + + /** + * Adds a step to the queue of undoable steps, and executes it. + * @param step + */ + protected void makeUndoableStep(Step step) { + + if (step != null) { + + // execution of the added step + step.execute(); + + // increment the index. + actualStepIndex++; + + if (actualStepIndex == undoableSteps.size()) { + undoableSteps.add(actualStepIndex, step); + + } else if (actualStepIndex < undoableSteps.size()){ + // means a step has been done after one or more undo-actions + undoableSteps.set(actualStepIndex, step); + int j = (undoableSteps.size()-1) - actualStepIndex; + // all steps which were undone have to be deleted to avoid a redo-action + for (int i = 0; i < j; i++) { + undoableSteps.remove(actualStepIndex + 1); + } + + // update all ovservers for redo is disabled + for (UndoableObserver uo : myUndoableObservers) { + uo.onRedoDisabled(); + //logger.info("onRedoDisabled"); + } + + } + + // update all ovservers for undo is enabled + if (actualStepIndex == 0) { + for (UndoableObserver uo : myUndoableObservers) { + uo.onUndoEnabled(); + //logger.info("onUndoEnabled"); + } + } + + } else { + // Exception-Treatment + //logger.info("The argument \"step\" is null."); + } + } + + /** + * Executes a step, which should not be undoable + * @param step + */ + public void makeStep(Step step) { + // if the first, already awailable step shouldn't be undoable + step.execute(); + } + + /** + * Revokes a step. + */ + public void undo() { + // by calling the method "undo()" of the last added Step of + // the queue "undoableSteps" and decrements the index. + //logger.info("undo-action"); + if (isUndoPossible()) { + undoableSteps.get(actualStepIndex).undo(); + actualStepIndex--; + + // update all ovservers for redo is enabled + if (actualStepIndex == undoableSteps.size()-2) { + for (UndoableObserver uo : myUndoableObservers) { + uo.onRedoEnabled(); + //logger.info("onRedoEnabled"); + } + } + + if (actualStepIndex == -1) { + + // update all ovservers for undo is disabled + for (UndoableObserver uo : myUndoableObservers) { + uo.onUndoDisabled(); + //logger.info("onUndoDisabled"); + } + + } + } + } + + /** + * Redoes the pre-revoked step. + */ + public void redo() { + // after incrementing the index to choose the right one + // from the list "undoableSteps". + //logger.info("redo-action"); + if (isRedoPossible()) { + actualStepIndex++; + undoableSteps.get(actualStepIndex).execute(); + + // update all ovservers for undo is enabled + if (actualStepIndex == 0) + for (UndoableObserver uo : myUndoableObservers) { + uo.onUndoEnabled(); + //logger.info("onUndoEnabled"); + } + + } + + if (actualStepIndex >= undoableSteps.size()-1) { + + // update all ovservers for redo is disabled + for (UndoableObserver uo : myUndoableObservers) { + uo.onRedoDisabled(); + //logger.info("onRedoDisabled"); + } + + } + } + + /** + * Revokes all steps done so far, with the ability to redo them. + */ + public void undoAll() { + + if (isUndoPossible()) { + + for (; actualStepIndex >= 0; actualStepIndex--) { + undoableSteps.get(actualStepIndex).undo(); + } + + // update all ovservers for undo is disabled + for (UndoableObserver uo : myUndoableObservers) { + uo.onUndoDisabled(); + //logger.info("onUndoDisabled"); + } + + // update all ovservers for redo is enabled + for (UndoableObserver uo : myUndoableObservers) { + uo.onRedoEnabled(); + //logger.info("onRedoEnabled"); + } + } +// +// while (isUndoPossible()) { +// undo(); +// } + + } + + /** + * Returns true, if a redo is allowed. + * @return boolean + */ + public boolean isRedoPossible() { + return (actualStepIndex < undoableSteps.size()-1); + } + + /** + * Returns true, if an undo is allowed. + * @return boolean + */ + public boolean isUndoPossible() { + return (actualStepIndex >= 0); + } + + /** + * Adds an UndoableOvserver. + */ + public void addUndoableObserver(UndoableObserver uo) { + // to the list "myUndoableObservers". + + this.myUndoableObservers.add(uo); + } + + /** + * Removes an UndoableObserver. + */ + public void removeUndoableObserver(UndoableObserver uo) { + // from the list "myUndoableObservers" + + this.myUndoableObservers.remove(uo); + } + + + /** + * @return the undoableSteps + */ + public LinkedList getUndoableSteps() { + return undoableSteps; + } + + + /** + * @return the myUndoableObservers + */ + public ArrayList getMyUndoableObservers() { + return myUndoableObservers; + } + + + /** + * @return the actualStepIndex + */ + public int getActualStepIndex() { + return actualStepIndex; + } +} diff --git a/src/org/jalgo/module/bfsdfs/undo/UndoableObserver.java b/src/org/jalgo/module/bfsdfs/undo/UndoableObserver.java new file mode 100644 index 0000000..dc20ee4 --- /dev/null +++ b/src/org/jalgo/module/bfsdfs/undo/UndoableObserver.java @@ -0,0 +1,33 @@ +/** + * interface: UndoableObserver - defines methods for classes which have to be able to observe + * the "Algo" or the "GraphController" for undo and redo being enabled + * and/or disabled. + * creation date: 08.05.09 + * completion date: 20.05.09 + * author: Ephraim Zimmer + */ + +package org.jalgo.module.bfsdfs.undo; + +public interface UndoableObserver { + + /** + * This method is called, if the revocation of a step is allowed. + */ + public void onUndoEnabled(); + + /** + * This method is called, if there is no step which could be revoked. + */ + public void onUndoDisabled(); + + /** + * This method is called, if the redo of a revoked step is allowed. + */ + public void onRedoEnabled(); + + /** + * This method is called, if there is no step which could be redone. + */ + public void onRedoDisabled(); +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/.grammar/CVS/Entries b/src/org/jalgo/module/c0h0/.grammar/CVS/Entries new file mode 100644 index 0000000..9d108cf --- /dev/null +++ b/src/org/jalgo/module/c0h0/.grammar/CVS/Entries @@ -0,0 +1,2 @@ +/c00-lexer.l/1.1/Sat Mar 5 14:12:06 2011/-kb/ +/c00-parser.g/1.1/Sat Mar 5 14:12:06 2011/-kb/ diff --git a/src/org/jalgo/module/c0h0/.grammar/CVS/Repository b/src/org/jalgo/module/c0h0/.grammar/CVS/Repository new file mode 100644 index 0000000..27bdbd3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/.grammar/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/.grammar diff --git a/src/org/jalgo/module/c0h0/.grammar/CVS/Root b/src/org/jalgo/module/c0h0/.grammar/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/.grammar/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/.grammar/c00-lexer.l b/src/org/jalgo/module/c0h0/.grammar/c00-lexer.l new file mode 100644 index 0000000..a85da30 --- /dev/null +++ b/src/org/jalgo/module/c0h0/.grammar/c00-lexer.l @@ -0,0 +1,72 @@ +package org.jalgo.module.c0h0.parser; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.c0h0.parser.ParserConstants; +import org.jalgo.module.c0h0.parser.GeneratedC00Parser.Terminals; + +%% + +%class C0Scanner +%extends Scanner +%function nextToken +%type Symbol +%yylexthrow Scanner.Exception +%eofval{ + return symbol(Terminals.EOF, ParserConstants.EOF); +%eofval} +%unicode +%line +%column + +%{ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } +%} + +LineTerminator = \n|\r|\r\n +Identifier = x[1-9][0-9]* +Number = 0 | [1-9][0-9]* +Comment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +Whitespace = {LineTerminator} | [\t\f ] + +%% + +{Comment} { /* ignore */ } +{Whitespace}+ { /* ignore */ } +"#include" { return symbol(Terminals.INCLUDE, "#include"); } +"" { return symbol(Terminals.STDIO, ""); } +"int" { return symbol(Terminals.INT, "int"); } +"main" { return symbol(Terminals.MAIN, "main"); } +"(" { return symbol(Terminals.LPAREN, "("); } +")" { return symbol(Terminals.RPAREN, ")"); } +"{" { return symbol(Terminals.LBRACKET, "{"); } +"}" { return symbol(Terminals.RBRACKET, "}"); } +"=" { return symbol(Terminals.ASSIGN, "="); } +"," { return symbol(Terminals.COMMA, ","); } +";" { return symbol(Terminals.SEMICOLON, ";"); } +"&" { return symbol(Terminals.AMP, "&"); } +"if" { return symbol(Terminals.IF, "if"); } +"else" { return symbol(Terminals.ELSE, "else"); } +"while" { return symbol(Terminals.WHILE, "while"); } +"printf" { return symbol(Terminals.PRINTF, "printf"); } +"scanf" { return symbol(Terminals.SCANF, "scanf"); } +"\"%i\"" { return symbol(Terminals.IFORMAT, "\"%i\""); } +"\"%d\"" { return symbol(Terminals.DFORMAT, "\"%d\""); } +"return" {Whitespace}+ "0" { return symbol(Terminals.RETURN, "return 0"); } +"+" { return symbol(Terminals.PLUS, "+"); } +"-" { return symbol(Terminals.MINUS, "-"); } +"/" { return symbol(Terminals.DIV, "/"); } +"*" { return symbol(Terminals.MULT, "*"); } +"%" { return symbol(Terminals.MOD, "%"); } +"==" { return symbol(Terminals.EQ, "=="); } +"!=" { return symbol(Terminals.NE, "!="); } +">=" { return symbol(Terminals.GE, ">="); } +"<=" { return symbol(Terminals.LE, "<="); } +">" { return symbol(Terminals.GT, ">"); } +"<" { return symbol(Terminals.LT, "<"); } +{Identifier} { return symbol(Terminals.IDENT, yytext()); } +{Number} { return symbol(Terminals.NUMBER, yytext()); } +.|\n { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); } diff --git a/src/org/jalgo/module/c0h0/.grammar/c00-parser.g b/src/org/jalgo/module/c0h0/.grammar/c00-parser.g new file mode 100644 index 0000000..4b13a63 --- /dev/null +++ b/src/org/jalgo/module/c0h0/.grammar/c00-parser.g @@ -0,0 +1,175 @@ +%package "org.jalgo.module.c0h0.parser"; + +%import "org.jalgo.module.c0h0.models.ast.*"; +%import "org.jalgo.module.c0h0.models.ast.Number"; +%import "beaver.Symbol"; + +%class "GeneratedC00Parser"; + +%init {: + this.report = ErrorEvents.createReport(); +:}; + +%embed {: + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + private int convertToInt(String str) { + return Integer.parseInt(str); + } +:}; + +%terminals INCLUDE, STDIO; +%terminals IF, ELSE, WHILE, MAIN, PRINTF, SCANF, RETURN, INT; +%terminals IFORMAT, DFORMAT; +%terminals COMMA, SEMICOLON, AMP, ASSIGN; +%terminals PLUS, MINUS, MULT, DIV, MOD; +%terminals EQ, NE, GE, LE, GT, LT; +%terminals LBRACKET, RBRACKET, LPAREN, RPAREN; +%terminals NUMBER, IDENT; + +%typeof Program = "Program"; +%typeof Declaration = "Declaration"; +%typeof ScanfSequence = "ScanfSequence"; +%typeof PrintfStatement = "PrintfStatement"; +%typeof Block = "Block"; +%typeof Statement = "Statement"; +%typeof Term = "Term"; +%typeof Relation = "Relation"; +%typeof RelationType = "RelationType"; +%typeof Operation = "Operation"; +%typeof OperationType = "OperationType"; +%typeof IDENT = "String"; +%typeof NUMBER = "String"; + +// resolve shift-reduce conflict (dangling else) +%nonassoc ELSE; +%nonassoc IF; + +%goal Program; + +Program + = INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c Block.b PrintfStatement.p RETURN SEMICOLON RBRACKET + {: return new Symbol(new Program(d, c, b, p)); :} + | INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c PrintfStatement.p RETURN SEMICOLON RBRACKET + {: return new Symbol(new Program(d, c, null, p)); :} + ; + +Declaration + = INT IDENT.i + {: return new Symbol(new Declaration(new Var(i))); :} + | Declaration.d COMMA IDENT.i + {: d.addVariable(new Var(i)); return new Symbol(d); :} + ; + +ScanfSequence + = + {: return new Symbol(new ScanfSequence()); :} + | ScanfSequence.s SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON + {: s.addScanf(new Var(i)); return new Symbol(s); :} + ; + +PrintfStatement + = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON + {: return new Symbol(new PrintfStatement(new Var(i))); :} + ; + +Block + = LBRACKET RBRACKET + {: return new Symbol(new Block(true)); :} + | LBRACKET Block.b Statement.stat RBRACKET + {: b.addStatement(stat); return new Symbol(b); :} + | Statement.stat + {: return new Symbol(new Block(stat, true)); :} + | Block.b Statement.stat + {: b.addStatement(stat); return new Symbol(b); :} + ; + +Statement + = SEMICOLON + {: return new Symbol(new Statement()); :} + | IDENT.i ASSIGN Term.t SEMICOLON + {: return new Symbol(new Assignment(new Var(i), t)); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(true), new Block(false))); :} + | IF LPAREN Relation.r RPAREN Statement.s + {: return new Symbol(new If(r, new Block(s, false), new Block(false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + {: return new Symbol(new If(r, b)); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(true), new Block(true))); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE Statement.s2 + {: return new Symbol(new If(r, new Block(true), new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, new Block(true), s2)); :} + | IF LPAREN Relation.r RPAREN Statement.s ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, new Block(s, false), new Block(true))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET ELSE LBRACKET RBRACKET + {: return new Symbol(new If(r, b, new Block(true))); :} + | IF LPAREN Relation.r RPAREN Statement.s1 ELSE Statement.s2 + {: return new Symbol(new If(r, new Block(s1, false), new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN Statement.s1 ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, new Block(s1, false), s2)); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE Statement.s2 + {: return new Symbol(new If(r, s1, new Block(s2, false))); :} + | IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE LBRACKET Block.s2 RBRACKET + {: return new Symbol(new If(r, s1, s2)); :} + | WHILE LPAREN Relation.r RPAREN Statement.s + {: return new Symbol(new While(r, new Block(s, false))); :} + | WHILE LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + {: return new Symbol(new While(r, b)); :} + | WHILE LPAREN Relation.r RPAREN LBRACKET RBRACKET + {: return new Symbol(new While(r, new Block(true))); :} + ; + +Term + = IDENT.i + {: return new Symbol(new Var(i)); :} + | NUMBER.n + {: return new Symbol(new Number(convertToInt(n))); :} + | LPAREN Term.t RPAREN + {: return new Symbol(new Term(t)); :} + | PLUS IDENT.i + {: return new Symbol(new Var(i, UnaryType.PLUS)); :} + | PLUS NUMBER.n + {: return new Symbol(new Number(convertToInt(n), UnaryType.PLUS)); :} + | PLUS LPAREN Term.t RPAREN + {: return new Symbol(new Term(t, UnaryType.PLUS)); :} + | MINUS IDENT.i + {: return new Symbol(new Var(i, UnaryType.MINUS)); :} + | MINUS NUMBER.n + {: return new Symbol(new Number(convertToInt(n), UnaryType.MINUS)); :} + | MINUS LPAREN Term.t RPAREN + {: return new Symbol(new Term(t, UnaryType.MINUS)); :} + | Operation.o + {: return new Symbol(o); :} + | Relation.r + {: return new Symbol(r); :} + ; + +Relation + = Term.l RelationType.rel Term.r + {: return new Symbol(new Relation(l, rel, r)); :} + ; + +RelationType + = EQ {: return new Symbol(RelationType.EQ); :} + | NE {: return new Symbol(RelationType.NE); :} + | LE {: return new Symbol(RelationType.LE); :} + | GE {: return new Symbol(RelationType.GE); :} + | LT {: return new Symbol(RelationType.LT); :} + | GT {: return new Symbol(RelationType.GT); :} + ; + +Operation + = Term.l OperationType.op Term.r + {: return new Symbol(new Operation(l, op, r)); :} + ; + +OperationType + = PLUS {: return new Symbol(OperationType.ADD); :} + | MINUS {: return new Symbol(OperationType.SUB); :} + | MULT {: return new Symbol(OperationType.MUL); :} + | DIV {: return new Symbol(OperationType.DIV); :} + | MOD {: return new Symbol(OperationType.MOD); :} + ; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/CVS/Entries b/src/org/jalgo/module/c0h0/CVS/Entries new file mode 100644 index 0000000..46f7c7e --- /dev/null +++ b/src/org/jalgo/module/c0h0/CVS/Entries @@ -0,0 +1,11 @@ +D/.grammar//// +/ModuleConnector.java/1.1/Sat Mar 5 14:12:06 2011// +/ModuleInfo.java/1.1/Sat Mar 5 14:12:06 2011// +D/controller//// +D/gui//// +D/models//// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// +D/parser//// +/res.properties/1.1/Sat Mar 5 14:12:06 2011// +D/tests//// +D/views//// diff --git a/src/org/jalgo/module/c0h0/CVS/Repository b/src/org/jalgo/module/c0h0/CVS/Repository new file mode 100644 index 0000000..767efc3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0 diff --git a/src/org/jalgo/module/c0h0/CVS/Root b/src/org/jalgo/module/c0h0/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/ModuleConnector.java b/src/org/jalgo/module/c0h0/ModuleConnector.java new file mode 100644 index 0000000..c91093a --- /dev/null +++ b/src/org/jalgo/module/c0h0/ModuleConnector.java @@ -0,0 +1,87 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.c0h0; + +import java.awt.BorderLayout; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.SwingConstants; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.c0h0.gui.ModuleContainer; +import org.jalgo.module.c0h0.views.TerminalView; +import org.jalgo.module.c0h0.controller.Controller; + +/** + * connects the module with j-Algo + */ +public class ModuleConnector extends AbstractModuleConnector{ + ModuleContainer container; + Controller controller; + JMenuItem beamerModeSelector; + + + @Override + public void init() { + container = new ModuleContainer(); + controller = new Controller(container, JAlgoGUIConnector.getInstance().getModuleToolbar( + this), JAlgoGUIConnector.getInstance().getModuleMenu(this)); + + JComponent contentPane = JAlgoGUIConnector.getInstance() + .getModuleComponent(this); + + JLabel helloJAlgo = new JLabel("C0H0 Modul", new ImageIcon(Messages + .getResourceURL("main", "ui.Logo")), SwingConstants.CENTER); + contentPane.add(helloJAlgo, BorderLayout.CENTER); + contentPane.add(container); + + } + + @Override + public void run() { + TerminalView.println("C0H0 Module is running"); + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + // no action + } + + @Override + public ByteArrayOutputStream getDataForFile() { + return null; + } + + @Override + public void print() { + // no action + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/ModuleInfo.java b/src/org/jalgo/module/c0h0/ModuleInfo.java new file mode 100644 index 0000000..f7668bf --- /dev/null +++ b/src/org/jalgo/module/c0h0/ModuleInfo.java @@ -0,0 +1,85 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.c0h0; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * provides information of the module + */ +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "C0H0"; + } + + public String getVersion() { + return "1.0"; + } + + public String getAuthor() { + return "Hendrik Sollich, Patrick Tempel, Peter Schwede, Philipp Geißler, Mathias Kaufmann"; + } + + public String getDescription() { + return "Ein Modul zur schrittweisen Visualisierung der " + + "algorithmischen Transformation von C0-Code in H0-Code."; + } + + public URL getLogoURL() { + return Messages.getResourceURL("c0h0", "logo"); + } + + public String getLicense() { + return "GNU General Public License"; + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("c0h0","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/controller/ButtonCommand.java b/src/org/jalgo/module/c0h0/controller/ButtonCommand.java new file mode 100644 index 0000000..54bb45e --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/ButtonCommand.java @@ -0,0 +1,9 @@ +package org.jalgo.module.c0h0.controller; + +/** + * enumeration of button commands + * + */ +public enum ButtonCommand { + newCode, loadCode, exampleCode, undoAll, undoStep, performStep, performAll, run, edit, toggleBeamerMode, toggleViewState, saveC0, saveFC, saveH0, viewC0Flow, viewFlowH0, viewC0H0, transviewOn, transviewOff +} diff --git a/src/org/jalgo/module/c0h0/controller/CVS/Entries b/src/org/jalgo/module/c0h0/controller/CVS/Entries new file mode 100644 index 0000000..723b860 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/CVS/Entries @@ -0,0 +1,8 @@ +/ButtonCommand.java/1.1/Sat Mar 5 14:12:05 2011// +/Controller.java/1.1/Sat Mar 5 14:12:05 2011// +/FileManager.java/1.1/Sat Mar 5 14:12:05 2011// +/InterfaceConstants.java/1.1/Sat Mar 5 14:12:05 2011// +/State.java/1.1/Sat Mar 5 14:12:05 2011// +/ViewManager.java/1.1/Sat Mar 5 14:12:05 2011// +/ViewState.java/1.1/Sat Mar 5 14:12:05 2011// +/package-info.java/1.1/Sat Mar 5 14:12:05 2011// diff --git a/src/org/jalgo/module/c0h0/controller/CVS/Repository b/src/org/jalgo/module/c0h0/controller/CVS/Repository new file mode 100644 index 0000000..2ddb5ec --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/controller diff --git a/src/org/jalgo/module/c0h0/controller/CVS/Root b/src/org/jalgo/module/c0h0/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/controller/Controller.java b/src/org/jalgo/module/c0h0/controller/Controller.java new file mode 100644 index 0000000..dc28621 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/Controller.java @@ -0,0 +1,385 @@ +package org.jalgo.module.c0h0.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.swing.JToolBar; +import javax.swing.JMenu; + +import org.jalgo.module.c0h0.gui.ModuleContainer; +import org.jalgo.module.c0h0.gui.ButtonManager; + +import org.jalgo.module.c0h0.models.Performer; +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.c0model.C0CodeModel; +import org.jalgo.module.c0h0.models.flowchart.FlowChartModel; +import org.jalgo.module.c0h0.models.h0model.H0CodeModel; +import org.jalgo.module.c0h0.models.tmodel.TRuleModel; + +/** + * Central Controller Class + * + * Organizes communication between Models and Views + * + * @author hendrik + * + */ +public class Controller { + private ViewManager viewManager; + private ButtonManager buttonManager; + private C0CodeModel c0CodeModel; + private ASTModel model; + private FlowChartModel fcModel; + private H0CodeModel h0CodeModel; + private TRuleModel tRuleModel; + private FileManager fileManager; + private int cPerf; + private List performers; + + /** + * @param container + * @param toolbar + * @param menu + */ + public Controller(ModuleContainer container, JToolBar toolbar, JMenu menu) { + fileManager = new FileManager(); + + // create Models first + model = new ASTModel(); + c0CodeModel = new C0CodeModel(this); + h0CodeModel = new H0CodeModel(this); + fcModel = new FlowChartModel(this); + tRuleModel = new TRuleModel(this); + + // the views come later, because the views need the models + viewManager = new ViewManager(this, container); + buttonManager = new ButtonManager(this, viewManager, toolbar, menu); + buttonManager.toggleTransView(false); + } + + /** + * Saves current content of codeModel into a file using the FileManager + * Class + * + */ + public void saveFileC0() { + List code = c0CodeModel.getPlainC0Code(); + fileManager.saveFile(code); + } + + /** + * Saves current content of codeModel into a file using the FileManager + * Class + * + */ + public void saveFileH0() { + String code = h0CodeModel.getCode(); + fileManager.saveFile(code, ".h0"); + } + + /** + * Saves the flowchart into an image + */ + public void saveFileFlowchart() { + fileManager.saveImage(viewManager.getFlowChartImage(), ".png"); + } + /** + * Toggles to edit mode + */ + public void newCode() { + setState(ViewState.EDIT); + updateViews(); + } + + /** + * Loads a .c0 File using the FileManager Class + * + */ + public void openFile() { + ArrayList file = fileManager.openFile(); + if (file.size() > 0) { + c0CodeModel.loadCode(file); + if (viewManager.getState() != ViewState.WELCOME) + returnToEditMode(); + else + setState(ViewState.EDIT); + } + } + + /** + * Same as openFile() - only it starts in a different directory + * + */ + public void openExample() { + ArrayList example = fileManager.openExample(); + if (example.size() > 0) { + c0CodeModel.loadCode(example); + if (viewManager.getState() != ViewState.WELCOME) + returnToEditMode(); + else + setState(ViewState.EDIT); + } + } + + /** + * + * Instructs the Model to generate the AST from the c0 code and enters + * RUN-state + * + */ + public void runTransformation() { + // Run Button pressed + + // Nun einen AST erstellen + + // Vorerst den Code im CodeModel ablegen + String code = viewManager.getC0Code(); + c0CodeModel.setCode(code); + model.create(code); + + // AST erstellt oder etwa doch nicht? + if (model.isValid()) { + buttonManager.setUndoAllEnabled(false); + buttonManager.setUndoStepEnabled(false); + c0CodeModel.generate(); + h0CodeModel.generate(); + fcModel.generate(); + tRuleModel.generate(); + initPerformers(); + setState(ViewState.RUN); + setArrows(0); + } else { + viewManager.updateErrorInformation(model.getErrorText()); + buttonManager.toggleTransView(true); + } + viewManager.updateViews(); + } + + /** + * Leaves the RUN-state + * + */ + public void returnToEditMode() { + // Edit Button pressed + c0CodeModel.clear(); + c0CodeModel.setActive(true); + h0CodeModel.setActive(false); + fcModel.setActive(false); + h0CodeModel.clear(); + fcModel.clear(); + model.setMarkedNode(""); + viewManager.updateErrorInformation(""); + viewManager.renderAllViews(); + setState(ViewState.EDIT); + } + + /** + * Tells the Model to set a node in the AST as marked + * + * @param addr + */ + public void markNode(String addr) { + model.setMarkedNode(addr); + viewManager.renderViews(); + } + + /** + * Initializes performers + */ + public void initPerformers() { + performers = new ArrayList(); + performers.add(c0CodeModel); + performers.add(fcModel); + performers.add(h0CodeModel); + cPerf = 0; + } + + /** + * Undo a single step + */ + public void undoStep() { + performers.get(cPerf).undoStep(); + setArrows(cPerf); + } + + /** + * Perform a single step + */ + public void performStep() { + performers.get(cPerf).performStep(); + setArrows(cPerf); + } + + /** + * Undo all steps + */ + public void undoAll() { + Performer current = performers.get(cPerf); + // switch view if neccessary + if (cPerf == 1 && current.isClear() && viewManager.getState() == ViewState.FLOWH0) { + setState(ViewState.C0FLOW); + cPerf -= 1; + current.setActive(false); + performers.get(cPerf).setActive(true); + updateViews(); + + } else { + // move through steps + if (current.isClear() && cPerf > 0) { + cPerf -= 1; + current.setActive(false); + performers.get(cPerf).setActive(true); + updateViews(); + } else + current.undoAll(); + } + setArrows(cPerf); + } + + /** + * Perform all steps not the smallest possible solution - but clear + */ + public void performAll() { + Performer current = performers.get(cPerf); + // switch view if neccessary + if (cPerf == 1 && current.isDone() && viewManager.getState() == ViewState.C0FLOW) { + setState(ViewState.FLOWH0); + cPerf += 1; + current.setActive(false); + performers.get(cPerf).setActive(true); + updateViews(); + } else { + // move through steps + if (current.isDone() && cPerf < performers.size() - 1) { + cPerf += 1; + current.setActive(false); + performers.get(cPerf).setActive(true); + updateViews(); + + } else { + current.performAll(); + } + } + setArrows(cPerf); + } + + /** + * Adjusts Arrowbuttons to fit situation + * + * @param cPerf + */ + private void setArrows(int cPerf) { + Performer current = performers.get(cPerf); + buttonManager.setUndoStepEnabled(!current.isClear()); + buttonManager.setPerformStepEnabled(!current.isDone()); + + buttonManager.setUndoAllEnabled(!(cPerf == 0 && current.isClear())); + buttonManager.setPerformAllEnabled(!(cPerf == performers.size() - 1 && current.isDone())); + } + + /** + * Updates views + */ + public void updateViews() { + viewManager.updateViews(); + } + + /** + * Calls setState in ViewManager and resets the combobox + * + * @param newState + */ + public void setState(ViewState newState) { + viewManager.setState(newState); + buttonManager.setState(newState); + } + + /** + * Returns the code header corresponding to the parameters + * + * @param m + * number of variables + * @param k + * number of variables scanned + * @param i + * index of the output variable + * @return code header + */ + public int readMKI(int m, int k, int i) { + int headLines = c0CodeModel.generateCodeFragement(m, k, i); + viewManager.updateViews(); + viewManager.focusCaret(headLines); + return headLines; + } + + /** + * Toggles the beamer mode in the view manager + */ + public void toggleBeamerMode() { + c0CodeModel.setCode(viewManager.getC0Code()); + viewManager.setBeamerMode(!viewManager.isBeamerMode()); + } + + /** + * Returns viewManager + * + * @return viewManager + */ + public ViewManager getViewManager() { + return this.viewManager; + } + + /** + * Returns C0CodeModel + * + * @return C0CodeModel + */ + public C0CodeModel getC0CodeModel() { + return c0CodeModel; + } + + /** + * Returns the AST model + * + * @return ASTModel + */ + public ASTModel getASTModel() { + return model; + } + + /** + * Returns the fcModel + * + * @return fcModel + */ + public FlowChartModel getFcmodel() { + return fcModel; + } + + /** + * Returns the h0CodeModel + * + * @return h0CodeModel + */ + public H0CodeModel getH0CodeModel() { + return h0CodeModel; + } + + /** + * Returns the tRuleModel + * + * @return tRuleModel + */ + public TRuleModel getTRuleModel() { + return tRuleModel; + } + + /** + * Returns the buttonManager + * + * @return buttonManager + */ + public ButtonManager getButtonManager() { + return this.buttonManager; + } +} diff --git a/src/org/jalgo/module/c0h0/controller/FileManager.java b/src/org/jalgo/module/c0h0/controller/FileManager.java new file mode 100644 index 0000000..f815675 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/FileManager.java @@ -0,0 +1,272 @@ +package org.jalgo.module.c0h0.controller; + +import java.awt.Image; +import java.awt.image.RenderedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; + +import org.jalgo.module.c0h0.views.TerminalView; + +/** + * this class provides file opening functionality, specifically .c0 files + * + * @author hendrik + * + */ + +public class FileManager { + + private JFileChooser c0fileChooser; + private JFileChooser h0fileChooser; + private JFileChooser fcfileChooser; + private JFileChooser exampleChooser; + private String home = System.getProperty("user.dir"); + private String sep = System.getProperty("file.separator"); + private String suffix = ".c0"; + + /** + * Checks for c0-files + */ + private FileFilter c0Filter = new FileFilter() { + + public String getDescription() { + return "*" + suffix; + } + + public boolean accept(File f) { + if (f.getName().endsWith(suffix)) + return true; + if (f.isDirectory()) + return true; + return false; + } + }; + + /** + * Checks for Flowchart-files + */ + private FileFilter fcFilter = new FileFilter() { + String suffix = ".png"; + + public String getDescription() { + return "*" + suffix; + } + + public boolean accept(File f) { + if (f.getName().endsWith(suffix)) + return true; + if (f.isDirectory()) + return true; + return false; + } + }; + + /** + * Checks for h0-files + */ + private FileFilter h0Filter = new FileFilter() { + String hsuffix = ".h0"; + + public String getDescription() { + return "*" + hsuffix; + } + + public boolean accept(File f) { + if (f.getName().endsWith(hsuffix)) + return true; + if (f.isDirectory()) + return true; + return false; + } + }; + + /** + * opens a file + * + * @return the file + */ + public ArrayList openFile() { + if (c0fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { // parsing + return readFile(c0fileChooser.getSelectedFile()); + } + return new ArrayList(); + } + + /** + * opens an example + * + * @return the example + */ + public ArrayList openExample() { + if (exampleChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { // parsing + return readFile(exampleChooser.getSelectedFile()); + } + return new ArrayList(); + } + + /** + * saves a file + * + * @param code + * @param suffix + */ + public void saveFile(String code, String suffix) { + File file; + if (h0fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + file = h0fileChooser.getSelectedFile(); + if (!file.getName().endsWith(suffix)) { + String path = file.getAbsolutePath(); + file = new File(path + suffix); + } + } else + return; + + try { + file.createNewFile(); + } catch (IOException e) { + TerminalView.println("can't create file - everything alright with your filesystem??"); + e.printStackTrace(); + } // Create the empty file with default permissions, etc. + + FileOutputStream fos = null; + + try { + fos = new FileOutputStream(file); + } catch (FileNotFoundException e) { + TerminalView.println("just made a file but can't find it anylonger - me so stupid"); + e.printStackTrace(); + } + + try { + fos.write(code.getBytes()); + fos.close(); + } catch (IOException e) { + TerminalView.println("just made a file but can't write in it - having a bad day?"); + e.printStackTrace(); + } + } + + /** + * save a file + * + * @param code + */ + public void saveFile(List code) { + + File file; + if (c0fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + file = c0fileChooser.getSelectedFile(); + if (!file.getName().endsWith(suffix)) { + String path = file.getAbsolutePath(); + file = new File(path + suffix); + } + } else + return; + + try { + file.createNewFile(); + } catch (IOException e) { + TerminalView.println("can't create file - everything alright with your filesystem??"); + e.printStackTrace(); + } // Create the empty file with default permissions, etc. + + FileOutputStream fos = null; + + try { + fos = new FileOutputStream(file); + } catch (FileNotFoundException e) { + TerminalView.println("just made a file but can't find it anylonger - me so stupid"); + e.printStackTrace(); + } + + for (String line : code) { + String lineString = line + "\n"; + try { + fos.write(lineString.getBytes()); + } catch (IOException e) { + TerminalView.println("just made a file but can't write in it - having a bad day?"); + e.printStackTrace(); + } + } + + } + + /** + * Saves an image with the given suffix + * + * @param img + * Image to be saved + * @param suffix + * String with the allowed suffix + */ + public void saveImage(Image img, String suffix) { + File file; + if (fcfileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { + file = fcfileChooser.getSelectedFile(); + if (!file.getName().endsWith(suffix)) { + String path = file.getAbsolutePath(); + file = new File(path + suffix); + } + } else + return; + try { + file.createNewFile(); + } catch (IOException e) { + TerminalView.println("can't create file - everything alright with your filesystem??"); + e.printStackTrace(); + } // Create the empty file with default permissions, etc. + + try { + ImageIO.write((RenderedImage)img, "png", file); + } catch (IOException e) { + TerminalView.println("Couldn't create file"); + e.printStackTrace(); + } + } + + public FileManager() { + c0fileChooser = new JFileChooser(); + h0fileChooser = new JFileChooser(); + fcfileChooser = new JFileChooser(); + exampleChooser = new JFileChooser(home + sep + "examples" + sep + "c0h0"); + c0fileChooser.setFileFilter(c0Filter); + h0fileChooser.setFileFilter(h0Filter); + fcfileChooser.setFileFilter(fcFilter); + exampleChooser.setFileFilter(c0Filter); + } + + /** + * read a file + * + * @param file + * @return the file + */ + private ArrayList readFile(File file) { + ArrayList code = new ArrayList(); + try { + FileReader in = new FileReader(file); + BufferedReader bReader = new BufferedReader(in); + try { + while (bReader.ready()) + code.add(bReader.readLine()); + } catch (IOException e) { + TerminalView.println("can't read file - everything alright with your filesystem??"); + // e.printStackTrace(); + return new ArrayList(); + } + return code; + } catch (FileNotFoundException e) { + return new ArrayList(); + } + } +} diff --git a/src/org/jalgo/module/c0h0/controller/InterfaceConstants.java b/src/org/jalgo/module/c0h0/controller/InterfaceConstants.java new file mode 100644 index 0000000..ce4e82b --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/InterfaceConstants.java @@ -0,0 +1,34 @@ +package org.jalgo.module.c0h0.controller; + +/** + * Contains all constants which are needed to set up the interface + * + */ +public interface InterfaceConstants { + /** + * Normal font-size while not in beamermode + */ + public final int NORMAL_FONTSIZE = 12; + + /** + * Beamermode font-size while this mode is active + */ + public final int BEAMERMODE_FONTSIZE = 18; + + /** + * Hex with the marked color while view is active + */ + public final String MARKEDCOLOR_ACTIVE = "FF9933"; + + + /** + * Hex with the marked color while view is not active + */ + public final String MARKEDCOLOR_INACTIVE = "AAAAAA"; + + + /** + * Hex with the content which is slightly grayed + */ + public final String GRAYED_CONTENT = "999999"; +} diff --git a/src/org/jalgo/module/c0h0/controller/State.java b/src/org/jalgo/module/c0h0/controller/State.java new file mode 100644 index 0000000..ee50133 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/State.java @@ -0,0 +1,78 @@ +package org.jalgo.module.c0h0.controller; + +import org.jalgo.module.c0h0.views.View; + +/** + * states of the containers + * + */ +public class State { + private View left, right, bottom; + private ViewState name; + + /** + * @param left + * @param right + * @param bottom + */ + public State(View left, View right, View bottom, ViewState name) { + this.left = left; + this.right = right; + this.bottom = bottom; + this.name = name; + } + + /** + * calls render on every currently visible view + */ + public void render() { + left.render(); + right.render(); + bottom.render(); + } + + /** + * calls update on every currently visible view + */ + public void update() { + left.update(); + right.update(); + bottom.update(); + } + + /** + * returns the left View + * + * @return left View + */ + public View getLeftView() { + return left; + } + + /** + * returns the right View + * + * @return right View + */ + public View getRightView() { + return right; + } + + /** + * returns the bottom View + * + * @return bottom View + */ + public View getBottomView() { + return bottom; + } + + /** + * returns the name of this ViewState + * + * @return name + */ + public ViewState getName() { + return name; + } +} diff --git a/src/org/jalgo/module/c0h0/controller/ViewManager.java b/src/org/jalgo/module/c0h0/controller/ViewManager.java new file mode 100644 index 0000000..6cebd95 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/ViewManager.java @@ -0,0 +1,259 @@ +package org.jalgo.module.c0h0.controller; + +import java.awt.Image; + +import org.jalgo.module.c0h0.gui.ModuleContainer; +import org.jalgo.module.c0h0.views.*; + +/** + * manages the views + * + * @author Hendrik Sollich, Peter Schwede + */ +public class ViewManager implements InterfaceConstants { + + private EditView editView; + private HelpView helpView; + private C0View c0View; + private FlowChartView fcView; + public H0View h0View; // TODO dirty durchreichen - move performer + private LogView logView; + private TransView transView; + private WelcomeView welcomeView; + + private ModuleContainer container; + + private State editHelp, welcome, c0Flow, c0H0, flowH0; + + private State state; + private View focusedView; + private boolean beamerMode = false; + + /** + * @param controller + * @param container + */ + public ViewManager(Controller controller, ModuleContainer container) { + this.container = container; + + editView = new EditView(controller, this); + helpView = new HelpView(controller, this); + c0View = new C0View(controller, this); + h0View = new H0View(controller, this); + fcView = new FlowChartView(controller, this); + logView = new LogView(controller, this); + welcomeView = new WelcomeView(controller, this); + transView = new TransView(controller, this); + transView.registerToView(h0View); // foo-foo-foo-foo-foo, need CORRECT + // observer in viewManager + + editHelp = new State(editView, helpView, logView, ViewState.EDIT); + welcome = new State(editView, helpView, logView, ViewState.WELCOME); + c0Flow = new State(c0View, fcView, transView, ViewState.C0FLOW); + c0H0 = new State(c0View, h0View, transView, ViewState.C0H0); + flowH0 = new State(fcView, h0View, transView, ViewState.FLOWH0); + + // First View to show is a Single WelcomeView + container.display(welcomeView); + + // First State is editHelp + state = welcome; + + // FocusedView is: + focusedView = helpView; + } + + /** + * Sets the views according to a short, describing String + * + * @param newState + * One out of "c0", "fc" or other + */ + public void setState(ViewState newState) { + switch (newState) { + case C0FLOW: + case RUN: + state = c0Flow; + TerminalView.println("c0Flow"); + break; + case FLOWH0: + state = flowH0; + TerminalView.println("flowH0"); + break; + case C0H0: + state = c0H0; + TerminalView.println("c0H0"); + break; + case EDIT: + default: + state = editHelp; + } + state.update(); + setViews(); + } + + /** + * returns the current state of the containers + * + * @return state + */ + public ViewState getState() { + return state.getName(); + } + + /** + * @return ModuleContainer + */ + public ModuleContainer getContainer() { + return this.container; + } + + /** + * calls update method on all Views of the current state + */ + public void updateViews() { + state.update(); + + // redraw container + container.updateUI(); + } + + /** + * Renders all Views + */ + public void renderAllViews() { + editView.render(); + helpView.render(); + c0View.render(); + fcView.render(); + h0View.render(); + logView.render(); + transView.render(); + welcomeView.render(); + } + + /** + * calls render method on all Views of the current state + */ + public void renderViews() { + state.render(); + + // redraw container + container.updateUI(); + } + + /** + * sets the views into the containers + */ + public void setViews() { + container.leftPane.removeAll(); + container.leftPane.add(state.getLeftView()); + + container.rightPane.removeAll(); + container.rightPane.add(state.getRightView()); + + container.bottomPane.removeAll(); + container.bottomPane.add(state.getBottomView()); + + // make width of containers equal + container.getLeftright().setDividerLocation(0.5); + container.display(); + + } + + /** + * sets the beamer mode + * + * @param beamerMode + */ + public void setBeamerMode(boolean beamerMode) { + this.beamerMode = beamerMode; + updateViews(); + } + + /** + * returns boolean if beamer mode is set + * + * @return beamerMode + */ + public boolean isBeamerMode() { + return beamerMode; + } + + /** + * sets a view focused + * + * @param fv + * the focused view + */ + public void setFocusedView(View fv) { + focusedView = fv; + focusedView.requestFocusInWindow(); + } + + /** + * returns the focused view + * + * @return focusedView + */ + public View getFocusedView() { + return focusedView; + } + + /** + * returns the c0 code from the editor + * + * @return c0 code + */ + public String getC0Code() { + /** * * * * + * * Greetings from White Rabbit! * + * * * * */ + if (editView.getC0Code().contains("wörmhoulruhding")) { + container.display(new Easter()); + } + return editView.getC0Code(); + } + + /** + * gives an error message to the log view + * + * @param error + */ + public void updateErrorInformation(String error) { + logView.setErrorText(error); + } + + /** + * set caret into the edit view + * + * @param line + * number + */ + public void focusCaret(int line) { + editView.requestFocus(); + editView.setCaret(line); + } + + /** + * Returns an image of the flowchart + * + * @return Image + */ + public Image getFlowChartImage() { + return fcView.getGraph(); + } + + /** + * Returns the currently set background color + * + * @param active + * @return String(Hex) + */ + public String backgroundColor(boolean active) { + if (active) + return "#ffffff"; + return "#dddddd"; + } + +} diff --git a/src/org/jalgo/module/c0h0/controller/ViewState.java b/src/org/jalgo/module/c0h0/controller/ViewState.java new file mode 100644 index 0000000..1aac44e --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/ViewState.java @@ -0,0 +1,9 @@ +package org.jalgo.module.c0h0.controller; + +/** + * enumeration of combinations of the views + * + */ +public enum ViewState { + C0FLOW, FLOWH0, C0H0, EDIT, RUN, WELCOME +} diff --git a/src/org/jalgo/module/c0h0/controller/package-info.java b/src/org/jalgo/module/c0h0/controller/package-info.java new file mode 100644 index 0000000..aaf03d1 --- /dev/null +++ b/src/org/jalgo/module/c0h0/controller/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes, which act as controller within MVC + */ +package org.jalgo.module.c0h0.controller; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/gui/ButtonManager.java b/src/org/jalgo/module/c0h0/gui/ButtonManager.java new file mode 100644 index 0000000..cf7d6bb --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/ButtonManager.java @@ -0,0 +1,477 @@ +package org.jalgo.module.c0h0.gui; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JToolBar; +import javax.swing.JMenu; + +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.c0h0.controller.ButtonCommand; +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.ViewManager; +import org.jalgo.module.c0h0.controller.ViewState; +import org.jalgo.module.c0h0.views.TerminalView; + +/** + * Takes Care of all ButtonActions, MouseEffects, Toolbar and Menu + * + * @author Hendrik Sollich + */ +public class ButtonManager implements ActionListener { + + private JToolBar toolbar; + public JLabel tipLine; + private JMenu menu; + private JToolbarButton runEditButton; + private ArrayList steps; + + private Controller controller; + private ViewManager viewManager; + + private JToolbarButton c0h0Button, c0flowButton, flowh0Button, transviewOnButton, transviewOffButton; + + private JMenuItem newCode, saveC0, saveFC, saveH0, loadCode, exampleCode; + + private ImageIcon performAllIcon, undoAllIcon, performStepIcon, undoStepIcon, viewC0FlowIcon, viewFlowH0Icon, + viewC0H0Icon, tvOnIcon, tvOffIcon, runIcon, editIcon; + private String runString, editString; + + /** + * @param controller + * @param viewManager + * @param toolbar + * @param menu + */ + public ButtonManager(final Controller controller, ViewManager viewManager, JToolBar toolbar, JMenu menu) { + this.toolbar = toolbar; + this.controller = controller; + this.menu = menu; + this.viewManager = viewManager; + + // Separator + toolbar.addSeparator(); + // TODO translate + runEditButton = createToolbarButton(ButtonCommand.run, runIcon, runString, "Transformation starten", false); + steps = new ArrayList(); + // Menu aufbauen + buildMenu(); + // Icons laden + initIcons(); + // Toolbar aufbauen + buildToolbar(); + } + + /** + * creates toolbar buttons + * + * @param cmd + * @param icon + * @param tooltip + * @param enabled + * @return + */ + private JToolbarButton createToolbarButton(ButtonCommand cmd, ImageIcon icon, String tooltip, boolean enabled) { + JToolbarButton ele = new JToolbarButton(icon, "", ""); + ele.setActionCommand(cmd.toString()); + ele.addActionListener(this); + ele.setIcon(icon); + ele.setToolTipText(tooltip); + ele.setEnabled(enabled); + return ele; + } + + /** + * creates toolbar buttons + * + * @param cmd + * @param icon + * @param text + * @param tooltip + * @param enabled + * @return + */ + private JToolbarButton createToolbarButton(ButtonCommand cmd, ImageIcon icon, String text, String tooltip, + boolean enabled) { + JToolbarButton button = createToolbarButton(cmd, icon, tooltip, enabled); + button.setText(text); + return button; + } + + /** + * Assigns menu items to "C0H0"-menu and connects them to Actions + */ + private void buildMenu() { + JCheckBoxMenuItem beamerModeSelector = new JCheckBoxMenuItem(); + beamerModeSelector.setText("Beamermode"); + beamerModeSelector.setActionCommand(ButtonCommand.toggleBeamerMode.toString()); + beamerModeSelector.addActionListener(this); + + newCode = new JMenuItem("Neuen c0-Code erstellen"); + newCode.setActionCommand(ButtonCommand.newCode.toString()); + newCode.addActionListener(this); + + saveC0 = new JMenuItem("Datei speichern (.c0)"); + saveC0.setActionCommand(ButtonCommand.saveC0.toString()); + saveC0.addActionListener(this); + + saveFC = new JMenuItem("Flowchart speichern (.png)"); + saveFC.setActionCommand(ButtonCommand.saveFC.toString()); + saveFC.addActionListener(this); + saveFC.setEnabled(false); + + saveH0 = new JMenuItem("Datei speichern (.h0)"); + saveH0.setActionCommand(ButtonCommand.saveH0.toString()); + saveH0.addActionListener(this); + saveH0.setEnabled(false); + + loadCode = new JMenuItem("Datei öffnen..."); + loadCode.setActionCommand(ButtonCommand.loadCode.toString()); + loadCode.addActionListener(this); + + exampleCode = new JMenuItem("Beispiel öffnen..."); + exampleCode.setActionCommand(ButtonCommand.exampleCode.toString()); + exampleCode.addActionListener(this); + + menu.add(newCode); + menu.add(loadCode); + menu.add(exampleCode); + menu.add(saveC0); + menu.add(saveFC); + menu.add(saveH0); + menu.add(beamerModeSelector); + } + + private void initIcons() { + // TODO translate this; upper case + runString = "Transfomieren"; // TODO: Wir simulieren doch garnicht!? + editString = "Bearbeiten"; + + runIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Finish_algorithm")); + editIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Abort_algorithm")); + performAllIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_all")); + undoAllIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_all")); + performStepIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_step")); + undoStepIcon = new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_step")); + viewC0FlowIcon = new ImageIcon(Messages.getResourceURL("c0h0", "viewC0FlowIcon")); + viewFlowH0Icon = new ImageIcon(Messages.getResourceURL("c0h0", "viewFlowH0Icon")); + viewC0H0Icon = new ImageIcon(Messages.getResourceURL("c0h0", "viewC0H0Icon")); + tvOnIcon = new ImageIcon(Messages.getResourceURL("c0h0", "transViewOnIcon")); + tvOffIcon = new ImageIcon(Messages.getResourceURL("c0h0", "transViewOffIcon")); + } + + /** + * Assigns buttons to toolbar and connects them to Actions + */ + private void buildToolbar() { + // TODO translate + JToolbarButton undoAll = createToolbarButton(ButtonCommand.undoAll, undoAllIcon, + "Vollständigen Transformationsschritt rückgängig machen", false); + JToolbarButton undoSingleStep = createToolbarButton(ButtonCommand.undoStep, undoStepIcon, + "Einzelschritt rückgängig machen", false); + JToolbarButton performSingleStep = createToolbarButton(ButtonCommand.performStep, performStepIcon, + "Einzelschritt vorwärts durchführen", false); + JToolbarButton performAll = createToolbarButton(ButtonCommand.performAll, performAllIcon, + "Vollständigen Transformationsschritt abschließen", false); + + // Viewstates + c0h0Button = createToolbarButton(ButtonCommand.viewC0H0, viewC0H0Icon, "C0-Code und H0-Code", false); + c0flowButton = createToolbarButton(ButtonCommand.viewC0Flow, viewC0FlowIcon, "C0-Code und Flowchart", false); + flowh0Button = createToolbarButton(ButtonCommand.viewFlowH0, viewFlowH0Icon, "Flowchart und H0-Code", false); + + // Buttons einfügen + steps.add(undoAll); // 1 + steps.add(undoSingleStep); + + steps.add(performSingleStep); + steps.add(performAll); + + for (JToolbarButton step : steps) + toolbar.add(step); + + // Separator + toolbar.addSeparator(); + toolbar.add(runEditButton, 0); + runEditButton.setText(runString); + runEditButton.setIcon(runIcon); + + // Separator + toolbar.addSeparator(); + + // View States + toolbar.add(c0flowButton); + toolbar.add(flowh0Button); + toolbar.add(c0h0Button); + // Buttons beim konkreten EventListener registrieren + // TODO translate this + transviewOnButton = createToolbarButton(ButtonCommand.transviewOn, tvOnIcon, "Regeln anzeigen", true); + transviewOffButton = createToolbarButton(ButtonCommand.transviewOff, tvOffIcon, "Regeln ausblenden", true); + transviewOnButton.setEnabled(false); + transviewOffButton.setEnabled(false); + + toolbar.addSeparator(); + toolbar.add(transviewOnButton); + toolbar.add(transviewOffButton); + + // Nur für die Optik: keine Vergrößerung bei Buttonchange + toolbar.updateUI(); + } + + /** + * Compares aa ActionCommand to BtnCmd-enum + * + * @param e + * @param b + * @return + */ + private boolean isCmd(ActionEvent e, ButtonCommand b) { + return (b.toString().equals(e.getActionCommand())); + } + + /** + * toggles undo buttons + * + * @param b + */ + public void setUndoStepEnabled(boolean b) { + steps.get(1).setEnabled(b); + } + + /** + * toggles undo buttons + * + * @param b + */ + public void setUndoAllEnabled(boolean b) { + steps.get(0).setEnabled(b); + } + + /** + * toggles perform buttons + * + * @param b + */ + public void setPerformStepEnabled(boolean b) { + steps.get(2).setEnabled(b); + } + + /** + * toggles perform buttons + * + * @param b + */ + public void setPerformAllEnabled(boolean b) { + steps.get(3).setEnabled(b); + } + + /** + * toggles trans view visibility + * + * @param on + */ + public void toggleTransView(boolean on) { + viewManager.getContainer().toggleBottomPane(on); + int position = 12; + + if (on) { + toolbar.remove(transviewOnButton); + toolbar.add(transviewOffButton, position); + } else { + toolbar.remove(transviewOffButton); + toolbar.add(transviewOnButton, position); + } + toolbar.updateUI(); + } + + /** + * toggles toolbar steps + */ + public void toggleToolbarSteps() { + for (java.awt.Component b : steps) { + b.setEnabled(!b.isEnabled()); + } + } + + /** + * sets the state + * + * @param state + */ + public void setState(ViewState state) { + switch (state) { + case C0FLOW: + TerminalView.println("views: C0FLOW"); + c0flowButton.setEnabled(false); + flowh0Button.setEnabled(true); + c0h0Button.setEnabled(true); + break; + + case FLOWH0: + TerminalView.println("views: FLOWH0"); + c0flowButton.setEnabled(true); + flowh0Button.setEnabled(false); + c0h0Button.setEnabled(true); + break; + + case C0H0: + TerminalView.println("views: C0H0"); + c0flowButton.setEnabled(true); + flowh0Button.setEnabled(true); + c0h0Button.setEnabled(false); + break; + + case RUN: + for (JToolbarButton b : steps) + b.setEnabled(true); + + runEditButton.setIcon(editIcon); + runEditButton.setText(editString); + + if (runEditButton.getActionListeners() != null) + runEditButton.removeActionListener(runEditButton.getActionListeners()[0]); + runEditButton.addActionListener(this); + runEditButton.setActionCommand(ButtonCommand.edit.toString()); + saveH0.setEnabled(true); + saveFC.setEnabled(true); + + c0flowButton.setEnabled(false); + flowh0Button.setEnabled(true); + c0h0Button.setEnabled(true); + break; + + case EDIT: + TerminalView.println("editView"); + for (JToolbarButton b : steps) + b.setEnabled(false); + runEditButton.setEnabled(true); + runEditButton.setIcon(runIcon); + runEditButton.setText(runString); + transviewOnButton.setEnabled(true); + transviewOffButton.setEnabled(true); + + if (runEditButton.getActionListeners() != null) + runEditButton.removeActionListener(runEditButton.getActionListeners()[0]); + runEditButton.addActionListener(this); + runEditButton.setActionCommand(ButtonCommand.run.toString()); + saveH0.setEnabled(false); + saveFC.setEnabled(false); + + c0flowButton.setEnabled(false); + flowh0Button.setEnabled(false); + c0h0Button.setEnabled(false); + break; + } + toolbar.updateUI(); + } + + /* + * (non-Javadoc) + * + * @see + * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent e) { + if (isCmd(e, ButtonCommand.run)) { + runAction(); + } else if (isCmd(e, ButtonCommand.edit)) { + editAction(); + } else if (isCmd(e, ButtonCommand.undoAll)) { + controller.undoAll(); + } else if (isCmd(e, ButtonCommand.undoStep)) { + controller.undoStep(); + } else if (isCmd(e, ButtonCommand.performAll)) { + controller.performAll(); + } else if (isCmd(e, ButtonCommand.performStep)) { + controller.performStep(); + } else if (isCmd(e, ButtonCommand.toggleBeamerMode)) { + controller.toggleBeamerMode(); + } else if (isCmd(e, ButtonCommand.newCode)) { + newButtonAction(); + } else if (isCmd(e, ButtonCommand.saveC0)) { + saveC0ButtonAction(); + } else if (isCmd(e, ButtonCommand.saveFC)) { + saveFCButtonAction(); + } else if (isCmd(e, ButtonCommand.saveH0)) { + saveH0ButtonAction(); + } else if (isCmd(e, ButtonCommand.loadCode)) { + loadButtonAction(); + } else if (isCmd(e, ButtonCommand.exampleCode)) { + exampleButtonAction(); + } else if (isCmd(e, ButtonCommand.viewC0Flow)) { + controller.setState(ViewState.C0FLOW); + } else if (isCmd(e, ButtonCommand.viewC0H0)) { + controller.setState(ViewState.C0H0); + } else if (isCmd(e, ButtonCommand.viewFlowH0)) { + controller.setState(ViewState.FLOWH0); + } else if (isCmd(e, ButtonCommand.transviewOn)) { + toggleTransView(true); + } else if (isCmd(e, ButtonCommand.transviewOff)) { + toggleTransView(false); + } + } + + /** + * Action for editButton + */ + private void editAction() { + // Edit Button pressed + // viewModeBox.setSelectedIndex(0); + controller.returnToEditMode(); + } + + /** + * Action for runButton + */ + private void runAction() { + // Run Button pressed + controller.runTransformation(); + } + + /** + * Action for newButton + */ + private void newButtonAction() { + controller.newCode(); + } + + /** + * Action for saveButton C0 + */ + private void saveC0ButtonAction() { + controller.saveFileC0(); + } + + /** + * Action for saveButton H0 + */ + private void saveH0ButtonAction() { + controller.saveFileH0(); + } + + /** + * Action for saveButton H0 + */ + private void saveFCButtonAction() { + controller.saveFileFlowchart(); + } + + /** + * Action for loadButton + */ + private void loadButtonAction() { + controller.openFile(); + } + + /** + * Action for exampleButton + */ + private void exampleButtonAction() { + controller.openExample(); + } +} diff --git a/src/org/jalgo/module/c0h0/gui/CVS/Entries b/src/org/jalgo/module/c0h0/gui/CVS/Entries new file mode 100644 index 0000000..1ba7b4e --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/CVS/Entries @@ -0,0 +1,3 @@ +/ButtonManager.java/1.1/Sat Mar 5 14:12:05 2011// +/ModuleContainer.java/1.1/Sat Mar 5 14:12:05 2011// +/package-info.java/1.1/Sat Mar 5 14:12:05 2011// diff --git a/src/org/jalgo/module/c0h0/gui/CVS/Repository b/src/org/jalgo/module/c0h0/gui/CVS/Repository new file mode 100644 index 0000000..3d87ba6 --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/gui diff --git a/src/org/jalgo/module/c0h0/gui/CVS/Root b/src/org/jalgo/module/c0h0/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/gui/ModuleContainer.java b/src/org/jalgo/module/c0h0/gui/ModuleContainer.java new file mode 100644 index 0000000..e870bb2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/ModuleContainer.java @@ -0,0 +1,99 @@ +package org.jalgo.module.c0h0.gui; + +import java.awt.Color; +import java.awt.Dimension; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JSplitPane; + +/** + * PanelComponent that splits window into 3 parts : left, right and bottom + * + * @author Hendrik Sollich + */ +public class ModuleContainer extends JPanel { + private static final long serialVersionUID = -3544118578261478226L; + public JPanel leftPane; + public JPanel rightPane; + public JPanel bottomPane; + + private JSplitPane leftright; + private JSplitPane trinity; + + public ModuleContainer() { + initTrinity(); + } + + /** + * Initiates display with only one component + * */ + public void display(JComponent component) { + // adopt division + removeAll(); + add(component); + updateUI(); + } + + /** + * Initiates display with three components (trinity) + * */ + public void display() { + // adopt division + removeAll(); + add(trinity); + updateUI(); + } + + /** + * initiates trinity components + */ + private void initTrinity() { + + leftPane = new JPanel(); + rightPane = new JPanel(); + bottomPane = new JPanel(); + + leftright = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, leftPane, rightPane); + trinity = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, leftright, bottomPane); + + leftPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); + leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.Y_AXIS)); + rightPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); + rightPane.setLayout(new BoxLayout(rightPane, BoxLayout.Y_AXIS)); + + bottomPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1)); + bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.Y_AXIS)); + bottomPane.setPreferredSize(new Dimension(0, 150)); + bottomPane.setMaximumSize(new Dimension(0, 150)); + bottomPane.setMinimumSize(new Dimension(0, 10)); + + // divison + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + trinity.setOneTouchExpandable(false); + leftright.setResizeWeight(0.5); + trinity.setResizeWeight(1); + + } + + public void toggleBottomPane(boolean on) { + bottomPane.setVisible(on); + if (on) { + trinity.setDividerLocation(trinity.getSize().height - trinity.getInsets().bottom - trinity.getDividerSize() + - bottomPane.getMaximumSize().height); + } + } + + /** + * returns the container split pane + * + * @return split pane + */ + public JSplitPane getLeftright() { + return leftright; + } + +} diff --git a/src/org/jalgo/module/c0h0/gui/package-info.java b/src/org/jalgo/module/c0h0/gui/package-info.java new file mode 100644 index 0000000..cf26071 --- /dev/null +++ b/src/org/jalgo/module/c0h0/gui/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes, that generate and manage Gui + */ +package org.jalgo.module.c0h0.gui; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/CVS/Entries b/src/org/jalgo/module/c0h0/models/CVS/Entries new file mode 100644 index 0000000..a8327eb --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/CVS/Entries @@ -0,0 +1,9 @@ +/Generator.java/1.1/Sat Mar 5 14:12:06 2011// +/Performer.java/1.1/Sat Mar 5 14:12:06 2011// +/Visitable.java/1.1/Sat Mar 5 14:12:06 2011// +D/ast//// +D/c0model//// +D/flowchart//// +D/h0model//// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// +D/tmodel//// diff --git a/src/org/jalgo/module/c0h0/models/CVS/Repository b/src/org/jalgo/module/c0h0/models/CVS/Repository new file mode 100644 index 0000000..8cf1016 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models diff --git a/src/org/jalgo/module/c0h0/models/CVS/Root b/src/org/jalgo/module/c0h0/models/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/Generator.java b/src/org/jalgo/module/c0h0/models/Generator.java new file mode 100644 index 0000000..e4b49f2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/Generator.java @@ -0,0 +1,13 @@ +package org.jalgo.module.c0h0.models; + +/** + * model interface to initialize the models + * + */ +public interface Generator { + + /** + * initializes the models + */ + public void generate(); +} diff --git a/src/org/jalgo/module/c0h0/models/Performer.java b/src/org/jalgo/module/c0h0/models/Performer.java new file mode 100644 index 0000000..f274786 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/Performer.java @@ -0,0 +1,51 @@ +package org.jalgo.module.c0h0.models; + +/** + * model interface to perform steps + * + */ +public interface Performer { + + /** + * Return true if next step is possible, return false, if next step is impossible + * aka Model is fully exposed. + * @return if the end is reached + */ + public boolean isDone(); + + /** + * Return true is previous step is possible, return false, if previous step is impossible + * aka Model is fully collapsed. + * @return if the performer is at the start + */ + public boolean isClear(); + + /** + * Perform all Steps until end + */ + public void performAll(); + + /** + * Performs a single Step + */ + public void performStep(); + + /** + * Undo a single Step + */ + public void undoStep(); + + /** + * Undo all Step until end + */ + public void undoAll(); + + /** + * Clears the model + */ + public void clear(); + + public void setActive(boolean a); + + public boolean isActive(); +} diff --git a/src/org/jalgo/module/c0h0/models/Visitable.java b/src/org/jalgo/module/c0h0/models/Visitable.java new file mode 100644 index 0000000..0705f70 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/Visitable.java @@ -0,0 +1,16 @@ +package org.jalgo.module.c0h0.models; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; + +/** + * visitor interface for visitible classes + * + */ +public interface Visitable { + /** + * accepts the visitor + * + * @param visitor + */ + public void accept(ASTVisitor visitor); +} diff --git a/src/org/jalgo/module/c0h0/models/ast/ASTModel.java b/src/org/jalgo/module/c0h0/models/ast/ASTModel.java new file mode 100644 index 0000000..2afbcb3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/ASTModel.java @@ -0,0 +1,146 @@ +package org.jalgo.module.c0h0.models.ast; + +import org.jalgo.module.c0h0.models.ast.tools.BFSIterator; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; +import org.jalgo.module.c0h0.models.c0model.AddressVisitor; +import org.jalgo.module.c0h0.models.c0model.SemanticVisitor; +import org.jalgo.module.c0h0.parser.C00Parser; + +/** + * the AST model + * + */ +public class ASTModel { + private boolean valid = false; + private ErrorInformation errorInformation; + private String errorText; + private Program program = null; + private String markedNode = ""; + private int maxdepth = 0; + + public ASTModel() { + // nothing... will create later, if the mighty controller is in mood to + + } + + /** + * Generates the AST-Model itself + * + * @param text + */ + public void create(String text) { + C00Parser parser = new C00Parser(); + valid = parser.parse(text); + program = parser.getProgram(); + + // Ein leeres Programm ist auch nicht valide! + valid &= program != null && program.getBlock() != null; + + if (valid) { + // Tiefe zuruecksetzen + maxdepth = 0; + + // Adressen hinzufuegen und Semantik ueberpruefen + BFSIterator iterator = new BFSIterator(this); + DFSIterator dfsiter = new DFSIterator(this); + SemanticVisitor semVisitor = new SemanticVisitor(program.getDecl() + .getVariableList(), program.getScanf().getScanfList(), + program.getPrintf().getVar()); + AddressVisitor addVisitor = new AddressVisitor(); + int printfAddress = 1; + Symbol nextStep; + while (iterator.hasNext()) { + nextStep = iterator.next(); + nextStep.accept(addVisitor); + + // Leider hier in dem While + if (!String.valueOf(nextStep.getAddress().charAt(1)).equals("f")) { + if (printfAddress < Integer.parseInt(String.valueOf(nextStep.getAddress().charAt(1))) + 1) { + printfAddress = Integer.parseInt(String.valueOf(nextStep.getAddress().charAt(1))) + 1; + } + } + if (nextStep.getAddress().length() > maxdepth) { + maxdepth = nextStep.getAddress().length(); + } + } + while (dfsiter.hasNext()) { + dfsiter.next().accept(semVisitor); + } + program.getPrintf().setAddress("f" + printfAddress); + valid = valid && semVisitor.isValid(); + errorText += "Semantischer Fehler:
          " + semVisitor.getError(); + } else { + if (program == null || program.getBlock() == null) { + errorText = "Bitte geben Sie ein Programm ein!"; + } + if (parser.getErrorText() != "") { + // TODO: Richtige Fehlerausgabe + // parser.getErrorText(); + errorText = "Syntax Fehler
          "; + } + } + } + + /** + * Sets the currently marked / highlighted Symbol + * + * @param address as String + */ + public void setMarkedNode(String address) { + markedNode = address; + } + + /** + * Returns Parser error + * + * @return the error information + */ + public ErrorInformation getErrorInformation() { + return errorInformation; + } + + /** + * Returns Parser/Semantic error as a String + * + * @return the error text + */ + public String getErrorText() { + return errorText; + } + + /** + * returns the validity of the AST + * + * @return if valid + */ + public boolean isValid() { + return valid; + } + + /** + * returns the program + * + * @return program + */ + public Program getProgram() { + return program; + } + + /** + * returns the marked node + * + * @return the marked node + */ + public String getMarkedNode() { + return markedNode; + } + + /** + * Returns the length of the longest address + * + * @return Integer with the depth + */ + public int getMaxDepth() { + return maxdepth; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/ASTVisitor.java b/src/org/jalgo/module/c0h0/models/ast/ASTVisitor.java new file mode 100644 index 0000000..c8312d0 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/ASTVisitor.java @@ -0,0 +1,31 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * visitor interface for the AST visitors + * + */ +public interface ASTVisitor { + /** + * visit assignment + * @param assignment + */ + public void visitAssignment(Assignment assignment); + + /** + * visit block + * @param block + */ + public void visitBlock(Block block); + + /** + * visit while + * @param whileStatement + */ + public void visitWhile(While whileStatement); + + /** + * visit if + * @param ifStatement + */ + public void visitIf(If ifStatement); +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Assignment.java b/src/org/jalgo/module/c0h0/models/ast/Assignment.java new file mode 100644 index 0000000..c1eecf8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Assignment.java @@ -0,0 +1,46 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * Representing an Assignment in the AST + * + */ +public class Assignment extends Statement { + private Var var; + private Term term; + + /** + * @param var + * @param term + */ + public Assignment(Var var, Term term) { + this.var = var; + this.term = term; + } + + /** + * Returns the Var of the Assignment + * + * @return var + * Var of the Assignment + */ + public Var getVar() { + return var; + } + + /** + * Returns the Term of the Assignment + * + * @return term + * Term of the Assignment + */ + public Term getTerm() { + return term; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Symbol#accept(org.jalgo.module.c0h0.models.ast.ASTVisitor) + */ + public void accept(ASTVisitor visitor) { + visitor.visitAssignment(this); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Block.java b/src/org/jalgo/module/c0h0/models/ast/Block.java new file mode 100644 index 0000000..c3f2f83 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Block.java @@ -0,0 +1,112 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.Visitable; +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Representing a Block in the AST + * + */ +public class Block extends Symbol implements Visitable, Iterable { + private ArrayList stats = new ArrayList(); + private boolean isBlock; + + /** + * @param isBlock + */ + public Block(boolean isBlock) { + this.isBlock = isBlock; + } + + /** + * @param s + * @param isBlock + */ + public Block(Statement s, boolean isBlock) { + stats.add(s); + this.isBlock = isBlock; + } + + /** + * adds a statement + * + * @param statement + * Statement which is to be added to the Declaration + */ + public void addStatement(Statement statement) { + stats.add(statement); + } + + /** + * If index is invalid, null is being returned + * + * @param index + * @return the statement + */ + public Statement getStatement(int index) { + if (index < 0 || index >= stats.size()) + return null; + return stats.get(index); + } + + /** + * returns last statement + * + * @return the last statement + */ + public Statement getLastStatement() { + if (stats.size() > 0) + return stats.get(stats.size() - 1); + else + return null; + } + + /** + * returns the statement list + * + * @return the statement list + */ + public ArrayList getStatementList() { + return stats; + } + + /** + * checks if Block is a Block with Brackets + * + * @return isBlock boolean if Block is a Block with Brackets + */ + public boolean isBlock() { + return isBlock; + } + + /** + * checks if Block is not a Block with Brackets + * + * @return !isBlock boolean if Block is not a Block with Brackets + */ + public boolean isALie() { + return !isBlock; + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.Symbol#accept(org.jalgo.module.c0h0. + * models.ast.ASTVisitor) + */ + public void accept(ASTVisitor visitor) { + visitor.visitBlock(this); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + return new ArrayList(stats); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/CVS/Entries b/src/org/jalgo/module/c0h0/models/ast/CVS/Entries new file mode 100644 index 0000000..02e65e9 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/CVS/Entries @@ -0,0 +1,23 @@ +/ASTModel.java/1.1/Sat Mar 5 14:12:05 2011// +/ASTVisitor.java/1.1/Sat Mar 5 14:12:05 2011// +/Assignment.java/1.1/Sat Mar 5 14:12:05 2011// +/Block.java/1.1/Sat Mar 5 14:12:05 2011// +/Declaration.java/1.1/Sat Mar 5 14:12:05 2011// +/ErrorInformation.java/1.1/Sat Mar 5 14:12:05 2011// +/If.java/1.1/Sat Mar 5 14:12:05 2011// +/Number.java/1.1/Sat Mar 5 14:12:05 2011// +/Operation.java/1.1/Sat Mar 5 14:12:05 2011// +/OperationType.java/1.1/Sat Mar 5 14:12:05 2011// +/PrintfStatement.java/1.1/Sat Mar 5 14:12:05 2011// +/Program.java/1.1/Sat Mar 5 14:12:05 2011// +/Relation.java/1.1/Sat Mar 5 14:12:05 2011// +/RelationType.java/1.1/Sat Mar 5 14:12:05 2011// +/ScanfSequence.java/1.1/Sat Mar 5 14:12:05 2011// +/Statement.java/1.1/Sat Mar 5 14:12:05 2011// +/Symbol.java/1.1/Sat Mar 5 14:12:05 2011// +/Term.java/1.1/Sat Mar 5 14:12:05 2011// +/UnaryType.java/1.1/Sat Mar 5 14:12:05 2011// +/Var.java/1.1/Sat Mar 5 14:12:05 2011// +/While.java/1.1/Sat Mar 5 14:12:05 2011// +/package-info.java/1.1/Sat Mar 5 14:12:05 2011// +D/tools//// diff --git a/src/org/jalgo/module/c0h0/models/ast/CVS/Repository b/src/org/jalgo/module/c0h0/models/ast/CVS/Repository new file mode 100644 index 0000000..484070e --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/ast diff --git a/src/org/jalgo/module/c0h0/models/ast/CVS/Root b/src/org/jalgo/module/c0h0/models/ast/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/ast/Declaration.java b/src/org/jalgo/module/c0h0/models/ast/Declaration.java new file mode 100644 index 0000000..a436ad3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Declaration.java @@ -0,0 +1,59 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Contains all declarated Vars + * + */ +public class Declaration extends Symbol implements Iterable { + private ArrayList vars; + + /** + * @param b + */ + public Declaration(Var b) { + vars = new ArrayList(); + vars.add(b); + } + + /** + * adds a variable which has to be added to the Declaration + * @param b + * Var which has to be added to the Declaration + */ + public void addVariable(Var b) { + vars.add(b); + } + + /** + * Returns the specific Var with the wanted index + * + * @param index + * index of the wanted Var + * @return Var + * returns the Var + */ + public Var getVariable(int index) { + return vars.get(index); + } + + /** + * Returns all Vars which got a Scanf-Statement + * + * @return scanfs + * ArrayList with all Variables in the sequence + */ + public ArrayList getVariableList() { + return vars; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + return new ArrayList(vars); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/ErrorInformation.java b/src/org/jalgo/module/c0h0/models/ast/ErrorInformation.java new file mode 100644 index 0000000..0581e77 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/ErrorInformation.java @@ -0,0 +1,28 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * contains the error information + * + */ +public class ErrorInformation { + private String text; + private Symbol errorNode; + + /** + * returns the error information + * + * @return the error information + */ + public String getText() { + return text; + } + + /** + * returns the error node + * + * @return the error node + */ + public Symbol getErrorNode() { + return errorNode; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/If.java b/src/org/jalgo/module/c0h0/models/ast/If.java new file mode 100644 index 0000000..9c983bb --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/If.java @@ -0,0 +1,83 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.Visitable; +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Representing an If-statement in the AST + * + */ +public class If extends Statement implements Visitable { + private Relation relation; + private Block ifBlock; + private Block elseBlock = new Block(false); + + /** + * @param r + * @param s + */ + public If(Relation r, Block s) { + relation = r; + ifBlock = s; + } + + /** + * @param das + * @param ist + * @param hahahaah + */ + public If(Relation das, Block ist, Block hahahaah) { + relation = das; + ifBlock = ist; + elseBlock = hahahaah;// ! + } + + /** + * Returns the Relation of the If-Statement + * + * @return relation + * Relation of the If-Statement + */ + public Relation getRelation() { + return relation; + } + + /** + * Returns the if-Block of the If-Statement + * + * @return block + * Block of the If-Statement + */ + public Block getIfSequence() { + return ifBlock; + } + + /** + * Returns the else-Block of the If-Statement + * + * @return block + * Block of the if-Statement + */ + public Block getElseSequence() { + return elseBlock; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Symbol#accept(org.jalgo.module.c0h0.models.ast.ASTVisitor) + */ + public void accept(ASTVisitor visitor) { + visitor.visitIf(this); + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Statement#getSequence() + */ + public ArrayList getSequence() { + ArrayList res = new ArrayList(); + res.add(getIfSequence()); + res.add(getElseSequence()); + return res; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Number.java b/src/org/jalgo/module/c0h0/models/ast/Number.java new file mode 100644 index 0000000..136f134 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Number.java @@ -0,0 +1,51 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +/** + * Representing a Number in the AST + * + */ +public class Number extends Term { + private int number; + private UnaryType type; + + /** + * @param number + */ + public Number(int number) { + this.number = number; + type = UnaryType.UNDEFINED; + } + + /** + * @param number + * @param type + */ + public Number(int number, UnaryType type) { + this.number = number; + this.type = type; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#toString() + */ + public String toString() { + String text; + if (type.equals(UnaryType.PLUS)) { + text = "+" + String.valueOf(number); + } else if (type.equals(UnaryType.MINUS)) { + text = "-" + String.valueOf(number); + } else { + text = String.valueOf(number); + } + return text; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#getVars() + */ + public ArrayList getVars() { + return new ArrayList(); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Operation.java b/src/org/jalgo/module/c0h0/models/ast/Operation.java new file mode 100644 index 0000000..425240b --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Operation.java @@ -0,0 +1,54 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +/** + * Representing an Operation in the AST + * + */ +public class Operation extends Term { + private OperationType op; + private Term left, right; + + /** + * @param left + * @param op + * @param right + */ + public Operation(Term left, OperationType op, Term right) { + this.op = op; + this.left = left; + this.right = right; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#toString() + */ + public String toString() { + String text = ""; + text += left; + if (op.equals(OperationType.ADD)) { + text += " + "; + } else if (op.equals(OperationType.SUB)) { + text += " - "; + } else if (op.equals(OperationType.MUL)) { + text += " * "; + } else if (op.equals(OperationType.DIV)) { + text += " / "; + } else if (op.equals(OperationType.MOD)) { + text += " % "; + } + text += right; + return text; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#getVars() + */ + public ArrayList getVars() { + ArrayList list = new ArrayList(); + list.addAll(left.getVars()); + list.addAll(right.getVars()); + return list; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/OperationType.java b/src/org/jalgo/module/c0h0/models/ast/OperationType.java new file mode 100644 index 0000000..334ba14 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/OperationType.java @@ -0,0 +1,9 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * Enumeration of all allowed operation types + * + */ +public enum OperationType { + ADD, SUB, MUL, DIV, MOD +} diff --git a/src/org/jalgo/module/c0h0/models/ast/PrintfStatement.java b/src/org/jalgo/module/c0h0/models/ast/PrintfStatement.java new file mode 100644 index 0000000..c47c645 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/PrintfStatement.java @@ -0,0 +1,40 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Representing the PrintfStatement in the AST + * + */ +public class PrintfStatement extends Symbol implements Iterable { + private Var var; + + /** + * @param var + */ + public PrintfStatement(Var var) { + this.var = var; + } + + /** + * Returns the Var of the PrintfStatement + * + * @return var + * Var of the PrintfStatement + */ + public Var getVar() { + return var; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + ArrayList arr = new ArrayList(); + arr.add(var); + return arr; + } + +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Program.java b/src/org/jalgo/module/c0h0/models/ast/Program.java new file mode 100644 index 0000000..492a8c5 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Program.java @@ -0,0 +1,92 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Contains all statements of the original code + * + */ +public class Program extends Symbol implements Iterable { + private Declaration decl; + private ScanfSequence scanf; + private Block statements; + private PrintfStatement printf; + + /** + * @param decl + * @param scanf + * @param statements + * @param printf + */ + public Program(final Declaration decl, final ScanfSequence scanf, + final Block statements, final PrintfStatement printf) { + this.decl = decl; + this.scanf = scanf; + this.statements = statements; + this.printf = printf; + } + + /** + * returns Declaration of all Vars + * + * @return declaration + * Declaration of all Vars + */ + public Declaration getDecl() { + return decl; + } + + /** + * retruns ScanfSequence of all Scanfs + * + * @return scanfsequence + * ScanfSequence of all Scanfs + */ + public ScanfSequence getScanf() { + return scanf; + } + + /** + * returns Block with all statements + * + * @return block + * Block with all statements + */ + public Block getBlock() { + return statements; + } + + /** + * returns ArrayList of all statements + * + * @return sequence + * ArrayList of all statements + */ + public ArrayList getBlockStatements() { + return statements.getSequence(); + } + + /** + * returns PrintfStatement with the Printf + * + * @return printfstatement + * PrintfStatement with the Printf + */ + public PrintfStatement getPrintf() { + return printf; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + ArrayList arr = new ArrayList(); + arr.add(decl); + arr.add(scanf); + arr.add(statements); + arr.add(printf); + return arr; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/ast/Relation.java b/src/org/jalgo/module/c0h0/models/ast/Relation.java new file mode 100644 index 0000000..1ae1b2e --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Relation.java @@ -0,0 +1,56 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +/** + * Representing a Relation in the AST + * + */ +public class Relation extends Term { + private RelationType rel; + private Term left, right; + + /** + * @param left + * @param rel + * @param right + */ + public Relation(Term left, RelationType rel, Term right) { + this.rel = rel; + this.left = left; + this.right = right; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#toString() + */ + public String toString() { + String text = ""; + text += left; + if (rel.equals(RelationType.EQ)) { + text += " == "; + } else if (rel.equals(RelationType.GE)) { + text += " >= "; + } else if (rel.equals(RelationType.GT)) { + text += " > "; + } else if (rel.equals(RelationType.LE)) { + text += " <= "; + } else if (rel.equals(RelationType.LT)) { + text += " < "; + } else { + text += " != "; + } + text += right; + return text; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#getVars() + */ + public ArrayList getVars() { + ArrayList list = new ArrayList(); + list.addAll(left.getVars()); + list.addAll(right.getVars()); + return list; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/RelationType.java b/src/org/jalgo/module/c0h0/models/ast/RelationType.java new file mode 100644 index 0000000..2b993c7 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/RelationType.java @@ -0,0 +1,9 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * Enumeration of all allowed relation types + * + */ +public enum RelationType { + EQ, NE, GT, LT, GE, LE +} diff --git a/src/org/jalgo/module/c0h0/models/ast/ScanfSequence.java b/src/org/jalgo/module/c0h0/models/ast/ScanfSequence.java new file mode 100644 index 0000000..b21b8f8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/ScanfSequence.java @@ -0,0 +1,55 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Sequence of all Scanf-calls made in the code + * + */ +public class ScanfSequence extends Symbol implements Iterable { + private ArrayList scanfs; + + public ScanfSequence() { + scanfs = new ArrayList(); + } + + /** + * add Var which is to be added to the sequence + * @param s + * Var which is to be added to the sequence + */ + public void addScanf(Var s) { + scanfs.add(s); + } + + /** + * Returns the specific Var with the wanted index + * + * @param index + * index of the wanted Var + * @return Var + * returns the Var + */ + public Var getScanfVar(int index) { + return scanfs.get(index); + } + + /** + * Returns all Vars which got a Scanf-Statement + * + * @return scanfs + * ArrayList with all Variables in the sequence + */ + public ArrayList getScanfList() { + return scanfs; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + return new ArrayList(scanfs); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Statement.java b/src/org/jalgo/module/c0h0/models/ast/Statement.java new file mode 100644 index 0000000..0f73952 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Statement.java @@ -0,0 +1,22 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Representing any statement in the AST + * + */ +public class Statement extends Symbol implements Iterable { + public Statement() { + + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + return new ArrayList(); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Symbol.java b/src/org/jalgo/module/c0h0/models/ast/Symbol.java new file mode 100644 index 0000000..8f36d37 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Symbol.java @@ -0,0 +1,38 @@ +package org.jalgo.module.c0h0.models.ast; + +import org.jalgo.module.c0h0.models.Visitable; + +/** + * Representing any symbol in the AST + * + */ +public class Symbol implements Visitable { + + private String address; + + /** + * sets the address of this node + * + * @param address + * + */ + public void setAddress(String address) { + this.address = address; + } + + /** + * returns the String with the address of this node + * @return address + * String with the address of this node + */ + public String getAddress() { + return address; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.Visitable#accept(org.jalgo.module.c0h0.models.ast.ASTVisitor) + */ + public void accept(ASTVisitor visitor) { + // This is a dummy. Dummies do basically nothing. Lazy dummies. + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Term.java b/src/org/jalgo/module/c0h0/models/ast/Term.java new file mode 100644 index 0000000..48b0bda --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Term.java @@ -0,0 +1,59 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +/** + * Representing a Term in the AST + * + */ +public class Term { + private Term term; + private UnaryType type; + + public Term() { + type = UnaryType.UNDEFINED; + } + + /** + * @param term + */ + public Term(Term term) { + this.term = term; + type = UnaryType.UNDEFINED; + } + + /** + * @param term + * @param type + */ + public Term(Term term, UnaryType type) { + this.term = term; + this.type = type; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() { + String text; + if (type.equals(UnaryType.PLUS)) { + text = "+(" + term + ")"; + } else if (type.equals(UnaryType.MINUS)) { + text = "-(" + term + ")"; + } else { + text = "(" + term + ")"; + } + return text; + } + + /** + * returns an ArrayList with all Vars contained in the whole Term + * @return list + * ArrayList with all Vars contained in the whole Term + */ + public ArrayList getVars() { + ArrayList list = new ArrayList(); + list.addAll(term.getVars()); + return list; + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/UnaryType.java b/src/org/jalgo/module/c0h0/models/ast/UnaryType.java new file mode 100644 index 0000000..c741b07 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/UnaryType.java @@ -0,0 +1,9 @@ +package org.jalgo.module.c0h0.models.ast; + +/** + * Enumeration of all allowed unary types + * + */ +public enum UnaryType { + UNDEFINED, PLUS, MINUS +} diff --git a/src/org/jalgo/module/c0h0/models/ast/Var.java b/src/org/jalgo/module/c0h0/models/ast/Var.java new file mode 100644 index 0000000..5838aa8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/Var.java @@ -0,0 +1,73 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Representing an If-statement in the AST + * + */ +public class Var extends Term implements Iterable { + private int index; + private UnaryType type; + + /** + * @param str + */ + public Var(String str) { + str = str.substring(1); + index = Integer.parseInt(str); + type = UnaryType.UNDEFINED; + } + + /** + * @param str + * @param type + */ + public Var(String str, UnaryType type) { + str = str.substring(1); + index = Integer.parseInt(str); + this.type = type; + } + + /** + * returns the integer of the Var's index# + * @return index + * integer of the Var's index + */ + public int getIndex() { + return index; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#toString() + */ + public String toString() { + String text; + if (type.equals(UnaryType.PLUS)) { + text = "+x" + String.valueOf(index); + } else if (type.equals(UnaryType.MINUS)) { + text = "-x" + String.valueOf(index); + } else { + text = "x" + String.valueOf(index); + } + return text; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Term#getVars() + */ + public ArrayList getVars() { + ArrayList list = new ArrayList(); + list.add(this); + return list; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.tools.Iterable#getSequence() + */ + public ArrayList getSequence() { + return new ArrayList(); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/While.java b/src/org/jalgo/module/c0h0/models/ast/While.java new file mode 100644 index 0000000..4fbe2ca --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/While.java @@ -0,0 +1,60 @@ +package org.jalgo.module.c0h0.models.ast; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.tools.Iterable; +import org.jalgo.module.c0h0.models.Visitable; + +/** + * Representing a While-statement in the AST + * + */ +public class While extends Statement implements Visitable, Iterable { + private Relation relation; + private Block seq; + + /** + * @param r + * @param s + */ + public While(Relation r, Block s) { + relation = r; + seq = s; + } + + /** + * Returns the Relation of the While-Statement + * + * @return relation + * Relation of the While-Statement + */ + public Relation getRelation() { + return relation; + } + + /** + * Returns the Block of the While-Statement + * + * @return block + * Block of the While-Statement + */ + public Block getBlock() { + return seq; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Statement#getSequence() + */ + public ArrayList getSequence() { + ArrayList arr = new ArrayList(); + arr.add(seq); + return arr; + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.Symbol#accept(org.jalgo.module.c0h0.models.ast.ASTVisitor) + */ + public void accept(ASTVisitor visitor) { + visitor.visitWhile(this); + } +} diff --git a/src/org/jalgo/module/c0h0/models/ast/package-info.java b/src/org/jalgo/module/c0h0/models/ast/package-info.java new file mode 100644 index 0000000..c0acaa9 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes containing the AST + */ +package org.jalgo.module.c0h0.models.ast; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.java b/src/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.java new file mode 100644 index 0000000..9dfc188 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/BFSIterator.java @@ -0,0 +1,58 @@ +package org.jalgo.module.c0h0.models.ast.tools; + +import java.util.LinkedList; + +import org.jalgo.module.c0h0.models.ast.ASTModel; + +/** + * Iterator through a syntax tree with breadth first search method. + * + */ +public class BFSIterator extends Iterator { + + /** + * @param ast + * the abstract syntax tree to iterate through + */ + public BFSIterator(ASTModel ast) { + super(ast); + if(prog != null) + bfs(prog.getBlock()); + it = list.iterator(); + } + + /** + * @param ast + * the abstract syntax tree to iterate through + * @param complete + * boolean wether the program should be iterated completely with + * declarations, scanfs and printfs or not + */ + public BFSIterator(ASTModel ast, boolean complete) { + super(ast); + if(prog != null) + bfs(prog); + it = list.iterator(); + } + + /** + * Chops AST using BFS and lines it up in an ArrayList + * + * @param symbol + * Iterable Symbol of the AST + */ + private void bfs(Iterable symbol) { + if (symbol != null) { + LinkedList queue = new LinkedList(); + queue.add(symbol); + while (!queue.isEmpty()) { + symbol = queue.pop(); + for (Iterable s : symbol.getSequence()) { + list.add(s); + queue.add(s); + } + } + } + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Entries b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Entries new file mode 100644 index 0000000..9066582 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Entries @@ -0,0 +1,5 @@ +/BFSIterator.java/1.1/Sat Mar 5 14:12:06 2011// +/DFSIterator.java/1.1/Sat Mar 5 14:12:06 2011// +/Iterable.java/1.1/Sat Mar 5 14:12:06 2011// +/Iterator.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Repository b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Repository new file mode 100644 index 0000000..5e0a809 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/ast/tools diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Root b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.java b/src/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.java new file mode 100644 index 0000000..4a07cb4 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/DFSIterator.java @@ -0,0 +1,61 @@ +package org.jalgo.module.c0h0.models.ast.tools; + + + +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.ast.Program; +import org.jalgo.module.c0h0.models.ast.tools.Iterator; +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * Iterator through a syntax tree with depth first search method. + * + * @author Peter Schwede + * + */ +public class DFSIterator extends Iterator { + /** + * @param ast + * the abstract syntax tree to iterate through + * @see DFSIterator + */ + public DFSIterator(ASTModel ast) { + super(ast); + if(prog != null) + for(Iterable item : prog.getBlockStatements()) { + dfs(item); + } + it = list.iterator(); + } + + /** + * @param ast + * @param complete + */ + public DFSIterator(ASTModel ast, boolean complete) { + super(ast); + Program prog = ast.getProgram(); + if (complete) { + dfs(prog.getDecl()); + dfs(prog.getScanf()); + } + dfs(prog.getBlock()); + if (complete) + dfs(prog.getPrintf()); + it = list.iterator(); + } + + /** + * chop AST using DFS and line it up in an ArrayList + * @param symbol + */ + private void dfs(Iterable symbol) { + if (symbol != null) { + list.add(symbol); + for (Iterable s : symbol.getSequence()) { + dfs(s); + } + } + } + +} diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/Iterable.java b/src/org/jalgo/module/c0h0/models/ast/tools/Iterable.java new file mode 100644 index 0000000..6d837f4 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/Iterable.java @@ -0,0 +1,16 @@ +package org.jalgo.module.c0h0.models.ast.tools; + +import java.util.ArrayList; + +/** + * interface for iterable classes + * + */ +public interface Iterable { + /** + * returns the sequence + * + * @return the sequence + */ + public ArrayList getSequence(); +} diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/Iterator.java b/src/org/jalgo/module/c0h0/models/ast/tools/Iterator.java new file mode 100644 index 0000000..8973c04 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/Iterator.java @@ -0,0 +1,40 @@ +package org.jalgo.module.c0h0.models.ast.tools; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.ast.Program; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.tools.Iterable; + +/** + * the abstract iterator for the depth/breadth first iterator + * + */ +public abstract class Iterator implements java.util.Iterator { + ArrayList list; + java.util.Iterator it; + Program prog; + + /** + * @param ast + * the abstract syntax tree to iterate through + */ + public Iterator(ASTModel ast) { + list = new ArrayList(); + prog = ast.getProgram(); + } + + public boolean hasNext() { + return it.hasNext(); + } + + public Symbol next() { + return (Symbol) it.next(); + } + + public void remove() { + it.remove(); + } + +} diff --git a/src/org/jalgo/module/c0h0/models/ast/tools/package-info.java b/src/org/jalgo/module/c0h0/models/ast/tools/package-info.java new file mode 100644 index 0000000..e8bd307 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/ast/tools/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes with tools which operate on the AST + */ +package org.jalgo.module.c0h0.models.ast.tools; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/c0model/AddressVisitor.java b/src/org/jalgo/module/c0h0/models/c0model/AddressVisitor.java new file mode 100644 index 0000000..2129f27 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/AddressVisitor.java @@ -0,0 +1,140 @@ +package org.jalgo.module.c0h0.models.c0model; + +import java.util.LinkedHashMap; +import java.util.Stack; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * Assigns addresses to AST-Symbols. This is to be used with BFSIterator. + * + * @author Peter Schwede + * + */ +public class AddressVisitor implements ASTVisitor { + private class AddrStack extends Stack { + /** + * Internal class used for address generation + */ + private static final long serialVersionUID = -3589885062259573874L; + + public String toString() { + String s = "f"; + for (Integer i : this) { + s += i; + } + return s; + } + + /** + * When calling AddrStack.clone() only the Stack head is cloned, not the + * contained list. This should do the work around. + * + * @return + */ + public AddrStack deepClone() { + AddrStack clone = new AddrStack(); + for (Integer item : this) { + clone.push(item.intValue()); + } + return clone; + } + } + + private AddrStack addr = new AddrStack(); + private LinkedHashMap awaitedIterables = new LinkedHashMap(); + + public AddressVisitor() { + addr.push(0); + } + + private boolean isAwaited(Symbol s) { + if (awaitedIterables.isEmpty() || !awaitedIterables.containsKey(s)) { + return false; + } + addr = awaitedIterables.get(s); + awaitedIterables.remove(s); + return true; + } + + private void await(Symbol s, AddrStack newAddr) { + awaitedIterables.put(s, newAddr); + } + + public void visitAssignment(Assignment assignment) { + if (!isAwaited(assignment)) { + addr.push(addr.pop() + 1); + } + assignment.setAddress(addr.toString()); + } + + public void visitBlock(Block block) { + if (!isAwaited(block)) { + addr.push(addr.pop() + 1); + } + if (block.isALie()) { + block.setAddress("s" + addr.toString()); + } else { + block.setAddress(addr.toString()); + } + + Symbol s = block.getStatement(0); + if (block.isBlock()) { + if (s != null) { + AddrStack newAddr = addr.deepClone(); + newAddr.push(1); + await(s, newAddr); + } + } else { + if (addr.pop() == 1) { + AddrStack newAddr = addr.deepClone(); + newAddr.push(1); + await(s, newAddr); + } else { + AddrStack newAddr = addr.deepClone(); + newAddr.push(2); + await(s, newAddr); + } + } + } + + public void visitIf(If ifStatement) { + if (!isAwaited(ifStatement)) { + addr.push(addr.pop() + 1); + } + ifStatement.setAddress(addr.toString()); + + Block i = ifStatement.getIfSequence(); + if (i != null) { + AddrStack newAddr = addr.deepClone(); + newAddr.push(1); + await(i, newAddr); + } + + Block e = ifStatement.getElseSequence(); + if (e != null) { + AddrStack newAddr = addr.deepClone(); + newAddr.push(2); + await(e, newAddr); + } + } + + public void visitWhile(While whileStatement) { + if (!isAwaited(whileStatement)) { + addr.push(addr.pop() + 1); + } + whileStatement.setAddress(addr.toString()); + + Block b = whileStatement.getBlock(); + if (b != null) { + AddrStack newAddr = addr.deepClone(); + newAddr.push(1); + await(b, newAddr); + } + } +} diff --git a/src/org/jalgo/module/c0h0/models/c0model/C0CodeModel.java b/src/org/jalgo/module/c0h0/models/c0model/C0CodeModel.java new file mode 100644 index 0000000..adf40ab --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/C0CodeModel.java @@ -0,0 +1,364 @@ +package org.jalgo.module.c0h0.models.c0model; + +import java.util.ArrayList; +import java.util.LinkedList; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.models.Generator; +import org.jalgo.module.c0h0.models.Performer; +import org.jalgo.module.c0h0.models.ast.Var; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; +import org.jalgo.module.c0h0.views.TerminalView; + +/** + * Generates, contains and returns C0 code. + * + */ +public class C0CodeModel implements Performer, Generator { + private ArrayList editCode = new ArrayList(); + private String code; + private StringBuilder addresses; + private LinkedList addressList = new LinkedList(); + private int currentStep, addressCount; + private Controller controller; + private boolean active = true; + private boolean actual = false; + + public C0CodeModel(Controller controller) { + this.controller = controller; + code = ""; + addresses = new StringBuilder(); + currentStep = 0; + } + + /** + * @return formatted C-Code of generateCodeFragment + */ + public String getCodeForm() { + String result = ""; + for (String l : editCode) { + result += l + "\n"; + } + return result; + } + + /** + * Returns if the View got the last address + * + * @return Boolean if createAddresses has been used + */ + public boolean isActual() { + return actual; + } + + /** + * creates Addresses for the left JEditPane of the C0View + */ + private void createAddresses() { + int i = 0; + actual = false; + addresses = new StringBuilder(); + addresses.append(""); + for (int s = 0; s < currentStep; s++) { + while (i < addressList.size() && "br".equals(addressList.get(i))) { + addresses.append(""); + i++; + } + if (i < addressList.size()) + addresses.append(""); + i++; + } + if (i > 0 && i < addressList.size() + 1) { + controller.markNode(addressList.get(i - 1)); + } else { + controller.markNode(""); + } + addresses.append("
          " + addressList.get(i) + "
          "); + } + + /** + * Returns the line of a given address + * + * @param address + * String with the address + * @return Integer with the line + */ + public int getLineOfAddress(String address) { + int line = 0; + if (addressList.contains(address)) { + line = addressList.indexOf(address); + } + return line; + } + + /** + * Returns the total amount of lines + * + * @return Integer with the amount + */ + public int getTotalLines() { + return addressList.size() + 1; + } + + /** + * Generates a C-Code mask with main, declarations, scanfs and + * printf-Statement + * + * @param m + * @param k + * @param i + * @return the C-Code mask + */ + public int generateCodeFragement(int m, int k, int i) { + int caret = 2; + // First empty List + editCode.clear(); + + // Head first + editCode.add("#include "); + editCode.add(""); + editCode.add("int main()"); + editCode.add("{"); + String vars = " int"; + for (int j = 1; j <= m; j++) { + vars += " x" + j; + if (j < m) { + vars += ","; + } else { + vars += ";"; + } + } + editCode.add(vars); + for (int j = 1; j <= k; j++) { + editCode.add(" scanf(\"%i\", &x" + j + ");"); + } + + // Move Caret + for (String line : editCode) + caret += line.length() + 1; + + // body empty + editCode.add(" "); + + // foot last + editCode.add(" printf(\"%d\", x" + i + ");"); + editCode.add(" return 0;"); + editCode.add("}"); + + return caret; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Generator#generate() + */ + public void generate() { + C0GeneratingVisitor visitor = new C0GeneratingVisitor(); + DFSIterator iter = new DFSIterator(controller.getASTModel()); + while (iter.hasNext()) { + iter.next().accept(visitor); + } + addressCount = visitor.getAddressCount() + 1; + + // include + addressList.add("br"); + // Leerzeichen + addressList.add("br"); + // Main + addressList.add("br"); + // Declaration + addressList.add("br"); + + code = ""; + code += ""; + code += ""; + code += ""; + + code += "
          "; + code += "
          #include <stdio.h>
          "; + code += "
          "; + code += "
          "; + code += "int main() {"; + code += "
          "; + code += "  int "; + ArrayList vars = controller.getASTModel().getProgram().getDecl() + .getVariableList(); + for (int i = 0; i < vars.size(); i++) { + code += vars.get(i).toString(); + if (i != vars.size() - 1) { + code += ", "; + } else { + code += ";"; + } + } + code += "
          "; + for (Var v : controller.getASTModel().getProgram().getScanf() + .getScanfList()) { + code += "  scanf(\"%i\", &" + v + + ");
          "; + addressList.add("br"); + } + code += "
          "; + addressList.add("br"); + code += visitor.getCode(); + addressList.addAll(visitor.getAddressList()); + addressList.add(controller.getASTModel().getProgram().getPrintf() + .getAddress()); + addressCount++; + code += ""; + code += "  printf(\"%d\", " + + controller.getASTModel().getProgram().getPrintf().getVar() + + ");"; + code += ""; + code += "
          "; + code += ""; + code += "
          "; + code += "  return 0;"; + code += "
          "; + code += "}"; + code += "
          "; + } + + /** + * Saves the given Code to the editCode + * + * @param code + */ + public void setCode(String code) { + editCode.clear(); + for (String s : code.split("\n")) { + editCode.add(s); + } + } + + /** + * @param code + * saves the ArrayList which normally comes from loading + * .c0-Code to the local editCode + */ + public void loadCode(ArrayList code) { + clear(); + TerminalView.println("c0 clear"); + this.editCode = code; + } + + /** + * @return editCode String which contains at least a C0Mask from + * generateCodeFragement + */ + public ArrayList getPlainC0Code() { + return editCode; + } + + /** + * @return code String with HTML-formatted C0-Code for the C0View + */ + public String getFormattedC0Code() { + return code; + } + + /** + * @return addresses String with HTML-formatted Addresses for the C0View + */ + public String getAddresses() { + actual = true; + return addresses.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#clear() + */ + public void clear() { + currentStep = 0; + addressCount = 0; + addressList.clear(); + code = ""; + actual = false; + addresses = new StringBuilder(); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#performAll() /* (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#isDone() + */ + public void performAll() { + currentStep = addressCount; + createAddresses(); + TerminalView.println("c0 : " + currentStep + " of " + addressCount); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#performStep() + * + * + * /* (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#isClear() + */ + public void performStep() { + if (addressCount > currentStep) + currentStep++; + createAddresses(); + TerminalView.println("c0 : " + currentStep + " of " + addressCount); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#undoStep() + */ + public void undoStep() { + if (currentStep > 0) { + currentStep--; + } + createAddresses(); + TerminalView.println("c0 : " + currentStep + " of " + addressCount); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#undoAll() + */ + public void undoAll() { + currentStep = 0; + createAddresses(); + TerminalView.println("c0 : " + currentStep + " of " + addressCount); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#isClear() + */ + public boolean isClear() { + return currentStep == 0; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.models.Performer#isDone() + */ + public boolean isDone() { + return currentStep == addressCount; + } + + public void setActive(boolean a) { + this.active = a; + } + + public boolean isActive() { + return active; + } +} diff --git a/src/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.java b/src/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.java new file mode 100644 index 0000000..f12c26f --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/C0GeneratingVisitor.java @@ -0,0 +1,558 @@ +package org.jalgo.module.c0h0.models.c0model; + +import java.util.LinkedList; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * Generates C0-Code. This is to be used with DFSIterator. + * + */ +public class C0GeneratingVisitor implements ASTVisitor { + private StringBuilder code; + private int addressCount, statementblockdepth; + private LinkedList addressStack; + private LinkedList addressListOutput; + + public C0GeneratingVisitor() { + statementblockdepth = 0; + code = new StringBuilder(); + code.append(""); + addressStack = new LinkedList(); + addressListOutput = new LinkedList(); + } + + /** + * Closes all While/else-Blocks + */ + private void closeBlocks() { + // Wir muessen nur alle while- und else-Bloecke schliessen, weil wir in + // jedem Fall den then-Block im visitBlock() abfangen koennen + while ( + // Erster Fall: f1, sf11, f11, sf111, f111, sf1111, f1111, f12 => + // bekommen f12 => Resultat f1, sf11, f11, f12 + (addressStack.size() > 3 + && addressStack.getLast().length() < addressStack.get( + addressStack.size() - 2).length() && + // Obriges Bsp: aber diesemal bekommen wir z.B. f1111 => erste + // Bedingungen waere ok => falsch + !addressStack.get(addressStack.size() - 2).equals( + "s" + addressStack.getLast())) + || ( + // Zweiter Fall: f1, sf11, f11, sf111, f111, sf1111, f1111, sf12 + // => bekommen sf12 => Resultat f1, sf11, f11, sf12 + String.valueOf(addressStack.getLast().charAt(0)).equals("s") && (addressStack + .getLast().length() - 1) < addressStack.get( + addressStack.size() - 2).length())) { + + // Algo zum Abbauen von while jeglicher Form(=> f- oder s-Adresse) + // Bekannt hierfuer ist aber bereits, dass dieser Block abgebaut + // werden muss + + if ( + // Erster Fall: f1, sf11, f11, xx => nur ein Statement und Block + // abbauen + addressStack.get(addressStack.size() - 3).equals( + "s" + addressStack.get(addressStack.size() - 2))) { + addressStack.remove(addressStack.size() - 2); + addressStack.remove(addressStack.size() - 2); + + // Nun bauen wir die table vom while/else ab + code.append("
          "); + + statementblockdepth--; + } else { + // Zweiter Fall: f1, f11, f111, f112, ..., f119, xx => Block und + // alle Statements in diesem abbauen + int end = addressStack.size() - 1; + int extra = addressStack.get(addressStack.size() - 2) + .substring( + 0, + addressStack.get(addressStack.size() - 2) + .length() - 1).length() + - addressStack.getLast().length(); + for (int i = addressStack + .indexOf(addressStack.get(addressStack.size() - 2) + .substring( + 0, + addressStack.get( + addressStack.size() - 2) + .length() - 1)); i < end; i++) { + addressStack.remove(addressStack.size() - 2); + } + // Neues Statement oeffnen + code.append(""); + // Wir haengen die schliessende Klammer an + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(extra); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append("}"); + // Das erste Statement wird natuerlich direkt geschlossen + code.append("
          "); + // Nun schliessen wir das Statement + code.append(""); + // Zuletzt bauen wir die table vom while/else ab + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add("br"); + } + } + } + + /** + * Initializes Statements: while/if/Assignment + * + * @param curdepth + * Integer with the current depth of the Symbol + * @param symbol + * Symbol to be displayed + */ + private void initStatement(int curdepth, Symbol symbol) { + // Als erstes bauen wir unseren Stack weiter auf + addressStack.add(symbol.getAddress()); + + // Nun schliessen wir alle Bloecke + closeBlocks(); + + // Anschliessend brauchen wir jedoch unser Statement auf der richtigen + // Hoehe + code.append(""); + code.append(""); + code.append(""); + } + + /** + * Creates a HTML-Tag with an attribute "token" + * + * @param symbol + * Symbol to be displayed + * @param content + * String with the content(for instance: while/if) + */ + private void createToken(Symbol symbol, String content) { + initStatement(symbol.getAddress().substring(1).length(), symbol); + code.append("
          "); + int bonus = 0; + for (String s : addressStack) { + if (String.valueOf(s.charAt(0)).equals("s")) { + bonus++; + } + } + for (int i = 0; i < addressStack.getLast().length() + bonus; i++) { + code.append(" "); + } + code.append(""); + code.append(""); + code.append(content + ""); + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitAssignment(org.jalgo + * .module.c0h0.models.ast.Assignment) + */ + public void visitAssignment(Assignment assignment) { + initStatement(assignment.getAddress().substring(1).length(), assignment); + code.append(""); + code.append(""); + code.append(assignment.getVar() + + " = " + + assignment.getTerm().toString().replaceAll("<", "<") + .replaceAll("<=", "<=") + ";"); + code.append("
          "); + addressListOutput.add(assignment.getAddress()); + addressCount++; + } + + /** + * Adds the amount of spaces which is needed to line up the code formatted + * + * @param extra + * Integer with an extra amount of Spaces + */ + private void addSpaces(int extra) { + int bonus = 0; + if (String.valueOf(addressStack.getLast().charAt(0)).equals("s")) { + bonus += 2; + } + for (int i = 0; i < addressStack.getLast().length() - bonus + extra + + statementblockdepth - 1; i++) { + code.append(" "); + } + + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitBlock(org.jalgo.module + * .c0h0.models.ast.Block) + */ + public void visitBlock(Block block) { + /* + * Notizen: Block.isBlock()mit leerer StatementList muss gezeichnet + * werden Block.isALie() mit leerer StatementList ist auf jeden Fall ein + * nicht vorhandenes else! + */ + + // Aufteilung des Blocks in die unterschiedlichen Moeglichkeiten + if (block.isBlock()) { + // Block mit Klammern + if (addressStack.contains(block.getAddress().substring(0, + block.getAddress().length() - 1) + + "1")) { + // Erster Block hat eine Klammer + + // Um doppelten Code zu ersparen: + addressStack.add(block.getAddress().substring(0, + block.getAddress().length() - 1)); + closeBlocks(); + addressStack.removeLast(); + addressStack.add(block.getAddress()); + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append(""); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add("br"); + + // Neues Statement + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add(block.getAddress()); + addressCount++; + } else if (addressStack.contains("s" + + block.getAddress().substring(0, + block.getAddress().length() - 1) + "1")) { + // Erster Block ist kein Block + + // Um doppelten Code zu ersparen: + addressStack.add(block.getAddress().substring(0, + block.getAddress().length() - 1)); + closeBlocks(); + addressStack.removeLast(); + addressStack.add(block.getAddress()); + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append(""); + code.append("else"); + code.append(""); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append(""); + code.append("{"); + code.append(""); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add("br"); + + // Neues Statement + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add(block.getAddress()); + addressCount++; + } else { + // Wir haben gerade einen einwandfreien neuen Block + // reinbekommen(while oder then-Block) + + // Zuerst fuellen wir unseren Stack auf + addressStack.add(block.getAddress()); + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append(""); + code.append("else"); + code.append(""); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append(""); + code.append("{"); + code.append(""); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add(block.getAddress()); + addressCount++; + + if (block.getStatementList().isEmpty()) { + // Der Block ist leer => wir sollten ein PseudoStatment in + // den addressStack einbauen + addressStack.add(block.getAddress() + "1"); + } + } + } else { + // Block ohne Klammern + if (addressStack.contains(block.getAddress().substring(0, + block.getAddress().length() - 1) + + "1")) { + // Erster Block ist kein Block + if (block.getStatementList().isEmpty()) { + // Else-Block ist nicht vorhanden: + // Wir machen in diesem Fall einfach nichts, sodass es + // spaeter als while erkannt wird + } else { + /* + * Bsp.: + * + * if(x1 2) { if(x1 > 10) x2 = 3; if(x1 < 10) + * x2 = 4; else x2 = 5; while(x1 > 2) x1 = x1 - 1; } else + * x3=x2; + */ + + // Um doppelten Code zu ersparen: + addressStack.add(block.getAddress().substring(1, + block.getAddress().length() - 1)); + closeBlocks(); + addressStack.removeLast(); + addressStack.add(block.getAddress()); + + // Es existiert ein weiterer Statement-Block in der Tiefe + statementblockdepth++; + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst mit dem Link hinzufuegen + code.append(""); + code.append("{"); + code.append(""); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add("br"); + } + } else if (addressStack.contains(block.getAddress().substring(1, + block.getAddress().length() - 1) + + "1")) { + // Erster Block hat eine Klammer + if (block.getStatementList().isEmpty()) { + // Else-Block ist nicht vorhanden + // Wir machen in diesem Fall einfach nichts, sodass es + // spaeter als while erkannt wird + } else { + // Um doppelten Code zu ersparen: + addressStack.add(block.getAddress().substring(0, + block.getAddress().length() - 1)); + closeBlocks(); + addressStack.removeLast(); + addressStack.add(block.getAddress()); + + // Es existiert ein weiterer Statement-Block in der Tiefe + statementblockdepth++; + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append(""); + addressListOutput.add(whileStatement.getAddress()); + addressCount++; + } + + /** + * Returns the created code + * + * @return code String with HTML-formatted C0-Code + */ + public String getCode() { + // Wir muessen sicherstellen, dass es noch ein letztes Element in der + // niedrigsten Ebene gibt + addressStack.add("e1"); + closeBlocks(); + return code.toString(); + } + + /** + * Returns a LinkedList with all Addresses + * + * @return addressListOutput LinkedList with all Addresses + */ + public LinkedList getAddressList() { + return addressListOutput; + } + + /** + * Returns an Integer how many addresses are displayed + * + * @return addressCount Integer which sums up all addresses + */ + public int getAddressCount() { + return addressCount; + } +} diff --git a/src/org/jalgo/module/c0h0/models/c0model/CVS/Entries b/src/org/jalgo/module/c0h0/models/c0model/CVS/Entries new file mode 100644 index 0000000..1e2ae0e --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/CVS/Entries @@ -0,0 +1,5 @@ +/AddressVisitor.java/1.1/Sat Mar 5 14:12:06 2011// +/C0CodeModel.java/1.1/Sat Mar 5 14:12:06 2011// +/C0GeneratingVisitor.java/1.1/Sat Mar 5 14:12:06 2011// +/SemanticVisitor.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/models/c0model/CVS/Repository b/src/org/jalgo/module/c0h0/models/c0model/CVS/Repository new file mode 100644 index 0000000..c598ed2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/c0model diff --git a/src/org/jalgo/module/c0h0/models/c0model/CVS/Root b/src/org/jalgo/module/c0h0/models/c0model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.java b/src/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.java new file mode 100644 index 0000000..b892261 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/SemanticVisitor.java @@ -0,0 +1,171 @@ +package org.jalgo.module.c0h0.models.c0model; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.Var; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * Checks AST for semantic Failures. This is to be used with DFSIterator. + * + */ +public class SemanticVisitor implements ASTVisitor { + private boolean valid; + private ArrayList availVars; + private String error; + private Var printfVar; + private ArrayList notInitializedVars; + + /** + * Creates a new Instance of the SemanticVisitor and already checks for + * undefined Vars + * + * @param availVars + * @param scanfVars + * @param printfVar + */ + @SuppressWarnings("unchecked") + public SemanticVisitor(ArrayList availVars, ArrayList scanfVars, + Var printfVar) { + valid = true; + this.availVars = getIndexOfVarList(availVars); + notInitializedVars = (ArrayList) this.availVars.clone(); + error = ""; + this.printfVar = printfVar; + + // Treten undefinierte Variablen auf? + for (int i : getIndexOfVarList(scanfVars)) { + if (!this.availVars.contains(i)) { + valid = false; + error += "x" + i + " nicht deklariert(Scanf)
          "; + this.availVars.add(i); + } + notInitializedVars.remove((Object) i); + } + if (!this.availVars.contains(printfVar.getIndex())) { + valid = false; + error += printfVar + " nicht deklariert(Printf)
          "; + this.availVars.add(printfVar.getIndex()); + } + } + + /** + * @param varList + * ArrayList which contains Vars + * @return vars ArrayList which contains the Index of the given Vars + */ + private ArrayList getIndexOfVarList(ArrayList varList) { + ArrayList vars = new ArrayList(); + for (Var v : varList) { + vars.add(v.getIndex()); + } + return vars; + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitAssignment(org.jalgo + * .module.c0h0.models.ast.Assignment) + */ + public void visitAssignment(Assignment assignment) { + if (!availVars.contains(assignment.getVar().getIndex())) { + valid = false; + error += assignment.getVar() + " nicht deklariert
          "; + } + for (int i : getIndexOfVarList(assignment.getTerm().getVars())) { + if (!availVars.contains(i)) { + valid = false; + error += "x" + i + " nicht deklariert
          "; + availVars.add(i); + } + if (notInitializedVars.contains(i)) { + valid = false; + error += "x" + i + " nicht definiert
          "; + notInitializedVars.remove((Object) i); + } + } + // Delete initialized Var + notInitializedVars.remove((Object) assignment.getVar().getIndex()); + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitIf(org.jalgo.module. + * c0h0.models.ast.If) + */ + public void visitIf(If ifStatement) { + for (int i : getIndexOfVarList(ifStatement.getRelation().getVars())) { + if (!availVars.contains(i)) { + valid = false; + error += "x" + i + " nicht deklariert
          "; + availVars.add(i); + } + if (notInitializedVars.contains(i)) { + valid = false; + error += "x" + i + " nicht definiert
          "; + notInitializedVars.remove((Object) i); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitWhile(org.jalgo.module + * .c0h0.models.ast.While) + */ + public void visitWhile(While whileStatement) { + for (int i : getIndexOfVarList(whileStatement.getRelation().getVars())) { + if (!availVars.contains(i)) { + valid = false; + error += "x" + i + " nicht deklariert
          "; + availVars.add(i); + } + if (notInitializedVars.contains(i)) { + valid = false; + error += "x" + i + " nicht definiert
          "; + notInitializedVars.remove((Object) i); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitBlock(org.jalgo.module + * .c0h0.models.ast.Block) + */ + public void visitBlock(Block block) { + // Ignore + } + + /** + * @return valid boolean whether the semantic check is valid + */ + public boolean isValid() { + if (notInitializedVars.contains(printfVar)) { + valid = false; + } + return valid; + } + + /** + * @return error String with ErrorInformations + */ + public String getError() { + if (notInitializedVars.contains(printfVar)) { + error += printfVar + " nicht definiert(Printf)
          "; + } + return error; + } +} diff --git a/src/org/jalgo/module/c0h0/models/c0model/package-info.java b/src/org/jalgo/module/c0h0/models/c0model/package-info.java new file mode 100644 index 0000000..45702c3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/c0model/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes to generate valid C0-Code + */ +package org.jalgo.module.c0h0.models.c0model; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/flowchart/Bundle.java b/src/org/jalgo/module/c0h0/models/flowchart/Bundle.java new file mode 100644 index 0000000..055e75d --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/Bundle.java @@ -0,0 +1,56 @@ +package org.jalgo.module.c0h0.models.flowchart; + +import java.util.List; + +/** + * bundles edges and vertizes for each step + * + * @author Philipp Geissler + * + */ +public class Bundle { + private List vertexes; + private List edges; + + private String address; + + /** + * @param vertexes + * @param edges + * @param address + */ + public Bundle(List vertexes, List edges, String address) { + this.vertexes = vertexes; + this.edges = edges; + this.address = address; + } + + /** + * returns all vertices of one step + * @return the vertices + */ + public List getVertexes() { + return vertexes; + } + + /** + * returns all edges of one step + * @return the edges + */ + public List getEdges() { + return edges; + } + + /** + * returns the address of the step + * + * @return the address + */ + public String getAddress() { + return address; + } + + + + +} diff --git a/src/org/jalgo/module/c0h0/models/flowchart/CVS/Entries b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Entries new file mode 100644 index 0000000..8659e88 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Entries @@ -0,0 +1,8 @@ +/Bundle.java/1.1/Sat Mar 5 14:12:06 2011// +/Edge.java/1.1/Sat Mar 5 14:12:06 2011// +/Element.java/1.1/Sat Mar 5 14:12:06 2011// +/FcGeneratingVisitor.java/1.1/Sat Mar 5 14:12:06 2011// +/FlowChartModel.java/1.1/Sat Mar 5 14:12:06 2011// +/LevelType.java/1.1/Sat Mar 5 14:12:06 2011// +/Vertex.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/models/flowchart/CVS/Repository b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Repository new file mode 100644 index 0000000..d5dc641 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/flowchart diff --git a/src/org/jalgo/module/c0h0/models/flowchart/CVS/Root b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/flowchart/Edge.java b/src/org/jalgo/module/c0h0/models/flowchart/Edge.java new file mode 100644 index 0000000..e8408b5 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/Edge.java @@ -0,0 +1,58 @@ +package org.jalgo.module.c0h0.models.flowchart; + + +/** + * an edge which contains two vertices + * @author Philipp + * + */ +public class Edge extends Element{ + private Vertex from; + private Vertex to; + + /** + * @param label + * @param from + * @param to + * @param style + */ + public Edge(String label, Vertex from, Vertex to, String style) { + super(style, label); + this.from = from; + this.to = to; + } + + /** + * returns the start vertex + * + * @return the start vertex + */ + public Vertex getFrom() { + return from; + } + + /** + * returns the end vertex + * + * @return the end vertex + */ + public Vertex getTo() { + return to; + } + + /** + * sets the start vertex + * @param from the start vertex + */ + public void setFrom(Vertex from) { + this.from = from; + } + + /** + * sets the end vertex + * @param to the end vertex + */ + public void setTo(Vertex to) { + this.to = to; + } +} diff --git a/src/org/jalgo/module/c0h0/models/flowchart/Element.java b/src/org/jalgo/module/c0h0/models/flowchart/Element.java new file mode 100644 index 0000000..f7977d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/Element.java @@ -0,0 +1,58 @@ +package org.jalgo.module.c0h0.models.flowchart; + + +/** + * an element of the flow chart + * + * @author Philipp + * + */ +public abstract class Element { + + private String style; + private String label; + + /** + * @param style + * @param label + */ + public Element(String style, String label) { + this.style = style; + this.label = label; + } + + /** + * returns the style + * + * @return the style + */ + public String getStyle() { + return style; + } + + /** + * returns the label + * @return the label + */ + public String getLabel() { + return label; + } + + /** + * sets the style + * + * @param style + */ + public void setStyle(String style) { + this.style = style; + } + + /** + * sets the label + * + * @param label + */ + public void setLabel(String label) { + this.label = label; + } +} diff --git a/src/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.java b/src/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.java new file mode 100644 index 0000000..cf626f2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/FcGeneratingVisitor.java @@ -0,0 +1,592 @@ +package org.jalgo.module.c0h0.models.flowchart; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.PrintfStatement; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * Generates the elements of the flowchart. Has to be used with BFSIterator. + * + * @author Philipp Geissler + * + */ +public class FcGeneratingVisitor implements ASTVisitor { + + /** + * Internal class to store the type of the level (while, if, ifelse, else) + * to work on later. + * + */ + private class level { + public LevelType type; + public Vertex v, vIn; + public Edge e; + public List eL; + public boolean isBlock; + public boolean isBlockElse; + + // else constructor + /** + * @param type + * @param v + * @param e + * @param eL + * @param isBlock + */ + public level(LevelType type, Vertex v, Edge e, List eL, boolean isBlock) { + this.type = type; + this.e = e; + this.eL = eL; + this.v = v; + this.isBlock = isBlock; + } + + // while constructor + /** + * @param type + * @param v + * @param vIn + * @param eL + * @param isBlock + */ + public level(LevelType type, Vertex v, Vertex vIn, List eL, boolean isBlock) { + this.type = type; + this.eL = eL; + this.v = v; + this.vIn = vIn; + this.isBlock = isBlock; + } + + // if-else constructor + /** + * @param type + * @param v + * @param eL + * @param isBlock + * @param isBlockElse + */ + public level(LevelType type, Vertex v, List eL, boolean isBlock, boolean isBlockElse) { + this.type = type; + this.v = v; + this.eL = eL; + this.isBlock = isBlock; + this.isBlockElse = isBlockElse; + } + } + + private List elementList; // big list with all flowchart elements + private List vertexList, lastVertexList; + private List edgeList, lastEdgeList; + private Vertex v1, v2, v3; + private Edge e1, e2, lastEdge; + private Bundle b; + private int depth, currentDepth, depthDifference; + private int y; // current vertical position, increases after every element + private int leftOffset; // offset between vertical arrows on the left side increases after every arrow (OFF) + private int rightOffset; // offset between vertical arrows on the right side, increases after every arrow (OFF) + private Stack levelStack; // stores the type of the current level (if, while, ...) + private Stack> elseQueue; // to store arrows going out from the if-block of the ifelse-block + private List levelQueue; // a list of elements from the levelStack to process (if multiple brackets close) + private List elseLevelQueue; // the top list of the elseQueue to process + private level l, lastWhile; + private boolean blockStarts, whileClosed, elseAhead; + + private final int OFF = 10; // ARROW offset + private final int MID = 0; // horizontal middle of container + private final int LEN = 25; // ARROW vertical length + private final int DIS = 70; // ARROW horizontal distance to middle + private final int ADD = 6; // ADDRESS diameter + private final int RHW = 90; // RHOMBUS width + private final int RHH = 30; // RHOMBUS height + private final int REW = 90; // RECTANGLE width + private final int REH = 25; // RECTANGLE height + private final int Y = 5; // vertical start point + + public FcGeneratingVisitor() { + vertexList = new ArrayList(); + lastVertexList = new ArrayList(); + edgeList = new ArrayList(); + lastEdgeList = new ArrayList(); + elementList = new ArrayList(); + y = Y + LEN; + depth = 1; + leftOffset = 0; + rightOffset = 0; + blockStarts = true; + levelStack = new Stack(); + elseQueue = new Stack>(); + } + + /** + * returns a list of Bundles with lists of flowchart elements + * @return list of bundles + */ + public List getElementList(PrintfStatement printf) { + + // add start arrow + v1 = new Vertex(null, MID, Y, 0, 0, "ANKER"); + v2 = new Vertex(null, MID, Y + LEN, 0, 0, "ANKER"); + e1 = new Edge(null, v1, v2, "ARROW"); + elementList.get(0).getEdges().add(e1); + + // process left stack + + if (levelStack.size() > 0 && depth > 0) { + checkLevel(""); + } + + // add print + + edgeList = new ArrayList(); + + v1 = new Vertex(printf.getAddress(), MID - ADD / 2, y, ADD, ADD, + "ADDRESS;spacingLeft="+addSpacing(printf.getAddress())); + y += ADD + LEN; + v2 = new Vertex("print(" + printf.getVar().toString()+")", MID - REW / 2, y, REW, REH, "RECTANGLE"); + + e1 = new Edge(null, v1, v2, "ARROW"); + edgeList.add(e1); + + b = new Bundle(new ArrayList(), edgeList, printf.getAddress()); + elementList.add(b); + + return elementList; + } + + /** + * Creates the arrows, if a level ends. + * + * @param address + * of the current symbol + */ + private void checkLevel(String address) { + currentDepth = address.length() - 1; + depthDifference = depth - currentDepth; + + // check if a higher level is reached + if (depthDifference > 0 && levelStack.size() > 0) { + + levelQueue = new LinkedList(); + + /* create levelQueue element for every closing bracket + * + * that is necessary to check if a higher while exists + * (if that is the case outgoing arrows have to be drawn upwards) + */ + while (depthDifference > 0 && !levelStack.isEmpty()) { + depthDifference -= 2; + if(!levelStack.peek().isBlock){ + depthDifference++; // if no brackets around block + } + levelQueue.add(levelStack.pop()); + } + + whileClosed = false; + + // search for else + elseAhead = false; + if (levelQueue.get(levelQueue.size() - 1).type == LevelType.IFELSE) { + elseAhead = true; + elseQueue.add(new LinkedList()); + } + + // process every level in queue (for every closing bracket) + while (!levelQueue.isEmpty()) { + + l = levelQueue.get(0); + levelQueue.remove(0); + + // search for last while + lastWhile = null; + for (int i = levelQueue.size() - 1; i >= 0; i--) + if (levelQueue.get(i).type == LevelType.WHILE) + lastWhile = levelQueue.get(i); + + /* process level + * + * NOTE: to store the vertices is not necessary because the flowchart is drawn by the edges + * (the edges always have a start and an end vertex which will be drawn) + */ + switch(l.type){ + case WHILE: + createIfOrWhile(); + break; + case IF: + createIfOrWhile(); + break; + case IFELSE: + createIfOrWhile(); + levelStack.push(new level(LevelType.ELSE, lastEdge.getFrom(), lastEdge, lastEdgeList, l.isBlockElse)); + if (!whileClosed && !elseQueue.isEmpty()) + elseQueue.peek().add(new level(LevelType.ELSE, lastEdge.getFrom(), lastEdge, lastEdgeList, true)); + break; + case ELSE: + if(!elseQueue.isEmpty()) + createElse(); + break; + } + } + } + } + + /** + * creates arrows from if or while + */ + private void createIfOrWhile() { + + // close while loop if not already closed + if (!whileClosed && l.type==LevelType.WHILE) { + lastEdge.setStyle("HORIZONTAL"); + + v1 = new Vertex(null, MID - DIS - leftOffset, lastEdge.getFrom().getY() + + lastEdge.getFrom().getHeight() / 2, 0, 0, "ANKER"); + lastVertexList.add(v1); + lastEdge.setTo(v1); + + v2 = new Vertex(null, MID - DIS - leftOffset, l.vIn.getY() + l.vIn.getHeight() / 2, 0, 0, "ANKER"); + lastVertexList.add(v2); + + e1 = new Edge(null, v1, v2, "VERTICAL"); + lastEdgeList.add(e1); + + v3 = new Vertex(null, MID - l.vIn.getWidth() / 2, l.vIn.getY() + l.vIn.getHeight() / 2, 0, 0, "ANKER"); + e2 = new Edge(null, v2, v3, "ARROW"); + lastEdgeList.add(e2); + + leftOffset += OFF; + + whileClosed = true; + } + + /* + * - in while loop + * + * => "nein"-arrow goes upwards and leads over the last while + */ + if (lastWhile != null){ + + createArrowUp(l, -1); + } + + /* + * - in if-block of an if-else-construct + * - not in while loop + * - not leading to an else block + * + * => "nein"-arrow will be stored in elseQueue to be drawn later (after else) + */ + else if (elseAhead && l.type!=LevelType.IFELSE) { + + elseQueue.peek().add(new level(LevelType.WHILE, l.v, l.eL, true, false)); + } + + /* + * - not in while loop + * - not in if-block of an if-else-construct + * + * => "nein"-arrow leads normally downwards around the while-block + */ + else { + + createArrowDown(l, +1); + } + } + + /** + * creates the arrow going around the else-block and the arrows going out of the if-block + */ + private void createElse() { + + // delete the arrow leading directly to the else-block + if (l.e.getStyle() != "HORIZONTAL") + l.e.setStyle("HORIZONTAL;opacity=0"); + + // create all arrows from the if-block of the ifelse-block + + elseLevelQueue = elseQueue.pop(); + + for (level r : elseLevelQueue) { + + /* + * - in while loop + * + * => arrow goes upwards and leads over the last while + */ + if (lastWhile != null){ + createArrowUp(r, -1); + } + + /* + * - not in while loop + * - else ahead not possible + * + * => arrow leads normally downwards + */ + else{ + createArrowDown(r, -1); + } + } + } + + /** + * creates arrow leading upwards over the last while + * + * @param k + * @param side + * -1 arrow on left side + * +1 arrow on right side + */ + private void createArrowUp(level k, int side){ + int offset; + if(side==-1) offset = -DIS - leftOffset; + else offset = DIS + rightOffset; + + v1 = new Vertex(null, MID + offset, k.v.getY() + k.v.getHeight() / 2, 0, 0, "ANKER"); + + if (k.type == LevelType.ELSE) // if the arrow is going around the else-block (then no label) + e1 = new Edge(null, k.v, v1, "HORIZONTAL"); + else + e1 = new Edge("nein", k.v, v1, "HORIZONTAL"); + + k.eL.add(e1); + + v2 = new Vertex(null, MID + offset, lastWhile.vIn.getY() + lastWhile.vIn.getHeight() / 2, 0, 0, + "ANKER"); + e1 = new Edge(null, v1, v2, "VERTICAL"); + k.eL.add(e1); + + v3 = new Vertex(null, MID + side*(lastWhile.vIn.getWidth() / 2), + lastWhile.vIn.getY() + lastWhile.vIn.getHeight() / 2, 0, 0, "ANKER"); + e1 = new Edge(null, v2, v3, "ARROW"); + k.eL.add(e1); + + if(side==-1) leftOffset += OFF; + else rightOffset += OFF; + } + + /** + * creates arrow leading downwards + * + * @param k + * @param side + * -1 arrow on left side + * +1 arrow on right side + */ + private void createArrowDown(level k, int side){ + int offset; + if(side==-1) offset = -DIS - leftOffset; + else offset = DIS + rightOffset; + + v1 = new Vertex(null, MID + offset, k.v.getY() + k.v.getHeight() / 2, 0, 0, "ANKER"); + + if (k.type == LevelType.ELSE) // if the arrow is going around the else-block (then no label) + e1 = new Edge(null, k.v, v1, "HORIZONTAL"); + else + e1 = new Edge("nein", k.v, v1, "HORIZONTAL"); + + k.eL.add(e1); + + v2 = new Vertex(null, MID + offset, y + ADD / 2, 0, 0, "ANKER"); + e1 = new Edge(null, v1, v2, "VERTICAL"); + k.eL.add(e1); + + v3 = new Vertex(null, MID + side*(ADD / 2), y + ADD / 2, 0, 0, "ANKER"); + e1 = new Edge(null, v2, v3, "ARROW"); + k.eL.add(e1); + + if(side==-1) leftOffset += OFF; + else rightOffset += OFF; + } + + /** + * positions the addresses dynamically + * + * @param address + * @return address spacing + */ + private String addSpacing(String address){ + Integer addressSpacing = address.length()*4; + return addressSpacing.toString(); + } + + public void visitBlock(Block block) { + + if(!block.getStatementList().isEmpty()){ // if no empty else block + if (!block.isBlock()) { // if no brackets around block + + if (!blockStarts){ + + // resolve if-else-anomaly + if(!levelStack.peek().isBlock && !levelStack.peek().isBlockElse) + checkLevel(block.getAddress().substring(2)); + else checkLevel(block.getAddress().substring(1)); + } + } + + else { // if brackets around block + vertexList = new ArrayList(); + edgeList = new ArrayList(); + + if (!blockStarts){ // else block + // resolve if-else-anomaly + if(levelStack.peek().isBlock) + checkLevel(block.getAddress()); + else checkLevel(block.getAddress().substring(1)); + } + + v1 = new Vertex(block.getAddress(), MID - ADD / 2, y, ADD, ADD, + "LEFTADDRESS;spacingRight="+addSpacing(block.getAddress())); + v2 = new Vertex(null, MID, y, 0, 0, "ANKER"); + + vertexList.add(v1); + vertexList.add(v2); + + e1 = new Edge(null, v1, v2, "opacity=0"); + edgeList.add(e1); + + b = new Bundle(vertexList, edgeList, block.getAddress()); + elementList.add(b); + } + blockStarts = false; + depth = 1; // to prevent a false level-up event caused by if-else-anomaly + } + } + + public void visitAssignment(Assignment assignment) { + + vertexList = new ArrayList(); + edgeList = new ArrayList(); + + checkLevel(assignment.getAddress()); // check if a bracket has closed + + v1 = new Vertex(assignment.getAddress(), MID - ADD / 2, y, ADD, ADD, + "ADDRESS;spacingLeft="+addSpacing(assignment.getAddress())); + y += ADD + LEN; + v2 = new Vertex(assignment.getVar().toString() + " = " + assignment.getTerm().toString(), MID - REW / 2, y, + REW, REH, "RECTANGLE"); + y += REH + LEN; + v3 = new Vertex(null, MID, y, 0, 0, "ANKER"); + + vertexList.add(v1); + vertexList.add(v2); + vertexList.add(v3); + + e1 = new Edge(null, v1, v2, "ARROW"); + edgeList.add(e1); + + e1 = new Edge(null, v2, v3, "ARROW"); + edgeList.add(e1); + + b = new Bundle(vertexList, edgeList, assignment.getAddress()); + elementList.add(b); + + lastEdge = new Edge(null, null, null, null); + lastVertexList = new ArrayList(); + lastEdgeList = new ArrayList(); + + lastEdge = e1; + lastVertexList = vertexList; + lastEdgeList = edgeList; + + blockStarts = false; + + depth = assignment.getAddress().length()-1; + + } + + public void visitIf(If ifStatement) { + + vertexList = new ArrayList(); + edgeList = new ArrayList(); + + checkLevel(ifStatement.getAddress()); // check if a bracket has closed + + v1 = new Vertex(ifStatement.getAddress(), MID - ADD / 2, y, ADD, ADD, + "ADDRESS;spacingLeft="+addSpacing(ifStatement.getAddress())); + y += ADD + LEN; + v2 = new Vertex(ifStatement.getRelation().toString(), MID - RHW / 2, y, RHW, RHH, "RHOMBUS"); + y += RHH + LEN; + v3 = new Vertex(null, MID, y, 0, 0, "ANKER"); + + vertexList.add(v1); + vertexList.add(v2); + vertexList.add(v3); + + e1 = new Edge(null, v1, v2, "ARROW"); + edgeList.add(e1); + + e1 = new Edge("ja", v2, v3, "ARROW"); + edgeList.add(e1); + + b = new Bundle(vertexList, edgeList, ifStatement.getAddress()); + elementList.add(b); + + if (ifStatement.getElseSequence().getStatementList().size() == 0) + levelStack.push(new level(LevelType.IF, v2, edgeList, ifStatement.getIfSequence().isBlock(), false)); + else + levelStack.push(new level(LevelType.IFELSE, v2, edgeList, + ifStatement.getIfSequence().isBlock(), ifStatement.getElseSequence().isBlock())); + + lastEdge = new Edge(null, null, null, null); + lastVertexList = new ArrayList(); + lastEdgeList = new ArrayList(); + + lastEdge = e1; + blockStarts = true; + lastVertexList = vertexList; + lastEdgeList = edgeList; + depth = ifStatement.getAddress().length()-1; + + } + + public void visitWhile(While whileStatement) { + + vertexList = new ArrayList(); + edgeList = new ArrayList(); + + checkLevel(whileStatement.getAddress()); // check if a bracket has closed + + v1 = new Vertex(whileStatement.getAddress(), MID - ADD / 2, y, ADD, ADD, + "ADDRESS;spacingLeft="+addSpacing(whileStatement.getAddress())); + y += ADD + LEN; + v2 = new Vertex(whileStatement.getRelation().toString(), MID - RHW / 2, y, RHW, RHH, "RHOMBUS"); + y += RHH + LEN; + v3 = new Vertex(null, MID, y, 0, 0, "ANKER"); + + vertexList.add(v1); + vertexList.add(v2); + vertexList.add(v3); + + e1 = new Edge(null, v1, v2, "ARROW"); + edgeList.add(e1); + + e1 = new Edge("ja", v2, v3, "ARROW"); + edgeList.add(e1); + + b = new Bundle(vertexList, edgeList, whileStatement.getAddress()); + + elementList.add(b); + + levelStack.push(new level(LevelType.WHILE, v2, v1, edgeList, whileStatement.getBlock().isBlock())); + + lastEdge = new Edge(null, null, null, null); + lastVertexList = new ArrayList(); + lastEdgeList = new ArrayList(); + + lastEdge = e1; + blockStarts = true; + lastVertexList = vertexList; + lastEdgeList = edgeList; + depth = whileStatement.getAddress().length()-1; + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.java b/src/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.java new file mode 100644 index 0000000..4894f49 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/FlowChartModel.java @@ -0,0 +1,110 @@ +package org.jalgo.module.c0h0.models.flowchart; + +import java.util.List; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.models.Generator; +import org.jalgo.module.c0h0.models.Performer; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; +import org.jalgo.module.c0h0.views.TerminalView; + +/** + * contains the flowchart and coordinates visibility + * + * @author Philipp Geissler + * + */ +public class FlowChartModel implements Performer, Generator { + private FcGeneratingVisitor fcVisitor; + private List elementList; + private int visibleTo; + private Controller controller; + private boolean active = false; + + public FlowChartModel(Controller controller) { + this.controller = controller; + fcVisitor = new FcGeneratingVisitor(); + visibleTo = 0; + } + + /** + * @return list of bundles with all flowchart elements + */ + public List getElements() { + return elementList; + } + + /** + * @return index of last visible bundle in flowchart list + */ + public int getVisibleTo() { + return visibleTo; + } + + public void performStep() { + visibleTo++; + if (visibleTo > elementList.size() + 1) + visibleTo = elementList.size() + 1; + markNode(); + TerminalView.println("flowChart "+visibleTo+" of "+ elementList.size()); + } + + public void performAll() { + visibleTo = elementList.size()+1; + markNode(); + TerminalView.println("flowChart "+visibleTo+" of "+ elementList.size()); + } + + public void undoStep() { + if (visibleTo > 0) + visibleTo--; + markNode(); + TerminalView.println("flowChart "+visibleTo+" of "+ elementList.size()); + } + + public void undoAll() { + visibleTo = 0; + markNode(); + TerminalView.println("flowChart "+visibleTo+" of "+ elementList.size()); + } + + public void clear() { + fcVisitor = new FcGeneratingVisitor(); + visibleTo = 0; + markNode(); + } + + public boolean isClear() { + return visibleTo == 0; + } + + public boolean isDone() { + return visibleTo == elementList.size()+1; + } + + public void generate() { + fcVisitor = new FcGeneratingVisitor(); + DFSIterator iter = new DFSIterator(controller.getASTModel()); + while (iter.hasNext()) { + iter.next().accept(fcVisitor); + } + elementList = fcVisitor.getElementList(controller.getASTModel().getProgram().getPrintf()); + } + + /** + * marks the current node + */ + public void markNode() { + if (visibleTo > 0 && elementList.size()>=visibleTo) + controller.markNode(elementList.get(visibleTo - 1).getAddress()); + else + controller.markNode(""); + } + public void setActive(boolean a) { + active = a; + } + + public boolean isActive() { + return active; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/flowchart/LevelType.java b/src/org/jalgo/module/c0h0/models/flowchart/LevelType.java new file mode 100644 index 0000000..b3cbe22 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/LevelType.java @@ -0,0 +1,10 @@ +package org.jalgo.module.c0h0.models.flowchart; + +/** + * an enumeration of level types + * @author Philipp + * + */ +public enum LevelType { + WHILE, IF, IFELSE, ELSE +} diff --git a/src/org/jalgo/module/c0h0/models/flowchart/Vertex.java b/src/org/jalgo/module/c0h0/models/flowchart/Vertex.java new file mode 100644 index 0000000..81cf9fe --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/Vertex.java @@ -0,0 +1,104 @@ +package org.jalgo.module.c0h0.models.flowchart; + + +/** + * a vertex of the flow chart + * + * @author Philipp + * + */ +public class Vertex extends Element{ + private int x; + private int y; + private int width; + private int height; + + /** + * @param label + * @param x + * @param y + * @param width + * @param height + * @param style + */ + public Vertex(String label, int x, int y, int width, int height, String style) { + super(style, label); + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + /** + * sets x + * + * @param x + */ + public void setX(int x) { + this.x = x; + } + + /** + * sets y + * + * @param y + */ + public void setY(int y) { + this.y = y; + } + + /** + * sets the width + * + * @param width + */ + public void setWidth(int width) { + this.width = width; + } + + /** + * sets the height + * + * @param height + */ + public void setHeight(int height) { + this.height = height; + } + + /** + * returns x + * + * @return x position + */ + public int getX() { + return x; + } + + /** + * returns y + * + * @return y position + */ + public int getY() { + return y; + } + + /** + * returns the width + * + * @return the width + */ + public int getWidth() { + return width; + } + + /** + * returns the height + * + * @return the height + */ + public int getHeight() { + return height; + } + +} diff --git a/src/org/jalgo/module/c0h0/models/flowchart/package-info.java b/src/org/jalgo/module/c0h0/models/flowchart/package-info.java new file mode 100644 index 0000000..17aa10c --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/flowchart/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes to generate the Flowchart + */ +package org.jalgo.module.c0h0.models.flowchart; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/h0model/CVS/Entries b/src/org/jalgo/module/c0h0/models/h0model/CVS/Entries new file mode 100644 index 0000000..789c87c --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/CVS/Entries @@ -0,0 +1,3 @@ +/H0CodeModel.java/1.1/Sat Mar 5 14:12:05 2011// +/H0GeneratingVisitor.java/1.1/Sat Mar 5 14:12:05 2011// +/package-info.java/1.1/Sat Mar 5 14:12:05 2011// diff --git a/src/org/jalgo/module/c0h0/models/h0model/CVS/Repository b/src/org/jalgo/module/c0h0/models/h0model/CVS/Repository new file mode 100644 index 0000000..6cd8b89 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/h0model diff --git a/src/org/jalgo/module/c0h0/models/h0model/CVS/Root b/src/org/jalgo/module/c0h0/models/h0model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/h0model/H0CodeModel.java b/src/org/jalgo/module/c0h0/models/h0model/H0CodeModel.java new file mode 100644 index 0000000..06fd961 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/H0CodeModel.java @@ -0,0 +1,196 @@ +package org.jalgo.module.c0h0.models.h0model; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.models.Generator; +import org.jalgo.module.c0h0.models.Performer; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; + +/** + * Generates, contains and returns Haskell0 code. + * + * @author Peter Schwede + * + */ +public class H0CodeModel implements Performer, Generator { + private H0GeneratingVisitor visitor; + private int step; + private Controller controller; + private String processedAddress; + private int maxStep = 0; + private boolean active = false; + + /** + * Generates, contains and returns Haskell0 code. + */ + public H0CodeModel(Controller controller) { + this.controller = controller; + visitor = new H0GeneratingVisitor(); + step = 0; + processedAddress = null; + } + + /** + * Generates Haskell0-Code. + * + * Internally a Visitor is used. + * + * @see H0GeneratingVisitor + * + */ + public void generate() { + clear(); + int m = controller.getASTModel().getProgram().getDecl() + .getVariableList().size(); + int k = controller.getASTModel().getProgram().getScanf().getScanfList() + .size(); + int i = controller.getASTModel().getProgram().getPrintf().getVar() + .getIndex(); + visitor.setMKI(m, k, i); + + for (DFSIterator bit = new DFSIterator(controller.getASTModel()); bit + .hasNext();) { + bit.next().accept(visitor); + } + maxStep = visitor.getSteps().size(); + } + + /** + * Delivers the contained code. + * + * @return Complete Haskell0 string with head, body and foot + */ + public String getCode() { + return visitor.getPlain(); + } + + /** + * Returns symbol at a given line + * + * Catches illegal line numbers + * + * @param line + * @return Symbol at a given line + */ + public Symbol getSymbolAtLine(int line) { + if (line > 0 && line < visitor.getSymbols().size()) + return visitor.getSymbols().get(line); + return null; + } + + /** + * Inverse of @see getSymbolAtLine + * + * Gets the first line where an Symbol with given address is written + * + * @param address + * @return line number + */ + public int getLineOfSymbol(String address) { + int i = 0; + if (address != "") + for (Symbol s : visitor.getSymbols()) { + if (s != null && s.getAddress() != null + && s.getAddress().equals(address)) + return i; + i++; + } + return i; + } + + /** + * @return HTML-formatted Haskell0-Code for the current step. + */ + public String getHTMLCode() { + // Show nothing on the first step + if (step == 0) + return ""; + + int lastLineOfStep = visitor.getSteps().get(Math.min(step, maxStep-1)); + Symbol sym = getSymbolAtLine(lastLineOfStep); + if (step <= maxStep) { + processedAddress = sym != null ? sym.getAddress() : ""; + } else { + processedAddress = ""; + } + return visitor.getHTML(0, lastLineOfStep, step >= maxStep); + } + + /** + * Delivers the contained code in HTML. + * + * @return HTML code + */ + public String getAllHTMLCode() { + return visitor.getHTML(); + } + + /** + * Resets this H0CodeModel, as if it's new. + */ + public void clear() { + visitor.clear(); + step = 0; + processedAddress = null; + maxStep = 0; + } + + public void performStep() { + step = Math.min(step + 1, maxStep + 1); + controller.updateViews(); + if (step < maxStep) + controller.markNode(processedAddress); + else if (step == maxStep) + controller.markNode(visitor.getPrintAddress()); + else { + controller.markNode(""); + } + } + + public void performAll() { + step = maxStep + 1; + controller.updateViews(); + controller.markNode(""); + } + + public void undoStep() { + step = Math.max(0, step - 1); + controller.updateViews(); + if (step < maxStep) + controller.markNode(processedAddress); + else if (step == maxStep) + controller.markNode(visitor.getPrintAddress()); + else { + controller.markNode(""); + } + } + + public void undoAll() { + step = 0; + controller.updateViews(); + } + + public boolean isDone() { + return step > maxStep; + } + + public boolean isClear() { + return step == 0; + } + + public String getAddress() { + return processedAddress; + } + + public void setActive(boolean a) { + active = a; + } + + public boolean isActive() { + return active; + } + + public int getNumberOfLines() { + return visitor.getNumberOfLines() + ((step <= maxStep) ? visitor.foot().split("\n").length : 0); + } +} diff --git a/src/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.java b/src/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.java new file mode 100644 index 0000000..e5d29fb --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/H0GeneratingVisitor.java @@ -0,0 +1,756 @@ +package org.jalgo.module.c0h0.models.h0model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.Term; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * Generates Haskell0-Code. Has to be used with BFSIterator. + * + * This works like a automaton with memory and look-ahead marking + * + * @author Peter Schwede + * + */ +public class H0GeneratingVisitor implements ASTVisitor { + private List plain = new ArrayList(); // plain code + private List html = new ArrayList(); // HTML code + private List symbols = new ArrayList();; // Line <-> + // Symbol + private List steps = new ArrayList(); // step <-> + // line + private HashMap awaited = new LinkedHashMap(); + + private int m, k, i, n; // s. script + + private int numberOfSymbols = 0; + private int numberOfLines = 0; + + /** + * Constructor + * + * sets m=1, k=1, i=1 + */ + public H0GeneratingVisitor() { + init(1, 1, 1); + } + + /** + * Constructor + * + * @param m + * @param k + * @param i + */ + public H0GeneratingVisitor(final int m, final int k, final int i) { + init(m, k, i); + } + + /** + * Sets the Haskell0-parameters m, k and i + * + * @param m + * @param k + * @param i + */ + private void init(final int m, final int k, final int i) { + n = 1; + setMKI(m, k, i); + } + + /** + * Makes setting parameters after construction possible + * + * Also generates the head of the code. This should be called on any + * construction or reset of this visitor. + * + * @param m + * @param k + * @param i + */ + public void setMKI(final int m, final int k, final int i) { + clear(); + + this.m = m; + this.k = k; + this.i = i; + + String line = "module Main where"; + addLine(line, null); + addEmptyLine(null); + addStep(); + } + + /** + * Generates the bottom part of the Haskell0 code. + * + * @return Code foot string + */ + public String foot() { + StringBuilder foot = new StringBuilder(); + String line = ""; + + // f(n) :: Int -> .. Int + line = funcHead("f" + n); + foot.append(line + "\n"); + + // f(n) x1 .. xm + line = "f" + n; + line += varChain(m); + line += " = x" + i; + foot.append(line + "\n"); + + // main = do x1 <- readln + // .. + // xk <- readln + line = "main = do\n"; + for (int j = 1; j <= k; j++) { + if(j > 1) { + line = " x" + j + " <- readLn\n"; + foot.append(line); + } else { + line += " x" + j + " <- readLn\n"; + foot.append(line); + } + } + + + // print (f1 x1 .. xk 0 .. 0); + line = " "; + line += "print (f1"; + line += varChain(k); + for (int j = 1; j <= m - k; j++) { + line += " 0"; + } + line += ")"; + foot.append(line + "\n"); + + return foot.toString(); + } + + /** + * Generates Haskell0-foot with HMTL formatting + * + * @return the html foot + */ + public String htmlFoot() { + StringBuilder foot = new StringBuilder(); + String line = "
          "; + + // + foot.append("
          "); + + // f(n) :: Int -> .. Int + line = htmlFuncHead("f" + n); + foot.append(""); + + // main = do x1 <- readln + // .. + // xk <- readln + line = "main = do "; + line += "x" + 1 + " <- readLn"; + foot.append(""); + for (int j = 2; j <= k; j++) { + line = "          "; + line += "x" + j + " <- readLn"; + foot.append(""); + } + + // print (f1 x1 .. xk 0 .. 0); + line = "         "; + line += " print (f1"; + line += varChain(k); + for (int j = 1; j <= m - k; j++) { + line += " 0"; + } + line += ")"; + foot.append(""); + + return foot.toString(); + } + + /** + * Generates Haskell0 function head. + * + * @param addr + * Address string of which the increment shall be returned + * @param m + * Number of defined varables + * @return f[addr] x1 .. xm + */ + private String funcHead(String addr) { + String line = ""; + line += addr + " ::"; + for (int i = 0; i < m; i++) { + line += " Int ->"; + } + line += " Int"; + return line; + } + + /** + * Generates Haskell0 function head in HTML + * + * @param address + * @return + */ + private String htmlFuncHead(String address) { + String line = ""; + line += address + " ::"; + for (int i = 0; i < m; i++) { + line += " Int ->"; + } + line += " Int"; + return line; + } + + /** + * Calls toString() on Term and transforms it to Haskell0-Syntax + * + * @param termFromAst + * @return String representation. + */ + private String termTrans(Term termFromAst) { + return termFromAst.toString().replaceAll("/", "`div`").replaceAll("!=", + "/=").replaceAll("%", "`mod`"); + } + + /** + * Generates a string of 1..m variables + * + * @see varString(int from, int to) + * + * @param m + * Number of Variables + * @return + */ + private String varChain(final int m) { + return varChain(1, m); + } + + /** + * Generates a string of from..to variables. + * + * Attention: first character is a ' ' which is needed in most of the cases. + * + * E.g.: to = 3, from = 1 --> " x1 x2 x3". + * + * @param from + * (usuall 1) + * @param to + * (usually m) + * @return + */ + private String varChain(final int from, final int to) { + String res = ""; + for (int j = from; j <= to; j++) { + res += " x" + j; + } + return res; + } + + /** + * Adds a line of code + * + * Makes sure, that each one is added to both, plain text and + * html code. Also numberOfLines is increased accurately. + * + * @param string + * String to be added + * @param associate + * Symbol to be associated with string + * @return + */ + private void addLine(String string, Symbol associate) { + if (!symbols.contains(associate)) { + numberOfSymbols++; + } + + symbols.add(associate); + plain.add(string + "\n"); + + string = string.replaceAll("<", "<").replaceAll(">", ">"); + string = string.replaceAll(" ", " "); + + String classStr = ""; + String addr = "none"; + if (associate != null) { + classStr += associate.getAddress(); + addr = classStr; + } + boolean isFuncHead = string.contains("::"); + boolean isHead = string.contains("module"); + + String line = ""; + html.add(line); + + numberOfLines++; + } + + private void addEmptyLine(Symbol associate) { + if (!symbols.contains(associate)) { + numberOfSymbols++; + } + + symbols.add(associate); + plain.add("\n"); + html.add(""); + + numberOfLines++; + } + + /** + * Increments addresses on same level. E.g.: f212 --> f213 + * + * Also increases n if Address length equals 2. Therefore, n is always the + * number of the greatest Address. f2 --> n = 2 + * + * Attention: This method does not work properly for Addresses like + * f[1-9]*9 + * + * Please use it where you can! + * + * @param address + * address string + * @return new address string + */ + private String incAddr(String address) { + int increment = Integer.valueOf("" + + address.charAt(address.length() - 1)) + 1; + if (address.length() == 2 && increment > n) + n = increment; + String res = address.substring(0, address.length() - 1) + increment; + return res; + } + + /** + * Remembers line of code for later step performing + * + * @param lineOfCode + */ + private void addStep() { + steps.add(numberOfLines - 1); + } + + private void beginFunction(String addr) { + // html.add(""); + } + + /** + * Makes sure, a symbol is awaited only once. + * + * @param s + * @param address + */ + private void awaitOnce(Symbol s, String address) { + if (!awaited.containsKey(s)) { + awaited.put(s, address); + } + } + + /* + * (non-Javadoc) Visits assignment + * + * Generates code like follows with transTerm = + * transTerm(assignment.getTerm()): + * + * + * + * f(n) :: Int .. -> Int (m-times) + * + * f(n) x1 .. xm = f(n+1) x1 .. x(v-1) transTerm x(v+1) .. xm + * + * + * + * Each line is added with addLine() to make sure some things. If + * the visitor has been waiting for this assignment, it uses it's designated + * address. + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitAssignment(org.jalgo + * .module.c0h0.models.ast.Assignment) + */ + public void visitAssignment(Assignment assignment) { + String addr = assignment.getAddress(); + String addr2 = ""; + if (awaited.containsKey(assignment)) { + addr2 = awaited.get(assignment); + awaited.remove(assignment); + } else { + addr2 = incAddr(addr); + } + int v = assignment.getVar().getIndex(); + + beginFunction(addr); + + String line = ""; + + // f(n) :: Int .. -> Int + line += funcHead(addr); + addLine(line, assignment); + + // f(n) x1 .. xm + line = addr; + line += varChain(m); + // ... = f(n+1) x1 .. x(v-1) term x(v+1) .. xm + line += " = " + addr2; + if (v >= 1 && m >= 1 && v <= m) + line += varChain(v - 1); + line += " (" + termTrans(assignment.getTerm()) + ")"; + if (v >= 1 && m >= 1 && v <= m) + line += varChain(v + 1, m); + addLine(line, assignment); + addEmptyLine(assignment); + + endFunction(); + + addStep(); + } + + /* + * (non-Javadoc) + * + * Generates Haskell0 code as follows: + * + * + * + * f(a) x1 .. xm = f(a)1 x1 .. xm + * + * + * + * Each line is added with addLine(). + * + * This method also makes sure, the visitor awaits the last statement of the + * block. Note, that the same last statement will get the address, the block + * had been assigned to before. + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitBlock(org.jalgo.module + * .c0h0.models.ast.Block) + */ + public void visitBlock(Block block) { + if (block.isALie() || block.getStatementList().isEmpty()) { // ignore + // empty + // blocks + if (awaited.containsKey(block)) + awaited.remove(block); + return; + } + + String addr = block.getAddress(); + if (awaited.containsKey(block)) { + String addr2 = awaited.get(block); + awaited.remove(block); + awaitOnce(block.getLastStatement(), addr2); + } + + beginFunction(addr); + + String line = ""; + + line += funcHead(addr); + addLine(line, block); + + line = addr + varChain(m); + line += " = "; + line += addr + "1" + varChain(m); + addLine(line, block); + addEmptyLine(block); + + endFunction(); + + addStep(); + } + + /* + * (non-Javadoc) + * + * Generates code as follows with transTerm = transformed relation: + * + * f(a) x1 .. xm = if (transTerm) then f(a)1 x1 .. xm + * + * (if there's one:) else f(a)2 x1 .. xm + * + * (if there's none:) else f(a+1) x1 .. xm + * + * Each line is added with addLine(). If the visitor has been + * waiting for this if-statement, this statement sets it's address to it's + * destined one. After this, the visitor will look forward to visit the if's + * if-block and else-block (if there's any) with a wide grin on his face. + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitIf(org.jalgo.module. + * c0h0.models.ast.If) + */ + public void visitIf(If ifStatement) { + String addr = ifStatement.getAddress(); + String addr2; + if (awaited.containsKey(ifStatement)) { + addr2 = awaited.get(ifStatement); + awaited.remove(ifStatement); + } else { + addr2 = incAddr(addr); + } + + beginFunction(addr); + + String line = ""; + // check if If has defined else block + line += funcHead(addr); + addLine(line, ifStatement); + + // fa x1 ... xm = if (be) then fa1 x1 .. xm + line = addr; + line += varChain(m); + line += " = if"; + line += " (" + termTrans(ifStatement.getRelation()) + ")"; + int indentLength = line.length(); // for pretty formating + + line += " then "; + if (ifStatement.getIfSequence().getStatementList().isEmpty()) { + line += addr2; + } else { + line += addr + "1"; + awaitOnce(ifStatement.getIfSequence().getLastStatement(), addr2); + } + line += varChain(m); + addLine(line, ifStatement); + + line = ""; + // add some spaces + for (int j = 0; j < indentLength; j++) { + line += " "; + } + + line += " else "; + if (ifStatement.getElseSequence().getSequence().isEmpty()) { + line += addr2; + } else { + line += addr + "2"; + awaitOnce(ifStatement.getElseSequence().getLastStatement(), addr2); + } + line += varChain(m); + addLine(line, ifStatement); + addEmptyLine(ifStatement); + + endFunction(); + + addStep(); + } + + /* + * (non-Javadoc) + * + * Generates code as follows: + * + * + * + * f(a) x1 .. xm = if (transTerm) f(a)1 x1 .. xm + * + * else f(a+1) x1 .. xm + * + * + * + * If the visitor has waited for this while statement, this particular while + * statement will await it's last statement with it's destined address. Just + * like and if, else do + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitWhile(org.jalgo.module + * .c0h0.models.ast.While) + */ + public void visitWhile(While whileStatement) { + String addr = whileStatement.getAddress(); + String addr2; + if (awaited.containsKey(whileStatement)) { + addr2 = awaited.get(whileStatement); + awaited.remove(whileStatement); + } else { + addr2 = incAddr(addr); + } + + beginFunction(addr); + + String line = ""; + line += funcHead(addr); + addLine(line, whileStatement); + + line = addr; + line += varChain(m); + line += " = if"; + line += " (" + termTrans(whileStatement.getRelation()) + ")"; + int indentLength = line.length(); // for pretty plain text formation + + if (whileStatement.getBlock().getStatementList().isEmpty()) { + // empty block + line += " then " + incAddr(addr); + } else { + line += " then " + addr + "1"; + } + line += varChain(m); + awaitOnce(whileStatement.getBlock().getLastStatement(), addr); // the + // return + addLine(line, whileStatement); + + line = ""; + // add some spaces + for (int j = 0; j < indentLength; j++) { + line += " "; + } + line += " else " + addr2; + line += varChain(m); + addLine(line, whileStatement); + awaitOnce(whileStatement.getBlock(), addr2); + addEmptyLine(whileStatement); + + endFunction(); + + addStep(); + } + + /** + * Returns plain Haskell0 code. (E.g. for saving) + * + * @return Complete Haskell0-Code with head, body and foot. + */ + public String getPlain() { + StringBuilder bob = new StringBuilder(); + for (String line : plain) + bob.append(line); + bob.append(foot()); + return bob.toString(); + } + + /** + * @return HTML formatted Haskell0-Code. (E.g. for viewing) + */ + public String getHTML() { + return getHTML(0, html.size() - 1, true); + } + + /** + * @return HTML formatted Haskell0-Code + */ + public String getHTML(final int from, final int to, boolean withFoot) { + StringBuilder bob = new StringBuilder(); + bob.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst hinzufuegen + code.append("else"); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + + // Adresse fuer die linke Seite hinzufuegen + addressListOutput.add("br"); + } + } else { + // Wir haben gerade einen einwandfreien neuen Block + // reinbekommen(while oder then-Block) + + // Zuerst fuellen wir unseren Stack auf + addressStack.add(block.getAddress()); + + // Es existiert ein weiterer Statement-Block in der Tiefe + statementblockdepth++; + + // Neue Reihe + code.append(""); + // Alles in diesem Block hat die oberste Adresse + code.append(""); + addressListOutput.add(ifStatement.getAddress()); + addressCount++; + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitWhile(org.jalgo.module + * .c0h0.models.ast.While) + */ + public void visitWhile(While whileStatement) { + createToken(whileStatement, "while"); + code.append(""); + code.append(" (" + + whileStatement.getRelation().toString().replaceAll("<", + "<").replaceAll("<=", "<=") + ")"); + code.append("
          "); + // Das erste Statement der table ist die oeffnende Klammer + code.append("
          "); + // Die Tiefe besteht aus abgezaehlt vielen erzwungenen + // Leerzeichen + addSpaces(0); + code.append(""); + // Nun noch das Token selbst hinzufuegen + code.append("else"); + // Die interne table des Statements wird natuerlich direkt + // geschlossen + code.append("
          "); + // Das Statement abschliessen + code.append("
          "); + // Der Block besteht aus einer table mit allen Statements in + // dieser + code.append(""); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.models.ast.ASTVisitor#visitIf(org.jalgo.module. + * c0h0.models.ast.If) + */ + public void visitIf(If ifStatement) { + createToken(ifStatement, "if"); + code.append(""); + code.append(" (" + + ifStatement.getRelation().toString().replaceAll("<", "<") + .replaceAll("<=", "<=") + ")"); + code.append("
           
          "); + foot.append(""); + + // f(n) x1 .. xm + line = "f" + n; + line += varChain(m); + line += " = x" + i; + foot.append(""); + foot.append("
          " + line + "
          " + + line + "
          "); + + foot.append("
           
          " + line + "
          " + line + "
          " + line + "
          "; + if (isFuncHead) + line += "
          "; + if (isHead) + line += "
          "; + if (!string.contains("module")) { + if(isFuncHead) + line += ""; + else + line += ""; + line += string; + line += ""; + } else { + line += string; + } + if (isHead) + line += "
          "; + if (isFuncHead) + line += "
          "; + line += "
           
          "); + } + + private void endFunction() { + // html.add("
          "); + if (to < html.size()) { + for (String line : html.subList(from, to)) { + bob.append(line); + } + if (withFoot) { + bob.append(htmlFoot()); + } + } + bob.append("
          "); + bob.append("
           
          "); + return bob.toString(); + } + + /** + * @return A List of Symbols so that each generated code-line is associated + * to anc AST-symbol + */ + public List getSymbols() { + return symbols; + } + + /** + * Counts Symbols and returns + */ + public int getNumberOfSymbols() { + return numberOfSymbols; + } + + /** + * Address of the Print + */ + public String getPrintAddress() { + return "f" + n; + } + + /** + * Returns the number of Lines + */ + public int getNumberOfLines() { + return numberOfLines; + } + + /** + * Returns the lines associated to steps + */ + public List getSteps() { + return steps; + } + + /** + * Returns the Number of foot-lines that print results in H0 + * @return k + */ + public int getNumberOfOutputLines() { + return k; + } + + /** + * Resets this Visitor + * + * To reuse an Object is faster! (s. Effective Java) + */ + public void clear() { + plain.clear(); + html.clear(); + symbols.clear(); + steps.clear(); + awaited.clear(); + m = 0; + k = 0; + i = 0; + n = 1; + numberOfSymbols = 0; + numberOfLines = 0; + } +} diff --git a/src/org/jalgo/module/c0h0/models/h0model/package-info.java b/src/org/jalgo/module/c0h0/models/h0model/package-info.java new file mode 100644 index 0000000..de267d9 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/h0model/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes to generate valid H0-Code + */ +package org.jalgo.module.c0h0.models.h0model; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/package-info.java b/src/org/jalgo/module/c0h0/models/package-info.java new file mode 100644 index 0000000..6404b01 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes, that represent the model within MVC + */ +package org.jalgo.module.c0h0.models; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/models/tmodel/CVS/Entries b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Entries new file mode 100644 index 0000000..ae0f5fd --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Entries @@ -0,0 +1,3 @@ +/TGeneratingVisitor.java/1.1/Sat Mar 5 14:12:06 2011// +/TRuleModel.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/models/tmodel/CVS/Repository b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Repository new file mode 100644 index 0000000..7c6c0dd --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/models/tmodel diff --git a/src/org/jalgo/module/c0h0/models/tmodel/CVS/Root b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.java b/src/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.java new file mode 100644 index 0000000..98a72d5 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/TGeneratingVisitor.java @@ -0,0 +1,108 @@ +package org.jalgo.module.c0h0.models.tmodel; + +import java.util.HashMap; +import java.util.Stack; + +import org.jalgo.module.c0h0.models.ast.ASTVisitor; +import org.jalgo.module.c0h0.models.ast.Assignment; +import org.jalgo.module.c0h0.models.ast.Block; +import org.jalgo.module.c0h0.models.ast.If; +import org.jalgo.module.c0h0.models.ast.While; + +/** + * saves the corresponding rules for the tree structured addresses + * @author mathias.kaufmann + */ +public class TGeneratingVisitor implements ASTVisitor { + private HashMap ruleList; + private String assignmentRule; + private String ifRule; + private String ifElseRule; + private String blockRule; + private String whileRule; + private Stack nesa; + + /** + * sttrans-rule-library + */ + public TGeneratingVisitor() { + ruleList = new HashMap(); + nesa = new Stack(); + String langBracket = "<"; + String rangBracket = ">"; + assignmentRule = "sttrans(xi = se, a, b, m) :=
          " + + "    fa :: Int -> ... -> Int (m-mal ->)
          " + + "    fa x1 ... xm = fb x1 ... x(i − 1) setrans(se) x(i + 1) ... xm
          " + + "  für alle se ∈ W(" + langBracket + "SimpleExpression" + rangBracket + "), a, b ∈ Adr und i,m ≥ 1 mit i ≤ m"; + ifRule = "sttrans(if (be) stat, a, b, m) :=
          " + + "    fa :: Int -> ... -> Int (m-mal ->)
          " + + "    fa x1 ... xm = if betrans(be) then fa1 x1 ... xm
          " + + "                                  else fb  x1 ... xm
          " + + "    sttrans(stat, a1, b, m)
          " + + "  für alle be ∈ W(" + langBracket + "BoolExpression" + rangBracket + "), stat ∈ W(" + langBracket + "Statement" + rangBracket + "), a, b ∈ Adr und m ≥ 1"; + ifElseRule = "sttrans(if (be) stat1 else stat2, a, b, m) :=
          " + + "    fa :: Int -> ... -> Int (m-mal ->)
          " + + "    fa x1 ... xm = if betrans(be) then fa1 x1 ... xm
          " + + "                                  else else fa2 x1 ... xm
          " + + "    sttrans(stat1, a1, b, m)
          " + + "    sttrans(stat2, a2, b, m)
          " + + "für alle be ∈ W(" + langBracket + "BoolExpression" + rangBracket + "), stat1, stat2 ∈ W(" + langBracket +"Statement" + rangBracket +"), a, b ∈ Adr und m ≥ 1"; + blockRule = "sttrans({ stat1 stat2 . . . statn }, a, b, m) :=
          " + + "    fa :: Int -> ... -> Int (m-mal ->)
          " + + "    fa x1 ... xm = fa1 x1 ... xm
          " + + "    sttrans(stat1, a1, a2, m)
          " + + "    sttrans(stat2, a2, a3, m)
          " + + "    . . .
          " + + "    sttrans(statn, an, b, m)
          " + + "für alle stat1, . . . , statn ∈ W(" + langBracket + "Statement" + rangBracket + "), a, b ∈ Adr und m ≥ 1"; + whileRule = "sttrans(while (be) stat , a, b, m) :=
          " + + "    fa :: Int -> ... -> Int (m-mal ->)
          " + + "    fa x1 ... xm = if betrans(be) then fa1 x1 ... xm
          " + + "                                  else else fb  x1 ... xm
          " + + "    sttrans(stat, a1, a, m)
          " + + "für alle be ∈ W(" + langBracket + "BoolExpression" + rangBracket + "), stat ∈ W(" + langBracket + "Statement" + rangBracket + ")," + "a, b ∈ Adr, m ≥ 1 (beachte: die 2. Adresse lautet a)"; + } + + public void visitAssignment(Assignment assignment) { + ruleList.put(assignment.getAddress(), assignmentRule); + } + + /* (non-Javadoc) + * @see org.jalgo.module.c0h0.models.ast.ASTVisitor#visitBlock(org.jalgo.module.c0h0.models.ast.Block) + * Block-Statement ist nur bei Else (ohne Block) besonders. + * Auf dem Stack liegt die naechste Else-BSA (falls moeglich) + * + */ + public void visitBlock(Block block) { + if (!nesa.isEmpty()) + if (block.getAddress() == nesa.lastElement()) { + ruleList.put(block.getAddress(), ifElseRule); + nesa.pop(); + return; + } + ruleList.put(block.getAddress(), blockRule); + } + + public void visitWhile(While whileStatement) { + ruleList.put(whileStatement.getAddress(), whileRule); + } + + public void visitIf(If ifStatement) { + if (ifStatement.getElseSequence().getSequence().isEmpty()) { + ruleList.put(ifStatement.getAddress(), ifRule); + } else { + ruleList.put(ifStatement.getAddress(), ifElseRule); + nesa.push(ifStatement.getElseSequence().getAddress()); + } + } + + /** + * returns the rule assigned to an address + * + * @param markedNode + * @return the rule + */ + public String getRuleByAddress(String markedNode) { + return this.ruleList.get(markedNode); + } +} diff --git a/src/org/jalgo/module/c0h0/models/tmodel/TRuleModel.java b/src/org/jalgo/module/c0h0/models/tmodel/TRuleModel.java new file mode 100644 index 0000000..dff0c9b --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/TRuleModel.java @@ -0,0 +1,94 @@ +package org.jalgo.module.c0h0.models.tmodel; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.models.Performer; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; + +/** + * saves the address-rule-assignment + * + * @author mathias.kaufmann + * + */ +public class TRuleModel implements Performer { + private TGeneratingVisitor visitor; + private Controller controller; + private String markedNode; + private boolean active = false; + + /** + * @param controller + */ + public TRuleModel(Controller controller) { + this.controller = controller; + visitor = new TGeneratingVisitor(); + } + + /** + * current sttrans-rule from marked node + * + * @return the rule + */ + public String getSTTrans() { + return visitor.getRuleByAddress(markedNode); + } + + /** + * update marked node + */ + public void setSTTrans() { + markedNode = controller.getASTModel().getMarkedNode(); + } + + /** + * set marked node + * @param markedNode + */ + public void setSTTrans(String markedNode) { + this.markedNode = markedNode; + } + /** + * creates the assignment + */ + public void generate() { + for (DFSIterator bit = new DFSIterator(controller.getASTModel()); bit.hasNext();) { + bit.next().accept(visitor); + } + } + public boolean isDone() { + // stateless, beeing in every state, thus return true + return true; + } + + public boolean isClear() { + // stateless, in case of doubt, i'm cleared too + return true; + } + + public void performStep() { + // stateless + } + + public void performAll() { + // stateless + } + + public void undoStep() { + // stateless + } + + public void undoAll() { + // stateless + } + + public void clear() { + // stateless + } + + public void setActive(boolean a) { + active = a; + } + public boolean isActive() { + return active; + } +} diff --git a/src/org/jalgo/module/c0h0/models/tmodel/package-info.java b/src/org/jalgo/module/c0h0/models/tmodel/package-info.java new file mode 100644 index 0000000..ce00302 --- /dev/null +++ b/src/org/jalgo/module/c0h0/models/tmodel/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes to generate transformation rules + */ +package org.jalgo.module.c0h0.models.tmodel; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/package-info.java b/src/org/jalgo/module/c0h0/package-info.java new file mode 100644 index 0000000..ed5f0f0 --- /dev/null +++ b/src/org/jalgo/module/c0h0/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains all c0h0 packages + */ +package org.jalgo.module.c0h0; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/parser/C00Parser.java b/src/org/jalgo/module/c0h0/parser/C00Parser.java new file mode 100644 index 0000000..d08a01b --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/C00Parser.java @@ -0,0 +1,61 @@ +package org.jalgo.module.c0h0.parser; + +import java.io.IOException; +import java.io.StringReader; + +import org.jalgo.module.c0h0.models.ast.*; + +/** + * the c00 parser + * + */ +public class C00Parser{ + private Program program; + private String errorText = ""; + + /** + * returns the program + * + * @return the program + */ + public Program getProgram() { + return program; + } + + /** + * returns the error text + * + * @return the error text + */ + public String getErrorText() { + return errorText; + } + + /** + * initiates the parsing + * + * @param text the text to parse + * @return if parsing was successful + */ + public boolean parse(String text) { + boolean errorFlag = false; + + GeneratedC00Parser parser = new GeneratedC00Parser(); + C0Scanner scanner = new C0Scanner(new StringReader(text)); + + try { + program = (Program) parser.parse(scanner); + }catch (beaver.Parser.Exception e) { + errorFlag = true; + }catch (IOException e) { + errorFlag = true; + } + if(!errorFlag && !parser.getErrorEvents().hasErrors()) { + return true; + } + // TODO mehr Fehlerbehandlung? + errorText = parser.getErrorEvents().getErrorText(); + return false; + } + +} diff --git a/src/org/jalgo/module/c0h0/parser/C0Scanner.java b/src/org/jalgo/module/c0h0/parser/C0Scanner.java new file mode 100644 index 0000000..6ef6b77 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/C0Scanner.java @@ -0,0 +1,781 @@ +/* The following code was generated by JFlex 1.4.3 on 11/30/10 5:21 PM */ + +package org.jalgo.module.c0h0.parser; + +import beaver.Symbol; +import beaver.Scanner; +import org.jalgo.module.c0h0.parser.ParserConstants; +import org.jalgo.module.c0h0.parser.GeneratedC00Parser.Terminals; + + +/** + * This class is a scanner generated by + * JFlex 1.4.3 + * on 11/30/10 5:21 PM from the specification file + * ../module/c0h0/.grammar/c00-lexer.l + */ +class C0Scanner extends Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\1\1\1\1\0\1\1\1\1\22\0\1\1\1\50\1\44"+ + "\1\7\1\0\1\45\1\37\1\0\1\30\1\31\1\6\1\46\1\35"+ + "\1\47\1\23\1\5\1\4\11\3\1\0\1\36\1\17\1\34\1\25"+ + "\42\0\1\27\1\0\1\12\1\15\1\16\1\40\1\0\1\24\1\10"+ + "\2\0\1\13\1\26\1\11\1\22\1\42\1\0\1\43\1\20\1\21"+ + "\1\14\1\0\1\41\1\2\2\0\1\32\1\0\1\33\uff82\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\1\2\3\1\4\1\5\3\1"+ + "\1\6\1\1\1\7\1\1\1\10\1\11\1\12\1\13"+ + "\1\14\1\15\1\16\1\17\4\1\1\20\1\21\1\22"+ + "\1\1\1\23\3\0\1\24\2\0\1\25\1\0\1\26"+ + "\1\0\1\27\4\0\1\30\3\0\1\31\12\0\1\2"+ + "\1\0\1\32\2\0\1\33\3\0\1\34\1\35\2\0"+ + "\1\36\1\37\4\0\1\40\4\0\1\41\1\0\1\42"+ + "\1\43"; + + private static int [] zzUnpackAction() { + int [] result = new int[90]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\51\0\122\0\173\0\244\0\51\0\315\0\51"+ + "\0\366\0\u011f\0\u0148\0\u0171\0\u019a\0\u01c3\0\u01ec\0\51"+ + "\0\51\0\51\0\51\0\u0215\0\51\0\51\0\51\0\u023e"+ + "\0\u0267\0\u0290\0\u02b9\0\51\0\51\0\51\0\u02e2\0\u030b"+ + "\0\u0334\0\u035d\0\u0386\0\51\0\u03af\0\u03d8\0\51\0\u0401"+ + "\0\51\0\u042a\0\51\0\u0453\0\u047c\0\u04a5\0\u04ce\0\51"+ + "\0\u04f7\0\u0520\0\u0549\0\51\0\u0572\0\u059b\0\u05c4\0\u05ed"+ + "\0\u0616\0\u063f\0\u0668\0\u0691\0\u06ba\0\u06e3\0\51\0\u070c"+ + "\0\51\0\u0735\0\u075e\0\51\0\u0787\0\u07b0\0\u07d9\0\51"+ + "\0\51\0\u0802\0\u082b\0\51\0\51\0\u0854\0\u087d\0\u08a6"+ + "\0\u08cf\0\51\0\u08f8\0\u0921\0\u094a\0\u0973\0\51\0\u099c"+ + "\0\51\0\51"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[90]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11"+ + "\1\12\5\2\1\13\1\14\1\15\4\2\1\16\1\17"+ + "\1\2\1\20\1\21\1\22\1\23\1\24\1\25\1\26"+ + "\1\27\1\2\1\30\1\31\1\32\1\33\1\34\1\35"+ + "\1\36\1\37\52\0\1\3\52\0\1\40\50\0\2\5"+ + "\52\0\1\41\52\0\1\42\51\0\1\43\26\0\1\44"+ + "\23\0\1\45\55\0\1\46\13\0\1\47\26\0\1\50"+ + "\72\0\1\51\43\0\1\52\55\0\1\53\40\0\1\54"+ + "\67\0\1\55\23\0\1\56\77\0\1\57\37\0\1\60"+ + "\17\0\2\40\44\0\6\61\1\62\42\61\11\0\1\63"+ + "\60\0\1\64\47\0\1\65\51\0\1\66\56\0\1\67"+ + "\31\0\1\70\50\0\1\71\50\0\1\72\61\0\1\73"+ + "\37\0\1\74\4\0\1\75\33\0\6\61\1\76\42\61"+ + "\5\0\1\77\1\62\54\0\1\100\54\0\1\101\47\0"+ + "\1\102\44\0\1\103\50\0\1\104\52\0\1\105\46\0"+ + "\1\106\53\0\1\107\100\0\1\110\50\0\1\111\4\0"+ + "\5\61\1\77\1\76\42\61\13\0\1\112\45\0\1\113"+ + "\100\0\1\114\26\0\1\115\53\0\1\116\72\0\1\117"+ + "\21\0\1\120\56\0\1\121\66\0\1\122\21\0\1\123"+ + "\54\0\1\124\56\0\1\125\26\0\1\126\65\0\1\127"+ + "\56\0\1\130\25\0\1\126\2\0\1\131\71\0\1\132"+ + "\23\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[2501]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\3\1\1\11\1\1\1\11\7\1\4\11"+ + "\1\1\3\11\4\1\3\11\2\1\3\0\1\11\2\0"+ + "\1\11\1\0\1\11\1\0\1\11\4\0\1\11\3\0"+ + "\1\11\12\0\1\11\1\0\1\11\2\0\1\11\3\0"+ + "\2\11\2\0\2\11\4\0\1\11\4\0\1\11\1\0"+ + "\2\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[90]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + @SuppressWarnings("unused") +private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + @SuppressWarnings("unused") +private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + @SuppressWarnings("unused") +private boolean zzEOFDone; + + /* user code: */ + private Symbol symbol(short id, Object value) + { + return new Symbol(id, yyline + 1, yycolumn + 1, yylength(), value); + } + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + C0Scanner(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + C0Scanner(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 118) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Symbol nextToken() throws java.io.IOException, Scanner.Exception { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 16: + { return symbol(Terminals.MOD, "%"); + } + case 36: break; + case 20: + { return symbol(Terminals.IF, "if"); + } + case 37: break; + case 19: + { return symbol(Terminals.IDENT, yytext()); + } + case 38: break; + case 18: + { return symbol(Terminals.MINUS, "-"); + } + case 39: break; + case 10: + { return symbol(Terminals.LBRACKET, "{"); + } + case 40: break; + case 22: + { return symbol(Terminals.GE, ">="); + } + case 41: break; + case 5: + { return symbol(Terminals.MULT, "*"); + } + case 42: break; + case 26: + { return symbol(Terminals.ELSE, "else"); + } + case 43: break; + case 6: + { return symbol(Terminals.LT, "<"); + } + case 44: break; + case 1: + { throw new Scanner.Exception(yyline + 1, yycolumn + 1, yytext()); + } + case 45: break; + case 3: + { return symbol(Terminals.NUMBER, yytext()); + } + case 46: break; + case 28: + { return symbol(Terminals.IFORMAT, "\"%i\""); + } + case 47: break; + case 4: + { return symbol(Terminals.DIV, "/"); + } + case 48: break; + case 23: + { return symbol(Terminals.EQ, "=="); + } + case 49: break; + case 21: + { return symbol(Terminals.LE, "<="); + } + case 50: break; + case 32: + { return symbol(Terminals.PRINTF, "printf"); + } + case 51: break; + case 17: + { return symbol(Terminals.PLUS, "+"); + } + case 52: break; + case 27: + { return symbol(Terminals.MAIN, "main"); + } + case 53: break; + case 29: + { return symbol(Terminals.DFORMAT, "\"%d\""); + } + case 54: break; + case 13: + { return symbol(Terminals.COMMA, ","); + } + case 55: break; + case 24: + { return symbol(Terminals.NE, "!="); + } + case 56: break; + case 7: + { return symbol(Terminals.GT, ">"); + } + case 57: break; + case 11: + { return symbol(Terminals.RBRACKET, "}"); + } + case 58: break; + case 14: + { return symbol(Terminals.SEMICOLON, ";"); + } + case 59: break; + case 31: + { return symbol(Terminals.WHILE, "while"); + } + case 60: break; + case 8: + { return symbol(Terminals.LPAREN, "("); + } + case 61: break; + case 34: + { return symbol(Terminals.RETURN, "return 0"); + } + case 62: break; + case 15: + { return symbol(Terminals.AMP, "&"); + } + case 63: break; + case 30: + { return symbol(Terminals.SCANF, "scanf"); + } + case 64: break; + case 9: + { return symbol(Terminals.RPAREN, ")"); + } + case 65: break; + case 33: + { return symbol(Terminals.INCLUDE, "#include"); + } + case 66: break; + case 25: + { return symbol(Terminals.INT, "int"); + } + case 67: break; + case 12: + { return symbol(Terminals.ASSIGN, "="); + } + case 68: break; + case 2: + { /* ignore */ + } + case 69: break; + case 35: + { return symbol(Terminals.STDIO, ""); + } + case 70: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + { return symbol(Terminals.EOF, ParserConstants.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/src/org/jalgo/module/c0h0/parser/CVS/Entries b/src/org/jalgo/module/c0h0/parser/CVS/Entries new file mode 100644 index 0000000..5ebb4ba --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/CVS/Entries @@ -0,0 +1,6 @@ +/C00Parser.java/1.1/Sat Mar 5 14:12:06 2011// +/C0Scanner.java/1.1/Sat Mar 5 14:12:06 2011// +/ErrorEvents.java/1.1/Sat Mar 5 14:12:06 2011// +/GeneratedC00Parser.java/1.1/Sat Mar 5 14:12:06 2011// +/ParserConstants.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/parser/CVS/Repository b/src/org/jalgo/module/c0h0/parser/CVS/Repository new file mode 100644 index 0000000..4f28cb3 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/parser diff --git a/src/org/jalgo/module/c0h0/parser/CVS/Root b/src/org/jalgo/module/c0h0/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/parser/ErrorEvents.java b/src/org/jalgo/module/c0h0/parser/ErrorEvents.java new file mode 100644 index 0000000..09e295d --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/ErrorEvents.java @@ -0,0 +1,299 @@ +package org.jalgo.module.c0h0.parser; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.c0h0.parser.GeneratedC00Parser; + +import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; + +import beaver.Scanner; +import beaver.Symbol; +import beaver.Parser.Events; + +/** + * Provides a replacement for the standard error reporting gateway of the Beaver + * parser generator. This class is not intended to be instantiated directly + * (since it is abstract), use {link not valid} or {link not valid} to get + * instances of this class that are specialized for AM0 and C0 error reporting, + * respectively. + * + * @author Martin Morgenstern + */ +public abstract class ErrorEvents extends Events { + /** + * CSS style for highlighted user input (tokens) in error messages. + */ + private final static String STYLE_TOKEN = "background-color:#fff3af;font-size:100%;font-weight:bold;"; //$NON-NLS-1$ + + /** + * CSS style for words indicating an error. + */ + private final static String STYLE_ERROR = "color: #ff0000;"; //$NON-NLS-1$ + + /** + * Collects all syntax errors. + */ + private List syntaxErrors = new ArrayList(); + + /** + * Collects all lexer errors. + */ + private List lexicalErrors = new ArrayList(); + + /** + * Caches forbidden input sequences. + */ + private StringBuilder forbiddenInput = new StringBuilder(); + + /** + * Marker for the last line where an unmatched character was found (i.e. the + * "catch-all" rule of the lexer matched) and a lexer error occured. + */ + private int lastScannerErrorLine = 1; + + /** + * Handles scanner errors. Unmatched characters are collected per line and + * printed together. + */ + @Override + public void scannerError(Scanner.Exception e) { + if (e.line != lastScannerErrorLine) { + finishScannerErrorLine(); + } + + forbiddenInput.append(e.getMessage()); + lastScannerErrorLine = e.line; + } + + /** + * Add an error message with the cached characters in {@code forbiddenInput} + * to the lexer error list and clear the cache. If the cache is empty, do + * nothing. + */ + private void finishScannerErrorLine() { + if (forbiddenInput.length() > 0) { + final String error = String.format( + translate("DontKnowWhatToDo"), //$NON-NLS-1$ + STYLE_TOKEN, escapeHtml(forbiddenInput.toString()), + lastScannerErrorLine); + lexicalErrors.add(error); + forbiddenInput = new StringBuilder(); + } + } + + /** + * Handle syntax errors. + */ + @Override + public void syntaxError(Symbol token) { + final String tokenValue = (token.value != null) ? token.value + .toString() : "#" + token.getId(); //$NON-NLS-1$ + + int line = Symbol.getLine(token.getStart()); + int col = Symbol.getColumn(token.getStart()); + + String error; + + if (ParserConstants.EOF.equals(tokenValue)) { + error = String.format(translate("UnexpectedEOF"), line, col); //$NON-NLS-1$ + } else if (ParserConstants.EOL.equals(tokenValue)) { + error = String.format(translate("UnexpectedEOL"), line, col); //$NON-NLS-1$ + } else { + error = String.format(translate("UnexpectedTokenAt"), STYLE_TOKEN, //$NON-NLS-1$ + escapeHtml(tokenValue), line, col); + } + + syntaxErrors.add(error); + } + + /** + * Handle the deletion of unexpected tokens. Here an error message is + * appended to the last error message to give the user a hint. + */ + @Override + public void unexpectedTokenRemoved(Symbol token) { + extendLastErrorMessage(translate("RemoveThisToken")); //$NON-NLS-1$ + } + + /** + * Helper method that appends a string to the last element of the syntax + * error list. + * + * @param extension + * the string to append + */ + protected void extendLastErrorMessage(String extension) { + int replacePosition = syntaxErrors.size() - 1; + + if (replacePosition >= 0) { + String error = syntaxErrors.get(replacePosition) + " " + extension; //$NON-NLS-1$ + syntaxErrors.set(replacePosition, error); + } + } + + /** + * Specific implementation of C0 error events to give the user better hints + * how to recover from a syntax error. + */ + private static class C0ErrorEvents extends ErrorEvents { + /** + * Contains a mapping of hints for terminal symbols that should be + * inserted by the user. + */ + private static final Map hints; + + static { + final Map m = new HashMap(); + + final String insertRelation = translate("InsertRelation"); //$NON-NLS-1$ + m.put(GeneratedC00Parser.Terminals.EQ, insertRelation); + m.put(GeneratedC00Parser.Terminals.NE, insertRelation); + m.put(GeneratedC00Parser.Terminals.LE, insertRelation); + m.put(GeneratedC00Parser.Terminals.GE, insertRelation); + m.put(GeneratedC00Parser.Terminals.LT, insertRelation); + m.put(GeneratedC00Parser.Terminals.GT, insertRelation); + + m.put(GeneratedC00Parser.Terminals.AMP, translate("InsertAmp")); //$NON-NLS-1$ + m.put(GeneratedC00Parser.Terminals.COMMA, translate("InsertComma")); //$NON-NLS-1$ + m.put(GeneratedC00Parser.Terminals.ASSIGN, translate("InsertAssign")); //$NON-NLS-1$ + m.put(GeneratedC00Parser.Terminals.SEMICOLON, + translate("InsertSemicolon")); //$NON-NLS-1$ + + m.put(GeneratedC00Parser.Terminals.IDENT, translate("InsertIdent")); //$NON-NLS-1$ + m.put(GeneratedC00Parser.Terminals.NUMBER, translate("InsertNumber")); //$NON-NLS-1$ + + hints = Collections.unmodifiableMap(m); + } + + @Override + public void missingTokenInserted(Symbol token) { + final Short id = token.getId(); + if (hints.containsKey(id)) { + extendLastErrorMessage(hints.get(id)); + } + } + } + + /** + * Indicates that an error can be recovered if {@code token} is inserted at + * the position of the syntax error. + */ + @Override + public abstract void missingTokenInserted(Symbol token); + + /** + * Indicates that an error can be recovered if the error token is replaced + * by {@code token}. + */ + @Override + public void misspelledTokenReplaced(Symbol token) { + } + + @Override + public void errorPhraseRemoved(Symbol error) { + } + + /** + * Used to collect string to int conversion errors because of too large + * integers. + * + * @param number + * the string containing the number that was too large to convert + * @param line + * the line on which the error occured + * @param col + * the column in which the error occured + */ + public void conversionError(final String number, final int line, + final int col) { + lexicalErrors.add(String.format(translate("NumberTooLarge"), + STYLE_TOKEN, escapeHtml(number), line, col, Integer.MAX_VALUE)); + } + + /** + * Get the total amount of errors collected. + * + * @return total amount of errors + */ + private int getErrorCount() { + return lexicalErrors.size() + syntaxErrors.size(); + } + + /** + * Check wether an error occured during parsing. + * + * @return {@code true}, if there was at least one error, otherwise + * {@code false} + */ + public boolean hasErrors() { + // update internal state + finishScannerErrorLine(); + return getErrorCount() > 0; + } + + /** + * Get a summarizing error text (HTML formatted) for all the errors that + * occured during parsing or {@code null}, if no error occured. Use + * {@link #hasErrors()} to check if errors occured. + * + * @return summarizing error text or {@code null}, if no error occured + */ + public String getErrorText() { + if (!hasErrors()) { + return null; + } + + StringBuilder result = new StringBuilder("

          "); // $NON-NLS-1$ + + if (getErrorCount() > 1) { + result.append(String.format(translate("FollowingErrors"), + STYLE_ERROR)); // $NON-NLS-1$ + } else { + result.append(String.format(translate("FollowingError"), + STYLE_ERROR)); // $NON-NLS-1$ + } + + result.append("
          "); // $NON-NLS-1$ + final String itemFormat = " - %s: %s
          "; //$NON-NLS-1$ + + for (String error : lexicalErrors) { + result.append(String.format(itemFormat, + translate("LexicalAnalysis"), error)); //$NON-NLS-1$ + } + + for (String error : syntaxErrors) { + result.append(String.format(itemFormat, + translate("SyntacticAnalysis"), error)); //$NON-NLS-1$ + } + + result.append("

          "); //$NON-NLS-1$ + + return result.toString(); + } + + /** + * Get a fresh {@link ErrorEvents} instance specialized for C0 parsers. + * + * @return a new {@link ErrorEvents} instance + */ + public static ErrorEvents createReport() { + return new C0ErrorEvents(); + } + + /** + * Convenience method to get translated strings for this class. + * + * @see Messages + * @param index + * the index name of the externalized string + * @return the translation + */ + protected static String translate(String index) { + return Messages.getString("c0h0", "ErrorEvents." + index); //$NON-NLS-1$ $NON-NLS-2$ + } +} diff --git a/src/org/jalgo/module/c0h0/parser/GeneratedC00Parser.java b/src/org/jalgo/module/c0h0/parser/GeneratedC00Parser.java new file mode 100644 index 0000000..e518841 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/GeneratedC00Parser.java @@ -0,0 +1,494 @@ +package org.jalgo.module.c0h0.parser; + +import org.jalgo.module.c0h0.models.ast.Number; +import beaver.*; +import beaver.Symbol; +import org.jalgo.module.c0h0.models.ast.*; + +/** + * This class is a LALR parser generated by + * Beaver v0.9.6.1 + * from the grammar specification "c00-parser.g". + */ +public class GeneratedC00Parser extends Parser { + /** + * terminal symbols (constant declarations) + * + */ + static public class Terminals { + static public final short EOF = 0; + static public final short IDENT = 1; + static public final short SEMICOLON = 2; + static public final short IF = 3; + static public final short WHILE = 4; + static public final short LPAREN = 5; + static public final short PLUS = 6; + static public final short MINUS = 7; + static public final short RBRACKET = 8; + static public final short LBRACKET = 9; + static public final short NUMBER = 10; + static public final short RPAREN = 11; + static public final short EQ = 12; + static public final short NE = 13; + static public final short LE = 14; + static public final short GE = 15; + static public final short LT = 16; + static public final short GT = 17; + static public final short MULT = 18; + static public final short DIV = 19; + static public final short MOD = 20; + static public final short RETURN = 21; + static public final short COMMA = 22; + static public final short ELSE = 23; + static public final short INT = 24; + static public final short PRINTF = 25; + static public final short INCLUDE = 26; + static public final short STDIO = 27; + static public final short MAIN = 28; + static public final short SCANF = 29; + static public final short IFORMAT = 30; + static public final short AMP = 31; + static public final short DFORMAT = 32; + static public final short ASSIGN = 33; + } + + static final ParsingTables PARSING_TABLES = new ParsingTables( + "U9orbLbiLKKOn$$dtjvosrlQidIphQMtz9RQ1P15G055PH4L1554G4751TIwMuc9yOt49ry" + + "C8IR6#AWFlXY83oQ#QL5H4Tnn5rHG4LHS67zdpjpJqtlFhS74a$pcMsVEp3TdvaZU6hLgeL" + + "gqG5FKhRFKf0krN5brQB8wbLENpb6FUcrqeTh8cruosaxql9BHQKJdbupErW8pL39w0NsJ9" + + "QABj8vePKmqlvgyl5e9FQHBaNbFcQxJE2t5KuKsNbirLkjrTnY$mewzEjBZR4rIIciAFEMw" + + "iS0pHhT6F7tMbzPKdQivM8FgrmndpL85LfyociaCyXdL#6f2grRzneJMH68JGgiUgyvP$bl" + + "wYzPzYVKtQ4d1V2vplHhDgPXUAtMHRjQgq6xMnRfU6uhoRg22YxMvoBz5SwdfxN2#bj5U1V" + + "Dq3UqcNQuhTPjMqFDQhQNTg9jeRz4TjDjqf#uoftMl1dIVxj7zUa0Fwc4zmku5ErnETJsi9" + + "FjNnOvLKwbQUewdAXDjDCZB$6$Htb6ZpQD64p7H$6hoie8grlEzL8IUHhxlhFNaa4ryzzre" + + "hM4y63lQeulJqLBaIHLvCYCydlLLa1TKkP6JvJahnRdohHxQfZ2Z3YiHMcaiXTOah5HeULZ" + + "rplBVKXcpxc16XVD9kru9#xRYNYbRcxpTpWXHUpWlooc8ytisFyiuVdLzAfsMOgoShNsGqM" + + "2reAsZVvhL#cjguqHvv2RiEgNjZya#ws4kR857uMbu1fw7Ps6Jozi6By1BC0IlmtuNEm1xO" + + "2ySWYDWuAYB$m8l6cDEEtitp8DNOPdlErDuNeEnJdyvujy7BO7kzKRy1w5dv1YUNvjFaVuN" + + "SHW6q3F87s3GzJlfScVHd49EWwIBxK0V4td7aqwcyC#9#DUwCMgW1nemTZbVSsG#$T21yfo" + + "pkoAn6R045i5oM0hJOJPCXHMm65Qw$5LEhexCeockbYxsb9CxOGDiB9NxRx3Fr5G3JZ#E6F" + + "Gd0e$$b$5uQk6967yRl1BZfuuQYl7FTzBVtyrEFy7Kgfnk8hbR0ndi3x8QMeRZtZWdMmlUu" + + "Sw4r#PaEqnmUdPahZSPwftUELeDpWIUxOfvp9yZh9C5qHDESbRD#$2sEMWEcFVCVlEkUSVi" + + "Cs#PDyqRPg$vqdnXypw7pymXgxFVvXFpiTK$CX#Q3wmMjCTj#oCSpNlDDrRxsdn5#xi$5$E" + + "R#HLv37woiU$XMtFO$6mjziiSCT$5hOh87$0N$8qnapzV3LJp9qX0ady1vvuRj9lREOSlnt" + + "sQuslqzQozLykWtDwjMNAozXPEsnjsMERzFfb8RZb$DS#HX8IZh40FSZh8wR9$Z68wYKr15" + + "jBt3ppeIBW="); + + public ErrorEvents getErrorEvents() { + return (ErrorEvents) report; + } + private int convertToInt(String str) { + return Integer.parseInt(str); + } + + private final Action[] actions; + + public GeneratedC00Parser() { + super(PARSING_TABLES); + actions = new Action[] { + new Action() { // [0] Program = INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c Block.b PrintfStatement.p RETURN SEMICOLON RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 8]; + final Declaration d = (Declaration) _symbol_d.value; + final Symbol _symbol_c = _symbols[offset + 10]; + final ScanfSequence c = (ScanfSequence) _symbol_c.value; + final Symbol _symbol_b = _symbols[offset + 11]; + final Block b = (Block) _symbol_b.value; + final Symbol _symbol_p = _symbols[offset + 12]; + final PrintfStatement p = (PrintfStatement) _symbol_p.value; + return new Symbol(new Program(d, c, b, p)); + } + }, + new Action() { // [1] Program = INCLUDE STDIO INT MAIN LPAREN RPAREN LBRACKET Declaration.d SEMICOLON ScanfSequence.c PrintfStatement.p RETURN SEMICOLON RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 8]; + final Declaration d = (Declaration) _symbol_d.value; + final Symbol _symbol_c = _symbols[offset + 10]; + final ScanfSequence c = (ScanfSequence) _symbol_c.value; + final Symbol _symbol_p = _symbols[offset + 11]; + final PrintfStatement p = (PrintfStatement) _symbol_p.value; + return new Symbol(new Program(d, c, null, p)); + } + }, + new Action() { // [2] Declaration = INT IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + return new Symbol(new Declaration(new Var(i))); + } + }, + new Action() { // [3] Declaration = Declaration.d COMMA IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_d = _symbols[offset + 1]; + final Declaration d = (Declaration) _symbol_d.value; + final Symbol _symbol_i = _symbols[offset + 3]; + final String i = (String) _symbol_i.value; + d.addVariable(new Var(i)); return new Symbol(d); + } + }, + new Action() { // [4] ScanfSequence = + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(new ScanfSequence()); + } + }, + new Action() { // [5] ScanfSequence = ScanfSequence.s SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_s = _symbols[offset + 1]; + final ScanfSequence s = (ScanfSequence) _symbol_s.value; + final Symbol _symbol_i = _symbols[offset + 7]; + final String i = (String) _symbol_i.value; + s.addScanf(new Var(i)); return new Symbol(s); + } + }, + new Action() { // [6] PrintfStatement = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 5]; + final String i = (String) _symbol_i.value; + return new Symbol(new PrintfStatement(new Var(i))); + } + }, + new Action() { // [7] Block = LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(new Block(true)); + } + }, + new Action() { // [8] Block = LBRACKET Block.b Statement.stat RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_b = _symbols[offset + 2]; + final Block b = (Block) _symbol_b.value; + final Symbol _symbol_stat = _symbols[offset + 3]; + final Statement stat = (Statement) _symbol_stat.value; + b.addStatement(stat); return new Symbol(b); + } + }, + new Action() { // [9] Block = Statement.stat + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_stat = _symbols[offset + 1]; + final Statement stat = (Statement) _symbol_stat.value; + return new Symbol(new Block(stat, true)); + } + }, + new Action() { // [10] Block = Block.b Statement.stat + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_b = _symbols[offset + 1]; + final Block b = (Block) _symbol_b.value; + final Symbol _symbol_stat = _symbols[offset + 2]; + final Statement stat = (Statement) _symbol_stat.value; + b.addStatement(stat); return new Symbol(b); + } + }, + new Action() { // [11] Statement = SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(new Statement()); + } + }, + new Action() { // [12] Statement = IDENT.i ASSIGN Term.t SEMICOLON + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 1]; + final String i = (String) _symbol_i.value; + final Symbol _symbol_t = _symbols[offset + 3]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new Assignment(new Var(i), t)); + } + }, + new Action() { // [13] Statement = IF LPAREN Relation.r RPAREN LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + return new Symbol(new If(r, new Block(true), new Block(false))); + } + }, + new Action() { // [14] Statement = IF LPAREN Relation.r RPAREN Statement.s + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s = _symbols[offset + 5]; + final Statement s = (Statement) _symbol_s.value; + return new Symbol(new If(r, new Block(s, false), new Block(false))); + } + }, + new Action() { // [15] Statement = IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_b = _symbols[offset + 6]; + final Block b = (Block) _symbol_b.value; + return new Symbol(new If(r, b)); + } + }, + new Action() { // [16] Statement = IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + return new Symbol(new If(r, new Block(true), new Block(true))); + } + }, + new Action() { // [17] Statement = IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE Statement.s2 + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s2 = _symbols[offset + 8]; + final Statement s2 = (Statement) _symbol_s2.value; + return new Symbol(new If(r, new Block(true), new Block(s2, false))); + } + }, + new Action() { // [18] Statement = IF LPAREN Relation.r RPAREN LBRACKET RBRACKET ELSE LBRACKET Block.s2 RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s2 = _symbols[offset + 9]; + final Block s2 = (Block) _symbol_s2.value; + return new Symbol(new If(r, new Block(true), s2)); + } + }, + new Action() { // [19] Statement = IF LPAREN Relation.r RPAREN Statement.s ELSE LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s = _symbols[offset + 5]; + final Statement s = (Statement) _symbol_s.value; + return new Symbol(new If(r, new Block(s, false), new Block(true))); + } + }, + new Action() { // [20] Statement = IF LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET ELSE LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_b = _symbols[offset + 6]; + final Block b = (Block) _symbol_b.value; + return new Symbol(new If(r, b, new Block(true))); + } + }, + new Action() { // [21] Statement = IF LPAREN Relation.r RPAREN Statement.s1 ELSE Statement.s2 + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s1 = _symbols[offset + 5]; + final Statement s1 = (Statement) _symbol_s1.value; + final Symbol _symbol_s2 = _symbols[offset + 7]; + final Statement s2 = (Statement) _symbol_s2.value; + return new Symbol(new If(r, new Block(s1, false), new Block(s2, false))); + } + }, + new Action() { // [22] Statement = IF LPAREN Relation.r RPAREN Statement.s1 ELSE LBRACKET Block.s2 RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s1 = _symbols[offset + 5]; + final Statement s1 = (Statement) _symbol_s1.value; + final Symbol _symbol_s2 = _symbols[offset + 8]; + final Block s2 = (Block) _symbol_s2.value; + return new Symbol(new If(r, new Block(s1, false), s2)); + } + }, + new Action() { // [23] Statement = IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE Statement.s2 + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s1 = _symbols[offset + 6]; + final Block s1 = (Block) _symbol_s1.value; + final Symbol _symbol_s2 = _symbols[offset + 9]; + final Statement s2 = (Statement) _symbol_s2.value; + return new Symbol(new If(r, s1, new Block(s2, false))); + } + }, + new Action() { // [24] Statement = IF LPAREN Relation.r RPAREN LBRACKET Block.s1 RBRACKET ELSE LBRACKET Block.s2 RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s1 = _symbols[offset + 6]; + final Block s1 = (Block) _symbol_s1.value; + final Symbol _symbol_s2 = _symbols[offset + 10]; + final Block s2 = (Block) _symbol_s2.value; + return new Symbol(new If(r, s1, s2)); + } + }, + new Action() { // [25] Statement = WHILE LPAREN Relation.r RPAREN Statement.s + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_s = _symbols[offset + 5]; + final Statement s = (Statement) _symbol_s.value; + return new Symbol(new While(r, new Block(s, false))); + } + }, + new Action() { // [26] Statement = WHILE LPAREN Relation.r RPAREN LBRACKET Block.b RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + final Symbol _symbol_b = _symbols[offset + 6]; + final Block b = (Block) _symbol_b.value; + return new Symbol(new While(r, b)); + } + }, + new Action() { // [27] Statement = WHILE LPAREN Relation.r RPAREN LBRACKET RBRACKET + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 3]; + final Relation r = (Relation) _symbol_r.value; + return new Symbol(new While(r, new Block(true))); + } + }, + new Action() { // [28] Term = IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 1]; + final String i = (String) _symbol_i.value; + return new Symbol(new Var(i)); + } + }, + new Action() { // [29] Term = NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_n = _symbols[offset + 1]; + final String n = (String) _symbol_n.value; + return new Symbol(new Number(convertToInt(n))); + } + }, + new Action() { // [30] Term = LPAREN Term.t RPAREN + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 2]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new Term(t)); + } + }, + new Action() { // [31] Term = PLUS IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + return new Symbol(new Var(i, UnaryType.PLUS)); + } + }, + new Action() { // [32] Term = PLUS NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_n = _symbols[offset + 2]; + final String n = (String) _symbol_n.value; + return new Symbol(new Number(convertToInt(n), UnaryType.PLUS)); + } + }, + new Action() { // [33] Term = PLUS LPAREN Term.t RPAREN + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 3]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new Term(t, UnaryType.PLUS)); + } + }, + new Action() { // [34] Term = MINUS IDENT.i + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_i = _symbols[offset + 2]; + final String i = (String) _symbol_i.value; + return new Symbol(new Var(i, UnaryType.MINUS)); + } + }, + new Action() { // [35] Term = MINUS NUMBER.n + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_n = _symbols[offset + 2]; + final String n = (String) _symbol_n.value; + return new Symbol(new Number(convertToInt(n), UnaryType.MINUS)); + } + }, + new Action() { // [36] Term = MINUS LPAREN Term.t RPAREN + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_t = _symbols[offset + 3]; + final Term t = (Term) _symbol_t.value; + return new Symbol(new Term(t, UnaryType.MINUS)); + } + }, + new Action() { // [37] Term = Operation.o + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_o = _symbols[offset + 1]; + final Operation o = (Operation) _symbol_o.value; + return new Symbol(o); + } + }, + new Action() { // [38] Term = Relation.r + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_r = _symbols[offset + 1]; + final Relation r = (Relation) _symbol_r.value; + return new Symbol(r); + } + }, + new Action() { // [39] Relation = Term.l RelationType.rel Term.r + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_l = _symbols[offset + 1]; + final Term l = (Term) _symbol_l.value; + final Symbol _symbol_rel = _symbols[offset + 2]; + final RelationType rel = (RelationType) _symbol_rel.value; + final Symbol _symbol_r = _symbols[offset + 3]; + final Term r = (Term) _symbol_r.value; + return new Symbol(new Relation(l, rel, r)); + } + }, + new Action() { // [40] RelationType = EQ + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.EQ); + } + }, + new Action() { // [41] RelationType = NE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.NE); + } + }, + new Action() { // [42] RelationType = LE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.LE); + } + }, + new Action() { // [43] RelationType = GE + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.GE); + } + }, + new Action() { // [44] RelationType = LT + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.LT); + } + }, + new Action() { // [45] RelationType = GT + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(RelationType.GT); + } + }, + new Action() { // [46] Operation = Term.l OperationType.op Term.r + public Symbol reduce(Symbol[] _symbols, int offset) { + final Symbol _symbol_l = _symbols[offset + 1]; + final Term l = (Term) _symbol_l.value; + final Symbol _symbol_op = _symbols[offset + 2]; + final OperationType op = (OperationType) _symbol_op.value; + final Symbol _symbol_r = _symbols[offset + 3]; + final Term r = (Term) _symbol_r.value; + return new Symbol(new Operation(l, op, r)); + } + }, + new Action() { // [47] OperationType = PLUS + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(OperationType.ADD); + } + }, + new Action() { // [48] OperationType = MINUS + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(OperationType.SUB); + } + }, + new Action() { // [49] OperationType = MULT + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(OperationType.MUL); + } + }, + new Action() { // [50] OperationType = DIV + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(OperationType.DIV); + } + }, + new Action() { // [51] OperationType = MOD + public Symbol reduce(Symbol[] _symbols, int offset) { + return new Symbol(OperationType.MOD); + } + } + }; + + + this.report = ErrorEvents.createReport(); + } + + protected Symbol invokeReduceAction(int rule_num, int offset) { + return actions[rule_num].reduce(_symbols, offset); + } +} diff --git a/src/org/jalgo/module/c0h0/parser/ParserConstants.java b/src/org/jalgo/module/c0h0/parser/ParserConstants.java new file mode 100644 index 0000000..c6e5022 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/ParserConstants.java @@ -0,0 +1,25 @@ +package org.jalgo.module.c0h0.parser; + +/** + * Set of constants that are used by the parser package. + * + */ +public final class ParserConstants { + /** + * This class is not designed to be instantiated, therefore it's constructor + * is private. + */ + private ParserConstants() { + throw new AssertionError(); + } + + /** + * Constant used as the value for end-of-file symbols (i.e. tokens). + */ + public static final String EOF = "end-of-file"; + + /** + * Constant used as the value for end-of-line symbols (i.e. tokens). + */ + public static final String EOL = "end-of-line"; +} diff --git a/src/org/jalgo/module/c0h0/parser/package-info.java b/src/org/jalgo/module/c0h0/parser/package-info.java new file mode 100644 index 0000000..a001510 --- /dev/null +++ b/src/org/jalgo/module/c0h0/parser/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes, which scan and parse c00-code + */ +package org.jalgo.module.c0h0.parser; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/res.properties b/src/org/jalgo/module/c0h0/res.properties new file mode 100644 index 0000000..302fe7e --- /dev/null +++ b/src/org/jalgo/module/c0h0/res.properties @@ -0,0 +1,14 @@ +HelpSet_Name=/help/jhelp/c0h0_help.hs + +logo=/c0h0_pix/logo16.png + +viewC0FlowIcon=/c0h0_pix/viewstateC0Flow.png +viewC0H0Icon=/c0h0_pix/viewstateC0H0.png +viewFlowH0Icon=/c0h0_pix/viewstateFlowH0.png + +transViewOnIcon=/c0h0_pix/transviewOn16.png +transViewOffIcon=/c0h0_pix/transviewOff16.png + +newButtonIcon=/c0h0_pix/newButtonIcon.png +loadButtonIcon=/c0h0_pix/loadButtonIcon.png +exampleButtonIcon=/c0h0_pix/exampleButtonIcon.png diff --git a/src/org/jalgo/module/c0h0/tests/AddressVisitorTest.java b/src/org/jalgo/module/c0h0/tests/AddressVisitorTest.java new file mode 100644 index 0000000..6d0b7f9 --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/AddressVisitorTest.java @@ -0,0 +1,110 @@ +package org.jalgo.module.c0h0.tests; + +import static org.junit.Assert.*; + +import java.util.ArrayList; + +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.ast.Statement; +import org.jalgo.module.c0h0.models.ast.Symbol; +import org.jalgo.module.c0h0.models.ast.tools.BFSIterator; +import org.jalgo.module.c0h0.models.ast.tools.Iterable; +import org.jalgo.module.c0h0.models.c0model.AddressVisitor; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * tests the address visitor + * + */ +public class AddressVisitorTest{ + private static ASTModel ast; + private static AddressVisitor addressV; + private static String programHead, programOutput; + + @BeforeClass + public static void setUpBeforeClass() { + addressV = new AddressVisitor(); + programHead = "#include " + + "int main() {" + + "int x1;" + + "scanf(\"%i\", &x1);"; + programOutput = "printf(\"%d\", x1);" + + "return 0;" + + "}"; + String text = programHead + + "while(x1 > 3) {" // f1 // f11 + + "if(x1 < 7) {" // f111 // f1111 + + "x1 = x1 - 2;" // f11111 + + "}else x1 = x1 - 1;" // f1112 // f11121 + + "}" + + "x1 = x1;" // f2 + + programOutput; + //TODO maybe load .c0 file instead? + ast = new ASTModel(); + ast.create(text); + + // make sure, DFS is used + BFSIterator it = new BFSIterator(ast); // body only + while (it.hasNext()) { + Symbol s = it.next(); + s.accept(addressV); + } + } + + /** + * Test for Addresses + */ + @Test + public void firstBlockTest() { + ArrayList arr = ast.getProgram().getBlock().getStatementList(); + for(int i=1; i<=arr.size(); i++) { + assertTrue(("f"+i).equals(arr.get(i-1).getAddress())); + } + } + + @Test + public void ifBlockTest() { + ArrayList arr = ast.getProgram().getBlock().getSequence(); + // go to block + arr = arr.get(0).getSequence(); + // go to while + arr = arr.get(0).getSequence(); + // go to if + arr = arr.get(0).getSequence(); + // test if block + assertTrue("f1111".equals(((Symbol) arr.get(0)).getAddress())); + } + + @Test + public void elseBlockTest() { + ArrayList arr = ast.getProgram().getBlock().getSequence(); + // go to block + arr = arr.get(0).getSequence(); + // go to while + arr = arr.get(0).getSequence(); + // go to if + arr = arr.get(0).getSequence(); + // test else block + assertTrue("f1112".equals(((Symbol) arr.get(1)).getAddress())); + // go to assignment in else block + arr = arr.get(1).getSequence(); + assertTrue("f11121".equals(((Symbol) arr.get(0)).getAddress())); + } + + @Test + public void advancedIfBlockTest() { + ArrayList arr = ast.getProgram().getBlock().getSequence(); + // go to block + arr = arr.get(0).getSequence(); + // go to while + arr = arr.get(0).getSequence(); + // go to if + arr = arr.get(0).getSequence(); + // test if block + assertTrue("f1111".equals(((Symbol) arr.get(0)).getAddress())); + // go to assignment in if block + arr = arr.get(0).getSequence(); + assertTrue("f11111".equals(((Symbol) arr.get(0)).getAddress())); + } +} diff --git a/src/org/jalgo/module/c0h0/tests/C00ParserTest.java b/src/org/jalgo/module/c0h0/tests/C00ParserTest.java new file mode 100644 index 0000000..493cbf4 --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/C00ParserTest.java @@ -0,0 +1,109 @@ +package org.jalgo.module.c0h0.tests; + +import static org.junit.Assert.*; + +import org.jalgo.module.c0h0.parser.C00Parser; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * tests the c00 parser + * + */ +public class C00ParserTest{ + private static C00Parser parser; + private static String programHead, programOutput; + + @BeforeClass + public static void setUpBeforeClass(){ + parser = new C00Parser(); + programHead = "#include " + + "int main() {" + + "int x1;" + + "scanf(\"%i\", &x1);"; + programOutput = "printf(\"%d\", x1);" + + "return 0;" + + "}"; + } + + /** + * Spezielle Spezialfaelle speziell testen + */ + + @Test + public void testValidStandardForm(){ + String text = programHead + programOutput; + assertTrue(parser.parse(text)); + } + + @Test + public void testAssignmentTerms(){ + String text = programHead + + "x1 = x1 + 1;" + + "x1 = -x1 + 1;" + + "x1 = (-3 < 2) * 2;" + + "x1 = (3 * -2) - 3;" + + "x1 = (2 < 3) > 4;" + + "x1 = -(3 - 2) / 3;" + + "x1 = -(3 < 2) % 2;" + + programOutput; + assertTrue(parser.parse(text)); + } + + @Test + public void testIfStatement(){ + String text = programHead + + "if(x1 > 1) x1 = 1;" + + "if(x1 == 2) ;" + + "if(x1 <= 3) { x1 = 2; }" + + "if(x1 >= 4) { x1 = 3; }else{ x1 = 4; }" + + "if(x1 != 5) x1 = 5; else x1 = 6;" + + "if(x1 < 6) { x1 = 7; }else x1 = 8;" + + "if((3 % 5) < 2) x1 = 9; else{ x1 = 10;}" + + programOutput; + assertTrue(parser.parse(text)); + } + + @Test + public void testWhileStatement(){ + String text = programHead + + "while(x1 > 1) x1 = 1;" + + "while(x1 == 2) ;" + + "while(x1 <= 3) { x1 = 2; }" + + programOutput; + assertTrue(parser.parse(text)); + } + + @Test + public void testStatement(){ + String text = programHead + + "while(x1 > 1) x1 = 1;" + + "while(x1 == 2) ;" + + "while(x1 <= 3) { x1 = 2; }" + + programOutput; + assertTrue(parser.parse(text)); + } + + @Test + public void testInvalidCode() { + String text = programHead + + "x1 = 1 (/3); " + + programOutput; + assertFalse(parser.parse(text)); + + text = programHead + + "x12 = 1 (+3); " + + programOutput; + assertFalse(parser.parse(text)); + + text = programHead + + "x1b = 1 / 3; " + + programOutput; + assertFalse(parser.parse(text)); + } +} + + + + + diff --git a/src/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.java b/src/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.java new file mode 100644 index 0000000..e7db240 --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/C0GeneratingVisitorTest.java @@ -0,0 +1,71 @@ +package org.jalgo.module.c0h0.tests; + +import static org.junit.Assert.*; + +import java.util.LinkedList; + +import org.jalgo.module.c0h0.models.ast.*; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; +import org.jalgo.module.c0h0.models.c0model.C0GeneratingVisitor; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * tests the c0 generating visitor + * + */ +public class C0GeneratingVisitorTest { + private static ASTModel ast; + private static C0GeneratingVisitor visitor; + private static DFSIterator iterator; + private static String programHead, programField, programOutput; + + @BeforeClass + public static void setUpBeforeClass() { + ast = new ASTModel(); + visitor = new C0GeneratingVisitor(); + programHead = "#include " + "int main() {" + "int x1;" + + "scanf(\"%i\", &x1);"; + programField = ""; + programOutput = "printf(\"%d\", x1);" + "return 0;" + "}"; + } + + /** + * Spezielle Spezialfaelle speziell testen + */ + + private void createAST() { + ast.create(programHead + programField + programOutput); + iterator = new DFSIterator(ast); + while (iterator.hasNext()) { + iterator.next().accept(visitor); + } + } + + @Test + public void testAddressCount() { + programField = "x1 = x1 + 1;" + "x1 = -x1 + 1;" + "x1 = (-3 < 2) * 2;" + + "x1 = (3 * -2) - 3;" + "x1 = (2 < 3) > 4;" + + "x1 = -(3 - 2) / 3;" + "x1 = -(3 < 2) % 2;"; + createAST(); + assertEquals(7, visitor.getAddressCount()); + } + + @Test + public void testResultingAddresssList() { + programField = "if(x1 > 1) x1 = 1;"; + createAST(); + LinkedList prefResult = new LinkedList(); + prefResult.add("f1"); + prefResult.add("f11"); + assertTrue(visitor.getAddressList().containsAll(prefResult)); + } + + @Test + public void testResultingCode() { + programField = "while(x1 > 7){x1 = x1 - 2;}x1 = x1 + 2;"; + createAST(); + String result = "
            while (x1 > 7)
            {
              x1 = x1 - 2;
            }
            x1 = x1 + 2;
          "; + assertFalse(visitor.getCode().equals(result)); + } +} diff --git a/src/org/jalgo/module/c0h0/tests/CVS/Entries b/src/org/jalgo/module/c0h0/tests/CVS/Entries new file mode 100644 index 0000000..aaba490 --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/CVS/Entries @@ -0,0 +1,6 @@ +/AddressVisitorTest.java/1.1/Sat Mar 5 14:12:06 2011// +/C00ParserTest.java/1.1/Sat Mar 5 14:12:06 2011// +/C0GeneratingVisitorTest.java/1.1/Sat Mar 5 14:12:06 2011// +/FcVisitorTest.java/1.1/Sat Mar 5 14:12:06 2011// +/H0GeneratingTest.java/1.1/Sat Mar 5 14:12:06 2011// +/package-info.java/1.1/Sat Mar 5 14:12:06 2011// diff --git a/src/org/jalgo/module/c0h0/tests/CVS/Repository b/src/org/jalgo/module/c0h0/tests/CVS/Repository new file mode 100644 index 0000000..2e1832c --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/tests diff --git a/src/org/jalgo/module/c0h0/tests/CVS/Root b/src/org/jalgo/module/c0h0/tests/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/tests/FcVisitorTest.java b/src/org/jalgo/module/c0h0/tests/FcVisitorTest.java new file mode 100644 index 0000000..114209a --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/FcVisitorTest.java @@ -0,0 +1,84 @@ +package org.jalgo.module.c0h0.tests; + +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.ast.PrintfStatement; +import org.jalgo.module.c0h0.models.ast.Var; +import org.jalgo.module.c0h0.models.ast.tools.DFSIterator; +import org.jalgo.module.c0h0.models.flowchart.FcGeneratingVisitor; +import org.junit.Test; +import static org.junit.Assert.*; + + +/** + * tests the flow chart visitor + * + */ +public class FcVisitorTest { + private static FcGeneratingVisitor fcVisitor; + private static ASTModel ast; + + @Test + public void testStepNumber(){ + + String programHead = "#include " + + "int main() {" + + "int x1;" + + "scanf(\"%i\", &x1);"; + String programOutput = "printf(\"%d\", x1);" + + "return 0;" + + "}"; + String text = programHead + + "while(x1 > 3) {" // f1 // f11 + + "if(x1 < 7) {" // f111 // f1111 + + "x1 = x1 - 2;" // f11111 + + "}else x1 = x1 - 1;" // f1112 // f11121 + + "}" + + "x1 = x1;" // f2 + + programOutput; + ast = new ASTModel(); + ast.create(text); + + fcVisitor = new FcGeneratingVisitor(); + DFSIterator iter = new DFSIterator(ast); + while (iter.hasNext()) { + iter.next().accept(fcVisitor); + } + + PrintfStatement p = new PrintfStatement(new Var("x1")); + p.setAddress("f3"); + assertTrue(fcVisitor.getElementList(p).size()==8); + } + + @Test + public void testStepNumberIf(){ + + String programHead = "#include " + + "int main() {" + + "int x1;" + + "scanf(\"%i\", &x1);"; + String programOutput = "printf(\"%d\", x1);" + + "return 0;" + + "}"; + String text = programHead + + "if(x1 > 1) x1 = 1;" + + "if(x1 == 2) x1 = 1;" + + "if(x1 <= 3) { x1 = 2; }" + + "if(x1 >= 4) { x1 = 3; }else{ x1 = 4; }" + + "if(x1 != 5) x1 = 5; else x1 = 6;" + + "if(x1 < 6) { x1 = 7; }else x1 = 8;" + + "if((3 % 5) < 2) x1 = 9; else{ x1 = 10;}" + + programOutput; + ast = new ASTModel(); + ast.create(text); + + fcVisitor = new FcGeneratingVisitor(); + DFSIterator iter = new DFSIterator(ast); + while (iter.hasNext()) { + iter.next().accept(fcVisitor); + } + + PrintfStatement p = new PrintfStatement(new Var("x1")); + p.setAddress("f3"); + assertTrue(fcVisitor.getElementList(p).size()==24); + } +} diff --git a/src/org/jalgo/module/c0h0/tests/H0GeneratingTest.java b/src/org/jalgo/module/c0h0/tests/H0GeneratingTest.java new file mode 100644 index 0000000..5e4dd4c --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/H0GeneratingTest.java @@ -0,0 +1,141 @@ +/** + * + */ +package org.jalgo.module.c0h0.tests; + +import static org.junit.Assert.*; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.models.ast.ASTModel; +import org.jalgo.module.c0h0.models.h0model.H0CodeModel; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * tests the H0 generating visitor + * + * @author Peter Schwede + * + */ +public class H0GeneratingTest{ + private static H0CodeModel model; + private static ASTModel ast; + + @BeforeClass + public static void setUpBeforeClass() { + ast = new ASTModel(); + model = new H0CodeModel(new Controller(null, null, null)); + } + + @Test + public void emptyCodeTest() { + ast.create(""); + model.generate(); + if (ast.isValid()) + assertTrue("".equals(model.getCode())); + } + + @Test + public void simpleCodeTest() { + ast.create("#include " + "int main() {" + "int x1;" + + "scanf(\"%i\", &x1);" + "x1 = x1 + 1;" + "x1 = -x1 + 1;" + + "x1 = (-3 < 2) * 2;" + "x1 = (3 * -2) - 3;" + + "x1 = (2 < 3) > 4;" + "x1 = -(3 - 2) / 3;" + + "x1 = -(3 < 2) % 2;" + "printf(\"%d\", x1);" + "return 0;" + + "}"); + model.generate(); + if (ast.isValid()) { + assertTrue(("module Main where\n" + "f1 :: Int -> Int\n" + + "f1 x1 = f2 (x1 + 1)\n" + "f2 :: Int -> Int\n" + + "f2 x1 = f3 (-x1 + 1)\n" + "f3 :: Int -> Int\n" + + "f3 x1 = f4 ((-3 < 2) * 2)\n" + "f4 :: Int -> Int\n" + + "f4 x1 = f5 ((3 * -2) - 3)\n" + "f5 :: Int -> Int\n" + + "f5 x1 = f6 ((2 < 3) > 4)\n" + "f6 :: Int -> Int\n" + + "f6 x1 = f7 (-(3 - 2) div 3)\n" + "f7 :: Int -> Int\n" + + "f7 x1 = f8 (-(3 < 2) mod 2)\n" + "f8 :: Int -> Int\n" + + "f8 x1 = x1\n" + "main = do x1 <- readLn\n" + + " print (f1 x1)\n").equals(model.getCode())); + } + } + + @Test + public void whileCodeTest() { + ast.create("#include " + "int main() {" + "int x1;" + + "scanf(\"%i\", &x1);" + "while(x1 == 1) { x1 = x1 - 1; }" + + "printf(\"%d\", x1);" + "return 0;" + "}"); + model.generate(); + String code = "module Main where\n" + "f1 :: Int -> Int\n" + + "f1 x1 = if (x1 == 1) then f11 x1\n" + + " else f2 x1\n" + "f11 :: Int -> Int\n" + + "f11 x1 = f111 x1\n" + "f111 :: Int -> Int\n" + + "f111 x1 = f2 (x1 - 1)\n" + "f2 :: Int -> Int\n" + + "f2 x1 = x1\n" + "main = do x1 <- readLn\n" + + " print (f1 x1)\n"; + if (ast.isValid()) { + assertTrue((code).equals(model.getCode())); + } + } + + @Test + public void ifCodeTest() { + ast.create("#include \n" + "int main() {" + "int x1;\n" + + "scanf(\"%i\", &x1);\n" + "if(x1 == 1) x1 = 2;\n" + + "x1 = 3;\n" + "printf(\"%d\", x1);\n" + "return 0;\n" + "}"); + model.generate(); + String code = "" + "module Main where\n" + + "f1 :: Int -> Int\n" + + "f1 x1 = if (x1 == 1) then f11 x1\n" + + " else f2 x1\n" + + "f11 :: Int -> Int\n" + + "f11 x1 = f111 x1\n" + + "f111 :: Int -> Int\n" + + "f111 x1 = f2 (2)\n" + + "f2 :: Int -> Int\n" + + "f2 x1 = f3 (3)\n" + + "f3 :: Int -> Int\n" + "f3 x1 = x1\n" + + "main = do x1 <- readLn\n" + " print (f1 x1)\n"; + if (ast.isValid()) { + assertTrue((code).equals(model.getCode())); + } + } + + @Test + public void moreComplexCodeTest() { + ast.create("#include \n" + "int main() {" + "int x1;\n" + + "scanf(\"%i\", &x1);\n" + + "while(x1 > 3) {\n" + + "if(x1 < 7) {\n" + + " x1 = x1 - 2;\n" + + "} else x1 = x1 - 1;\n" + + "}" + + "x1 = x1;" + + "printf(\"%d\", x1);\n" + "return 0;\n" + "}"); + model.generate(); + String code = "" + "module Main where\n" + + "f1 :: Int -> Int\n" + + "f1 x1 = if (x1 > 3) then f11 x1\n" + + " else f2 x1\n" + + "f11 :: Int -> Int\n" + + "f11 x1 = f111 x1\n" + + "f111 :: Int -> Int\n" + + "f111 x1 = if (x1 < 7) then f1111 x1\n" + + " else f1112 x1\n" + + "f1111 :: Int -> Int\n" + + "f1111 x1 = f11111 x1\n" + + "f11111 :: Int -> Int\n" + + "f11111 x1 = f2 (x1 - 2)\n" + + "f1112 :: Int -> Int\n" + + "f1112 x1 = f11121 x1\n" + + "f11121 :: Int -> Int\n" + + "f11121 x1 = f2 (x1 - 1)\n" + + "f2 :: Int -> Int\n" + + "f2 x1 = f3 (x1)\n" + + "f3 :: Int -> Int\n" + + "f3 x1 = x1\n" + + "main = do x1 <- readLn\n" + + " print (f1 x1)\n"; + if (ast.isValid()) { + assertTrue((code).equals(model.getCode())); + } + } +} diff --git a/src/org/jalgo/module/c0h0/tests/package-info.java b/src/org/jalgo/module/c0h0/tests/package-info.java new file mode 100644 index 0000000..f2c05ba --- /dev/null +++ b/src/org/jalgo/module/c0h0/tests/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains JUnit test classes + */ +package org.jalgo.module.c0h0.tests; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/views/C0View.java b/src/org/jalgo/module/c0h0/views/C0View.java new file mode 100644 index 0000000..899adc7 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/C0View.java @@ -0,0 +1,236 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; + +import javax.swing.text.DefaultCaret; +import javax.swing.text.html.HTMLDocument; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.InterfaceConstants; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * C0View which contains formatted C0-Code after successfully parsing the Code + * + */ +public class C0View extends View { + private static final long serialVersionUID = 1724259710236167118L; + private TextEditor addressbar, textEditor; + private Controller controller; + private ViewManager viewManager; + private JScrollPane scrollPane; + + private String lastFocusedElement; + private String currentFocus; + + /** + * @param controller + * Controller + * @param viewManager + * ViewManager + */ + public C0View(final Controller controller, ViewManager viewManager) { + // Anlegen der Variablen + this.controller = controller; + this.viewManager = viewManager; + textEditor = new TextEditor(); + addressbar = new TextEditor(); + lastFocusedElement = ""; + currentFocus = ""; + + // Aufbau des Grundskeletts + textEditor.setContentType("text/html"); + addressbar.setContentType("text/html"); + textEditor.setEditable(false); + addressbar.setEditable(false); + textEditor.setBackground(Color.WHITE); + + addressbar.setPreferredSize(new Dimension(80, getHeight())); + addressbar.setBackground(new Color(238, 238, 255)); + + scrollPane = new JScrollPane(); + JPanel innerPane = new JPanel(); + innerPane.setLayout(new BorderLayout()); + innerPane.add(addressbar, BorderLayout.WEST); + innerPane.add(textEditor, BorderLayout.CENTER); + innerPane.doLayout(); + scrollPane.getViewport().setView(innerPane); + + // Layout + setLayout(new BorderLayout()); + add(scrollPane, BorderLayout.CENTER); + doLayout(); + + // Auto-Scrolling off + ((DefaultCaret) textEditor.getCaret()) + .setUpdatePolicy(DefaultCaret.NEVER_UPDATE); + + // Setting Scrollspeed + scrollPane.getVerticalScrollBar().setUnitIncrement(20); + + // Listener + MouseAdapter realListener = new MouseAdapter() { + public void mouseReleased(MouseEvent e) { + if (!currentFocus.equals("")) { + textEditor.fireHyperlinkUpdate(new HyperlinkEvent(this, + HyperlinkEvent.EventType.ACTIVATED, null, + currentFocus)); + } + } + }; + HyperlinkListener listener = new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if (!lastFocusedElement.equals(currentFocus)) { + controller.markNode(currentFocus); + } + } else if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + currentFocus = e.getDescription(); + } else { + currentFocus = ""; + } + } + }; + textEditor.addMouseListener(realListener); + textEditor.addHyperlinkListener(listener); + addressbar.addMouseListener(realListener); + addressbar.addHyperlinkListener(listener); + + setCSS(); + + } + + /** + * Sets all relevant CSS-Rules(is only to be used once in the Constructor!) + */ + private void setCSS() { + TerminalView.println("css set " + + String.valueOf(InterfaceConstants.NORMAL_FONTSIZE)); + // Farbe der Tokens + String tokenRule = ".token { color: #0000FF; }"; + // Einzelne Zellen haengen aneinander + String tableRule = "table { border-collapse: collapse; }"; + // Der Abstand zwischen den Zellen ist 0 + String paddingRule = "table td { padding: 0px; }"; + // Schriftart ist monospace + String fontRule = "body { font-family: 'Courier New'; font-size: " + + InterfaceConstants.NORMAL_FONTSIZE + " pt; }"; + // Links ohne typischem Linkstyle + String aRule = "a { color: #000000; text-decoration: none; }"; + // Head und Foot eingrauen + String grayedRule = "td.grayed { color: #" + + InterfaceConstants.GRAYED_CONTENT + "; }"; + + // Regeln muessen auch in den Editor eingefuegt werden + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + tokenRule); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + tableRule); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + paddingRule); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + fontRule); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet() + .addRule(aRule); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + grayedRule); + + ((HTMLDocument) addressbar.getDocument()).getStyleSheet().addRule( + fontRule); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet().addRule( + tableRule); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet().addRule( + paddingRule); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet() + .addRule(aRule); + } + + /* + * (non-Javadoc) This method is implicitly called in Controller.markNode() + * + * @see org.jalgo.module.c0h0.views.View#render() + */ + public boolean render() { + // MarkedNode bekommt eigene Farbe + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().removeStyle( + "." + lastFocusedElement); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + "." + controller.getASTModel().getMarkedNode() + + " { background-color: #" + + InterfaceConstants.MARKEDCOLOR_ACTIVE + "; }"); + lastFocusedElement = controller.getASTModel().getMarkedNode(); + + // Hole die neuen Adressen + if (controller.getC0CodeModel().isActive() && !controller.getC0CodeModel().isActual()) + addressbar.setText(controller.getC0CodeModel().getAddresses()); + + // Scroll zum Knoten + textEditor.scrollToReference(lastFocusedElement); + + updateUI(); + return true; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.views.View#update() + */ + public boolean update() { + render(); + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().removeStyle( + "body"); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet().removeStyle( + "body"); + if (viewManager.isBeamerMode()) { + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + "body { font-family: 'Courier New'; font-size: " + + InterfaceConstants.BEAMERMODE_FONTSIZE + + " pt; background-color:" + + viewManager.backgroundColor(controller + .getC0CodeModel().isActive()) + ";}"); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet() + .addRule( + "body { font-family: 'Courier New'; font-size: " + + InterfaceConstants.BEAMERMODE_FONTSIZE + + " pt; }"); + addressbar.setPreferredSize(new Dimension(controller.getASTModel() + .getMaxDepth() + * InterfaceConstants.BEAMERMODE_FONTSIZE * 5 / 8 + 5, + getHeight() - 20)); + } else { + ((HTMLDocument) textEditor.getDocument()).getStyleSheet().addRule( + "body { font-family: 'Courier New'; font-size: " + + InterfaceConstants.NORMAL_FONTSIZE + + " pt; background-color:" + + viewManager.backgroundColor(controller + .getC0CodeModel().isActive()) + ";}"); + ((HTMLDocument) addressbar.getDocument()).getStyleSheet().addRule( + "body { font-family: 'Courier New'; font-size: " + + InterfaceConstants.NORMAL_FONTSIZE + " pt; }"); + addressbar.setPreferredSize(new Dimension(controller.getASTModel() + .getMaxDepth() + * InterfaceConstants.NORMAL_FONTSIZE * 5 / 8 + 5, + getHeight() - 20)); + } + if (controller.getASTModel().isValid()) { + // Hole den Code + textEditor + .setText(controller.getC0CodeModel().getFormattedC0Code()); + } else + return false; + updateUI(); + return true; + } + +} diff --git a/src/org/jalgo/module/c0h0/views/CVS/Entries b/src/org/jalgo/module/c0h0/views/CVS/Entries new file mode 100644 index 0000000..8a4a3b7 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/CVS/Entries @@ -0,0 +1,17 @@ +/C0View.java/1.1/Sat Mar 5 14:12:04 2011// +/Easter.java/1.1/Sat Mar 5 14:12:04 2011// +/EditView.java/1.1/Sat Mar 5 14:12:04 2011// +/FlowChartView.java/1.1/Sat Mar 5 14:12:04 2011// +/H0View.java/1.1/Sat Mar 5 14:12:04 2011// +/HelpView.java/1.1/Sat Mar 5 14:12:04 2011// +/LogView.java/1.1/Sat Mar 5 14:12:04 2011// +/TerminalView.java/1.1/Sat Mar 5 14:12:04 2011// +/TextEditor.java/1.1/Sat Mar 5 14:12:04 2011// +/TransView.java/1.1/Sat Mar 5 14:12:04 2011// +/View.java/1.1/Sat Mar 5 14:12:04 2011// +/WelcomeView.java/1.1/Sat Mar 5 14:12:04 2011// +/WelcomeViewButton.java/1.1/Sat Mar 5 14:12:04 2011// +/package-info.java/1.1/Sat Mar 5 14:12:04 2011// +/teamView.java/1.1/Sat Mar 5 14:12:04 2011// +/teamViewListener.java/1.1/Sat Mar 5 14:12:04 2011// +/teamViewUpdateEvent.java/1.1/Sat Mar 5 14:12:04 2011// diff --git a/src/org/jalgo/module/c0h0/views/CVS/Repository b/src/org/jalgo/module/c0h0/views/CVS/Repository new file mode 100644 index 0000000..ff6f187 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/c0h0/views diff --git a/src/org/jalgo/module/c0h0/views/CVS/Root b/src/org/jalgo/module/c0h0/views/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/c0h0/views/Easter.java b/src/org/jalgo/module/c0h0/views/Easter.java new file mode 100644 index 0000000..2b402ad --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/Easter.java @@ -0,0 +1,413 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Toolkit; +import java.awt.Transparency; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferStrategy; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Random; + +import javax.swing.JFrame; +import javax.swing.WindowConstants; + +/** * * + * some magic * * * + * * * * + * @author White Rabbit * + * * * * */ +@SuppressWarnings("serial") +public class Easter extends View { + private static class Egg extends Thread { + private boolean isRunning = true; + private Canvas canvas; + private BufferStrategy strategy; + private BufferedImage background; + private Graphics2D backgroundGraphics; + private Graphics2D graphics; + private JFrame frame; + private int width = 160; + private int height = 120; + private int scale = 4; + private GraphicsConfiguration config = GraphicsEnvironment + .getLocalGraphicsEnvironment().getDefaultScreenDevice() + .getDefaultConfiguration(); + + private Random ra = new Random(); + private List obs = new ArrayList(); + private List tail = new LinkedList(); + private final int starttail = 6; + private int tailctr = starttail; + private boolean pause = false; + + private Player plr = new Player(); + + public class Obstacle extends Thing { + private short type; + private int speed = 1; + private boolean horiz; + private Color clr; + + public Obstacle() { + if (ra.nextInt(5) == 0) + type = (short) ra.nextInt(5); + else + type = 0; + + horiz = ra.nextBoolean(); + + switch (type) { + case 1: + clr = Color.PINK; + break; + case 2: + clr = Color.GREEN; + break; + case 3: + clr = Color.RED; + break; + case 4: + clr = Color.CYAN; + break; + default: + clr = Color.LIGHT_GRAY; + } + if (horiz) + set(0, ra.nextInt(width), clr); + else + set(ra.nextInt(width), 0, clr); + } + + public boolean update() { + if (y < height && y >= 0 && x >= 0 && x < width) { + if (horiz) + set(x + speed, y, clr); + else + set(x, y + speed, clr); + } else { + obs.remove(this); + return false; + } + + for (Tail t : tail) { + if (t.x == x && t.y == y) { + tail.remove(t); // t.set(t.x, t.y, this.clr); + this.speed *= -1; // obs.remove(this); + switch (type) { + case 1: + tailctr -= 1; + plr.pts += 7; + break; + case 2: + tailctr += 10; + plr.pts += 10; + break; + case 3: + tailctr = 4; + plr.pts += 100; + break; + case 4: + for (Obstacle o : obs) { + o.speed *= -1; + } + plr.pts += 17; + break; + default: + tailctr++; + plr.pts++; + break; + } + return false; + } + } + return true; + } + } + + public class Player extends Thing { + protected int speed = 1; + protected int dx = 1, dy = 0, hp = 3, pts; + protected long counter = 100; // 1000 frames + + public Player() { + set(width / 2, height / 2, Color.WHITE); + pts = 0; + tailctr = starttail; + for (int i = tailctr; i > 0; i--) + tail.add(new Tail(x + i, y)); + } + + public void update() { + if (dx != 0 || dy != 0) { + tail.add(new Tail(x, y)); + while (tail.size() > tailctr) + tail.remove(0); + } + // Staying inside the field + if (x > width-1) + x = 1; + if (y > height-1) + y = 1; + if (x < 1) + x = width-1; + if (y < 1) + y = height-1; + + set(x + dx * speed, y + dy * speed, Color.WHITE); + + if (counter == 0) { + tailctr--; // die slowly! + counter = 100; + } + counter--; + } + } + + public class Tail extends Thing { + public Tail(int x, int y) { + set(x, y, Color.BLUE); + } + } + + public class Thing { + protected int x, y; + protected Color clr; + + public void set(int x, int y, Color clr) { + this.x = x; + this.y = y; + this.clr = clr; + } + + public void render(Graphics2D g) { + g.setColor(clr); + g.fillRect(x, y, 1, 1); + } + } + + // create a hardware accelerated image + public final BufferedImage create(final int width, final int height, + final boolean alpha) { + return config.createCompatibleImage(width, height, + alpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE); + } + + // Setup + public Egg() { + // JFrame + frame = new JFrame(); + frame.addWindowListener(new FrameClose()); + frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + frame.setSize(width * scale, height * scale); + frame.setVisible(true); + + // Canvas + canvas = new Canvas(config); + canvas.setSize(width * scale, height * scale); + frame.add(canvas, 0); + + // Background & Buffer + background = create(width, height, false); + canvas.createBufferStrategy(2); + do { + strategy = canvas.getBufferStrategy(); + } while (strategy == null); + start(); + + frame.addKeyListener(new FrameKey()); + } + + private class FrameClose extends WindowAdapter { + @Override + public void windowClosing(final WindowEvent e) { + isRunning = false; + } + } + + private class FrameKey implements KeyListener { + + public void keyPressed(KeyEvent e) { + switch (e.getKeyCode()) { + case KeyEvent.VK_UP: + case KeyEvent.VK_W: + plr.dy = -1; + plr.dx = 0; + break; + case KeyEvent.VK_DOWN: + case KeyEvent.VK_S: + plr.dy = 1; + plr.dx = 0; + break; + case KeyEvent.VK_LEFT: + case KeyEvent.VK_A: + plr.dx = -1; + plr.dy = 0; + break; + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_D: + plr.dx = 1; + plr.dy = 0; + break; + case KeyEvent.VK_Q: + case KeyEvent.VK_ESCAPE: + isRunning = false; + break; + case KeyEvent.VK_ENTER: + pause = !pause; + break; + case KeyEvent.VK_P: + pause = true; + break; + } + } + + public void keyReleased(KeyEvent e) { + } + + public void keyTyped(KeyEvent e) { + } + + } + + // Screen and buffer stuff + private Graphics2D getBuffer() { + if (graphics == null) { + try { + graphics = (Graphics2D) strategy.getDrawGraphics(); + } catch (IllegalStateException e) { + return null; + } + } + return graphics; + } + + private boolean updateScreen() { + graphics.dispose(); + graphics = null; + try { + strategy.show(); + Toolkit.getDefaultToolkit().sync(); + return (!strategy.contentsLost()); + + } catch (NullPointerException e) { + return true; + + } catch (IllegalStateException e) { + return true; + } + } + + public void run() { + backgroundGraphics = (Graphics2D) background.getGraphics(); + long fpsWait = (long) (1.0 / 30 * 1000); + main: while (isRunning) { + long renderStart = System.nanoTime(); + updateGame(); + + // Update Graphics + do { + Graphics2D bg = getBuffer(); + if (!isRunning) { + break main; + } + renderGame(backgroundGraphics); // this calls your draw + if (scale != 1) { + bg.drawImage(background, 0, 0, width * scale, height + * scale, 0, 0, width, height, null); + } else { + bg.drawImage(background, 0, 0, null); + } + bg.dispose(); + } while (!updateScreen()); + + // Better do some FPS limiting here + long renderTime = (System.nanoTime() - renderStart) / 1000000; + try { + Thread.sleep(Math.max(0, fpsWait - renderTime)); + } catch (InterruptedException e) { + Thread.interrupted(); + break; + } + renderTime = (System.nanoTime() - renderStart) / 1000000; + + } + frame.dispose(); + } + + public void updateGame() { + if (pause) { + return; + } + + plr.update(); + + if (ra.nextInt((int) (5 + Math.pow(2, -width * height / 30 / 30 + / 100 / 100 / (plr.pts + 1)))) == 0) + obs.add(new Obstacle()); + int o = 0; + + while (o < obs.size()) { + if (obs.get(o).update()) { + o++; + } + } + + if (tail.size() == 0) { + if (plr.hp > 0) { + int hp = plr.hp; + int pts = plr.pts; + plr = new Player(); + plr.hp = hp - 1; + plr.pts = pts; + tailctr = 5; + obs.clear(); + pause = true; + } else { + isRunning = false; // GAME OVER + } + } + } + + public void renderGame(Graphics2D g) { + g.setColor(Color.BLACK); + g.fillRect(0, 0, width, height); + + if (pause) { + g.setColor(Color.WHITE); + int size = 12; + g.setFont(new Font("Monospace", Font.PLAIN, size)); + g.drawString("REM LIFES: " + plr.hp, 2, + height / 2 - size); + g.drawString("SCORE: " + plr.pts, 2, height / 2); + g.drawString("CONTINUE? [ENTER]", 2, + height / 2 + size); + return; + } + + for (Tail t : tail) + t.render(g); + for (Obstacle o : obs) + o.render(g); + plr.render(g); + } + } + + public Easter() { + new Egg(); + } + + public static void main(final String args[]) { + new Egg(); + } +} diff --git a/src/org/jalgo/module/c0h0/views/EditView.java b/src/org/jalgo/module/c0h0/views/EditView.java new file mode 100644 index 0000000..ba4a266 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/EditView.java @@ -0,0 +1,69 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; +import java.awt.Font; + +import javax.swing.JScrollPane; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.InterfaceConstants; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * View that provides a textEditor for entering C0 code + * + * @author hendrik + * + */ +public class EditView extends View { + private static final long serialVersionUID = -3224880580661414522L; + private TextEditor textEditor; + private Font font; + private Controller controller; + private ViewManager viewManager; + + public EditView(Controller con, ViewManager viewManager) { + controller = con; + this.viewManager = viewManager; + textEditor = new TextEditor(); + JScrollPane scrollPane = new JScrollPane(textEditor); + setLayout(new BorderLayout()); + add(scrollPane, BorderLayout.CENTER); + doLayout(); + textEditor.setContentType("text/c"); + } + + /** + * Facade for texteditors setDot() + * + * @param line + */ + public void setCaret(int line) { + textEditor.getCaret().setDot(line); + textEditor.requestFocus(); + } + + /** + * returns the c0Code from textpane + * @return the c0Code + */ + public String getC0Code() { + return textEditor.getText(); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.views.View#update() + */ + public boolean update() { + textEditor.setText(controller.getC0CodeModel().getCodeForm()); + if (viewManager.isBeamerMode()) + font = new Font("Courier New", Font.PLAIN, InterfaceConstants.BEAMERMODE_FONTSIZE); + else font = new Font("Courier New", Font.PLAIN, InterfaceConstants.NORMAL_FONTSIZE); + textEditor.setFont(font); + return true; + // textEditor.setText(controller.getC0Code().highlightEditorText()); + + } +} diff --git a/src/org/jalgo/module/c0h0/views/FlowChartView.java b/src/org/jalgo/module/c0h0/views/FlowChartView.java new file mode 100644 index 0000000..707bae8 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/FlowChartView.java @@ -0,0 +1,450 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Image; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.print.Paper; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.ViewManager; +import org.jalgo.module.c0h0.models.flowchart.Bundle; +import org.jalgo.module.c0h0.models.flowchart.Edge; +import org.jalgo.module.c0h0.controller.InterfaceConstants; + +import com.mxgraph.swing.mxGraphComponent; +import com.mxgraph.util.mxCellRenderer; +import com.mxgraph.util.mxConstants; +import com.mxgraph.util.mxRectangle; +import com.mxgraph.view.mxGraph; +import com.mxgraph.view.mxStylesheet; + +/** + * draws the flowchart + * + * @author Philipp Geissler + * @author Mathias Kaufmann + * + */ +public class FlowChartView extends View { + + private static final long serialVersionUID = 1993191423448829250L; + + private Controller con; + private ViewManager viewManager; + public mxGraphComponent graphComponent; + private EventHandler eventHandler; + + private JPanel completeFlowChartView; + private JPanel navigateFlowChart; + private JSlider zoomSlider; + private mxGraph flowChartGraph; + private Object parent, from, to, connect; + + private final double ZOOMFACTOR = 1.1; + private final double NOBEAMERMODEZOOM = 1.5; + private final double BEAMERMODEZOOM = 2; + + private Paper paper; + private int markedMinY; + private int markedMaxY; + private mxRectangle minimumSize; + + private Map objectConnector; // connects drawn objects and + // elements of the model + private List elementList; + private boolean beamerMode = false; // to toggle beamer mode only once when + + // selected + + /** + * @param con + * the controller + * @param viewManager + */ + public FlowChartView(final Controller con, ViewManager viewManager) { + + this.viewManager = viewManager; + + objectConnector = new HashMap(); + + this.con = con; + + completeFlowChartView = new JPanel(); + completeFlowChartView.setLayout(new BoxLayout(completeFlowChartView, + BoxLayout.Y_AXIS)); + navigateFlowChart = new JPanel(); + navigateFlowChart.setLayout(new BoxLayout(navigateFlowChart, + BoxLayout.X_AXIS)); + + eventHandler = new EventHandler(); + + flowChartGraph = new mxGraph(); + + zoomSlider = new JSlider(JSlider.HORIZONTAL, 5, 25, + (int) (NOBEAMERMODEZOOM * 10)); + zoomSlider.addChangeListener(eventHandler); + zoomSlider.setPaintTicks(true); + zoomSlider.setPaintLabels(false); + + minimumSize = new mxRectangle(); + minimumSize.setWidth(220); + minimumSize.setHeight(230); + + parent = flowChartGraph.getDefaultParent(); + + // create element styles + + mxStylesheet stylesheet = flowChartGraph.getStylesheet(); + + Hashtable rhombus = new Hashtable(); + Hashtable rectangle = new Hashtable(); + Hashtable anker = new Hashtable(); + Hashtable address = new Hashtable(); + Hashtable leftAddress = new Hashtable(); + Hashtable vertical = new Hashtable(); + Hashtable horizontal = new Hashtable(); + Hashtable arrow = new Hashtable(); + + rhombus.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RHOMBUS); + rhombus.put(mxConstants.STYLE_SPACING_TOP, 2); + rhombus.put(mxConstants.STYLE_FONTCOLOR, "#000000"); + rectangle.put(mxConstants.STYLE_SPACING_TOP, 2); + rectangle.put(mxConstants.STYLE_FONTCOLOR, "#000000"); + address.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE); + address.put(mxConstants.STYLE_FILLCOLOR, "#FF0000"); + address.put(mxConstants.STYLE_FONTCOLOR, "#FF0000"); + address.put(mxConstants.STYLE_SPACING_TOP, 12); + leftAddress.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE); + leftAddress.put(mxConstants.STYLE_FILLCOLOR, "#FF0000"); + leftAddress.put(mxConstants.STYLE_FONTCOLOR, "#FF0000"); + leftAddress.put(mxConstants.STYLE_SPACING_TOP, 12); + vertical.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_LINE); + vertical.put(mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_SOUTH); + vertical.put(mxConstants.STYLE_SPACING_LEFT, 10); + vertical.put(mxConstants.STYLE_STROKEWIDTH, 2); + horizontal.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_LINE); + horizontal.put(mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_WEST); + horizontal.put(mxConstants.STYLE_SPACING_BOTTOM, 5); + horizontal.put(mxConstants.STYLE_STROKEWIDTH, 2); + arrow.put(mxConstants.STYLE_SPACING_RIGHT, 10); + arrow.put(mxConstants.STYLE_STROKEWIDTH, 2); + anker.put(mxConstants.STYLE_OPACITY, 0); + + stylesheet.putCellStyle("RHOMBUS", rhombus); + stylesheet.putCellStyle("ADDRESS", address); + stylesheet.putCellStyle("LEFTADDRESS", leftAddress); + stylesheet.putCellStyle("VERTICAL", vertical); + stylesheet.putCellStyle("HORIZONTAL", horizontal); + stylesheet.putCellStyle("ARROW", arrow); + stylesheet.putCellStyle("RECTANGLE", rectangle); + stylesheet.putCellStyle("ANKER", anker); + + + graphComponent = new mxGraphComponent(flowChartGraph); + setBackground(); + + graphComponent.getViewport().setOpaque(false); + graphComponent.setMinimumSize(new Dimension()); + graphComponent.setEnabled(false); + graphComponent.getVerticalScrollBar().setUnitIncrement(10); + + graphComponent.setZoomFactor(ZOOMFACTOR); + graphComponent.zoom(NOBEAMERMODEZOOM); + + graphComponent.setCenterPage(true); + graphComponent.setPageVisible(true); + graphComponent.setPageScale(1); + graphComponent.setPreferPageSize(true); + paper = new Paper(); + paper.setSize(500, 900); + graphComponent.getPageFormat().setPaper(paper); + graphComponent.setCenterZoom(true); + + flowChartGraph.setMinimumGraphSize(minimumSize); + flowChartGraph.setCellsLocked(true); + flowChartGraph.setConnectableEdges(false); + flowChartGraph.setAllowDanglingEdges(false); + + navigateFlowChart.add(zoomSlider); + + completeFlowChartView.add(graphComponent); + completeFlowChartView.add(navigateFlowChart); + setLayout(new BorderLayout()); + this.add(completeFlowChartView); + + MouseAdapter m = new MouseAdapter() { + + public void mouseReleased(MouseEvent e) { + Object cell = graphComponent.getCellAt(e.getX(), e.getY()); + if (cell != null) { + // mark symbol + String add = objectConnector.get(cell); + if (add != null) + con.markNode(add); // if element is visible + } + } + }; + + graphComponent.getGraphControl().addMouseListener(m); + } + + private void setBackground() { + Color notWhite = Color.decode(viewManager.backgroundColor(con + .getFcmodel().isActive())); + + graphComponent.setBackground(notWhite); + graphComponent.setPageBackgroundColor(notWhite); + graphComponent.setPageBorderColor(notWhite); + graphComponent.setPageShadowColor(notWhite); + + } + + /** + * action listener for the zoom buttons of the flowchart + * + */ + public class EventHandler implements ChangeListener { + + public void stateChanged(ChangeEvent e) { + JSlider source = (JSlider) e.getSource(); + flowChartGraph.getView().setScale(source.getValue() * .1); + centerHorizontalScrollbar(); + } + } + + /** + * Creates the flowchart-graph which is visibleTo a specific node + * + * @param visibleTo + * Integer with the index of the last visible node + */ + private void createFlowChartGraph(int visibleTo) { + int mid = (int) (graphComponent.getPageFormat().getWidth() / 2); + Bundle theMarkedBundle = null; + + // clear flowchart + flowChartGraph.selectAll(); + flowChartGraph.removeCells(); + + flowChartGraph.getModel().beginUpdate(); + try { + + for (int i = 0; i < elementList.size(); i++) { + + Bundle l = elementList.get(i); + List edgeList = l.getEdges(); + + for (Edge e : edgeList) { + + if (i < visibleTo) { + // marked elements + if (l.getAddress().equals( + con.getASTModel().getMarkedNode())) { + theMarkedBundle = l; + break; + } + // draw unmarked elements + + from = flowChartGraph.insertVertex(parent, null, e + .getFrom().getLabel(), + e.getFrom().getX() + mid, e.getFrom().getY(), e + .getFrom().getWidth(), e.getFrom() + .getHeight(), e.getFrom().getStyle()); + to = flowChartGraph.insertVertex(parent, null, e + .getTo().getLabel(), e.getTo().getX() + mid, e + .getTo().getY(), e.getTo().getWidth(), e + .getTo().getHeight(), e.getTo().getStyle()); + connect = flowChartGraph.insertEdge(parent, null, e + .getLabel(), from, to, e.getStyle()); + + objectConnector.put(connect, l.getAddress()); + objectConnector.put(from, l.getAddress()); + objectConnector.put(to, l.getAddress()); + } + + else { + // draw invisible elements + from = flowChartGraph.insertVertex(parent, null, e + .getFrom().getLabel(), + e.getFrom().getX() + mid, e.getFrom().getY(), e + .getFrom().getWidth(), e.getFrom() + .getHeight(), e.getFrom().getStyle() + + getInv(e.getFrom().getStyle())); + to = flowChartGraph.insertVertex(parent, null, e + .getTo().getLabel(), e.getTo().getX() + mid, e + .getTo().getY(), e.getTo().getWidth(), e + .getTo().getHeight(), e.getTo().getStyle() + + getInv(e.getTo().getStyle())); + connect = flowChartGraph.insertEdge(parent, null, e + .getLabel(), from, to, e.getStyle() + + getInv(e.getStyle())); + } + } + } + if (theMarkedBundle != null) { + // draw marked elements + + markedMaxY = 0; + markedMinY = 9999; + + List edgeList2 = theMarkedBundle.getEdges(); + for (Edge e : edgeList2) { + + from = flowChartGraph.insertVertex(parent, null, e + .getFrom().getLabel(), e.getFrom().getX() + mid, e + .getFrom().getY(), e.getFrom().getWidth(), e + .getFrom().getHeight(), e.getFrom().getStyle() + + getMark(e.getFrom().getStyle())); + to = flowChartGraph.insertVertex(parent, null, e.getTo() + .getLabel(), e.getTo().getX() + mid, e.getTo() + .getY(), e.getTo().getWidth(), e.getTo() + .getHeight(), e.getTo().getStyle() + + getMark(e.getTo().getStyle())); + connect = flowChartGraph.insertEdge(parent, null, e + .getLabel(), from, to, e.getStyle() + + getMark(e.getStyle())); + + objectConnector.put(connect, theMarkedBundle.getAddress()); + objectConnector.put(from, theMarkedBundle.getAddress()); + objectConnector.put(to, theMarkedBundle.getAddress()); + + // coordinates for automatic scrolling + if (e.getFrom().getStyle() != "ANKER") { + if (e.getFrom().getY() < markedMinY) + markedMinY = e.getFrom().getY(); + if (e.getFrom().getY() > markedMaxY) + markedMaxY = e.getFrom().getY(); + } + + } + + // scroll automatically + + int height = (int) (graphComponent.getHeight()); + int min = (int) (markedMinY * flowChartGraph.getView() + .getScale()); + int max = (int) (markedMaxY * flowChartGraph.getView() + .getScale()); + + if (markedMinY != 9999 && markedMaxY != 0) + graphComponent.getVerticalScrollBar().setValue( + (int) ((min + max) / 2 - height / 2)); + + } + + } finally { + flowChartGraph.getModel().endUpdate(); + } + } + public boolean render() { + elementList = con.getFcmodel().getElements(); + + if(elementList==null) return false; + + objectConnector.clear(); + + // Creates the flowchartgraph + createFlowChartGraph(con.getFcmodel().getVisibleTo()); + + // adapt paper to flowchart + paper.setSize( + (flowChartGraph.getGraphBounds().getWidth() / flowChartGraph + .getView().getScale()) * (1.5), flowChartGraph + .getGraphBounds().getHeight() + / flowChartGraph.getView().getScale()); + graphComponent.getPageFormat().setPaper(paper); + + graphComponent.updateUI(); + completeFlowChartView.updateUI(); + + centerHorizontalScrollbar(); + + return true; + } + + /** + * defines the style of invisible elements + * + * @param style + * @return style addition + */ + private String getInv(String style) { + String GREYBACKG = viewManager.backgroundColor(con.getFcmodel().isActive()).substring(1); + String GREY = "CCCCCC"; + + if (style == "RHOMBUS" || style == "RECTANGLE") + return ";fillColor=#"+GREY+";strokeColor=#"+GREY+";fontColor=#"+GREY; + return ";fillColor=#"+GREY+";strokeColor=#"+GREY+";fontColor=#"+GREYBACKG; + } + + /** + * defines the style of marked elements + * + * @param style + * @return style addition + */ + private String getMark(String style) { + if (style == "RHOMBUS" || style == "RECTANGLE") + return ";fillColor=#" + InterfaceConstants.MARKEDCOLOR_ACTIVE + + ";strokeColor=#" + InterfaceConstants.MARKEDCOLOR_ACTIVE; + return ";fillColor=#" + InterfaceConstants.MARKEDCOLOR_ACTIVE + + ";fontColor=#" + InterfaceConstants.MARKEDCOLOR_ACTIVE + + ";strokeColor=#" + InterfaceConstants.MARKEDCOLOR_ACTIVE; + } + + /** + * centers the horizontal scrollbar + */ + private void centerHorizontalScrollbar(){ + graphComponent.zoomAndCenter(); + graphComponent.getHorizontalScrollBar().setValue( + (int) (((1-(graphComponent.getWidth()/(graphComponent.getPageFormat().getWidth() + *flowChartGraph.getView().getScale())))*graphComponent.getHorizontalScrollBar().getMaximum())/2)); + } + + public boolean update() { + setBackground(); + + // check for beamer mode + if (viewManager.isBeamerMode() && !beamerMode) { + flowChartGraph.getView().setScale(BEAMERMODEZOOM); + zoomSlider.setValue((int) (BEAMERMODEZOOM * 10)); + beamerMode = true; + } else if (!viewManager.isBeamerMode() && beamerMode) { + flowChartGraph.getView().setScale(NOBEAMERMODEZOOM); + zoomSlider.setValue((int) (NOBEAMERMODEZOOM * 10)); + beamerMode = false; + } + + render(); + return true; + } + + /** + * Returns an image of the graph + * + * @return Image + */ + public Image getGraph() { + String backUp = con.getASTModel().getMarkedNode(); + con.getASTModel().setMarkedNode(""); + createFlowChartGraph(elementList.size()); + Image img = mxCellRenderer.createBufferedImage(flowChartGraph, null, 1, Color.WHITE, false, null); + con.getASTModel().setMarkedNode(backUp); + render(); + return img; + } +} diff --git a/src/org/jalgo/module/c0h0/views/H0View.java b/src/org/jalgo/module/c0h0/views/H0View.java new file mode 100644 index 0000000..17ea450 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/H0View.java @@ -0,0 +1,202 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JScrollPane; +import javax.swing.event.EventListenerList; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.StyleSheet; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.InterfaceConstants; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * view which displays the H0 code + * + * @author Peter Schwede + * + */ +public class H0View extends View implements teamView { + private static final long serialVersionUID = -657432685963819871L; + private static final String BODYFONTWIDTHMARGIN = "body {font-family: Courier, \"Courier New\", monospace; width:100%; padding: 3px; margin: 0; font-size: "; + private TextEditor textEditor; + private JScrollPane scrollpane; + private Controller controller; + private String currentlyMarked = null; + private String currentlyEntered = ""; + private EventListenerList team; + + private final String markedPrefix = "."; + private StringBuilder bob = new StringBuilder(); + + /** + * @param controller + * @param viewManager + */ + public H0View(final Controller controller, ViewManager viewManager) { + this.controller = controller; + + textEditor = new TextEditor(); + textEditor.setContentType("text/html"); + textEditor.setEditable(false); + + this.team = new EventListenerList(); + + // setup CSS + StyleSheet ss = ((HTMLDocument) textEditor.getDocument()) + .getStyleSheet(); + ss + .addRule("body {width:100%; font-family: Courier, \"Courier New\", monospace; padding: 3px; margin: 0;}"); + ss.addRule("table td {width: 100%; margin: 0; padding: 0;}"); + ss + .addRule("table {width: 100%; border-collapse: collapse; padding: 0; margin: 0;}"); + ss + .addRule(".greyed {color:" + InterfaceConstants.GRAYED_CONTENT + + ";}"); + ss.addRule(".head {color: " + InterfaceConstants.GRAYED_CONTENT + ";}"); + ss.addRule(".foot {color: " + InterfaceConstants.GRAYED_CONTENT + ";}"); + ss.addRule("a {color: #000000; text-decoration: none;}"); + + scrollpane = new JScrollPane(textEditor); + setLayout(new BorderLayout()); + add(scrollpane, BorderLayout.CENTER); + + // Listener for touch display work-around + MouseAdapter mouseListener = new MouseAdapter() { + public void mouseReleased(MouseEvent e) { + if (!currentlyEntered.equals("")) { + textEditor.fireHyperlinkUpdate(new HyperlinkEvent(this, + HyperlinkEvent.EventType.ACTIVATED, null, + currentlyEntered)); + } + } + }; + HyperlinkListener hyperListener = new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + if (!currentlyMarked.equals(currentlyEntered)) { + controller.markNode(currentlyEntered); + } + } else if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + currentlyEntered = e.getDescription(); + } else { + currentlyEntered = ""; + } + } + }; + textEditor.addMouseListener(mouseListener); + textEditor.addHyperlinkListener(hyperListener); + + doLayout(); + } + + /* + * (non-Javadoc) This method is implicitly called in Controller.markNode() + * It handles all visible, non-text. + * + * @see org.jalgo.module.c0h0.views.View#render() + */ + public boolean render() { + StyleSheet ss = ((HTMLDocument) textEditor.getDocument()) + .getStyleSheet(); + + ss.removeStyle(markedPrefix + currentlyMarked); + currentlyMarked = controller.getASTModel().getMarkedNode(); + StringBuilder bob = new StringBuilder(); + bob.append(markedPrefix); + bob.append(currentlyMarked); + bob.append(" { background-color: "); + if (controller.getH0CodeModel().isActive()) + bob.append(InterfaceConstants.MARKEDCOLOR_ACTIVE); + else + bob.append(InterfaceConstants.MARKEDCOLOR_INACTIVE); + bob.append(";}"); + ss.addRule(bob.toString()); + + textEditor.scrollToReference(currentlyMarked); + return true; + } + + /* + * (non-Javadoc) This handles all content + * + * @see org.jalgo.module.c0h0.views.View#update() + */ + public boolean update() { + if (controller.getASTModel().isValid()) { + // fetch current code + textEditor.setText(controller.getH0CodeModel().getHTMLCode()); + } + + if(!controller.getASTModel().getMarkedNode().equals(currentlyMarked)) + render(); + + StyleSheet ss = ((HTMLDocument) textEditor.getDocument()) + .getStyleSheet(); + + bob.setLength(0); + if (controller.getViewManager().isBeamerMode()) { + bob.append(BODYFONTWIDTHMARGIN); + bob.append(InterfaceConstants.BEAMERMODE_FONTSIZE); + bob.append("pt; background-color: "); + bob.append(controller.getViewManager().backgroundColor( + controller.getH0CodeModel().isActive())); + bob.append(";}"); + } else { + bob.append(BODYFONTWIDTHMARGIN); + bob.append(InterfaceConstants.NORMAL_FONTSIZE); + bob.append("pt; background-color: "); + bob.append(controller.getViewManager().backgroundColor( + controller.getH0CodeModel().isActive())); + bob.append(";}"); + } + ss.addRule(bob.toString()); + return true; + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.views.teamView#registerTeamPerformerMember(org. + * jalgo.module.c0h0.views.View) + */ + public void registerTeamPerformerMember(View member) { + team.add(View.class, member); + } + + /* + * (non-Javadoc) + * + * @see + * org.jalgo.module.c0h0.views.teamView#unregisterTeamPerformerMember(org + * .jalgo.module.c0h0.views.View) + */ + public void unregisterTeamPerformerMember(View member) { + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.views.teamView#notifyTeamPerformers() + */ + public void notifyTeamPerformers() { + for (View view : team.getListeners(View.class)) { + view.teamUpdate(); + } + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.c0h0.views.teamView#getTeamPerformerAddress() + */ + public String getTeamPerformerAddress() { + return controller.getH0CodeModel().getAddress(); + } +} diff --git a/src/org/jalgo/module/c0h0/views/HelpView.java b/src/org/jalgo/module/c0h0/views/HelpView.java new file mode 100644 index 0000000..c619d62 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/HelpView.java @@ -0,0 +1,159 @@ +package org.jalgo.module.c0h0.views; + +import javax.swing.*; + +import java.awt.Color; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * view which provides the menu promt for the C0 code parameters + * @author Peter Schwede + * + */ +public class HelpView extends View { + private static final long serialVersionUID = -6347171988776084694L; + private JComboBox boxM = new JComboBox(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + private JComboBox boxK = new JComboBox(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + private JComboBox boxI = new JComboBox(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + private JButton okButton = new JButton("Code erzeugen"); + private JButton transButton = new JButton("Transformieren"); + private JPanel pane = new JPanel(); + + /** + * @param controller + * @param viewManager + */ + @SuppressWarnings("serial") + public HelpView(final Controller controller, ViewManager viewManager) { + Color foreground = Color.black; + + AbstractAction generateAction = new AbstractAction() { + public void actionPerformed(ActionEvent e) { + Integer m = ((Integer) boxM.getSelectedItem()).intValue(); + Integer k = ((Integer) boxK.getSelectedItem()).intValue(); + Integer i = ((Integer) boxI.getSelectedItem()).intValue(); + + if(m>=k && m>=i) + controller.readMKI(m, k, i); + } + }; + + AbstractAction transformAction = new AbstractAction() { + + public void actionPerformed(ActionEvent arg0) { + controller.runTransformation(); + } + }; + + + GridBagLayout gridbag = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + setLayout(new BorderLayout()); + pane.setLayout(gridbag); + + JLabel headline = new JLabel("C0/H0 Transformation"); + headline.setForeground(foreground); + headline.setAlignmentX(CENTER_ALIGNMENT); + headline.setFont(new Font(headline.getFont().getFontName(), headline.getFont().getStyle(), 20)); + c.gridwidth = GridBagConstraints.REMAINDER; + gridbag.setConstraints(headline, c); + pane.add(headline); + + // + JLabel l = new JLabel( + "
          Bitte wähle die Größe der Parameter,
          um ein neues Programm zu schreiben!
           "); + l.setForeground(foreground); + l.setFont(new Font(l.getFont().getFontName(), l.getFont().getStyle(), 16)); + c.gridwidth = GridBagConstraints.REMAINDER; + gridbag.setConstraints(l, c); + pane.add(l); + + l = new JLabel("Anzahl der Variablen (m):"); + l.setForeground(foreground); + l.setFont(new Font(l.getFont().getFontName(), l.getFont().getStyle(), 16)); + c.gridwidth = GridBagConstraints.RELATIVE; + c.insets = new Insets(0 ,0, 10, 0); + gridbag.setConstraints(l, c); + pane.add(l); + c.gridwidth = GridBagConstraints.REMAINDER; + gridbag.setConstraints(boxM, c); + pane.add(boxM); + + l = new JLabel("Anzahl der Eingaben (k):"); + l.setForeground(foreground); + l.setFont(new Font(l.getFont().getFontName(), l.getFont().getStyle(), 16)); + c.gridwidth = GridBagConstraints.RELATIVE; + gridbag.setConstraints(l, c); + pane.add(l); + c.gridwidth = GridBagConstraints.REMAINDER; + gridbag.setConstraints(boxK, c); + pane.add(boxK); + + l = new JLabel("Auszugebende Variable (i):"); + l.setForeground(foreground); + l.setFont(new Font(l.getFont().getFontName(), l.getFont().getStyle(), 16)); + c.gridwidth = GridBagConstraints.RELATIVE; + gridbag.setConstraints(l, c); + pane.add(l); + c.gridwidth = GridBagConstraints.REMAINDER; + gridbag.setConstraints(boxI, c); + pane.add(boxI); + + c.gridwidth = GridBagConstraints.REMAINDER; + + JPanel buttonPain = new JPanel(); + buttonPain.setLayout(new BoxLayout(buttonPain,BoxLayout.X_AXIS)); + buttonPain.add(transButton); + buttonPain.add(okButton); + + gridbag.setConstraints(buttonPain, c); + + + okButton.setAction(generateAction); + + ActionListener actionlistener = new ActionListener(){ + + public void actionPerformed(ActionEvent e) { + Integer m = ((Integer) boxM.getSelectedItem()).intValue(); + Integer k = ((Integer) boxK.getSelectedItem()).intValue(); + Integer i = ((Integer) boxI.getSelectedItem()).intValue(); + if(m>=k && m>=i) + okButton.setEnabled(true); + else okButton.setEnabled(false); + } + + }; + + boxM.addActionListener(actionlistener); + boxK.addActionListener(actionlistener); + boxI.addActionListener(actionlistener); + + transButton.setAction(transformAction); + + okButton.setText("Code erzeugen"); + transButton.setText("Transformieren"); + pane.add(buttonPain); + // pane.setBackground(background); + add(new JScrollPane(pane), BorderLayout.CENTER); + doLayout(); + } + + /** + * Renders the view. + * + * @return success + */ + public boolean render() { + return true; + } +} diff --git a/src/org/jalgo/module/c0h0/views/LogView.java b/src/org/jalgo/module/c0h0/views/LogView.java new file mode 100644 index 0000000..b5c8105 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/LogView.java @@ -0,0 +1,53 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; + +import javax.swing.JScrollPane; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * displays error messages + * + */ +public class LogView extends View { + private static final long serialVersionUID = -6055576254061914463L; + + private Controller controller; + private TextEditor editor; + + /** + * @param controller + * @param viewManager + */ + public LogView(Controller controller, ViewManager viewManager) { + this.controller = controller; + editor = new TextEditor(); + + // Aufbau des Grundskeletts + editor.setContentType("text/html"); + JScrollPane scrollPane = new JScrollPane(editor); + setLayout(new BorderLayout()); + add(scrollPane, BorderLayout.CENTER); + doLayout(); + } + + /** + * Renders the view. + * + * @return success + */ + public boolean render() { + controller.getC0CodeModel(); + return true; + } + + /** + * sets the current error text + * @param error text + */ + public void setErrorText(String error) { + editor.setText(error); + } +} diff --git a/src/org/jalgo/module/c0h0/views/TerminalView.java b/src/org/jalgo/module/c0h0/views/TerminalView.java new file mode 100644 index 0000000..f268ef2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/TerminalView.java @@ -0,0 +1,22 @@ +package org.jalgo.module.c0h0.views; + +/** + * this is not realy a view + * consider this rather to be a development tool :D + * + * @author hendrik + * + */ +public class TerminalView { + static boolean showlog = true; + + /** + * prints line number for development purposes + * @param line + */ + public static void println(String line){ + if(showlog) + System.out.println("TerminalView: "+line); + } + +} diff --git a/src/org/jalgo/module/c0h0/views/TextEditor.java b/src/org/jalgo/module/c0h0/views/TextEditor.java new file mode 100644 index 0000000..f8e29bd --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/TextEditor.java @@ -0,0 +1,59 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.Rectangle; + +import javax.swing.JEditorPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; + +import jsyntaxpane.DefaultSyntaxKit; + +/** + * the editor for the C0 code + * + * @author Patrick + * @author Peter + * + */ +public class TextEditor extends JEditorPane { + private static final long serialVersionUID = -8737844952931068720L; + + public TextEditor() { + DefaultSyntaxKit.initKit(); + } + + /** + * Vertically *centers* the marked function; + * + * http://online.chinaitpower.com/source/jdk122/javax/swing/JEditorPane.java + * .html helped a lot. + * + * @param reference + */ + @Override + public void scrollToReference(String reference) { + HTMLDocument d = (HTMLDocument) getDocument(); + HTMLDocument.Iterator it = d.getIterator(HTML.Tag.A); + for (; it.isValid(); it.next()) { + String name = (String) it.getAttributes().getAttribute( + HTML.Attribute.NAME); + if (name != null && reference.equals(name)) { + try { + Rectangle r = modelToView(it.getStartOffset()); + if (r != null) { + // the view is visible, scroll it to the + // center of the current visible area. + Rectangle vis = getVisibleRect(); + r.y = Math.max(0, r.y - (vis.height / 2)); + r.height = vis.height; + scrollRectToVisible(r); + return; + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/org/jalgo/module/c0h0/views/TransView.java b/src/org/jalgo/module/c0h0/views/TransView.java new file mode 100644 index 0000000..e7a4959 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/TransView.java @@ -0,0 +1,81 @@ +package org.jalgo.module.c0h0.views; + +import java.awt.BorderLayout; + +import javax.swing.JScrollPane; +import javax.swing.text.html.HTMLDocument; + +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.InterfaceConstants; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * displayes the sstrans-rule provided by the TRuleModel + * @author mathias.kaufmann + */ +public class TransView extends View { + private static final long serialVersionUID = 6788651920838700007L; + private TextEditor texteditor; + private JScrollPane scrollPane; + private ViewManager viewManager; + private Controller controller; + + /** + * @param controller + * @param viewManager + */ + public TransView(final Controller controller, ViewManager viewManager){ + this.viewManager = viewManager; + this.controller = controller; + texteditor = new TextEditor(); + scrollPane = new JScrollPane(texteditor); + setLayout(new BorderLayout()); + add(scrollPane, BorderLayout.CENTER); + texteditor.setEditable(false); + texteditor.setContentType("text/html"); + String bodyRule = "body { font-family: helvetica, arial, 'lucida console'; font-size: " + InterfaceConstants.NORMAL_FONTSIZE + "pt; }"; + ((HTMLDocument)texteditor.getDocument()).getStyleSheet().addRule(bodyRule); + render(); + } + + /** + * Renders the view. + * @return success + */ + public boolean render() { + controller.getTRuleModel().setSTTrans(); + texteditor.setText(controller.getTRuleModel().getSTTrans()); + return true; + } + + public boolean update() { + String bodyRule; + if (viewManager.isBeamerMode()){ + bodyRule = "body { font-family: monospace; " + + "font-size: " + InterfaceConstants.BEAMERMODE_FONTSIZE + "pt; }"; + } + else { + bodyRule = "body { font-family: monospace; " + + "font-size: " + InterfaceConstants.NORMAL_FONTSIZE + "pt; }"; + } + + ((HTMLDocument)texteditor.getDocument()).getStyleSheet().removeStyle("body"); + ((HTMLDocument)texteditor.getDocument()).getStyleSheet().addRule(bodyRule); + render(); + scrollPane.updateUI(); + return true; + } + + public void teamUpdate() { + controller.getTRuleModel().setSTTrans(viewManager.h0View.getTeamPerformerAddress()); + texteditor.setText(controller.getTRuleModel().getSTTrans()); + } + + /** + * register this view + * @param h0View + */ + public void registerToView(H0View h0View) { + h0View.registerTeamPerformerMember(this); + } +} diff --git a/src/org/jalgo/module/c0h0/views/View.java b/src/org/jalgo/module/c0h0/views/View.java new file mode 100644 index 0000000..c5890cb --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/View.java @@ -0,0 +1,42 @@ +package org.jalgo.module.c0h0.views; + +import java.util.EventListener; + +import javax.swing.JPanel; + +/** + * Abstract superclass of all views. + * @author hendrik + * + */ +public abstract class View extends JPanel implements EventListener { + + + private static final long serialVersionUID = 9003570112807424330L; + + public View() { + } + + /** + * Renders the view. + * @return success + */ + public boolean render() { + return true; + } + + /** + * Updates the view. + * @return success + */ + public boolean update() { + this.render(); + return true; + } + + /** + * only for TeamViews (transView) + */ + public void teamUpdate() { + } +} diff --git a/src/org/jalgo/module/c0h0/views/WelcomeView.java b/src/org/jalgo/module/c0h0/views/WelcomeView.java new file mode 100644 index 0000000..ead6e99 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/WelcomeView.java @@ -0,0 +1,156 @@ +package org.jalgo.module.c0h0.views; + +import javax.swing.*; + +import org.jalgo.main.util.Messages; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import org.jalgo.module.c0h0.controller.ButtonCommand; +import org.jalgo.module.c0h0.controller.Controller; +import org.jalgo.module.c0h0.controller.ViewManager; + +/** + * Presents J-Algo-typical 3 Button welcomming Screen + * + * Codedatei Laden - Beispiel Auswählen - Neu schreiben + * + * @author hendrik + * + * + */ +public class WelcomeView extends View implements ActionListener, MouseListener { + + private static final long serialVersionUID = 1L; + private static final Color foreground = Color.white; + private static final Color background = new Color(115, 0, 13); + + private Controller controller; + public JLabel tipLine; + + private JToggleButton loadButton; + private ImageIcon loadButtonIcon; + private JToggleButton exampleButton; + private ImageIcon exampleButtonIcon; + private JToggleButton newButton; + private ImageIcon newButtonIcon; + + /** + * @param con the controller + * @param viewManager + */ + public WelcomeView(Controller con, ViewManager viewManager) { + controller = con; + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + setBackground(background); + + JPanel pane = new JPanel(); + tipLine = new JLabel(); + + pane.setBackground(background); + + String newButtonTipp = "Neuen C0-Code schreiben"; + newButtonIcon = new ImageIcon(Messages.getResourceURL("c0h0", "newButtonIcon")); + newButton = new WelcomeViewButton(newButtonIcon, newButtonTipp, ButtonCommand.newCode, newButtonTipp, this); + + String loadButtonTipp = "eigene .c0 Datei öffnen"; + loadButtonIcon = new ImageIcon(Messages.getResourceURL("c0h0", "loadButtonIcon")); + loadButton = new WelcomeViewButton(loadButtonIcon, loadButtonTipp, ButtonCommand.loadCode, loadButtonTipp, this); + + String exampleButtonTipp = "Vorgefertigte .c0 Datei öffnen"; + exampleButtonIcon = new ImageIcon(Messages.getResourceURL("c0h0", "exampleButtonIcon")); + exampleButton = new WelcomeViewButton(exampleButtonIcon, exampleButtonTipp, ButtonCommand.exampleCode, + exampleButtonTipp, this); + + pane.add(newButton); + pane.add(Box.createRigidArea(new Dimension(20, 0))); + pane.add(loadButton); + pane.add(Box.createRigidArea(new Dimension(20, 0))); + pane.add(exampleButton); + + add(Box.createVerticalStrut(150)); + add(pane); + tipLine.setAlignmentX(CENTER_ALIGNMENT); + tipLine.setForeground(foreground); + add(tipLine); + add(Box.createVerticalStrut(150)); + + doLayout(); + } + + /** + * Compares aa ActionCommand to BtnCmd-enum + * + * @param e + * @param b + * @return + */ + private boolean isCmd(ActionEvent e, ButtonCommand b) { + return (b.toString().equals(e.getActionCommand())); + } + + public void actionPerformed(ActionEvent e) { + if (isCmd(e, ButtonCommand.loadCode)) { + loadButtonAction(); + } else if (isCmd(e, ButtonCommand.exampleCode)) { + exampleButtonAction(); + } else if (isCmd(e, ButtonCommand.newCode)) { + newButtonAction(); + } + } + + /** + * Action for newButton + */ + private void newButtonAction() { + controller.newCode(); + } + + /** + * Action for loadButton + */ + private void loadButtonAction() { + controller.openFile(); + } + + /** + * Action for exampleButton + */ + private void exampleButtonAction() { + controller.openExample(); + } + + /** + * Identifies which WelcomeButton was hovered + * + * @param e + * @return + */ + private WelcomeViewButton caller(MouseEvent e) { + WelcomeViewButton caller = (WelcomeViewButton) e.getSource(); + return caller; + } + + public void mouseClicked(MouseEvent arg0) { + } + + public void mouseEntered(MouseEvent arg0) { + tipLine.setText(caller(arg0).getTip()); + } + + public void mouseExited(MouseEvent arg0) { + tipLine.setText(""); + } + + public void mousePressed(MouseEvent arg0) { + } + + public void mouseReleased(MouseEvent arg0) { + } +} diff --git a/src/org/jalgo/module/c0h0/views/WelcomeViewButton.java b/src/org/jalgo/module/c0h0/views/WelcomeViewButton.java new file mode 100644 index 0000000..2634c83 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/WelcomeViewButton.java @@ -0,0 +1,41 @@ +package org.jalgo.module.c0h0.views; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; + +import org.jalgo.module.c0h0.controller.ButtonCommand; + +/** + * Button for welcomeView + * + * @author hendrik + */ +public class WelcomeViewButton extends JToggleButton{ + + private static final long serialVersionUID = 1L; + private String tip; + + /** + * @param icon + * @param tip + * @param cmd + * @param toolTip + * @param welcomeView + */ + public WelcomeViewButton(ImageIcon icon, String tip, ButtonCommand cmd, String toolTip, WelcomeView welcomeView){ + setIcon(icon); + this.tip = tip; + this.setActionCommand(cmd.toString()); + this.addActionListener(welcomeView); + this.addMouseListener(welcomeView); + this.setToolTipText(toolTip); + } + + /** + * returns the tip + * @return the tip + */ + public String getTip(){ + return this.tip; + } +} diff --git a/src/org/jalgo/module/c0h0/views/package-info.java b/src/org/jalgo/module/c0h0/views/package-info.java new file mode 100644 index 0000000..9e308ee --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/package-info.java @@ -0,0 +1,4 @@ +/** + * Package that contains classes, represent view in MVC + */ +package org.jalgo.module.c0h0.views; \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/views/teamView.java b/src/org/jalgo/module/c0h0/views/teamView.java new file mode 100644 index 0000000..d525bb2 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/teamView.java @@ -0,0 +1,32 @@ +package org.jalgo.module.c0h0.views; + +/** + * allows a view to update an other view (observer pattern) + * @author mathias.kaufmann + */ +public interface teamView { + /** + * register a new team performer + * + * @param member + */ + abstract public void registerTeamPerformerMember(View member); + + /** + * unregister a new team performer + * + * @param member + */ + abstract public void unregisterTeamPerformerMember(View member); + + /** + * notify team performers + */ + abstract public void notifyTeamPerformers(); + + /** + * returns the address of the team performer + * @return the address + */ + abstract public String getTeamPerformerAddress(); +} \ No newline at end of file diff --git a/src/org/jalgo/module/c0h0/views/teamViewListener.java b/src/org/jalgo/module/c0h0/views/teamViewListener.java new file mode 100644 index 0000000..39ff616 --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/teamViewListener.java @@ -0,0 +1,16 @@ +package org.jalgo.module.c0h0.views; + +import java.util.EventListener; + +/** + * interface to coordinate view updates + * + */ +public interface teamViewListener extends EventListener { + /** + * updates team + * + * @param e + */ + void teamUpdate(teamViewUpdateEvent e); +} diff --git a/src/org/jalgo/module/c0h0/views/teamViewUpdateEvent.java b/src/org/jalgo/module/c0h0/views/teamViewUpdateEvent.java new file mode 100644 index 0000000..9d0c98f --- /dev/null +++ b/src/org/jalgo/module/c0h0/views/teamViewUpdateEvent.java @@ -0,0 +1,32 @@ +package org.jalgo.module.c0h0.views; + +import java.util.EventObject; + +/** + * to update an View from another View a teamViewUpdateEvent is sent from source to sink + * + * @author mathias.kaufmann + */ +public class teamViewUpdateEvent extends EventObject { + + private static final long serialVersionUID = 8518681423550314908L; + + private String Address; + + /** + * @param source + * @param Address + */ + public teamViewUpdateEvent(Object source,String Address) { + super(source); + this.Address = Address; + } + /** + * returns the address of the corresponding Symbol which triggered the update + * + * @return the address + */ + public String getAddress() { + return this.Address; + } +} diff --git a/src/org/jalgo/module/dijkstra/CVS/Entries b/src/org/jalgo/module/dijkstra/CVS/Entries new file mode 100644 index 0000000..f896524 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/CVS/Entries @@ -0,0 +1,10 @@ +/ModuleConnector.java/1.3/Thu Jan 31 20:15:09 2008/-kk/ +/ModuleInfo.java/1.5/Thu Jan 31 20:15:09 2008/-kk/ +D/actions//// +/de.properties/1.2/Sat Mar 4 13:36:11 2006/-kk/ +/en.properties/1.2/Sat Mar 4 13:36:11 2006/-kk/ +D/gfx//// +D/gui//// +D/model//// +/res.properties/1.3/Sun Mar 12 16:05:41 2006/-kk/ +D/util//// diff --git a/src/org/jalgo/module/dijkstra/CVS/Repository b/src/org/jalgo/module/dijkstra/CVS/Repository new file mode 100644 index 0000000..ae0c875 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra diff --git a/src/org/jalgo/module/dijkstra/CVS/Root b/src/org/jalgo/module/dijkstra/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/ModuleConnector.java b/src/org/jalgo/module/dijkstra/ModuleConnector.java new file mode 100644 index 0000000..b5688ec --- /dev/null +++ b/src/org/jalgo/module/dijkstra/ModuleConnector.java @@ -0,0 +1,88 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Aug 15, 2004 $Id: ModuleConnector.java,v 1.3 2005/07/13 23:01:10 + * styjdt Exp $ + */ +package org.jalgo.module.dijkstra; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.dijkstra.gui.Controller; + + +/** + * @see AbstractModuleConnector + * + * @author Julian Stecklina + */ +public class ModuleConnector +extends AbstractModuleConnector { + + private Controller controller; + + public void init() { + // initialization is taken here in run() + JAlgoGUIConnector.getInstance().getModuleMenu(this).setEnabled(false); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#run() + */ + public void run() { + controller = new Controller(this); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + public void setDataFromFile(ByteArrayInputStream data) { + controller.setSerializedData(data); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#getDataForFile() + */ + public ByteArrayOutputStream getDataForFile() { + return controller.getSerializedData(); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#print() + */ + public void print() { + // printing is currently not supported + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/ModuleInfo.java b/src/org/jalgo/module/dijkstra/ModuleInfo.java new file mode 100644 index 0000000..3cc4831 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/ModuleInfo.java @@ -0,0 +1,105 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on Aug 15, 2004 + * $Id$ + */ +package org.jalgo.module.dijkstra; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * @author Julian Stecklina + */ +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getName() + */ + public String getName() { + return Messages.getString("dijkstra", "Module_name"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getVersion() + */ + public String getVersion() { + return Messages.getString("dijkstra", "Module_version"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getAuthor() + */ + public String getAuthor() { + return Messages.getString("dijkstra", "Module_authors"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getDescription() + */ + public String getDescription() { + return Messages.getString("dijkstra", "Module_description_1")+ //$NON-NLS-1$ //$NON-NLS-2$ + System.getProperty("line.separator")+ //$NON-NLS-1$ + Messages.getString("dijkstra", "Module_description_2"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getLogo() + */ + public URL getLogoURL() { + return Messages.getResourceURL("dijkstra", "Module_logo"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getLicense() + */ + public String getLicense() { + return Messages.getString("dijkstra", "Module_license"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("dijkstra","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/actions/Action.java b/src/org/jalgo/module/dijkstra/actions/Action.java new file mode 100644 index 0000000..8659e58 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/Action.java @@ -0,0 +1,83 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 09.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank + * + * Your derived Action class should look like this + * + * class FooAction extends Action + * { + * FooAction(Controller ctrl) + * { + * super(ctrl); + * registerAndDo(true); + * } + * } + * + * + */ + +public abstract class Action { + protected Controller m_Controller; + + public Action(Controller ctrl) { + m_Controller = ctrl; + } + + /** + * @return Return m_Controller field + */ + public Controller getController() { + return m_Controller; + } + + /** + * It's intend that You call this function in the constructor of Your derived class. + * @param bRegisterInStack true if You want to register the action in the controller's action stack + * @return Return the result of doAction() + * @throws ActionException + */ + protected boolean registerAndDo(boolean bRegisterInStack) throws ActionException { + return m_Controller.registerAndDoAction(this, bRegisterInStack); + } + + /** + * Implement the actions You want to be performed. + * @return return true if the action was successful performed. + * @throws ActionException + */ + public abstract boolean doAction() throws ActionException; + + /** + * Provide code to undo the changes made by the doAction() function. + * @return return true if undoing the action was successful performed. + * @throws ActionException + */ + public abstract boolean undoAction() throws ActionException; + +} diff --git a/src/org/jalgo/module/dijkstra/actions/ActionException.java b/src/org/jalgo/module/dijkstra/actions/ActionException.java new file mode 100644 index 0000000..bb3eaa3 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ActionException.java @@ -0,0 +1,18 @@ +/* + * Created on 16.07.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +/** + * + * @author Stephan Creutz + */ +public class ActionException extends Exception { + + private static final long serialVersionUID = 1324373595192609350L; + + public ActionException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/ActionStack.java b/src/org/jalgo/module/dijkstra/actions/ActionStack.java new file mode 100644 index 0000000..0a2cbdb --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ActionStack.java @@ -0,0 +1,179 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + * + * Created on 09.05.2005 + */ +package org.jalgo.module.dijkstra.actions; + +/** + * This class implements a simple stack. In this stack You can move forward and + * backward. You can limit the stack size by providing an int in the + * constructor. A value of zero means unlimited size. + * + * @author Frank Staudinger + */ +// FIXME wieso kein Adapter zu org.jalgo.main.util.Stack (Stephan) +// wenn, dann java.util.Stack, org.jalgo.main.util.Stack ist gelöscht +// (Alexander) +public class ActionStack { + + final protected class Node { + + private Node m_PrevNode; + private Node m_NextNode; + private Action m_Action; + + public Node(Node PrevNode, Action action) { + m_PrevNode = PrevNode; + m_NextNode = null; + m_Action = action; + } + + public boolean hasNextNode() { + return m_NextNode != null; + } + + public boolean hasPrevNode() { + return m_PrevNode != null; + } + + public Action getAction() { + return m_Action; + } + + public Node getPrevNode() { + return m_PrevNode; + } + + public void setPrevNode(Node pNode) { + m_PrevNode = pNode; + } + + public Node getNextNode() { + return m_NextNode; + } + + public void setNextNode(Node pNode) { + m_NextNode = pNode; + } + } + + protected int m_nMaxCount; + protected int m_nCurrentCount; + protected Node m_pHead; + protected Node m_pTail; + + /** + * @param nMaxCount maximum of stack elements. A value of zero means + * unlimited size. + */ + public ActionStack(int nMaxCount) { + super(); + m_nCurrentCount = 0; + m_pHead = null; + m_pTail = null; + m_nMaxCount = (nMaxCount >= 0) ? nMaxCount : 0; + } + + /** + * @param pAction Reference to the action You want to add. + * @return Returns true if the action is in the stack, false if the stack is + * full + */ + public boolean add(Action pAction) { + boolean bCanInsert = ((m_nMaxCount <= 0) ? (true) + : (m_nCurrentCount < m_nMaxCount)); + + if (bCanInsert == true) { + Node pNewNode = new Node(m_pTail, pAction); + if (m_nCurrentCount == 0) m_pHead = pNewNode; + if (m_pTail != null) { + m_pTail.setNextNode(pNewNode); + } + m_pTail = pNewNode; + m_nCurrentCount++; + } + else { + // Stack ist voll -> die letzte Action fliegt raus + Node pOldHead = m_pHead; + m_pHead = pOldHead.getNextNode(); + m_nCurrentCount--; + return add(pAction); + } + return bCanInsert; + } + + /** + * @return Returns true if the stack pointer doesn't point to the top + * element. + */ + public boolean canMoveNext() { + if (m_nCurrentCount == 0) { return (m_pHead != null); } + return m_pTail.hasNextNode(); + } + + /** + * @return Returns the next action in the stack or null. + */ + public Action moveNext() { + if (canMoveNext() == false) return null; + + // Die erste Action wieder aus der Versenkung holen + if ((m_nCurrentCount == 0) && (m_pHead != null)) { + m_nCurrentCount++; + m_pTail = m_pHead; + return m_pHead.getAction(); + + } + + m_pTail = m_pTail.getNextNode(); + m_nCurrentCount++; + return m_pTail.getAction(); + } + + /** + * @return Returns true if the stack pointer doesn't point to the bottom + * element. + */ + public boolean canMovePrevious() { + return m_nCurrentCount != 0; + } + + /** + * @return Returns the previous action in the stack or null. + */ + public Action movePrevious() { + if (canMovePrevious() == false) return null; + + Action pAction = m_pTail.getAction(); + m_pTail = m_pTail.getPrevNode(); + m_nCurrentCount--; + return pAction; + } + + /** + * @return Returns the m_nCurrentCount field. + */ + public int getCount() { + return m_nCurrentCount; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.java b/src/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.java new file mode 100644 index 0000000..be547ed --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ApplyEdgeListAction.java @@ -0,0 +1,71 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 20.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.util.EdgeListParser; +import org.jalgo.module.dijkstra.util.ParsingException; + +/** + * @author Frank Staudinger + * This class uses the EdgeListParser to convert a string into a Graph and + * updates the Controllers model + * + */ +public class ApplyEdgeListAction extends ApplyGraphTextAction { + + /** + * @param ctrl Reference to the Controller object + * @param strEdgeList The text You want to parse. + * @throws ActionException ParsingException thrown by the EdgeListParser + */ + public ApplyEdgeListAction(Controller ctrl, String strEdgeList) throws ActionException { + super(ctrl, strEdgeList); + + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.demo.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + try { + + Graph gr = new EdgeListParser().getParsedEdgeList(this.m_strText, getOldGraph()); + this.getController().setGraph(gr); + } catch (ParsingException e) { + getController().setGraph(m_oldGraph); + } + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.demo.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + this.getController().setGraph(getOldGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.java b/src/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.java new file mode 100644 index 0000000..36f6273 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ApplyGraphTextAction.java @@ -0,0 +1,48 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 20.05.2005 + * + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank Staudinger + * Base for the ApplyEdgeListAction and ApplyNodeListAction + */ + +public abstract class ApplyGraphTextAction extends GraphAction { + + protected String m_strText; + + /** + * @param ctrl Controller-Object + * @param strText current text of the nodelist/edgelist textfield + */ + public ApplyGraphTextAction(Controller ctrl, String strText) throws ActionException { + super(ctrl); + m_strText = strText; + registerAndDo(true); + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.java b/src/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.java new file mode 100644 index 0000000..56cea44 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ApplyNodeListAction.java @@ -0,0 +1,68 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 20.05.2005 + * + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.util.NodeListParser; +import org.jalgo.module.dijkstra.util.ParsingException; + +/** + * @author Frank Staudinger + * This class uses the NodeListParser to convert a string into a Graph and + * updates the Controllers model + * + */ +public class ApplyNodeListAction extends ApplyGraphTextAction { + + /** + * @param ctrl Reference to the Controller object + * @param strText The text You want to parse. + * @throws ActionException ParsingException thrown by the NodeListParser + */ + public ApplyNodeListAction(Controller ctrl, String strText) throws ActionException { + super(ctrl, strText); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.demo.actions.Action#Do() + */ + public boolean doAction() throws ActionException { + try { + this.getController().setGraph(new NodeListParser().getParsedNodeList(this.m_strText, getOldGraph())); + } catch (ParsingException e) { + getController().setGraph(getOldGraph()); + } + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.demo.actions.Action#Undo() + */ + public boolean undoAction() throws ActionException { + this.getController().setGraph(getOldGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/CVS/Entries b/src/org/jalgo/module/dijkstra/actions/CVS/Entries new file mode 100644 index 0000000..a9dcf2b --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/CVS/Entries @@ -0,0 +1,25 @@ +/Action.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/ActionException.java/1.1/Mon Oct 24 20:17:23 2005/-kk/ +/ActionStack.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/ApplyEdgeListAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/ApplyGraphTextAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/ApplyNodeListAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/DeleteEdgeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/DeleteNodeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/GotoMacroStepAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/GotoMicroStepAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/GotoStepAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/GraphAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/MoveNodeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/NewEdgeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/NewNodeAction.java/1.3/Thu Jan 31 20:15:06 2008/-kk/ +/RedoAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/RescaleGraphAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/SetEditingModeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/SetStartNodeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/ShowAlgorithmPageAction.java/1.3/Thu Jan 31 20:15:06 2008/-kk/ +/ShowEditPageAction.java/1.4/Thu Jan 31 20:15:06 2008/-kk/ +/StartAnimationAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/StopAnimationAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/UndoAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ +/WeighEdgeAction.java/1.2/Thu Jan 31 20:15:06 2008/-kk/ diff --git a/src/org/jalgo/module/dijkstra/actions/CVS/Repository b/src/org/jalgo/module/dijkstra/actions/CVS/Repository new file mode 100644 index 0000000..fb51881 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/actions diff --git a/src/org/jalgo/module/dijkstra/actions/CVS/Root b/src/org/jalgo/module/dijkstra/actions/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.java b/src/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.java new file mode 100644 index 0000000..3ed1888 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/DeleteEdgeAction.java @@ -0,0 +1,59 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 01.06.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * This class provides the functionality for deleting an Edge. + * @author Hannes Strass + * + */ +public class DeleteEdgeAction extends GraphAction { + private Edge m_Edge; + + /** Creates a new DeleteEdgeAction, which deletes an Edge. + * @param ctrl the Controller + * @param edge the Edge to delete + * @throws ActionException + */ + public DeleteEdgeAction(Controller ctrl, Edge edge) throws ActionException { + super(ctrl); + this.m_Edge = edge; + this.registerAndDo(true); + + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().getGraph().setAllChangedFlagsFalse(); + getController().getGraph().deleteEdge(m_Edge); + getController().setGraph(getController().getGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/DeleteNodeAction.java b/src/org/jalgo/module/dijkstra/actions/DeleteNodeAction.java new file mode 100644 index 0000000..34764c6 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/DeleteNodeAction.java @@ -0,0 +1,60 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Node; + +/** + * This class provides the functionality for deleting a Node. + * @author Hannes Strass + * + */ +public class DeleteNodeAction extends GraphAction { + + private Node m_Node; + + /** Creates a new DeleteNodeAction, which deletes a Node. + * @param ctrl the Controller + * @param node the Node to delete + * @throws ActionException + */ + public DeleteNodeAction(Controller ctrl, Node node) throws ActionException { + super(ctrl); + this.m_Node = node; + this.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().getGraph().setAllChangedFlagsFalse(); + getController().getGraph().deleteNode(m_Node); + getController().getGraph().replaceMissingNodes(); + getController().setGraph(getController().getGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.java b/src/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.java new file mode 100644 index 0000000..2f8bb69 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/GotoMacroStepAction.java @@ -0,0 +1,47 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 19:24:12 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * This class moves to the naxt/previous macro step in the Dijkstra + * @author Frank Staudinger + * + */ +public class GotoMacroStepAction extends GotoStepAction { + + /** + * @param ctrl + * @param bNext true if you want to go forward + */ + public GotoMacroStepAction(Controller ctrl, boolean bNext) throws ActionException { + super(ctrl, 0); + + setGotoStepIndex(((bNext == true) ? getController().getNextMacroStepIndex() : getController() + .getPrevMacroStepIndex())); + registerAndDo(true); + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.java b/src/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.java new file mode 100644 index 0000000..3415345 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/GotoMicroStepAction.java @@ -0,0 +1,44 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 19:30:10 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank Staudinger + * + */ +public class GotoMicroStepAction extends GotoStepAction { + + /** + * @param ctrl + * @param bNext true if you want to go forward + */ + public GotoMicroStepAction(Controller ctrl, boolean bNext) throws ActionException { + super(ctrl, 0); + + setGotoStepIndex(((bNext == true) ? getController().getNextStepIndex() : getController().getPrevStepIndex())); + registerAndDo(true); + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/GotoStepAction.java b/src/org/jalgo/module/dijkstra/actions/GotoStepAction.java new file mode 100644 index 0000000..b9abb71 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/GotoStepAction.java @@ -0,0 +1,101 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 19:10:27 + * + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.*; + +/** + * @author Frank Staudinger + * + */ +public class GotoStepAction extends Action { + + protected int m_nGotoStep; + + protected int m_nLastStep; + + /** + * @param ctrl + * @param nGotoStepIndex zero-based index for the next step in the algo + * @param bExcuteNow true if the action should do it now + */ + public GotoStepAction(Controller ctrl, int nGotoStepIndex, boolean bExcuteNow) throws ActionException { + this(ctrl, nGotoStepIndex); + if (bExcuteNow == true) + super.registerAndDo(true); + } + + /** + * @param ctrl + * @param nGotoStepIndex zero-based index for the next step in the algo + * + */ + protected GotoStepAction(Controller ctrl, int nGotoStepIndex) throws ActionException { + super(ctrl); + m_nGotoStep = nGotoStepIndex; + m_nLastStep = getController().getCurrentStep(); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + + public boolean doAction() throws ActionException { + + State state = getController().getState(m_nGotoStep); + if (state != null) { + getController().setStatusbarText(state.getDescriptionEx()); + getController().setModifiedFlag(); + } + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + State state = getController().getState(m_nLastStep); + if (state != null) { + getController().setStatusbarText(state.getDescriptionEx()); + getController().setModifiedFlag(); + } + return true; + } + + /** + * @return Returns the m_nGotoStep. + */ + protected int getGotoStepIndex() { + return m_nGotoStep; + } + + /** + * @param gotoStep The m_nGotoStep to set. + */ + protected void setGotoStepIndex(int gotoStep) { + m_nGotoStep = gotoStep; + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/GraphAction.java b/src/org/jalgo/module/dijkstra/actions/GraphAction.java new file mode 100644 index 0000000..ac2575d --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/GraphAction.java @@ -0,0 +1,63 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 26.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Graph; + +/** + * @author Frank Staudinger + * + */ +public abstract class GraphAction extends Action { + + protected Graph m_oldGraph; + + protected Graph getOldGraph() { + return (m_oldGraph != null) ? (Graph) m_oldGraph.clone() : null; + } + + protected void setOldGraph(Graph oldGraph) { + if (oldGraph != null) + m_oldGraph = (Graph) oldGraph.clone(); + else + m_oldGraph = null; + } + + /** + * @param ctrl Controller for this action + */ + public GraphAction(Controller ctrl) { + super(ctrl); + setOldGraph(ctrl.getGraph()); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + getController().setGraph(getOldGraph()); + return true; + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/MoveNodeAction.java b/src/org/jalgo/module/dijkstra/actions/MoveNodeAction.java new file mode 100644 index 0000000..00cb835 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/MoveNodeAction.java @@ -0,0 +1,77 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 01.06.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Position; +import org.jalgo.module.dijkstra.model.Node; + +/** + * This class provides the functionality for changing the Position of a Node. + * @author Hannes Strass + * + */ +public class MoveNodeAction extends GraphAction { + private Node m_Node; + + private Position m_NewPosition; + + /** Creates a MoveNodeAction, which moves a Node. + * @param ctrl the Controller + * @param node the Node to move + * @param newPosition the new Position of the Node + * @throws ActionException + */ + public MoveNodeAction(Controller ctrl, Node node, Position newPosition) throws ActionException { + super(ctrl); + this.m_Node = node; + this.m_NewPosition = newPosition; + this.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + + Node node = getController().getGraph().findNode(m_Node.getIndex()); + if (node.getPosition().equals(m_NewPosition)) + return false; + getController().getGraph().setAllChangedFlagsFalse(); + node.setChanged(true); + node.setPosition(m_NewPosition); + getController().setGraph(getController().getGraph()); + + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + getController().setGraph(getOldGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/NewEdgeAction.java b/src/org/jalgo/module/dijkstra/actions/NewEdgeAction.java new file mode 100644 index 0000000..8c9a42a --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/NewEdgeAction.java @@ -0,0 +1,65 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 01.06.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * This class provides the functionality for creating a new Edge. + * @author Hannes Strass + * + */ +public class NewEdgeAction extends GraphAction { + private Node m_StartNode; + + private Node m_EndNode; + + /** Creates a NewEdgeAction, which creates a new Edge. + * @param ctrl the Controller + * @param startNode the start Node + * @param endNode the end Node + * @throws ActionException + */ + public NewEdgeAction(Controller ctrl, Node startNode, Node endNode) throws ActionException { + super(ctrl); + this.m_StartNode = startNode; + this.m_EndNode = endNode; + this.registerAndDo(true); + + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().getGraph().setAllChangedFlagsFalse(); + Edge newEdge = new Edge(this.m_StartNode, this.m_EndNode); + getController().getGraph().addEdge(newEdge); + getController().setGraph(getController().getGraph()); + + return true; + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/NewNodeAction.java b/src/org/jalgo/module/dijkstra/actions/NewNodeAction.java new file mode 100644 index 0000000..93416aa --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/NewNodeAction.java @@ -0,0 +1,92 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import java.awt.Dimension; +import java.awt.Point; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.Position; + +/** + * This class provides the functionality for creating a new Node. + * + * @author Hannes Strass, Martin Winter + * + */ +public class NewNodeAction +extends GraphAction { + + private Position position; + + /* + * Changed to Position position; because of this: Place a new node in the + * top right corner of the drawing rectangle Undo the last NewNodeAction + * compact the jAlgo-Window Redo the last NewNodeAction -> the Node will be + * invisible + * + * private Point m_screenCoordinates; private Rectangle m_Bounds; + */ + + /** + * Creates a NewNodeAction, which creates a new Node + * + * @param ctrl the Controller + * @param screenCoordinates Point on screen where user wants new Node to + * appear + * @param screenSize bounds of the canvas where Nodes can be drawn + * @throws ActionException + */ + public NewNodeAction(Controller ctrl, Point screenCoordinates, + Dimension screenSize) throws ActionException { + super(ctrl); + + position = new Position(screenCoordinates, screenSize); + this.registerAndDo(true); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() + throws ActionException { + + if (getController().getGraph().getNextNodeIndex() == 10) return false; + getController().getGraph().setAllChangedFlagsFalse(); + // Position position = new Position(m_screenCoordinates, m_Bounds); + getController().getGraph().addNode( + new Node(getController().getGraph().getNextNodeIndex(), position)); + getController().setGraph(getController().getGraph()); + + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/RedoAction.java b/src/org/jalgo/module/dijkstra/actions/RedoAction.java new file mode 100644 index 0000000..3ee5378 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/RedoAction.java @@ -0,0 +1,48 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 09.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank + * + */ +public class RedoAction extends Action { + /** + * + */ + public RedoAction(Controller ctrl) throws ActionException { + super(ctrl); + registerAndDo(false); + } + + public boolean doAction() throws ActionException { + return this.getController().redoAction(); + } + + public boolean undoAction() throws ActionException { + return this.getController().undoAction(); + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/RescaleGraphAction.java b/src/org/jalgo/module/dijkstra/actions/RescaleGraphAction.java new file mode 100644 index 0000000..c7ade9e --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/RescaleGraphAction.java @@ -0,0 +1,46 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 06.06.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Hannes Stra"s + * + */ +public class RescaleGraphAction extends GraphAction { + public RescaleGraphAction(Controller ctrl) throws ActionException { + super(ctrl); + this.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().getGraph().rescale(); + getController().setGraph(getController().getGraph()); + return true; + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/SetEditingModeAction.java b/src/org/jalgo/module/dijkstra/actions/SetEditingModeAction.java new file mode 100644 index 0000000..6816112 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/SetEditingModeAction.java @@ -0,0 +1,85 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 30.05.2005 18:26:35 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank + * + */ +public class SetEditingModeAction extends Action { + + protected int m_iMode; + + protected int m_iOldMode; + + /** + * @return Returns the m_iMode. + */ + protected int getMode() { + return m_iMode; + } + + /** + * @param mode The m_iMode to set. + */ + protected void setMode(int mode) { + m_iMode = mode; + } + + /** + * @param ctrl Controller for this action + * @param iMode new Editing mode + * @throws ActionException + */ + public SetEditingModeAction(Controller ctrl, int iMode) throws ActionException { + this(ctrl, iMode, false); + } + + public SetEditingModeAction(Controller ctrl, int iMode, boolean bRegister) throws ActionException { + super(ctrl); + m_iMode = iMode; + this.registerAndDo(bRegister); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + m_iOldMode = getController().getEditingMode(); + getController().setEditingMode(m_iMode); + getController().getGraph().setAllChangedFlagsFalse(); // HS + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + getController().setEditingMode(m_iOldMode); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/SetStartNodeAction.java b/src/org/jalgo/module/dijkstra/actions/SetStartNodeAction.java new file mode 100644 index 0000000..ee85689 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/SetStartNodeAction.java @@ -0,0 +1,91 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 31.05.2005 22:06:08 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.*; + +/** + * @author Frank + * + */ +public class SetStartNodeAction extends GraphAction { + + int m_nNewNode; + + int m_nOldNode = 0; + + int m_nOldStep = 0; + + /** + * @param ctrl Controller for this action + * @param nNode Index of the new start node + * @throws ActionException + */ + public SetStartNodeAction(Controller ctrl, int nNode) throws ActionException { + super(ctrl); + m_nNewNode = nNode; + Graph gr = getController().getGraph(); + Node node = gr.getStartNode(); + if (node != null) + m_nOldNode = node.getIndex(); + m_nOldStep = getController().getCurrentStep(); + super.registerAndDo(true); + + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + + Graph gr = getController().getGraph(); + Node node = gr.getStartNode(); + if (node != null) + node.setStart(false); + gr.findNode(m_nNewNode).setStart(true); + getController().setGraph(gr); + State state = getController().getState(0); + if (state != null) { + getController().setStatusbarText(state.getDescriptionEx()); + } + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + super.undoAction(); + getController().getGraph().findNode(m_nNewNode).setStart(false); + if (m_nOldNode > 0) + getController().getGraph().findNode(m_nOldNode).setStart(true); + State state = getController().getState(m_nOldStep); + if (state != null) { + getController().setStatusbarText(state.getDescriptionEx()); + } + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.java b/src/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.java new file mode 100644 index 0000000..54e792d --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ShowAlgorithmPageAction.java @@ -0,0 +1,76 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 30.05.2005 10:00:39 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.State; + +/** + * @author Frank + * + */ +public class ShowAlgorithmPageAction extends SetEditingModeAction { + + Graph m_oldGraph = null; + + public ShowAlgorithmPageAction(Controller ctrl) throws ActionException { + super(ctrl, Controller.MODE_ALGORITHM, true); + m_oldGraph = getController().getGraph(); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#Do() + */ + public boolean doAction() throws ActionException { + getController().showAlgorithmPage(); + Graph gr = getController().getGraph(); + Node node = gr.getStartNode(); + if (node == null && + gr.getNodeList().size() > 0) { //Alexander + gr.findNode(1).setStart(true); + } +// gr.getStartNode().getIndex(); --Alexander + getController().setGraph(gr); + super.doAction(); + State state = getController().getState(0); + if (state != null) { + getController().setStatusbarText(state.getDescriptionEx()); + getController().setModifiedFlag(); + } + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#Undo() + */ + public boolean undoAction() throws ActionException { + super.undoAction(); + getController().setGraph(m_oldGraph); + getController().showEditingPage(); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/ShowEditPageAction.java b/src/org/jalgo/module/dijkstra/actions/ShowEditPageAction.java new file mode 100644 index 0000000..84a2245 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/ShowEditPageAction.java @@ -0,0 +1,58 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 30.05.2005 10:39:37 + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; +//import org.jalgo.module.dijkstra.util.StatusbarText; + +/** + * @author Frank + * + */ +public class ShowEditPageAction extends SetEditingModeAction { + + /** + * @param ctrl + * @throws ActionException + */ + public ShowEditPageAction(Controller ctrl) throws ActionException { + super(ctrl, Controller.MODE_NO_TOOL_ACTIVE, true); + + } + + public boolean doAction() throws ActionException { + super.doAction(); +// getController().setStatusbarText(new StatusbarText("", null)); //$NON-NLS-1$ + getController().showEditingPage(); + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#Undo() + */ + public boolean undoAction() throws ActionException { + super.undoAction(); + getController().showAlgorithmPage(); + return true; + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/StartAnimationAction.java b/src/org/jalgo/module/dijkstra/actions/StartAnimationAction.java new file mode 100644 index 0000000..dbf2179 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/StartAnimationAction.java @@ -0,0 +1,56 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * @author Frank Staudinger + * + * Created on 09.06.2005 00:17:53 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +public class StartAnimationAction extends Action { + + protected int m_iMilliseconds; + + public StartAnimationAction(Controller ctrl, int iMilliseconds) throws ActionException { + super(ctrl); + m_iMilliseconds = iMilliseconds; + super.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().startAnimation(m_iMilliseconds); + return false; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + getController().stopAnimation(); + return false; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/StopAnimationAction.java b/src/org/jalgo/module/dijkstra/actions/StopAnimationAction.java new file mode 100644 index 0000000..4b4a06b --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/StopAnimationAction.java @@ -0,0 +1,61 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * @author Frank Staudinger + * + * Created on 09.06.2005 09:55:38 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank Staudinger + * + + */ +public class StopAnimationAction extends Action { + + protected int m_iMilliseconds; + + public StopAnimationAction(Controller ctrl) throws ActionException { + super(ctrl); + this.m_iMilliseconds = ctrl.getAnimationMillis(); + super.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().stopAnimation(); + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#undoAction() + */ + public boolean undoAction() throws ActionException { + getController().startAnimation(this.m_iMilliseconds); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/actions/UndoAction.java b/src/org/jalgo/module/dijkstra/actions/UndoAction.java new file mode 100644 index 0000000..9ef7a0a --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/UndoAction.java @@ -0,0 +1,45 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 09.05.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Frank Staudinger + * + */ +public class UndoAction extends RedoAction { + + public UndoAction(Controller ctrl) throws ActionException { + super(ctrl); + } + + public boolean doAction() throws ActionException { + return super.undoAction(); + } + + public boolean undoAction() throws ActionException { + return super.doAction(); + } +} diff --git a/src/org/jalgo/module/dijkstra/actions/WeighEdgeAction.java b/src/org/jalgo/module/dijkstra/actions/WeighEdgeAction.java new file mode 100644 index 0000000..6b17cdf --- /dev/null +++ b/src/org/jalgo/module/dijkstra/actions/WeighEdgeAction.java @@ -0,0 +1,64 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 01.06.2005 + * + */ +package org.jalgo.module.dijkstra.actions; + +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * This class provides the functionality for changing the weight of an Edge. + * @author Hannes Strass + * + */ +public class WeighEdgeAction extends GraphAction { + private int m_iNewWeight; + + private Edge m_Edge; + + /** Creates a new WeighEdgeAction, which changes the weight of an Edge. + * @param ctrl the Controller + * @param edge the Edge to weigh + * @param newWeight the new weight + * @throws ActionException + */ + public WeighEdgeAction(Controller ctrl, Edge edge, int newWeight) throws ActionException { + super(ctrl); + this.m_Edge = edge; + this.m_iNewWeight = newWeight; + this.registerAndDo(true); + } + + /* (non-Javadoc) + * @see org.jalgo.module.dijkstra.actions.Action#doAction() + */ + public boolean doAction() throws ActionException { + getController().getGraph().setAllChangedFlagsFalse(); + Edge edge = getController().getGraph().findEdge(m_Edge.getStartNode(), m_Edge.getEndNode()); + edge.setChanged(true); + edge.setWeight(this.m_iNewWeight); + getController().setGraph(getController().getGraph()); + return true; + } + +} diff --git a/src/org/jalgo/module/dijkstra/de.properties b/src/org/jalgo/module/dijkstra/de.properties new file mode 100644 index 0000000..1878647 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/de.properties @@ -0,0 +1,86 @@ +Module_name=Dijkstra +Module_version=1.1 +Module_authors=Alexander Claus, Frank Staudinger, Julian Stecklina, Hannes Straß, Steven Voigt, Martin Winter +Module_description_1=Dieses Modul behandelt Dijkstra's Algorithmus zum Finden kürzester Wege in Graphen. +Module_description_2=Es können Graphen modelliert werden, der Algorithmus wird intuitiv visualisiert. +Module_license=GNU General Public License + +Undo=Rückgängig +Undo_tooltip=Macht die letzte Änderung rückgängig. +Redo=Wiederherstellen +Redo_tooltip=Stellt die letzte Änderung wieder her. + +EditModeToolPanel.Tools=Werkzeuge +EditModeToolPanel.Add_move_node=Knoten erstellen/verschieben +EditModeToolPanel.Add_move_node_tooltip=Erstellen und verschieben Sie Knoten auf der Zeichenfläche +EditModeToolPanel.Add_eval_edge=Kante hinzufügen/bewerten +EditModeToolPanel.Add_eval_edge_tooltip=Erstellen und bewerten Sie Kanten intuitiv. +EditModeToolPanel.Remove_node=Knoten löschen +EditModeToolPanel.Remove_node_tooltip=Löschen Sie ausgewählte Knoten durch Klick. +EditModeToolPanel.Remove_edge=Kante löschen +EditModeToolPanel.Remove_edge_tooltip=Löschen Sie ausgewählte Kanten durch Klick. + +AlgorithmModeToolPanel.Tools=Werkzeuge +AlgorithmModeToolPanel.Start_node=Startknoten: +AlgorithmModeToolPanel.Algorithm_step=Algorithmusschritt: +AlgorithmModeToolPanel.Start_animation=Animation starten +AlgorithmModeToolPanel.Of=von +AlgorithmModeToolPanel.Go_to=Gehe zu + +GraphPanel.Graph=Graph +GraphPanel.Arrange_nodes_automatically=Knoten automatisch anordnen +GraphPanel.Arrange_tooltip=Alle Knoten automatisch in einem regelmäßigen Vieleck anordnen. + +NodeListPanel.Node_list=Knotenliste + +EdgeListPanel.Edge_list=Kantenliste +EdgeListPanel.Apply=Anwenden + +MatrixPanel.Distance_matrix=Distanzmatrix +MatrixPanel.Tooltip=Eingabe von Kantengewichten. Kante löschen durch Eingabe von Minus (-). + +AlgorithmModeCalculationTablePanel.Calc_table=Rechentableau + +AlgorithmModeResultTablePanel.Result=Ergebnis + +StatusbarComposite.Start_algorithm=Algorithmus starten +StatusbarComposite.Start_algorithm_tooltip=Wechselt die Ansicht und startet den Algorithmus +StatusbarComposite.Edit_graph=Graph bearbeiten +StatusbarComposite.Edit_graph_tooltip=Wechselt die Ansicht zum Bearbeiten des Graphen +StatusbarComposite.Restart_algorithm=Algorithmus neu starten + +EdgeListParser.Syntax_error_1=Kantenliste: Syntaxfehler im Eingabestring: +EdgeListParser.Syntax_error_2=Syntaxfehler in der Kantenliste: ( +EdgeListParser.Syntax_error_3=). Erwartet: (Startknoten, Gewicht, Endknoten). +EdgeListParser.Syntax_hint_1=Kantenliste muss mit "{" beginnen\! +EdgeListParser.Syntax_hint_2=Kantenliste muss auf "}" enden\! +EdgeListParser.Syntax_hint_3=Kante muss mit "(" beginnen\! +EdgeListParser.Syntax_hint_4=Kante muss auf "(" enden\! +EdgeListParser.Syntax_hint_5=Kanten m\u00FCssen mit "," getrennt werden\! +EdgeListParser.Syntax_hint_6=Einzelne Elemente innerhalb der Kante m\u00FCssen mit "," getrennt werden\! +EdgeListParser.Syntax_error_4=Unerwartetes Ende des Eingabestrings\! Erwartet: Startknoten. +EdgeListParser.Syntax_error_5=Unerwartetes Ende des Eingabestrings\! Erwartet: Endknoten. +NodeListParser.Syntax_error_1=Knotenliste: Syntaxfehler im Eingabestring: " +NodeListParser.Syntax_hint_1=Knotenliste muss mit "{" beginnen\! +NodeListParser.Syntax_hint_2=Knotenliste muss auf "}" enden\! +NodeListParser.Syntax_error_2=Unerwartetes Ende des Eingabestrings\! Erwartet: Knoten. +NodeListParser.Syntax_error_3=Kein zul\u00E4ssiger Knoten: +NodeListParser.Syntax_hint_3=\! Nur Dezimalzahlen von 1 - 9 erlaubt. +NodeListParser.Syntax_hint_4=Knoten m\u00FCssen mit "," getrennt werden\! +DijkstraAlgorithm.Node=Knoten +DijkstraAlgorithm.Is_over=\ ist \u00FCber +DijkstraAlgorithm.Reachable_on_shorter_path=\ auf einem k\u00FCrzeren Wege erreichbar. +DijkstraAlgorithm.Reachable_over_existing_path_shorter=\ ist \u00FCber den bestehenden Weg k\u00FCrzer zu erreichen. +DijkstraAlgorithm.New_node=Neuer Knoten im Rand: +DijkstraAlgorithm.Error_1=Predecessor of border node is null +DijkstraAlgorithm.Error_2=Node equals predecessor +DijkstraAlgorithm.Choosed_as_start_node=\ als Startknoten gew\u00E4hlt. +DijkstraAlgorithm.Fringe_complete_for_start_node=Randknotenmenge f\u00FCr Startknoten komplett. +DijkstraAlgorithm.New_choosen=Neuer gew\u00E4hlter +DijkstraAlgorithm.Fringe_complete=Randknotenmenge komplett +DijkstraAlgorithm.Algorithm_finished=Algorithmus beendet +AlgorithmCalculationTableComposite.Chosen=Gew\u00E4hlt +AlgorithmResultTableComposite.Target_node=Zielknoten +AlgorithmResultTableComposite.Path_length=Wegl\u00E4nge +AlgorithmResultTableComposite.Shortest_path=k\u00FCrzester Weg +AlgorithmCalculationTableComposite.Fringe_node=Randknoten \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/en.properties b/src/org/jalgo/module/dijkstra/en.properties new file mode 100644 index 0000000..01a69e1 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/en.properties @@ -0,0 +1,86 @@ +Module_name=Dijkstra +Module_version=1.1 +Module_authors=Alexander Claus, Frank Staudinger, Julian Stecklina, Hannes Straß, Steven Voigt, Martin Winter +Module_description_1=This module is about Dijkstra's algorithm for finding the shortest path in graphs. +Module_description_2=Graphs can be created, the algorithm will be visualized intuitively. +Module_license=GNU General Public License + +Undo=Undo +Undo_tooltip=Undoes the last change. +Redo=Redo +Redo_tooltip=Redoes the last change. + +EditModeToolPanel.Tools=Tools +EditModeToolPanel.Add_move_node=Add/Move node +EditModeToolPanel.Add_move_node_tooltip=Create and move nodes on canvas. +EditModeToolPanel.Add_eval_edge=Add/Evaluate edge +EditModeToolPanel.Add_eval_edge_tooltip=Create and evaluate edges intuitively. +EditModeToolPanel.Remove_node=Remove node +EditModeToolPanel.Remove_node_tooltip=Remove nodes per click. +EditModeToolPanel.Remove_edge=Remove edge +EditModeToolPanel.Remove_edge_tooltip=Remove edges per click. + +AlgorithmModeToolPanel.Tools=Tools +AlgorithmModeToolPanel.Start_node=Start node: +AlgorithmModeToolPanel.Algorithm_step=Algorithm step: +AlgorithmModeToolPanel.Start_animation=Start animation +AlgorithmModeToolPanel.Of=of +AlgorithmModeToolPanel.Go_to=Go to + +GraphPanel.Graph=Graph +GraphPanel.Arrange_nodes_automatically=Arrange nodes automatically +GraphPanel.Arrange_tooltip=Arranges all nodes in a regular polygon. + +NodeListPanel.Node_list=Nodelist + +EdgeListPanel.Edge_list=Edgelist +EdgeListPanel.Apply=Apply + +MatrixPanel.Distance_matrix=Distance matrix +MatrixPanel.Tooltip=Insert edge weights. Type '-' for removing edge. + +AlgorithmModeCalculationTablePanel.Calc_table=Calculation table + +AlgorithmModeResultTablePanel.Result=Result + +StatusbarComposite.Start_algorithm=Start algorithm +StatusbarComposite.Start_algorithm_tooltip=Switches the layout and starts the algorithm +StatusbarComposite.Edit_graph=Edit graph +StatusbarComposite.Edit_graph_tooltip=Switches the layout for editing the graph +StatusbarComposite.Restart_algorithm=Restart algorithm + +EdgeListParser.Syntax_error_1=Edgelist: syntax error in input string: +EdgeListParser.Syntax_error_2=syntax error in edgelist: ( +EdgeListParser.Syntax_error_3=). Expected: (start node, weight, end node). +EdgeListParser.Syntax_hint_1=Edgelist has to start with "{"\! +EdgeListParser.Syntax_hint_2=Edgelist has to end with "}"\! +EdgeListParser.Syntax_hint_3=Edge has to start with "("\! +EdgeListParser.Syntax_hint_4=Edge has to end with ")"\! +EdgeListParser.Syntax_hint_5=Separate edges with ","\! +EdgeListParser.Syntax_hint_6=Separate edge elements with ","\! +EdgeListParser.Syntax_error_4=Unexpected end of input string\! Expected: start node. +EdgeListParser.Syntax_error_5=Unexpected end of input string\! Expected: end node. +NodeListParser.Syntax_error_1=Nodelist: syntax error in input string: +NodeListParser.Syntax_hint_1=Nodelist has to start with "{"\! +NodeListParser.Syntax_hint_2=Nodelist has to end with "}"\! +NodeListParser.Syntax_error_2=Unexpected end of input string\! Expected: node. +NodeListParser.Syntax_error_3=No valid node: +NodeListParser.Syntax_hint_3=\! Only integers from 1 to 9 allowed. +NodeListParser.Syntax_hint_4=Separate nodes with ","\! +DijkstraAlgorithm.Node=Node +DijkstraAlgorithm.Is_over=\ is over +DijkstraAlgorithm.Reachable_on_shorter_path=\ reachable on shorter path. +DijkstraAlgorithm.Reachable_over_existing_path_shorter=\ is reachable shorter over existing path. +DijkstraAlgorithm.New_node=New node in fringe: +DijkstraAlgorithm.Error_1=Predecessor of border node is null +DijkstraAlgorithm.Error_2=Node equals predecessor +DijkstraAlgorithm.Choosed_as_start_node=\ choosed as start node. +DijkstraAlgorithm.Fringe_complete_for_start_node=Fringe complete for start node. +DijkstraAlgorithm.New_choosen=New chosen +DijkstraAlgorithm.Fringe_complete=Fringe complete +DijkstraAlgorithm.Algorithm_finished=Algorithm finished +AlgorithmCalculationTableComposite.Chosen=Chosen +AlgorithmResultTableComposite.Target_node=Target node +AlgorithmResultTableComposite.Path_length=Path length +AlgorithmResultTableComposite.Shortest_path=Shortest Path +AlgorithmCalculationTableComposite.Fringe_node=Fringe node \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gfx/CVS/Entries b/src/org/jalgo/module/dijkstra/gfx/CVS/Entries new file mode 100644 index 0000000..24cc20a --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/CVS/Entries @@ -0,0 +1,5 @@ +/EdgeVisual.java/1.3/Thu Jan 31 20:15:10 2008/-kk/ +/EdgeWeightVisual.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/NewEdgeLine.java/1.2/Sat Mar 4 13:36:03 2006/-kk/ +/NodeVisual.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/Visual.java/1.3/Thu Jan 31 20:15:10 2008/-kk/ diff --git a/src/org/jalgo/module/dijkstra/gfx/CVS/Repository b/src/org/jalgo/module/dijkstra/gfx/CVS/Repository new file mode 100644 index 0000000..f0c8d6f --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/gfx diff --git a/src/org/jalgo/module/dijkstra/gfx/CVS/Root b/src/org/jalgo/module/dijkstra/gfx/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/gfx/EdgeVisual.java b/src/org/jalgo/module/dijkstra/gfx/EdgeVisual.java new file mode 100644 index 0000000..425ce70 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/EdgeVisual.java @@ -0,0 +1,235 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 06.05.2005 + */ + +package org.jalgo.module.dijkstra.gfx; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Shape; +import java.awt.Stroke; +import java.awt.geom.AffineTransform; +import java.awt.geom.GeneralPath; + +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.GraphElement; + +/** + * Visual representation of an edge connecting two nodes. It has an + * {@link EdgeWeightVisual} at its center which displays the edge's weight. + * + * @author Martin Winter + */ +public class EdgeVisual +extends Visual { + + private NodeVisual source; + private NodeVisual target; + private Edge modelEdge; + private EdgeWeightVisual weightVisual; + + private transient Color lineColor; + private transient Stroke lineStroke; + private transient boolean arrowVisible; + private transient boolean bigArrow; + + private static final Stroke boldLineStroke = new BasicStroke(7); + private static final Stroke thinLineStroke = new BasicStroke(3); + private static final GeneralPath arrow = new GeneralPath(); + static { + arrow.moveTo(0, 0); + arrow.lineTo(-22, -11); + arrow.lineTo(-22, 11); + arrow.closePath(); + } + + /** + * Creates a new edge visual, which is backed by the given model edge. + * + * @param modelEdge the model edge this edge visual represents + */ + public EdgeVisual(Edge modelEdge) { + source = (NodeVisual)modelEdge.getStartNode().getVisual(); + target = (NodeVisual)modelEdge.getEndNode().getVisual(); + this.modelEdge = modelEdge; + + weightVisual = new EdgeWeightVisual(modelEdge); + + updateLocation(GraphDisplay.getScreenSize()); + update(); // Initialize appearance. + } + + public EdgeWeightVisual getWeightVisual() { + return weightVisual; + } + + public void setControllerMode(int controllerMode) { + super.setControllerMode(controllerMode); + weightVisual.setControllerMode(controllerMode); + } + + /* Methods inherited from Visual. */ + + /** + * Update appearance according to flags. Call this method after modifying + * any flags. The flags are also passed on the the edge weight visual. + */ + public void update() { + weightVisual.update(); + if (isInEditingMode()) { + // Flag with highest priority comes first. + if (modelEdge.isActive()) { + lineColor = Visual.RED; + lineStroke = boldLineStroke; + arrowVisible = false; + } + else if (modelEdge.isHighlighted()) { + lineColor = Visual.BLACK; + lineStroke = thinLineStroke; + arrowVisible = false; + } + else if (modelEdge.isChanged()) { + lineColor = Visual.RED; + lineStroke = thinLineStroke; + arrowVisible = false; + } + else { + lineColor = Visual.BLACK; + lineStroke = thinLineStroke; + arrowVisible = false; + } + } + else { + if (modelEdge.isReversed()) { + //TODO: assert, that update is never called twice in alg.mode + NodeVisual tmp = source; + source = target; + target = tmp; + } + if (modelEdge.isChosen()) { + lineColor = Visual.GREEN; + lineStroke = boldLineStroke; + arrowVisible = true; + bigArrow = true; + } + else if (modelEdge.isBorder()) { + if (modelEdge.isActive()) { + if (modelEdge.isConflict()) { + lineColor = Visual.ORANGE; + lineStroke = boldLineStroke; + arrowVisible = true; + bigArrow = true; + } + else { + lineColor = Visual.RED; + lineStroke = boldLineStroke; + arrowVisible = true; + bigArrow = true; + } + } + else { + lineColor = Visual.ORANGE; + lineStroke = thinLineStroke; + arrowVisible = true; + bigArrow = false; + } + } + else { + lineColor = Visual.GRAY; + lineStroke = thinLineStroke; + arrowVisible = false; + } + } + } + + /** + * Retrieves a Shape object, which represents the arrow for the + * backing edge. For correct orientation the angle theta is + * passed here. + * + * @param theta the angle of the edge + * @return the arrow of this edge as Shape + */ + private Shape getArrow(double theta) { + AffineTransform transform = new AffineTransform(); + transform.translate(target.getCenter().getX(), target.getCenter().getY()); + transform.rotate(theta); + transform.translate(-NodeVisual.NODE_RADIUS, 0); + if (!bigArrow) transform.scale(0.6, 0.6); + return arrow.createTransformedShape(transform); + } + + @Override + public void draw(Graphics2D g, Dimension screenSize) { + double deltaX = target.getCenter().getX() - source.getCenter().getX(); + double deltaY = target.getCenter().getY() - source.getCenter().getY(); + double theta = Math.atan(deltaY/deltaX); + if (deltaX < 0.0) theta = theta+Math.PI; + + g.setColor(lineColor); + g.setStroke(lineStroke); + if (arrowVisible) { + // draw line shorter to avoid intersection with arrowhead + g.drawLine( + source.getCenter().x, + source.getCenter().y, + (int)(target.getCenter().x - Math.cos(theta)* + (NodeVisual.NODE_RADIUS+12)), + (int)(target.getCenter().y - Math.sin(theta)* + (NodeVisual.NODE_RADIUS+12))); + weightVisual.draw(g, screenSize); + g.fill(getArrow(theta)); + } + else { + g.drawLine(source.getCenter().x, source.getCenter().y, + target.getCenter().x, target.getCenter().y); + weightVisual.draw(g, screenSize); + } + } + + @Override + public void updateModel(GraphElement edge) { + this.source = (NodeVisual)((Edge)edge).getStartNode().getVisual(); + this.target = (NodeVisual)((Edge)edge).getEndNode().getVisual(); + weightVisual.updateModel(edge); + } + + @Override + public boolean hit(Dimension screenSize, Point p) { + return weightVisual.hit(screenSize, p); + } + + @Override + public void updateLocation(Dimension screenSize) { + source.updateLocation(screenSize); + target.updateLocation(screenSize); + weightVisual.updateLocation(screenSize); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.java b/src/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.java new file mode 100644 index 0000000..571f899 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/EdgeWeightVisual.java @@ -0,0 +1,218 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 10.05.2005 + */ + +package org.jalgo.module.dijkstra.gfx; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics2D; +import java.awt.Point; + +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.GraphElement; + +/** + * Visual representation of an edge weight, displayed at the center of an + * {@link EdgeVisual}. It allows the weight to be changed interactively with + * the mouse.
          + *
          + * Note: An edge weight visual has three actual drawing components: a + * label, a circle and a square. The label is always visible, but only one of + * the other two is displayed at any point in time. The circle is used to + * "punch a hole" in the edge visual under it, so the label can be easily read. + * The square is used when the edge weight visual is highlighted or its weight + * is interactively changed. + * + * @author Martin Winter + */ +public class EdgeWeightVisual +extends Visual { + + private Edge modelEdge; + private int weight; + private Point initialLocation; + private int initialWeight; + private Point center; + + private transient Color boxColor; + private transient Color labelColor; + private transient boolean boxVisible; + + private static final int WEIGHT_DIAMETER = 30; + private static final int WEIGHT_RADIUS = WEIGHT_DIAMETER / 2; + private static final Font labelFont = + new Font("Verdana", java.awt.Font.BOLD, 19); + + /** + * Creates a new edge weight visual on an edge visual. + * + * @param modelEdge the model edge this edge weight visual represents + */ + public EdgeWeightVisual(Edge modelEdge) { + this.modelEdge = modelEdge; + this.weight = modelEdge.getWeight(); + + update(); + } + + /** + * Sets the weight of the edge weight visual. It does not change the + * weight of the model edge. Values are automatically limited to the range 0 + * ... 99. + * + * @param weight the weight + */ + public void setWeight(int weight) { + this.weight = Math.min(weight, 99); + this.weight = Math.max(this.weight, 0); + } + + /** + * Returns the weight of the edge weight visual. It does not fetch + * the the weight from the model edge. + * + * @return the weight + */ + public int getWeight() { + return weight; + } + + public void beginDragging(Point startPoint) { + initialLocation = startPoint; + initialWeight = getWeight(); + } + + public void updateWeightToDragging(Point currPoint) { + setWeight(initialWeight - (currPoint.y-initialLocation.y)/5); + } + + /* Methods inherited from Visual. */ + + /** + * Update appearance according to flags. Call this method after modifying + * any flags. + */ + public void update() { + if (isInEditingMode()) { + // Flag with highest priority comes first. + if (modelEdge.isActive()) { + boxColor = Visual.RED; + boxVisible = true; + labelColor = Visual.WHITE; + } + else if (modelEdge.isHighlighted()) { + boxColor = Visual.BLACK; + boxVisible = true; + labelColor = Visual.WHITE; + } + else if (modelEdge.isChanged()) { + boxVisible = false; + labelColor = Visual.RED; + } + else { + boxVisible = false; + labelColor = Visual.BLACK; + } + } + else { + if (modelEdge.isChosen()) { + boxVisible = false; + labelColor = Visual.GREEN; + } + else if (modelEdge.isBorder()) { + if (modelEdge.isActive()) { + if (modelEdge.isConflict()) { + boxVisible = false; + labelColor = Visual.ORANGE; + } + else { + boxVisible = false; + labelColor = Visual.RED; + } + } + else { + boxVisible = false; + labelColor = Visual.ORANGE; + } + } + else { + boxVisible = false; + labelColor = Visual.GRAY; + } + } + } + + private void setCenter(Point screenPoint) { + center = screenPoint; + } + + private Point getCenter() { + return center; + } + + public void updateLocation(Dimension screenSize) { + Point n1Point = + ((NodeVisual)modelEdge.getStartNode().getVisual()).getCenter(); + Point n2Point = + ((NodeVisual)modelEdge.getEndNode().getVisual()).getCenter(); + setCenter(new Point( + (n1Point.x+n2Point.x)/2, + (n1Point.y+n2Point.y)/2)); + } + + @Override + public void draw(Graphics2D g, Dimension screenSize) { + updateLocation(screenSize); + if (boxVisible) { + g.setColor(boxColor); + g.fillRect(center.x-WEIGHT_RADIUS, center.y-WEIGHT_RADIUS, + WEIGHT_DIAMETER, WEIGHT_DIAMETER); + } + else { + g.setColor(Visual.WHITE); + g.fillOval(center.x-WEIGHT_RADIUS, center.y-WEIGHT_RADIUS, + WEIGHT_DIAMETER, WEIGHT_DIAMETER); + } + g.setColor(labelColor); + g.setFont(labelFont); + if (getWeight()<10) g.drawString(""+getWeight(), center.x-7, center.y+8); + else g.drawString(""+getWeight(), center.x-14, center.y+8); + } + + @Override + public void updateModel(GraphElement modelElement) { + this.modelEdge = (Edge)modelElement; + weight = modelEdge.getWeight(); + } + + @Override + public boolean hit(Dimension screenSize, Point p) { + if (getCenter().distance(p) < 10) return true; + return false; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gfx/NewEdgeLine.java b/src/org/jalgo/module/dijkstra/gfx/NewEdgeLine.java new file mode 100644 index 0000000..25244de --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/NewEdgeLine.java @@ -0,0 +1,47 @@ +package org.jalgo.module.dijkstra.gfx; + +import java.awt.geom.Line2D; +import java.awt.geom.Point2D; + +import org.jalgo.module.dijkstra.model.Node; + +/** + * The class NewEdgeLine represents a simple line, which is shown + * during the user creates a new edge. + * + * @author Alexander + */ +public class NewEdgeLine +extends Line2D.Double { + + private final Node sourceNode; + + public NewEdgeLine(Node sourceNode) { + this.sourceNode = sourceNode; + setP2(((NodeVisual)sourceNode.getVisual()).getCenter()); + } + + public Node getSourceNode() { + return sourceNode; + } + + @Override + public Point2D getP1() { + return ((NodeVisual)sourceNode.getVisual()).getCenter(); + } + + @Override + public double getX1() { + return getP1().getX(); + } + + @Override + public double getY1() { + return getP1().getY(); + } + + public void setP2(Point2D p2) { + x2 = p2.getX(); + y2 = p2.getY(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gfx/NodeVisual.java b/src/org/jalgo/module/dijkstra/gfx/NodeVisual.java new file mode 100644 index 0000000..802abb9 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/NodeVisual.java @@ -0,0 +1,212 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 06.05.2005 + */ + +package org.jalgo.module.dijkstra.gfx; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Stroke; + +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.GraphElement; +import org.jalgo.module.dijkstra.model.Node; + +/** + * Visual representation of a node. It can be connected with other node visuals + * using {@link EdgeVisual} objects.
          + *
          + * Note: What is actually drawn is two circles (an inner and an outer + * circle), and a label. The inner circle is visible, whereas the outer circle + * acts as a spacer for the line connection of edge visuals (see the class + * description there for more info). + * + * @author Martin Winter, Hannes Strass + */ +public class NodeVisual +extends Visual { + + private Point center; + private Node modelNode; + + private Color fillingColor; + private Color contourColor; + private Color labelColor; + + private static final int NODE_DIAMETER = 32; + static final int NODE_RADIUS = NODE_DIAMETER / 2; + private static final Stroke contourStroke = new BasicStroke(3); + private static final java.awt.Font labelFont = + new java.awt.Font("Verdana", java.awt.Font.BOLD, 20); + + /** + * Creates a new node visual. + * + * @param modelNode the model node that this node visual represents + */ + public NodeVisual(Node modelNode) { + this.modelNode = modelNode; + + center = modelNode.getPosition().getScreenPoint( + GraphDisplay.getScreenSize()); + + update(); // Initialize appearance. + } + + /** + * Sets the center of the node visual in pixel coordinates. + * + * @param center the center of the node visual in pixel coordinates + */ + public void setCenter(Point center) { + this.center = center; + } + + /** + * Returns the center of the node visual in pixel coordinates. + * + * @return the center of the node visual in pixel coordinates + */ + public Point getCenter() { + return center; + } + + /* Methods inherited from Visual. */ + + /** + * Update appearance according to flags. Call this method after modifying + * any flags. + */ + public void update() { + if (isInEditingMode()) { + // Flag with highest priority comes first. + if (modelNode.isActive()) { + fillingColor = Visual.RED; + contourColor = Visual.RED; + labelColor = Visual.WHITE; + } + else if (modelNode.isHighlighted()) { + fillingColor = Visual.BLACK; + contourColor = Visual.BLACK; + labelColor = Visual.WHITE; + } + else if (modelNode.isChanged()) { + fillingColor = Visual.WHITE; + contourColor = Visual.RED; + labelColor = Visual.RED; + } + else { + fillingColor = Visual.WHITE; + contourColor = Visual.BLACK; + labelColor = Visual.BLACK; + } + } + else { + if (modelNode.isStart()) { + if (modelNode.isActive()) { + fillingColor = Visual.BLUE; + contourColor = Visual.BLUE; + labelColor = Visual.WHITE; + } + else { + fillingColor = Visual.WHITE; + contourColor = Visual.BLUE; + labelColor = Visual.BLUE; + } + } + else if (modelNode.isChosen()) { + if (modelNode.isActive()) { + fillingColor = Visual.GREEN; + contourColor = Visual.GREEN; + labelColor = Visual.WHITE; + } + else { + fillingColor = Visual.WHITE; + contourColor = Visual.GREEN; + labelColor = Visual.GREEN; + } + } + else if (modelNode.isBorder()) { + if (modelNode.isActive()) { + fillingColor = Visual.RED; + contourColor = Visual.RED; + labelColor = Visual.WHITE; + } + else { + fillingColor = Visual.WHITE; + contourColor = Visual.ORANGE; + labelColor = Visual.ORANGE; + } + } + else { + fillingColor = Visual.WHITE; + contourColor = Visual.GRAY; + labelColor = Visual.GRAY; + } + } + + // Explicitly perform drawing update. +// performUpdate(); + } + + public void updateModel(GraphElement node) { + this.modelNode = (Node)node; + } + + @Override + public void draw(Graphics2D g, Dimension screenSize) { + g.setColor(fillingColor); + g.fillOval( + getCenter().x-NODE_RADIUS, + getCenter().y-NODE_RADIUS, + NODE_DIAMETER, NODE_DIAMETER); + + g.setColor(contourColor); + g.setStroke(contourStroke); + g.drawOval( + getCenter().x-NODE_RADIUS, + getCenter().y-NODE_RADIUS, + NODE_DIAMETER, NODE_DIAMETER); + + g.setColor(labelColor); + g.setFont(labelFont); + g.drawString(modelNode.getLabel(), getCenter().x-7, getCenter().y+8); + } + + @Override + public boolean hit(Dimension screenSize, Point p) { + return + modelNode.getPosition().getScreenPoint(screenSize).distance(p) < 20; + } + + @Override + public void updateLocation(Dimension screenSize) { + setCenter(modelNode.getPosition().getScreenPoint(screenSize)); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gfx/Visual.java b/src/org/jalgo/module/dijkstra/gfx/Visual.java new file mode 100644 index 0000000..e67cbb4 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gfx/Visual.java @@ -0,0 +1,145 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2005 + */ + +package org.jalgo.module.dijkstra.gfx; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Point; +import java.io.Serializable; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.GraphElement; + +/** + * Semi-abstract class that serves as a foundation for visual representation + * objects. Visuals are wrapper objects which contain other actual drawing + * elements that are displayed.
          + *
          + * The flags of the underlying model element are interpreted by the update() + * method, which is implemented differently by each visual subclass and changes + * the appearance of the drawing elements. Most flags are not exclusive but can + * be interpreted in a hierarchic manner. For example, the ACTIVE flag overrides + * all other flags, CHANGED has second priority, and so on. In addition, some + * flags have different meanings depending on the mode (editing or algorithm) or + * may have no meaning at all in one of the modes. + * + * @author Martin Winter + */ +public abstract class Visual +implements Serializable { + + /** A custom red color (#CC0000). */ + public static Color RED = new Color(204, 0, 0); + + /** A custom orange color (#CC9900). */ + public static Color ORANGE = new Color(204, 153, 0); + + /** A custom green color (#009900). */ + public static Color GREEN = new Color(0, 153, 0); + + /** A custom blue color (#000099). */ + public static Color BLUE = new Color(0, 0, 153); + + /** A custom white color (#FFFFFF). */ + public static Color WHITE = new Color(255, 255, 255); + + /** A custom gray color (#999999). */ + public static Color GRAY = new Color(153, 153, 153); + + /** A custom black color (#000000). */ + public static Color BLACK = new Color(0, 0, 0); + + private int controllerMode; + + /** + * Returns the mode of the controller. + * + * @return the mode of the controller or -1 controller is null + */ + public int getControllerMode() { + return controllerMode; + } + + public void setControllerMode(int controllerMode) { + this.controllerMode = controllerMode; + } + + /** + * Returns true if the controller is in editing mode. + * + * @return true if the controller is in editing mode + */ + public boolean isInEditingMode() { + return (getControllerMode() != Controller.MODE_ALGORITHM); + } + + /** + * Update appearance according to flags. Call this method after modifying + * any flags. + */ + public abstract void update(); + + /** + * Determines, if the given point on screen hits the current visual. For + * additional information to determine the current scale, the screenSize is + * given. + * + * @param screenSize the current size of the display component + * @param p the point to be tested + * @return true, if p hits this visual, + * false otherwise + */ + public abstract boolean hit(Dimension screenSize, Point p); + + /** + * This method is called, when graph is repainted. Every visual component + * has to implement this method to determine how to draw itself. + * + * @param g the Graphics2D context to draw on it + * @param screensize the size of the GraphDisplay component + */ + public abstract void draw(Graphics2D g, Dimension screensize); + + /** + * Updates the reference to the backing model element. Without use of this, + * sometimes there occur strange things... (Reason: the graph is cloned all + * the way.) + * + * @param modelElement the model element to synchronize + */ + public abstract void updateModel(GraphElement modelElement); + + /** + * Updates the location of this visual component regarding to the given size + * of the display component. + * + * @param screenSize the size of the display component + */ + public abstract void updateLocation(Dimension screenSize); +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/CVS/Entries b/src/org/jalgo/module/dijkstra/gui/CVS/Entries new file mode 100644 index 0000000..8152307 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/CVS/Entries @@ -0,0 +1,4 @@ +/Controller.java/1.4/Tue Oct 6 08:39:33 2009/-kk/ +/GUIController.java/1.2/Sat Mar 4 13:36:09 2006/-kk/ +D/components//// +D/event//// diff --git a/src/org/jalgo/module/dijkstra/gui/CVS/Repository b/src/org/jalgo/module/dijkstra/gui/CVS/Repository new file mode 100644 index 0000000..ef6bc78 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/gui diff --git a/src/org/jalgo/module/dijkstra/gui/CVS/Root b/src/org/jalgo/module/dijkstra/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/gui/Controller.java b/src/org/jalgo/module/dijkstra/gui/Controller.java new file mode 100644 index 0000000..90cf871 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/Controller.java @@ -0,0 +1,664 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * @author Frank Staudinger, Julian Stecklina, Martin Winter, Hannes Strass, + * Steven Voigt + * + * + */ +package org.jalgo.module.dijkstra.gui; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.Timer; + +import org.jalgo.main.InternalErrorException; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.module.dijkstra.ModuleConnector; +import org.jalgo.module.dijkstra.actions.Action; +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.ActionStack; +import org.jalgo.module.dijkstra.actions.ShowAlgorithmPageAction; +import org.jalgo.module.dijkstra.actions.ShowEditPageAction; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.DijkstraAlgorithm; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.State; + +/** + * The Controller is the central point of the Dijkstra's MVC-architecture. It + * controls all operations and notifys it's observers about changes in the + * model. + * + * @author Alexander Claus, Frank Staudinger, Julian Stecklina, Martin Winter, + * Hannes Strass, Steven Voigt + */ +public class Controller +extends Observable { + + private class _Observable + extends Observable { + + public _Observable() { + super(); + } + + /* + * (non-Javadoc) + * + * @see java.util.Observable#clearChanged() + */ + protected synchronized void clearChanged() { + super.clearChanged(); + } + + /* + * (non-Javadoc) + * + * @see java.util.Observable#setChanged() + */ + protected synchronized void setChanged() { + super.setChanged(); + } + } + + private class _AlgoAnimator + implements ActionListener { + + private Controller m_ctrl; + private Timer timer; + + public _AlgoAnimator(Controller ctrl) { + m_ctrl = ctrl; + timer = new Timer(ctrl.m_iAniMillis, this); + } + + public void start() { + timer.setDelay(m_ctrl.m_iAniMillis); + timer.start(); + } + + public void stop() { + timer.stop(); + } + + public void actionPerformed(ActionEvent e) { + if (m_ctrl.m_iAniMillis > 0) { + int nStep = m_ctrl.getCurrentStep(); + if (m_ctrl.hasNextStep(nStep) == true) { + nStep = m_ctrl.getNextStepIndex(); + State state = m_ctrl.getState(nStep); + if (state != null) { + m_ctrl.setStatusbarText(state.getDescriptionEx()); + m_ctrl.setModifiedFlag(); + } + } + else { + m_ctrl.stopAnimation(); + m_ctrl.setModifiedFlag(); + return; + } + } + } + } + + protected int m_iAniMillis = -1; + protected ActionStack m_actions; + protected Graph m_curGraph; + + // When in editing mode but with no visual tool selected + public static final int MODE_NO_TOOL_ACTIVE = 0; + public static final int MODE_ADD_MOVE_NODE = 1; + public static final int MODE_DELETE_NODE = 2; + public static final int MODE_ADD_WEIGH_EDGE = 4; + public static final int MODE_DELETE_EDGE = 8; + public static final int MODE_ALGORITHM = 16; // When in algorithm mode. + + protected static final int _MAX_MODE = MODE_ALGORITHM; + protected static final int _MIN_MODE = MODE_NO_TOOL_ACTIVE; + + protected int m_iEditingMode = MODE_NO_TOOL_ACTIVE; + + protected _Observable m_StatusbarObservable; + protected HashMap> m_mapNodes2AlgoStatesArrayLists = + new HashMap>(); + + protected int m_nCurStep = 0; + + private final ModuleConnector connector; + private _AlgoAnimator m_animator; + private GUIController gui; + + public Controller(ModuleConnector connector) { + super(); + this.connector = connector; + m_actions = new ActionStack(0); + m_curGraph = new Graph(new ArrayList(), new ArrayList()); + m_StatusbarObservable = new _Observable(); + + // Create stuff here... + gui = new GUIController(connector, this); + gui.createGUI(); + m_animator = new _AlgoAnimator(this); + } + + /** + * deserialize the data, given by the + * + * @param data must be a bytearrayinputstream with int for mode + * @author Steven Voigt + */ + private void deserialize(ByteArrayInputStream data) { + try { + ObjectInputStream serializedObjects = new ObjectInputStream(data); + + int newMode = serializedObjects.readInt(); + setGraph((Graph)serializedObjects.readObject()); + switch (newMode) { + case MODE_ADD_MOVE_NODE: + setEditingMode(MODE_ADD_MOVE_NODE); + break; + + case MODE_ADD_WEIGH_EDGE: + setEditingMode(MODE_ADD_WEIGH_EDGE); + break; + + case MODE_DELETE_NODE: + setEditingMode(MODE_DELETE_NODE); + break; + + case MODE_ALGORITHM: + setEditingMode(MODE_ALGORITHM); + break; + + case MODE_NO_TOOL_ACTIVE: + setEditingMode(MODE_NO_TOOL_ACTIVE); + break; + + default: + setEditingMode(MODE_NO_TOOL_ACTIVE); + } + + } + catch (IOException IOExc) { + java.lang.System.err.println(IOExc); + throw new InternalErrorException(IOExc.getMessage()); + + } + catch (ClassNotFoundException cnfExc) { + java.lang.System.err.println("Error while loading."); + throw new InternalErrorException(cnfExc.getMessage()); + } + try { + if (this.getEditingMode() == MODE_ALGORITHM) { + new ShowAlgorithmPageAction(this); + + } + else { + new ShowEditPageAction(this); + } + + this.setModifiedFlag(); + } + catch (ActionException e) { + e.printStackTrace(); + } + + } + + /** + * Get the graph to cast it in a ByteArrayOutputStream + * + * @return the graph as an ByteArrayOutputStream with int for the actual + * mode + * @author Steven Voigt + */ + private ByteArrayOutputStream serialize() { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + ObjectOutputStream serializedObjects = new ObjectOutputStream( + outputStream); + + serializedObjects.writeInt(getEditingMode()); + serializedObjects.writeObject(getGraph()); + serializedObjects.close(); + } + catch (IOException IOExc) { + java.lang.System.err.println(IOExc); + throw new InternalErrorException(IOExc.getMessage()); + } + return outputStream; + } + + /** + * Get the serialized data to store it in a file. + * + * @return the serialiazed data + * @author Steven Voigt + */ + public ByteArrayOutputStream getSerializedData() { + return serialize(); + } + + /** + * Set data. that was loaded from file. This data will be deserialized to + * restore the saved state. + * + * @param data earlier serialized data + * @author Steven Voigt + */ + public void setSerializedData(ByteArrayInputStream data) { + deserialize(data); + } + + /** + * (MW) Call setModifiedFlag() after calling this method, except when + * calling from an action. When setModifiedFlag() was called from within + * this method, updates occurred multiple times because + * registerAndDoAction() already calls it. + * + * @param mode The new mode (_MIN_MODE < mode < _MAX_MODE) + */ + public void setEditingMode(int mode) { + m_iEditingMode = (((mode > _MAX_MODE) || (mode < _MIN_MODE)) ? + MODE_NO_TOOL_ACTIVE : mode); + if (mode == MODE_ALGORITHM) { + computeAlgoStates(); + } + } + + /** + * @return Returns the m_iEditingMode field + */ + public int getEditingMode() { + return m_iEditingMode; + } + + /** + * @author Frank Staudinger + * + * This function recomputes the Dijkstra for the current graph + */ + protected void computeAlgoStates() { + m_nCurStep = 0; + m_mapNodes2AlgoStatesArrayLists.clear(); + DijkstraAlgorithm DijkstraAlgorithm = new DijkstraAlgorithm(getGraph()); + Graph graph = getGraph(); + Node prevStartNode = graph.getStartNode(); + for (Node node : graph.getNodeList()) { + boolean bStart = node.isStart(); + DijkstraAlgorithm.generateStates(node); + ArrayList arList = new ArrayList(); + + int nStateCount = DijkstraAlgorithm.getStateCount(); + + for (int i = 0; i < nStateCount; i++) { + DijkstraAlgorithm.gotoState(i); + arList.add(DijkstraAlgorithm.getCurrentState()); + } + node.setStart(bStart); + m_mapNodes2AlgoStatesArrayLists.put(new Integer(node.getIndex()), + arList); + } + + if (prevStartNode != null) { + prevStartNode.setStart(true); + } + } + + /** + * @param nStep The zero-based # of the state + * @return Returns the state of the given number + */ + public State getState(int nStep) { + Node node = getGraph().getStartNode(); + if (node == null) return null; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + if (nStep >= arList.size()) nStep = arList.size() - 1; + else if (nStep < 0) nStep = 0; + + State state = (State)arList.get(nStep); + m_nCurStep = nStep; + return state; + } + + /** + * @return Returns the next state or null of the Dijkstra + */ + public State getNextState() { + m_nCurStep++; + return getState(m_nCurStep); + } + + /** + * @return Returns the # of the current step + */ + public int getCurrentStep() { + return m_nCurStep; + } + + /** + * @return Returns the # of steps for the current start node + */ + public int getStepCount() { + Node node = getGraph().getStartNode(); + if (node == null) return 0; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + return ((arList != null) ? (arList.size()) : 0); + } + + /** + * @param nStep Zero-based index of the current step + * @return Returns true if we have a next step in the Dijkstra + */ + public boolean hasNextStep(int nStep) { + Node node = getGraph().getStartNode(); + if (node == null) return false; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + return ((arList != null) ? (nStep + 1) < arList.size() : false); + } + + /** + * @param nStep Zero-based index of the current step + * @return Returns true if we have a previous step in the Dijkstra + */ + public boolean hasPrevStep(int nStep) { + Node node = getGraph().getStartNode(); + if (node == null) return false; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + return ((arList != null) ? (nStep > 0) : false); + } + + /** + * @param nStep Zero-based index of the current step + * @return Returns true if we have a next macro step in the Dijkstra + */ + public boolean hasNextMacroStep(int nStep) { + if (hasNextStep(nStep) == false) return false; + Node node = getGraph().getStartNode(); + if (node == null) return false; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + Iterator iter = arList.iterator(); + for (int i = 0; iter.hasNext(); i++) { + State state = (State)iter.next(); + if (i > nStep && (state.isMacro() == true)) return true; + } + return false; + } + + /** + * @param nStep Zero-based index of the current step + * @return Returns true if we have a previous macro step in the Dijkstra + */ + public boolean hasPrevMacroStep(int nStep) { + if (hasPrevStep(nStep) == false) return false; + Node node = getGraph().getStartNode(); + if (node == null) return false; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + Iterator iter = arList.iterator(); + for (int i = 0; iter.hasNext(); i++) { + State state = (State)iter.next(); + if (i < nStep && (state.isMacro() == true)) return true; + } + return false; + } + + /** + * @return Returns the # of the previous step in the Dijkstra + */ + public int getPrevStepIndex() { + return this.getCurrentStep() - 1; + } + + /** + * @return Returns the # of the next step in the Dijkstra + */ + public int getNextStepIndex() { + return this.getCurrentStep() + 1; + } + + /** + * @return Returns the # of the previous macro step in the Dijkstra + */ + public int getPrevMacroStepIndex() { + Node node = getGraph().getStartNode(); + if (node == null) return 0; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + + for (int i = getCurrentStep() - 1; i >= 0; i--) { + State state = (State)arList.get(i); + if (state == null) break; + else if (state.isMacro() == true) return i; + } + return 0; + } + + /** + * @return Returns the # of the previous macro step in the Dijkstra + */ + public int getNextMacroStepIndex() { + Node node = getGraph().getStartNode(); + if (node == null) return 0; + List arList = m_mapNodes2AlgoStatesArrayLists.get(node.getIndex()); + + for (int i = getCurrentStep() + 1; i < arList.size(); i++) { + State state = (State)arList.get(i); + if (state == null) break; + else if (state.isMacro() == true) return i; + } + return 0; + } + + /** + * Show the part of the GUI where the user can manipulate Graphs. + */ + public void showEditingPage() { + this.setEditingMode(MODE_NO_TOOL_ACTIVE); + resetGraphVisuals(); + gui.showEditModePanel(); + this.setModifiedFlag(); + } + + /** + * Shows the part of the GUI where the user witnesses the progression of + * Dijkstra's Algorithm. + */ + public void showAlgorithmPage() { + gui.showAlgorithmModePanel(); + this.setEditingMode(MODE_ALGORITHM); + } + + /** + * @return Returns the m_curGraph field + */ + public Graph getGraph() { + return m_curGraph; + } + + /** + * (MW) Call setModifiedFlag() after calling this method, except when + * calling from an action. When setModifiedFlag() was called from within + * this method, updates occurred multiple times because + * registerAndDoAction() already calls it. + * + * @param graph + * @return the old graph + */ + public Graph setGraph(Graph graph) { + + Graph oldGraph = (Graph)m_curGraph.clone(); + this.m_curGraph = graph; + // i don't know how this works in detail, but because of the permanent + // copying of the graph the mapping between some nodes and its visuals + // is crashed, here a workaround - Alexander + for (Node node : graph.getNodeList()) { + node.getVisual().updateModel(node); + node.getVisual().updateLocation(GraphDisplay.getScreenSize()); + node.setActive(false); + node.setHighlighted(false); + node.getVisual().update(); + } + for (Edge edge : graph.getEdgeList()) { + edge.getVisual().updateModel(edge); + edge.getVisual().updateLocation(GraphDisplay.getScreenSize()); + edge.setActive(false); + edge.setHighlighted(false); + edge.getVisual().update(); + } + + if (this.m_iEditingMode == Controller.MODE_ALGORITHM) computeAlgoStates(); + if (!oldGraph.equals(graph)) + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + return oldGraph; + } + + /** + * Updates the visual components of the graph elements. + */ + private void resetGraphVisuals() { + for (Node node : m_curGraph.getNodeList()) { + node.getVisual().setControllerMode(getEditingMode()); + node.getVisual().update(); + } + for (Edge edge : m_curGraph.getEdgeList()) { + edge.getVisual().setControllerMode(getEditingMode()); + edge.getVisual().update(); + } + } + + /** + * @author Frank Staudinger + * + * It is intend to call this function from the contructor of Your Action + * derived class + * + * @param act The Action You want to be executed and registered in the + * action stack + * @param bRegister True if the Action should be registered in the action + * stack + * @return Returns the result of act.doAction() + * @throws ActionException + */ + public boolean registerAndDoAction(Action act, boolean bRegister) + throws ActionException { + if (bRegister == true) m_actions.add(act); + + if (act.doAction()) { + setModifiedFlag(); + return true; + } + if (bRegister == true) m_actions.movePrevious(); + return false; + } + + /** + * Undoes the last Action + * + * @return Returns the last actions doAction() function result + * @throws ActionException + */ + public boolean undoAction() + throws ActionException { + Action pAction = m_actions.movePrevious(); + return ((pAction == null) ? false : pAction.undoAction()); + } + + /** + * @return Returns true if the action stack is not empty + */ + public boolean hasUndoAction() { + return m_actions.canMovePrevious(); + } + + /** + * Redoes the last Action + * + * @return Returns the last actions doAction() function result + * @throws ActionException + */ + public boolean redoAction() + throws ActionException { + Action pAction = m_actions.moveNext(); + return ((pAction == null) ? false : pAction.doAction()); + } + + /** + * @return Returns true if there is an action to redo + */ + public boolean hasRedoAction() { + return m_actions.canMoveNext(); + } + + /** + * Call this function to inform the Controller's observers about changes + */ + public void setModifiedFlag() { + gui.updateToolBar(); + super.setChanged(); + super.notifyObservers(this); + super.clearChanged(); + } + + public void registerStatusbarObserver(Observer observer) { + this.m_StatusbarObservable.addObserver(observer); + } + + public void setStatusbarText(String strText) { + gui.setStatusbarText(strText); + this.m_StatusbarObservable.setChanged(); + this.m_StatusbarObservable.notifyObservers(this); + this.m_StatusbarObservable.clearChanged(); + } + + public void startAnimation(int iMilliseconds) { + this.m_iAniMillis = iMilliseconds; + m_animator.start(); + } + + public void stopAnimation() { + m_iAniMillis = -1; + m_animator.stop(); + } + + /** + * @return Returns the m_iAniMillis. + */ + public int getAnimationMillis() { + return m_iAniMillis; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/GUIController.java b/src/org/jalgo/module/dijkstra/gui/GUIController.java new file mode 100644 index 0000000..d24dec3 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/GUIController.java @@ -0,0 +1,277 @@ +package org.jalgo.module.dijkstra.gui; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JToolBar; +import javax.swing.SwingConstants; +import javax.swing.border.EmptyBorder; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.ModuleConnector; +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.GotoStepAction; +import org.jalgo.module.dijkstra.actions.ShowAlgorithmPageAction; +import org.jalgo.module.dijkstra.actions.ShowEditPageAction; +import org.jalgo.module.dijkstra.gui.components.AlgorithmCalculationTablePanel; +import org.jalgo.module.dijkstra.gui.components.AlgorithmModeToolPanel; +import org.jalgo.module.dijkstra.gui.components.AlgorithmResultTablePanel; +import org.jalgo.module.dijkstra.gui.components.EdgeListPanel; +import org.jalgo.module.dijkstra.gui.components.EditModeToolPanel; +import org.jalgo.module.dijkstra.gui.components.GraphPanel; +import org.jalgo.module.dijkstra.gui.components.MatrixPanel; +import org.jalgo.module.dijkstra.gui.components.NodeListPanel; +import org.jalgo.module.dijkstra.gui.event.ToolbarActionHandler; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * The class GUIController is the main part of the gui of the + * dijkstra module. It is responsible for creating the several gui parts and for + * updating their states. + * + * @author Alexander Claus + */ +public class GUIController +implements Observer { + + private final Controller controller; + + private JToolBar toolbar; + private JButton undoButton; + private JButton redoButton; + private ToolbarActionHandler toolbarActionHandler; + + private JComponent rootPane; + private GraphPanel graphPane; + private EditModeToolPanel editModeToolPane; + private JPanel editModePane; + private JPanel editModeLeftPane; + private JPanel algModePane; + private JPanel algModeLeftPane; + private JButton startAlgorithmButton; + private JButton restartAlgorithmButton; + private JButton editGraphButton; + private JLabel statusLabel; + + public GUIController(ModuleConnector connector, Controller controller) { + this.controller = controller; + // get the relevant components from the main program + rootPane = JAlgoGUIConnector.getInstance().getModuleComponent(connector); + toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar(connector); + + controller.addObserver(this); + } + + /** + * Constructs the whole gui, namely the toolbar, the graph display panel and + * the composed panels for editing and algorithm mode.
          + * Switches the layout initially to the editing mode view. + */ + public void createGUI() { + createToolbar(); + graphPane = new GraphPanel(controller); + createEditModePanel(); + createAlgorithmModePanel(); + rootPane.setLayout(new BorderLayout()); + showEditModePanel(); + } + + private void createToolbar() { + toolbarActionHandler = new ToolbarActionHandler(controller); + undoButton = new JToolbarButton( + new ImageIcon(Messages.getResourceURL("main", "Icon.Undo")), //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("dijkstra", "Undo_tooltip"), //$NON-NLS-1$ //$NON-NLS-2$ + "undo"); //$NON-NLS-1$ + undoButton.setEnabled(false); + undoButton.addActionListener(toolbarActionHandler); + undoButton.addMouseListener(StatusLineUpdater.getInstance()); + toolbar.add(undoButton); + redoButton = new JToolbarButton( + new ImageIcon(Messages.getResourceURL("main", "Icon.Redo")), //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("dijkstra", "Redo_tooltip"), //$NON-NLS-1$ //$NON-NLS-2$ + "redo"); //$NON-NLS-1$ + redoButton.setEnabled(false); + redoButton.addActionListener(toolbarActionHandler); + redoButton.addMouseListener(StatusLineUpdater.getInstance()); + toolbar.add(redoButton); + } + + private void createEditModePanel() { + editModePane = new JPanel(new BorderLayout()); + JPanel contentPane = new JPanel(new GridLayout(1,2)); + editModeLeftPane = new JPanel(new BorderLayout()); + editModeToolPane = new EditModeToolPanel(controller); + editModeLeftPane.add(editModeToolPane, BorderLayout.NORTH); + contentPane.add(editModeLeftPane); + + JPanel rightPane = new JPanel(new BorderLayout()); + JPanel innerRightPane = new JPanel(); + innerRightPane.setLayout(new BoxLayout(innerRightPane, BoxLayout.PAGE_AXIS)); + NodeListPanel nodeListPane = new NodeListPanel(controller); + innerRightPane.add(nodeListPane); + EdgeListPanel edgeListPane = new EdgeListPanel(controller); + innerRightPane.add(edgeListPane); + MatrixPanel matrixPane = new MatrixPanel(controller); + innerRightPane.add(matrixPane); + rightPane.add(innerRightPane, BorderLayout.CENTER); + + JPanel southPane = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 2)); + startAlgorithmButton = new JButton(Messages.getString("dijkstra", //$NON-NLS-1$ + "StatusbarComposite.Start_algorithm")); //$NON-NLS-1$ + startAlgorithmButton.setToolTipText(Messages.getString("dijkstra", //$NON-NLS-1$ + "StatusbarComposite.Start_algorithm_tooltip")); //$NON-NLS-1$ + startAlgorithmButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + try { + new ShowAlgorithmPageAction(controller); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + }); + southPane.add(startAlgorithmButton); + rightPane.add(southPane, BorderLayout.SOUTH); + contentPane.add(rightPane); + editModePane.add(contentPane, BorderLayout.CENTER); + } + + private void createAlgorithmModePanel() { + algModePane = new JPanel(new BorderLayout()); + JPanel contentPane = new JPanel(new GridLayout(1, 2)); + algModeLeftPane = new JPanel(new BorderLayout()); + AlgorithmModeToolPanel toolPane = new AlgorithmModeToolPanel(controller); + algModeLeftPane.add(toolPane, BorderLayout.NORTH); + contentPane.add(algModeLeftPane); + + JPanel rightPane = new JPanel(new BorderLayout()); + JPanel innerRightPane = new JPanel(new BorderLayout()); + JPanel tablePane = new JPanel(new GridLayout(2, 1)); + AlgorithmCalculationTablePanel calcTablePane = + new AlgorithmCalculationTablePanel(controller); + tablePane.add(calcTablePane); + AlgorithmResultTablePanel resultTablePane = + new AlgorithmResultTablePanel(controller); + tablePane.add(resultTablePane); + innerRightPane.add(tablePane, BorderLayout.CENTER); + statusLabel = new JLabel(); + statusLabel.setMaximumSize(new Dimension(1000, 60)); + statusLabel.setMinimumSize(new Dimension(100, 60)); + statusLabel.setPreferredSize( + new Dimension(statusLabel.getPreferredSize().width, 60)); + statusLabel.setHorizontalAlignment(SwingConstants.LEFT); + statusLabel.setVerticalAlignment(SwingConstants.TOP); + statusLabel.setBorder(new EmptyBorder(2, 2, 2, 2)); + innerRightPane.add(statusLabel, BorderLayout.SOUTH); + rightPane.add(innerRightPane, BorderLayout.CENTER); + + JPanel southPane = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 2)); + restartAlgorithmButton = new JButton(Messages.getString("dijkstra", //$NON-NLS-1$ + "StatusbarComposite.Restart_algorithm")); //$NON-NLS-1$ + restartAlgorithmButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + try { + new GotoStepAction(controller, 0, true); + } + catch (ActionException exc) { + new DefaultExceptionHandler(exc); + } + } + }); + southPane.add(restartAlgorithmButton); + editGraphButton = new JButton(Messages.getString("dijkstra", //$NON-NLS-1$ + "StatusbarComposite.Edit_graph")); //$NON-NLS-1$ + editGraphButton.setToolTipText(Messages.getString("dijkstra", //$NON-NLS-1$ + "StatusbarComposite.Edit_graph_tooltip")); //$NON-NLS-1$ + editGraphButton.addActionListener(new ActionListener() { + @SuppressWarnings("synthetic-access") + public void actionPerformed(ActionEvent e) { + try { + new ShowEditPageAction(controller); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + }); + southPane.add(editGraphButton); + rightPane.add(southPane, BorderLayout.SOUTH); + contentPane.add(rightPane); + algModePane.add(contentPane, BorderLayout.CENTER); + } + + /** + * Updates the enabled state of the redo- and undo-button. + */ + public void updateToolBar() { + undoButton.setEnabled(controller.hasUndoAction()); + redoButton.setEnabled(controller.hasRedoAction()); + } + + /** + * Switches the layout to the editing mode view. + */ + public void showEditModePanel() { + editModeToolPane.reset(); + graphPane.setEditMode(true); + editModeLeftPane.add(graphPane, BorderLayout.CENTER); + switchLayoutTo(editModePane); + } + + /** + * Switch the layout to the algorithm mode view. + */ + public void showAlgorithmModePanel() { + graphPane.setEditMode(false); + algModeLeftPane.add(graphPane, BorderLayout.CENTER); + switchLayoutTo(algModePane); + } + + private void switchLayoutTo(JPanel pane) { + rootPane.removeAll(); + rootPane.add(pane, BorderLayout.CENTER); + rootPane.updateUI(); + } + + /** + * Sets the given text to the result label in algorithm mode. The text can + * be in HTML format to support styles. + * + * @param text the text to be displayed + */ + public void setStatusbarText(String text) { + statusLabel.setText(text); + } + + /** + * Updates the states of the edit-graph- and the restart-algorithm-button. + */ + public void update(Observable o, Object arg) { + if (controller.getAnimationMillis() > 0 && + controller.getEditingMode() == Controller.MODE_ALGORITHM) { + editGraphButton.setEnabled(false); + restartAlgorithmButton.setEnabled(false); + } + else { + editGraphButton.setEnabled(true); + restartAlgorithmButton.setEnabled(true); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.java b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.java new file mode 100644 index 0000000..b3db870 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmCalculationTablePanel.java @@ -0,0 +1,42 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.BorderLayout; +import java.awt.Color; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * The class AlgorithmCalculationTablePanel represents the + * calculation table in algorithm mode.
          + * The event handling for this table is handled in + * {@link org.jalgo.module.dijkstra.gui.components.CalculationTableModel}. + * + * @author Alexander Claus + */ +public class AlgorithmCalculationTablePanel +extends JPanel { + + public AlgorithmCalculationTablePanel(Controller controller) { + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeCalculationTablePanel.Calc_table"))); //$NON-NLS-1$ + setLayout(new BorderLayout()); + + JTable table = new JTable(new CalculationTableModel(controller)); + table.getColumnModel().getColumn(0).setPreferredWidth(50); + table.getColumnModel().getColumn(1).setPreferredWidth(300); + table.getTableHeader().setReorderingAllowed(false); + table.setShowGrid(false); + JScrollPane scrollPane = new JScrollPane(table); + scrollPane.getViewport().setBackground(Color.WHITE); + + add(scrollPane, BorderLayout.CENTER); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.java b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.java new file mode 100644 index 0000000..52b8c3e --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmModeToolPanel.java @@ -0,0 +1,254 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.Dimension; +import java.awt.GridLayout; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.JToggleButton; +import javax.swing.SwingConstants; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.event.AlgorithmModeToolPanelActionHandler; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; + +/** + * This panel provides tools for the algorithm mode. + * + * @author Alexander Claus + */ +public class AlgorithmModeToolPanel +extends JPanel +implements Observer { + + private Controller controller; + private AlgorithmModeToolPanelActionHandler action; + + private JComboBox startNodeSelection; + private JTextField algStepSelection; + private JLabel ofNStepsLabel; + private JButton gotoButton; + private JButton undoBlockStepButton; + private JButton undoButton; + private JButton performButton; + private JButton performBlockStepButton; + private JToggleButton startAnimButton; + + public AlgorithmModeToolPanel(Controller controller) { + super(new GridLayout(2, 1, 5, 5)); + this.controller = controller; + + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeToolPanel.Tools"))); //$NON-NLS-1$ + + action = new AlgorithmModeToolPanelActionHandler(controller, this); + + JPanel northPane = new JPanel(); + northPane.add(Box.createHorizontalStrut(5)); + northPane.setLayout(new BoxLayout(northPane, BoxLayout.LINE_AXIS)); + JLabel startNodeLabel = new JLabel(Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeToolPanel.Start_node")); //$NON-NLS-1$ + northPane.add(startNodeLabel); + northPane.add(Box.createHorizontalStrut(5)); + startNodeSelection = new JComboBox(); + startNodeSelection.setPreferredSize(new Dimension(50, 16)); + startNodeSelection.setActionCommand("startNode"); + startNodeSelection.addActionListener(action); + northPane.add(startNodeSelection); + northPane.add(Box.createHorizontalStrut(5)); + JLabel algStepLabel = new JLabel(Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeToolPanel.Algorithm_step"), SwingConstants.RIGHT); //$NON-NLS-1$ + northPane.add(algStepLabel); + northPane.add(Box.createHorizontalStrut(5)); + algStepSelection = new JTextField(10); + algStepSelection.addKeyListener(action); + northPane.add(algStepSelection); + northPane.add(Box.createHorizontalStrut(5)); + ofNStepsLabel = new JLabel(" "); //$NON-NLS-1$ + northPane.add(ofNStepsLabel); + northPane.add(Box.createHorizontalStrut(5)); + add(northPane); + + JPanel southPane = new JPanel(); + southPane.setLayout(new BoxLayout(southPane, BoxLayout.LINE_AXIS)); + gotoButton = new JButton(Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeToolPanel.Go_to")); //$NON-NLS-1$ + gotoButton.setActionCommand("goto"); + gotoButton.addActionListener(action); + southPane.add(gotoButton); + Dimension controlButtonDim = new Dimension(40, gotoButton.getPreferredSize().height); + undoBlockStepButton = new JButton(new ImageIcon( + Messages.getResourceURL("main", "Icon.Undo_blockstep"))); //$NON-NLS-1$ //$NON-NLS-2$ + undoBlockStepButton.setMaximumSize(controlButtonDim); + undoBlockStepButton.setPreferredSize(controlButtonDim); + undoBlockStepButton.setActionCommand("perform"); //$NON-NLS-1$ + undoBlockStepButton.putClientProperty("forward", false); + undoBlockStepButton.putClientProperty("macroStep", true); + undoBlockStepButton.addActionListener(action); + southPane.add(undoBlockStepButton); + undoButton = new JButton(new ImageIcon( + Messages.getResourceURL("main", "Icon.Undo_step"))); //$NON-NLS-1$ //$NON-NLS-2$ + undoButton.setMaximumSize(controlButtonDim); + undoButton.setPreferredSize(controlButtonDim); + undoButton.setActionCommand("perform"); //$NON-NLS-1$ + undoButton.putClientProperty("forward", false); + undoButton.putClientProperty("macroStep", false); + undoButton.addActionListener(action); + southPane.add(undoButton); + performButton = new JButton(new ImageIcon( + Messages.getResourceURL("main", "Icon.Perform_step"))); //$NON-NLS-1$ //$NON-NLS-2$ + performButton.setMaximumSize(controlButtonDim); + performButton.setPreferredSize(controlButtonDim); + performButton.setActionCommand("perform"); //$NON-NLS-1$ + performButton.putClientProperty("forward", true); + performButton.putClientProperty("macroStep", false); + performButton.addActionListener(action); + southPane.add(performButton); + performBlockStepButton = new JButton(new ImageIcon( + Messages.getResourceURL("main", "Icon.Perform_blockstep"))); //$NON-NLS-1$ //$NON-NLS-2$ + performBlockStepButton.setMaximumSize(controlButtonDim); + performBlockStepButton.setPreferredSize(controlButtonDim); + performBlockStepButton.setActionCommand("perform"); //$NON-NLS-1$ + performBlockStepButton.putClientProperty("forward", true); + performBlockStepButton.putClientProperty("macroStep", true); + performBlockStepButton.addActionListener(action); + southPane.add(performBlockStepButton); + startAnimButton = new JToggleButton(Messages.getString( + "dijkstra", "AlgorithmModeToolPanel.Start_animation")); //$NON-NLS-1$ //$NON-NLS-2$ + startAnimButton.setActionCommand("startAnim"); + startAnimButton.addActionListener(action); + southPane.add(startAnimButton); + add(southPane); + + controller.addObserver(this); + } + + /** + * Updates the enabled state of all control components. This method is used + * for blocking user input during animation. + * + * @param enabled + */ + private void setControlsEnabled(boolean enabled) { + startNodeSelection.setEnabled(enabled); + algStepSelection.setEnabled(enabled); + gotoButton.setEnabled(enabled); + undoBlockStepButton.setEnabled(enabled); + undoButton.setEnabled(enabled); + performButton.setEnabled(enabled); + performBlockStepButton.setEnabled(enabled); + } + + /** + * Retrieves the step index, which is entered in the textfield. + * + * @return the step which the user has selected + */ + public int getSelectedStep() { + return Integer.valueOf(algStepSelection.getText()).intValue()-1; + } + + /** + * Updates the enabled state of the goto-step-button. This method is used + * for synchronize this state with the content (empty or not)of the textfield. + * + * @param enabled the new enabled state of the goto-button + */ + public void setGotoButtonEnabled(boolean enabled) { + gotoButton.setEnabled(enabled); + } + + /** + * Updates the states of all components. + */ + public void update(Observable o, Object arg) { + Controller controller = (Controller)o; + if (controller.getEditingMode() != Controller.MODE_ALGORITHM) return; + Graph graph = controller.getGraph(); + + if (controller.getAnimationMillis() > 0) setControlsEnabled(false); + else setControlsEnabled(true); + + // update startnode combo box + int iSelectedIndex = startNodeSelection.getSelectedIndex(); + int iMaxNode = + (graph.getNodeList() == null) ? 0 : graph.getNodeList().size(); + startNodeSelection.removeActionListener(action); + startNodeSelection.removeAllItems(); + for (int i = 0; i < iMaxNode; i++) + startNodeSelection.insertItemAt("" + (i + 1), i); //$NON-NLS-1$ + // if no node is selected as startnode, set the selection to node #1 + // and generate the states + if (iSelectedIndex == -1) { + Node node = graph.getStartNode(); + if (node != null) + startNodeSelection.setSelectedIndex(node.getIndex() - 1); + else startNodeSelection.setSelectedIndex(-1); + } + else { + Node node = graph.getStartNode(); + iSelectedIndex = + (node == null) ? iSelectedIndex : (node.getIndex() - 1); + startNodeSelection.setSelectedIndex(iSelectedIndex); + } + startNodeSelection.addActionListener(action); + + // update label + if ((controller.getCurrentStep()+1) > 0) + algStepSelection.setText("" + (controller.getCurrentStep()+1)); //$NON-NLS-1$ + else algStepSelection.setText(""); //$NON-NLS-1$ + + if ((controller.getStepCount()) > 0) + ofNStepsLabel.setText(Messages.getString( + "dijkstra", "AlgorithmModeToolPanel.Of") + //$NON-NLS-1$ //$NON-NLS-2$ + (controller.getStepCount())); + else ofNStepsLabel.setText(" "); //$NON-NLS-1$ + + // update enabled state of goto button + if (gotoButton.isEnabled()) gotoButton.setEnabled( + algStepSelection.getText().length() > 0); + + // update enabled state of control buttons + updateButtonState(undoBlockStepButton); + updateButtonState(undoButton); + updateButtonState(performButton); + updateButtonState(performBlockStepButton); + + // update state of start anim button + startAnimButton.setSelected(controller.getAnimationMillis() > 0); + } + + /** + * Helper method for {@link #update(Observable, Object)}. + * + * @param button the button, whose state should be updated + */ + private void updateButtonState(JButton button) { + boolean bEnable = false; + + if ((Boolean)button.getClientProperty("macroStep")) + bEnable = ((Boolean)button.getClientProperty("forward") ? + controller.hasNextMacroStep(controller.getCurrentStep()) : + controller.hasPrevMacroStep(controller.getCurrentStep())); + else bEnable = ((Boolean)button.getClientProperty("forward") ? + controller.hasNextStep(controller.getCurrentStep()) : + controller.hasPrevStep(controller.getCurrentStep())); + if (controller.getAnimationMillis() > 0 && + controller.getEditingMode() == Controller.MODE_ALGORITHM) + bEnable = false; + button.setEnabled(bEnable); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.java b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.java new file mode 100644 index 0000000..e734b0e --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/AlgorithmResultTablePanel.java @@ -0,0 +1,43 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.BorderLayout; +import java.awt.Color; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * The class AlgorithmResultTablePanel represents the result table + * in algorithm mode. It displays the shortest paths and so on.
          + * The event handling for this table is handled in + * {@link org.jalgo.module.dijkstra.gui.components.ResultTableModel}. + * + * @author Alexander Claus + */ +public class AlgorithmResultTablePanel +extends JPanel { + + public AlgorithmResultTablePanel(Controller controller) { + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmModeResultTablePanel.Result"))); //$NON-NLS-1$ + setLayout(new BorderLayout()); + + JTable table = new JTable(new ResultTableModel(controller)); + table.getColumnModel().getColumn(0).setPreferredWidth(100); + table.getColumnModel().getColumn(1).setPreferredWidth(200); + table.getColumnModel().getColumn(2).setPreferredWidth(200); + table.getTableHeader().setReorderingAllowed(false); + table.setShowGrid(false); + JScrollPane scrollPane = new JScrollPane(table); + scrollPane.getViewport().setBackground(Color.WHITE); + + add(scrollPane, BorderLayout.CENTER); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/CVS/Entries b/src/org/jalgo/module/dijkstra/gui/components/CVS/Entries new file mode 100644 index 0000000..97367aa --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/CVS/Entries @@ -0,0 +1,11 @@ +/AlgorithmCalculationTablePanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/AlgorithmModeToolPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/AlgorithmResultTablePanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/CalculationTableModel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/EdgeListPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/EditModeToolPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphDisplay.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/GraphPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/MatrixPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/NodeListPanel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ +/ResultTableModel.java/1.2/Sat Mar 4 13:36:26 2006/-kk/ diff --git a/src/org/jalgo/module/dijkstra/gui/components/CVS/Repository b/src/org/jalgo/module/dijkstra/gui/components/CVS/Repository new file mode 100644 index 0000000..160dc85 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/gui/components diff --git a/src/org/jalgo/module/dijkstra/gui/components/CVS/Root b/src/org/jalgo/module/dijkstra/gui/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.java b/src/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.java new file mode 100644 index 0000000..ad8ce02 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/CalculationTableModel.java @@ -0,0 +1,111 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.table.AbstractTableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.BorderState; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.State; + +/** + * This class defines the TableModel for the calculation table in + * algorithm mode. + * + * @author Alexander Claus + */ +public class CalculationTableModel +extends AbstractTableModel +implements Observer { + + private List chosenNodes; + private List fringeNodes; + private List> tableContent; + + private static final String[] columnNames = new String[] { + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmCalculationTableComposite.Chosen"),//$NON-NLS-1$ + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmCalculationTableComposite.Fringe_node")}; //$NON-NLS-1$; + + public CalculationTableModel(Controller controller) { + chosenNodes = new LinkedList(); + fringeNodes = new LinkedList(); + tableContent = new ArrayList>(); + tableContent.add(chosenNodes); + tableContent.add(fringeNodes); + + controller.addObserver(this); + } + + public int getRowCount() { + return chosenNodes.size(); + } + + public int getColumnCount() { + return 2; + } + + @Override + public String getColumnName(int column) { + return columnNames[column]; + } + + public Object getValueAt(int rowIndex, int columnIndex) { + return tableContent.get(columnIndex).get(rowIndex); + } + + /** + * Updates the table content. + */ + public void update(Observable o, Object arg) { + Controller controller = (Controller)o; + // only react, when in algorithm mode + if (controller.getEditingMode() != Controller.MODE_ALGORITHM) return; + + State dj = controller.getState(controller.getCurrentStep()); + if (dj != null) { + if (dj.getBorderStates() == null) return; + + chosenNodes.clear(); + fringeNodes.clear(); + + Iterator iter = dj.getBorderStates().iterator(); + while (iter.hasNext()) { + BorderState bdstate = (BorderState)iter.next(); + + // Write chosen edge. As we are given a node, try to get the + // edge from the graph. + Node chosen = bdstate.getChosen(); + Node realChosen = dj.getGraph().findNode(chosen.getIndex()); + Node pred = realChosen.getPredecessor(); + + if (pred != null) { + Edge chosenEdge = dj.getGraph().findEdge(realChosen, pred); + chosenNodes.add("" + chosenEdge.getAlgoText(true, bdstate)); //$NON-NLS-1$ + } + else { + int index = chosen.getIndex(); + chosenNodes.add("(" + index + ",0," + index + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + Iterator edgeIter = bdstate.getBorder().iterator(); + String strText = ""; //$NON-NLS-1$ + while (edgeIter.hasNext()) { + Edge ed = (Edge)edgeIter.next(); + if (strText.length() > 0) strText += ", "; //$NON-NLS-1$ + strText += ed.getAlgoText(true, bdstate); + } + fringeNodes.add(strText); + } + fireTableDataChanged(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.java b/src/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.java new file mode 100644 index 0000000..7d9c998 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/EdgeListPanel.java @@ -0,0 +1,92 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.ScrollPaneConstants; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.ApplyEdgeListAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * The EdgeListPanel provides a textfield and a button to edit the + * edgelist for the graph. + * + * @author Alexander Claus + */ +public class EdgeListPanel +extends JPanel +implements Observer { + + private final Controller controller; + private JTextArea textArea; + + public EdgeListPanel(Controller controller) { + super(); + this.controller = controller; + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", "EdgeListPanel.Edge_list"))); //$NON-NLS-1$ //$NON-NLS-2$ + setLayout(new BorderLayout(2, 2)); + textArea = new JTextArea(); + textArea.setLineWrap(true); + JScrollPane scrollPane = new JScrollPane(textArea, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + textArea.addFocusListener(new FocusAdapter() { + public void focusLost(FocusEvent e) { + fireChangedEvent(); + } + }); + add(scrollPane, BorderLayout.CENTER); + JPanel buttonPane = new JPanel(new BorderLayout()); + JButton applyButton = new JButton(Messages.getString( + "dijkstra", "EdgeListPanel.Apply")); //$NON-NLS-1$ //$NON-NLS-2$ + applyButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + fireChangedEvent(); + } + }); + buttonPane.add(applyButton, BorderLayout.EAST); + add(buttonPane, BorderLayout.SOUTH); + + controller.addObserver(this); + } + + /** + * This method is called, when this component lost the focus or when the + * user presses the apply-button. It causes to apply the changes. + */ + void fireChangedEvent() { + String strText = textArea.getText(); + try { + new ApplyEdgeListAction(controller, strText); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + textArea.setText(strText); + } + } + + /** + * Updates the content of the text area. + */ + public void update(Observable o, Object arg) { + if (o == null) return; + + textArea.setText(((Controller)o).getGraph().getEdgeListText()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.java b/src/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.java new file mode 100644 index 0000000..f164aa5 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/EditModeToolPanel.java @@ -0,0 +1,125 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JPanel; +import javax.swing.JToggleButton; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.event.EditModeToolPanelActionHandler; + +/** + * This panel provides tools for the editing mode. + * + * @author Alexander Claus + */ +public class EditModeToolPanel +extends JPanel { + + // action handlers + private ButtonGroupManager groupManager; + private EditModeToolPanelActionHandler action; + + private JToggleButton addMoveNodeButton; + private JToggleButton addEvalEdgeButton; + private JToggleButton removeNodeButton; + private JToggleButton removeEdgeButton; + JToggleButton invisibleButton; + + public EditModeToolPanel(Controller controller) { + super(new GridLayout(2, 2, 5, 5)); + + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", "EditModeToolPanel.Tools"))); //$NON-NLS-1$ //$NON-NLS-2$ + ButtonGroup group = new ButtonGroup(); + + groupManager = new ButtonGroupManager(); + action = new EditModeToolPanelActionHandler(controller); + + addMoveNodeButton = createToggleButton( + "EditModeToolPanel.Add_move_node", //$NON-NLS-1$ + "EditModeToolPanel.Add_move_node_tooltip", //$NON-NLS-1$ + "addMoveNode");//$NON-NLS-1$ + group.add(addMoveNodeButton); + add(addMoveNodeButton); + + addEvalEdgeButton = createToggleButton( + "EditModeToolPanel.Add_eval_edge", //$NON-NLS-1$ + "EditModeToolPanel.Add_eval_edge_tooltip", //$NON-NLS-1$ + "addEvalEdge"); //$NON-NLS-1$ + group.add(addEvalEdgeButton); + add(addEvalEdgeButton); + + removeNodeButton = createToggleButton( + "EditModeToolPanel.Remove_node", //$NON-NLS-1$ + "EditModeToolPanel.Remove_node_tooltip", //$NON-NLS-1$ + "removeNode"); //$NON-NLS-1$ + group.add(removeNodeButton); + add(removeNodeButton); + + removeEdgeButton = createToggleButton( + "EditModeToolPanel.Remove_edge", //$NON-NLS-1$ + "EditModeToolPanel.Remove_edge_tooltip", //$NON-NLS-1$ + "removeEdge"); //$NON-NLS-1$ + group.add(removeEdgeButton); + add(removeEdgeButton); + + // invisible button is for disabling any of the buttons + invisibleButton = new JToggleButton(); + group.add(invisibleButton); + } + + /** + * Unselects all buttons. + */ + @SuppressWarnings("synthetic-access") + public void reset() { + invisibleButton.setSelected(true); + groupManager.lastPressedButton = null; + } + + /** + * Helper method to construct component. + * + * @param labelKey the key to get the label text + * @param tooltipKey the key to get the tooltip text + * @param actionCommand the action command + * @return a new JToggleButton with the given properties + */ + private JToggleButton createToggleButton(String labelKey, + String tooltipKey, String actionCommand) { + JToggleButton button = new JToggleButton(Messages.getString( + "dijkstra", labelKey)); //$NON-NLS-1$ + button.setToolTipText(Messages.getString( + "dijkstra", tooltipKey)); //$NON-NLS-1$ + button.setActionCommand(actionCommand); + button.addActionListener(groupManager); + button.addActionListener(action); + button.addMouseListener(StatusLineUpdater.getInstance()); + return button; + } + + /** + * This class is responsible for the behaviour of unselecting a button. + */ + private class ButtonGroupManager + implements ActionListener { + + private JToggleButton lastPressedButton; + + public void actionPerformed(ActionEvent e) { + if (lastPressedButton == e.getSource()) { + lastPressedButton = null; + invisibleButton.setSelected(true); + } + else lastPressedButton = (JToggleButton)e.getSource(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/GraphDisplay.java b/src/org/jalgo/module/dijkstra/gui/components/GraphDisplay.java new file mode 100644 index 0000000..8bfd4f6 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/GraphDisplay.java @@ -0,0 +1,174 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.JComponent; +import javax.swing.border.BevelBorder; + +import org.jalgo.module.dijkstra.gfx.NewEdgeLine; +import org.jalgo.module.dijkstra.gfx.Visual; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.event.GraphDisplayActionHandler; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.State; + +/** + * The class GraphDisplay is responsible for drawing the current + * graph to the screen. Furthermore it contains methods to find the graph + * element under a specific screen point. + * + * @author Alexander Claus + */ +public class GraphDisplay +extends JComponent +implements Observer { + + private Controller controller; + private GraphDisplayActionHandler actionHandler; + + //the offscreen context + private BufferedImage offI; + private Graphics2D offG; + + private Graph graph; + private NewEdgeLine newEdgeLine; + + private static Dimension screenSize = new Dimension(); + + public GraphDisplay(Controller controller) { + super(); + this.controller = controller; + offI = new BufferedImage(1600, 1600, BufferedImage.TYPE_INT_RGB); + offG = offI.createGraphics(); + offG.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); + + actionHandler = new GraphDisplayActionHandler(this, controller); + addMouseListener(actionHandler); + addMouseMotionListener(actionHandler); + controller.addObserver(this); + } + + /** + * Paints the graph. + */ + @Override + protected void paintComponent(Graphics g) { + offG.setColor(Color.WHITE); + offG.fillRect(0, 0, getWidth(), getHeight()); + + if (controller.getEditingMode() == Controller.MODE_ALGORITHM) { + State dj = controller.getState(controller.getCurrentStep()); + if (dj != null) graph = dj.getGraph(); + else graph = controller.getGraph(); + } + else graph = controller.getGraph(); + + for (Edge edge : graph.getEdgeList()) + edge.getVisual().draw(offG, screenSize); + if (newEdgeLine != null) { + offG.setColor(Visual.RED); + offG.setStroke(new BasicStroke(7)); + offG.draw(newEdgeLine); + } + for (Node node : graph.getNodeList()) + node.getVisual().draw(offG, screenSize); + + g.drawImage(offI, 0, 0, this); + } + + /** + * This method is overridden to rescale the graph, when component is resized. + */ + @Override + public void setBounds(int x, int y, int width, int height) { + super.setBounds(x, y, width, height); + screenSize.width = width; + screenSize.height = height; + + // update positions of all elements + if (controller.getEditingMode() != Controller.MODE_ALGORITHM) + graph = controller.getGraph(); + else { + State dj = controller.getState(controller.getCurrentStep()); + if (dj != null) graph = dj.getGraph(); + else graph = controller.getGraph(); + } + for (Edge edge : graph.getEdgeList()) + edge.getVisual().updateLocation(screenSize); + for (Node node : graph.getNodeList()) + node.getVisual().updateLocation(screenSize); + + repaint(); + } + + /** + * Updates the contents. + */ + public void update(Observable o, Object arg) { + if (controller.getEditingMode() != Controller.MODE_ALGORITHM) + graph = controller.getGraph(); + else { + State dj = controller.getState(controller.getCurrentStep()); + if (dj != null) graph = dj.getGraph(); + else graph = controller.getGraph(); + } + repaint(); + } + + /** + * Finds the Node under the given point. + * + * @param point the screen coordinates to test + * @return the underlying node, or null, if there is no such + */ + public Node findNode(Point point) { + Graph graph = controller.getGraph(); + for (Node node : graph.getNodeList()) + if (node.getVisual().hit(screenSize, point)) return node; + return null; + } + + /** + * Finds the Edge under the given point. + * + * @param point the screen coordinates to test + * @return the underlying edge, or null, if there is no such + */ + public Edge findEdge(Point point) { + Graph graph = controller.getGraph(); + for (Edge edge : graph.getEdgeList()) + if (edge.getVisual().hit(screenSize, point)) return edge; + return null; + } + + public void setNewEdgeLine(NewEdgeLine line) { + newEdgeLine = line; + } + + public NewEdgeLine getNewEdgeLine() { + return newEdgeLine; + } + + /** + * Currently for easy creation of NodeVisuals + */ + public static Dimension getScreenSize() { + return screenSize; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/GraphPanel.java b/src/org/jalgo/module/dijkstra/gui/components/GraphPanel.java new file mode 100644 index 0000000..7fc5120 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/GraphPanel.java @@ -0,0 +1,71 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.RescaleGraphAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * The class GraphPanel holds the GraphDisplay + * component and, in editing mode, a button to rearrange the nodes. + * + * @author Alexander Claus + */ +public class GraphPanel +extends JPanel { + + private JButton arrangeButton; + private JPanel buttonPane; + private GraphDisplay graphDisplay; + + public GraphPanel(final Controller controller) { + super(new BorderLayout(5, 5)); + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", "GraphPanel.Graph"))); //$NON-NLS-1$ //$NON-NLS-2$ + graphDisplay = new GraphDisplay(controller); + add(graphDisplay, BorderLayout.CENTER); + + arrangeButton = new JButton(Messages.getString("dijkstra", //$NON-NLS-1$ + "GraphPanel.Arrange_nodes_automatically")); //$NON-NLS-2$ + arrangeButton.setToolTipText(Messages.getString("dijkstra", //$NON-NLS-1$) + "GraphPanel.Arrange_tooltip")); //$NON-NLS-2$ + arrangeButton.addMouseListener(StatusLineUpdater.getInstance()); + arrangeButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + new RescaleGraphAction(controller); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + }); + buttonPane = new JPanel(); + buttonPane.setLayout(new BorderLayout()); + buttonPane.add(arrangeButton, BorderLayout.EAST); + } + + /** + * Updates the controller mode. + * + * @param isEditMode true, if the controller is in editing mode, + * false, otherwise + */ + public void setEditMode(boolean isEditMode) { + if (isEditMode) add(buttonPane, BorderLayout.SOUTH); + else remove(buttonPane); + updateUI(); + validate(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/MatrixPanel.java b/src/org/jalgo/module/dijkstra/gui/components/MatrixPanel.java new file mode 100644 index 0000000..83b1472 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/MatrixPanel.java @@ -0,0 +1,257 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.util.HashMap; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.ApplyEdgeListAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * The class MatrixPanel provides an editable view for the + * adjacency matrix. + * + * @author Alexander Claus + */ +public class MatrixPanel +extends JPanel +implements Observer, KeyListener, ActionListener, FocusListener { + + private final Controller controller; + private JTextField[][] textFields; + private HashMap symmetrics; + + public MatrixPanel(Controller controller) { + super(); + this.controller = controller; + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", "MatrixPanel.Distance_matrix"))); //$NON-NLS-1$ //$NON-NLS-2$ + // the following is for optimizing layout under linux, otherwise the + // edgelist is not really shown + if (System.getProperty("os.name").toLowerCase().startsWith("linux")) + setLayout(new GridLayout(10, 10, 2, 2)); + else setLayout(new GridLayout(10, 10, 5, 5)); + //create columns headers + add(new JLabel()); + for (int i=1; i<10; i++) + add(new JLabel(""+i, SwingConstants.CENTER)); + //create rows + textFields = new JTextField[9][9]; + for (int y=0; y<9; y++) { + add(new JLabel(""+(y+1), SwingConstants.CENTER)); + for (int x=0; x<9; x++) { + textFields[y][x] = new JTextField(); + textFields[y][x].putClientProperty("X",x); + textFields[y][x].putClientProperty("Y",y); + textFields[y][x].setToolTipText("("+(y+1)+","+(x+1)+")"); + if (y==x) { + textFields[y][x].setText("0"); //$NON-NLS-1$ + textFields[y][x].setEditable(false); + } + textFields[y][x].addKeyListener(this); + textFields[y][x].addActionListener(this); + textFields[y][x].addFocusListener(this); + add(textFields[y][x]); + } + } + // build a mapping between symmetric fields + symmetrics = new HashMap(); + for (int y=0; y<9; y++) { + for (int x=0; x<9; x++) { + if (x == y) continue; + symmetrics.put(textFields[y][x], textFields[x][y]); + } + } + setToolTipText(Messages.getString( + "dijkstra", "MatrixPanel.Tooltip")); //$NON-NLS-1$ //$NON-NLS-2$ + addMouseListener(StatusLineUpdater.getInstance()); + + controller.addObserver(this); + } + + /** + * the getEdgeList() method returns the actual graph() as an EdgeList using + * entries of the matrix + * @return String with Syntax of EdgeList + * + * @author Steven Voigt + */ + public String getEdgeList() { + String edgeList = ""; //$NON-NLS-1$ + for (int m = 0; m < 9; m++) { + if (nodeExist(m + 1)) { + for (int n = 0; n < 9; n++) { + boolean notminus = (!textFields[n][m].getText().equals( + "-")); //$NON-NLS-1$ + boolean notnull = (!textFields[n][m].getText().equals( + "")); //$NON-NLS-1$ + if (notminus && !(n == m) && notnull) { + edgeList = edgeList + + "(" + (m + 1) + "," + textFields[n][m].getText() //$NON-NLS-1$ //$NON-NLS-2$ + + "," + (n + 1) + "),"; //$NON-NLS-1$ //$NON-NLS-2$ + } + if (!notminus) edgeList = edgeList + + "(" + (m + 1) + "," + "1," + (m + 1) + "),"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + } + if (edgeList.endsWith(",")) //$NON-NLS-1$ + edgeList = edgeList.substring(0, edgeList.length() - 1); + return edgeList; + } + + /** + * check existing of a node if nodeexist + * @return boolean true else false + * + * @author Steven Voigt + */ + protected boolean nodeExist(int nodeNr) { + for (int i=0; i nodeCount || + x > nodeCount) textFields[y][x].setText(null); + else textFields[y][x].setText("-"); //$NON-NLS-1$ + } + } + for (Edge edge : g.getEdgeList()) { + int y = edge.getStartNodeIndex() - 1; + int x = edge.getEndNodeIndex() - 1; + if ((y>=0) && (y<=8) && (x>=0) && (x<=8)) { + textFields[y][x].setText("" + edge.getWeight()); //$NON-NLS-1$ + textFields[x][y].setText("" + edge.getWeight()); //$NON-NLS-1$ + } + } + } + + /** + * Asserts, that only integers and minus ('-') are accepted. Other keys + * will be ignored. + */ + public void keyTyped(KeyEvent e) { + JTextField source = (JTextField)e.getSource(); + // check for maximum of 2 characters + if (source.getText().length() >= 2) e.consume(); + // check that only minus is accepted, when field is empty + if (e.getKeyChar() == '-' && source.getText().length() > 0) e.consume(); + // check that only numbers an minus is accepted + if ((e.getKeyChar() < 48 || e.getKeyChar() > 57) && + e.getKeyChar() != '-') e.consume(); + } + + public void keyPressed(KeyEvent e) { + // this method has no effect + } + + /** + * Validates the symmetric field to the field, the user typed in. Checks, if + * all nodes with smaller indices exist and fill the according fields, if + * necessary. Finally this method updates the graph structure. + */ + public void keyReleased(KeyEvent e) { + // if key is number or minus, copy value to the symmetric field + if ((e.getKeyChar() >= 48 && e.getKeyChar() <= 57) || + e.getKeyChar() == '-' || + e.getKeyCode() == KeyEvent.VK_DELETE || + e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { + JTextField source = (JTextField)e.getSource(); + if (source.getText().length() == 0) return; + + // check that all nodes with smaller index exist + int nodeIndex = Math.max( + (Integer)source.getClientProperty("X"), + (Integer)source.getClientProperty("Y")); + for (int i=0; iNodeListPanel provides a textfield to edit the nodelist for + * the graph. + * + * @author Alexander Claus + */ +public class NodeListPanel +extends JPanel +implements Observer { + + private final Controller controller; + private JTextField textField; + + public NodeListPanel(Controller controller) { + super(); + this.controller = controller; + setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), + Messages.getString("dijkstra", "NodeListPanel.Node_list"))); //$NON-NLS-1$ //$NON-NLS-2$ + setLayout(new BorderLayout()); + textField = new JTextField(); + textField.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + fireChangedEvent(); + } + }); + textField.addFocusListener(new FocusAdapter() { + public void focusLost(FocusEvent e) { + fireChangedEvent(); + } + }); + add(textField, BorderLayout.CENTER); + setMaximumSize(new Dimension( + getMaximumSize().width, getMinimumSize().height)); + + controller.addObserver(this); + } + + /** + * This method is called, when this component lost the focus or when the + * user presses enter. It causes to apply the changes. + */ + void fireChangedEvent() { + String strText = textField.getText(); + try { + new ApplyNodeListAction(controller, strText); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + textField.setText(strText); + } + } + + /** + * Updates the content of the textfiel. + */ + public void update(Observable o, Object arg) { + if (o == null) return; + + textField.setText(((Controller)o).getGraph().getNodeListText()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/components/ResultTableModel.java b/src/org/jalgo/module/dijkstra/gui/components/ResultTableModel.java new file mode 100644 index 0000000..ed79101 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/components/ResultTableModel.java @@ -0,0 +1,103 @@ +package org.jalgo.module.dijkstra.gui.components; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.table.AbstractTableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.State; + +/** + * This class defines the TableModel for the result table in + * algorithm mode. + * + * @author Alexander Claus + */ +public class ResultTableModel +extends AbstractTableModel +implements Observer { + + private List targetNodes; + private List shortestPaths; + private List pathLengths; + private List> tableContent; + + private static final String[] columnNames = new String[] { + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmResultTableComposite.Target_node"),//$NON-NLS-1$ + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmResultTableComposite.Shortest_path"), //$NON-NLS-1$; + Messages.getString("dijkstra", //$NON-NLS-1$ + "AlgorithmResultTableComposite.Path_length")}; //$NON-NLS-1$; + + public ResultTableModel(Controller controller) { + targetNodes = new LinkedList(); + shortestPaths = new LinkedList(); + pathLengths = new LinkedList(); + tableContent = new ArrayList>(); + tableContent.add(targetNodes); + tableContent.add(shortestPaths); + tableContent.add(pathLengths); + + controller.addObserver(this); + } + + public int getRowCount() { + return targetNodes.size(); + } + + public int getColumnCount() { + return 3; + } + + @Override + public String getColumnName(int column) { + return columnNames[column]; + } + + public Object getValueAt(int rowIndex, int columnIndex) { + return tableContent.get(columnIndex).get(rowIndex); + } + + /** + * Updates the table content. + */ + public void update(Observable o, Object arg) { + Controller controller = (Controller)o; + // only react, when in algorithm mode + if (controller.getEditingMode() != Controller.MODE_ALGORITHM) return; + + State dj = controller.getState(controller.getCurrentStep()); + if (dj != null) { + if (dj.getBorderStates() == null) return; + targetNodes.clear(); + shortestPaths.clear(); + pathLengths.clear(); + + Iterator iter = dj.getGraph().getNodeList().iterator(); + dj.getBorderStates().iterator(); + while (iter.hasNext()) { + Node node = (Node)iter.next(); + if (node != dj.getGraph().getStartNode()) { + targetNodes.add(node.getLabel()); + String strPath = node.getShortestPath(); + if (strPath.length() > 0) shortestPaths.add( + "(" + node.getShortestPath() + "," + //$NON-NLS-1$ //$NON-NLS-2$ + node.getIndex() + ")"); //$NON-NLS-1$ + else shortestPaths.add(""); + if (node.getDistance() > 0) pathLengths.add( + "" + node.getDistance()); //$NON-NLS-1$ + else pathLengths.add(""); + } + } + fireTableDataChanged(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.java b/src/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.java new file mode 100644 index 0000000..8a2d391 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/AlgorithmModeToolPanelActionHandler.java @@ -0,0 +1,90 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JTextField; +import javax.swing.JToggleButton; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.GotoMacroStepAction; +import org.jalgo.module.dijkstra.actions.GotoMicroStepAction; +import org.jalgo.module.dijkstra.actions.GotoStepAction; +import org.jalgo.module.dijkstra.actions.SetStartNodeAction; +import org.jalgo.module.dijkstra.actions.StartAnimationAction; +import org.jalgo.module.dijkstra.actions.StopAnimationAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.AlgorithmModeToolPanel; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class handles all events around the tool panel in algorithm mode. + * + * @author Alexander Claus + */ +public class AlgorithmModeToolPanelActionHandler +implements ActionListener, KeyListener { + + private final Controller controller; + private final AlgorithmModeToolPanel toolPane; + + public AlgorithmModeToolPanelActionHandler(Controller controller, + AlgorithmModeToolPanel toolPane) { + this.controller = controller; + this.toolPane = toolPane; + } + + /** + * Handles button clicks. + */ + public void actionPerformed(ActionEvent e) { + try { + if (e.getActionCommand().equals("perform")) { + if ((Boolean) + ((JComponent)e.getSource()).getClientProperty("macroStep")) + new GotoMacroStepAction(controller, (Boolean) + ((JComponent)e.getSource()).getClientProperty("forward")); + else new GotoMicroStepAction(controller, (Boolean) + ((JComponent)e.getSource()).getClientProperty("forward")); + } + else if (e.getActionCommand().equals("startNode")) + new SetStartNodeAction(controller, + ((JComboBox)e.getSource()).getSelectedIndex()+1); + else if (e.getActionCommand().equals("goto")) + new GotoStepAction(controller, toolPane.getSelectedStep(), true); + else if (e.getActionCommand().equals("startAnim")) { + if (((JToggleButton)e.getSource()).isSelected()) + new StartAnimationAction(controller, 750); + else new StopAnimationAction(controller); + } + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + + /** + * Assert valid inputs in textfield. + */ + public void keyTyped(KeyEvent e) { + // check that only numbers are accepted + if (e.getKeyChar() < 48 || e.getKeyChar() > 57) e.consume(); + + } + + public void keyPressed(KeyEvent e) { + // this method has no effect + } + + /** + * Updates the enabled state of the goto-button. + */ + public void keyReleased(KeyEvent e) { + toolPane.setGotoButtonEnabled( + ((JTextField)e.getSource()).getText().length()>0); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/CVS/Entries b/src/org/jalgo/module/dijkstra/gui/event/CVS/Entries new file mode 100644 index 0000000..081dce5 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/CVS/Entries @@ -0,0 +1,9 @@ +/AlgorithmModeToolPanelActionHandler.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/EditModeToolPanelActionHandler.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/GraphDisplayActionHandler.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/GraphDisplayState.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/StateAddEvalEdge.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/StateAddMoveNode.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/StateRemoveEdge.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/StateRemoveNode.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ +/ToolbarActionHandler.java/1.2/Sat Mar 4 13:36:25 2006/-kk/ diff --git a/src/org/jalgo/module/dijkstra/gui/event/CVS/Repository b/src/org/jalgo/module/dijkstra/gui/event/CVS/Repository new file mode 100644 index 0000000..9b2301d --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/gui/event diff --git a/src/org/jalgo/module/dijkstra/gui/event/CVS/Root b/src/org/jalgo/module/dijkstra/gui/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.java b/src/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.java new file mode 100644 index 0000000..b0c81c3 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/EditModeToolPanelActionHandler.java @@ -0,0 +1,50 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.SetEditingModeAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class handles all events around the tool panel in editing mode. + * + * @author Alexander Claus + */ +public class EditModeToolPanelActionHandler +implements ActionListener { + + private final Controller controller; + + public EditModeToolPanelActionHandler(Controller controller) { + this.controller = controller; + } + + /** + * Handles button clicks. + */ + public void actionPerformed(ActionEvent e) { + int mode = controller.getEditingMode(); + int newMode = Controller.MODE_NO_TOOL_ACTIVE; + if (e.getActionCommand().equals("addMoveNode")) + newMode = Controller.MODE_ADD_MOVE_NODE; + else if (e.getActionCommand().equals("addEvalEdge")) + newMode = Controller.MODE_ADD_WEIGH_EDGE; + else if (e.getActionCommand().equals("removeNode")) + newMode = Controller.MODE_DELETE_NODE; + else if (e.getActionCommand().equals("removeEdge")) + newMode = Controller.MODE_DELETE_EDGE; + try { + // current mode disabled + if (mode == newMode) new SetEditingModeAction( + controller, Controller.MODE_NO_TOOL_ACTIVE); + else new SetEditingModeAction(controller, newMode); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + controller.setModifiedFlag(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.java b/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.java new file mode 100644 index 0000000..0378d39 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayActionHandler.java @@ -0,0 +1,100 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; + +/** + * This class handles mouse events on the graph display component. The events + * are delegated to state objects. So this class represents the client in the + * state design pattern. + * + * @author Alexander Claus + */ +public class GraphDisplayActionHandler +implements MouseListener, MouseMotionListener { + + private final GraphDisplay display; + private final Controller controller; + + private GraphDisplayState currentState; + private GraphDisplayState addMoveNodeState; + private GraphDisplayState addEvalEdgeState; + private GraphDisplayState removeNodeState; + private GraphDisplayState removeEdgeState; + + public GraphDisplayActionHandler(GraphDisplay display, Controller controller) { + this.display = display; + this.controller = controller; + + addMoveNodeState = new StateAddMoveNode(display, controller); + addEvalEdgeState = new StateAddEvalEdge(display, controller); + removeNodeState = new StateRemoveNode(display, controller); + removeEdgeState = new StateRemoveEdge(display, controller); + } + + private void updateState() { + switch (controller.getEditingMode()) { + case Controller.MODE_ADD_MOVE_NODE: + currentState = addMoveNodeState; + break; + case Controller.MODE_ADD_WEIGH_EDGE: + currentState = addEvalEdgeState; + break; + case Controller.MODE_DELETE_NODE: + currentState = removeNodeState; + break; + case Controller.MODE_DELETE_EDGE: + currentState = removeEdgeState; + break; + case Controller.MODE_NO_TOOL_ACTIVE: + currentState = null; + break; + case Controller.MODE_ALGORITHM: + currentState = null; + break; + } + + } + + public void mouseClicked(MouseEvent e) { + updateState(); + if (currentState != null) currentState.mouseClicked(e.getPoint()); + display.repaint(); + } + + public void mousePressed(MouseEvent e) { + updateState(); + if (currentState != null) currentState.mousePressed(e.getPoint()); + display.repaint(); + } + + public void mouseReleased(MouseEvent e) { + updateState(); + if (currentState != null) currentState.mouseReleased(e.getPoint()); + display.repaint(); + } + + public void mouseDragged(MouseEvent e) { + updateState(); + if (currentState != null) currentState.mouseDragged(e.getPoint()); + display.repaint(); + } + + public void mouseMoved(MouseEvent e) { + updateState(); + if (currentState != null) currentState.mouseMoved(e.getPoint()); + display.repaint(); + } + + public void mouseEntered(MouseEvent e) { + // this method has no effect + } + + public void mouseExited(MouseEvent e) { + // this method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.java b/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.java new file mode 100644 index 0000000..cc686c5 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/GraphDisplayState.java @@ -0,0 +1,35 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.Point; + +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; + +/** + * This class defines an interface for states, which are used in graph display. + * Subclasses collaborate with the modes in the Controller. Those + * states handle mouse events on their individually way.
          + * This class is part of the state design pattern. + * + * @author Alexander Claus + */ +public abstract class GraphDisplayState { + + protected GraphDisplay display; + protected Controller controller; + + public GraphDisplayState(GraphDisplay display, Controller controller) { + this.display = display; + this.controller = controller; + } + + public abstract void mousePressed(Point p); + + public abstract void mouseReleased(Point p); + + public abstract void mouseClicked(Point p); + + public abstract void mouseMoved(Point p); + + public abstract void mouseDragged(Point p); +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.java b/src/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.java new file mode 100644 index 0000000..f9031b2 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/StateAddEvalEdge.java @@ -0,0 +1,247 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.Point; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.NewEdgeAction; +import org.jalgo.module.dijkstra.actions.WeighEdgeAction; +import org.jalgo.module.dijkstra.gfx.EdgeVisual; +import org.jalgo.module.dijkstra.gfx.EdgeWeightVisual; +import org.jalgo.module.dijkstra.gfx.NewEdgeLine; +import org.jalgo.module.dijkstra.gfx.NodeVisual; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class represents the state, which collaborates with the mode + * {@link org.jalgo.module.dijkstra.gui.Controller#MODE_ADD_WEIGH_EDGE}. + * + * @author Alexander Claus + */ +public class StateAddEvalEdge +extends GraphDisplayState { + + private EdgeWeightVisual clickedEdgeWeight; + private Edge evaluatedEdge; + private boolean draggingEdgeCreation; + private boolean edgeCreation; + private Node selectedNode; + private Node sourceNode; + private Edge selectedEdge; + + public StateAddEvalEdge(GraphDisplay display, Controller controller) { + super(display, controller); + } + + @Override + public void mousePressed(Point p) { + Edge clickedEdge = display.findEdge(p); + // finding an edge means, that user wants to evaluate the edge + if (clickedEdge != null) { + clickedEdgeWeight = + ((EdgeVisual)clickedEdge.getVisual()).getWeightVisual(); + if (clickedEdgeWeight != null) { + evaluatedEdge = clickedEdge; + clickedEdgeWeight.beginDragging(p); + evaluatedEdge.setActive(true); + evaluatedEdge.getVisual().update(); + } + } + // if no edge is selected, perhaps it is the start node of a new + // edge? + else { + Node clickedNode = display.findNode(p); + if (clickedNode != null) { + // this is the start node of a new edge + if (display.getNewEdgeLine() == null) { + sourceNode = clickedNode; + sourceNode.setActive(true); + sourceNode.getVisual().update(); + display.setNewEdgeLine(new NewEdgeLine(sourceNode)); + edgeCreation = true; + } + // else this mouse press is the begin of the 2nd click + // of new edge creation + } + } + } + + @Override + public void mouseReleased(Point p) { + // end of evaluating the edge + if (clickedEdgeWeight != null) { + try { + new WeighEdgeAction(controller, evaluatedEdge, + clickedEdgeWeight.getWeight()); + evaluatedEdge.setActive(false); + evaluatedEdge.getVisual().update(); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + evaluatedEdge = null; + clickedEdgeWeight = null; + } + // end of creating a new edge, react only to release events, + // when + // edge is created by dragging. otherwise mouseClicked is + // responsible + else if (display.getNewEdgeLine() != null) { + if (draggingEdgeCreation) { + Node clickedNode = display.findNode(p); + if (clickedNode != null) { + // it is really the end node, not the start node + if (sourceNode != clickedNode) try { + new NewEdgeAction(controller, sourceNode, clickedNode); + clickedNode.setActive(false); + clickedNode.setHighlighted(true); + clickedNode.getVisual().update(); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + else { + Node startNode = display.findNode((Point) + display.getNewEdgeLine().getP1()); + // it is only for robust application, normally, the start + // node can't be null! + if (startNode != null) { + startNode.setActive(false); + startNode.setHighlighted(false); + startNode.getVisual().update(); + } + } + display.setNewEdgeLine(null); + draggingEdgeCreation = false; + edgeCreation = false; + } + } + } + + @Override + public void mouseClicked(Point p) { + // clicking in add_eval_edge mode means to create edge by selecting + // nodes + Node clickedNode = display.findNode(p); + if (clickedNode != null) { + // clickedNode is the target node + if (display.getNewEdgeLine() != null && + display.getNewEdgeLine().getSourceNode() != clickedNode) { + try { + new NewEdgeAction(controller, + display.getNewEdgeLine().getSourceNode(), + clickedNode); + display.setNewEdgeLine(null); + edgeCreation = false; + clickedNode.setHighlighted(true); + clickedNode.getVisual().update(); + sourceNode = null; + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + } + else { + // user aborted new edge creation by clicking somewhere + if (sourceNode != null) { + sourceNode.setActive(false); + sourceNode.setHighlighted(false); + sourceNode.getVisual().update(); + } + display.setNewEdgeLine(null); + edgeCreation = false; + } + } + + @Override + public void mouseMoved(Point p) { + Edge currentEdge = display.findEdge(p); + // mouse leaved selectedEdge + if (selectedEdge != null && + currentEdge != selectedEdge) { + selectedEdge.setHighlighted(false); + selectedEdge.getVisual().update(); + } + selectedEdge = currentEdge; + // there is an edge under mouse, do not highlight, when edge is created + if (selectedEdge != null && + !edgeCreation) { + selectedEdge.setHighlighted(true); + selectedEdge.getVisual().update(); + } + // when no edge, perhaps there is a node under the mouse? + else { + Node currentNode = display.findNode(p); + // the user is searching the target node for a new edge + if (display.getNewEdgeLine() != null) { + if (currentNode != null) { + display.getNewEdgeLine().setP2( + ((NodeVisual)currentNode.getVisual()).getCenter()); + currentNode.setActive(true); + } + else { + // mouse leaved selected node, source node is ignored + if (selectedNode != null && + selectedNode != sourceNode) { + selectedNode.setActive(false); + selectedNode.setHighlighted(false); + selectedNode.getVisual().update(); + selectedNode = null; + } + display.getNewEdgeLine().setP2(p); + } + } + // the user is searching a source node for a new edge + // mouse leaved selected Edge + else if (selectedNode != null && + currentNode != selectedNode) { + selectedNode.setActive(false); + selectedNode.setHighlighted(false); + selectedNode.getVisual().update(); + } + selectedNode = currentNode; + // there is a node under mouse + if (selectedNode != null) { + selectedNode.setHighlighted(true); + selectedNode.getVisual().update(); + } + } + } + + @Override + public void mouseDragged(Point p) { + // evaluating the edge weight + if (clickedEdgeWeight != null) + clickedEdgeWeight.updateWeightToDragging(p); + else { + Node currentNode = display.findNode(p); + // the user is searching the target node for a new edge + if (display.getNewEdgeLine() != null) { + if (currentNode != null) { + display.getNewEdgeLine().setP2( + ((NodeVisual)currentNode.getVisual()).getCenter()); + currentNode.setActive(true); + currentNode.getVisual().update(); + selectedNode = currentNode; + } + else { + // mouse leaved selected node, source node is ignored + if (selectedNode != null && + selectedNode != sourceNode) { + selectedNode.setActive(false); + selectedNode.setHighlighted(false); + selectedNode.getVisual().update(); + selectedNode = null; + } + display.getNewEdgeLine().setP2(p); + } + draggingEdgeCreation = true; + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.java b/src/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.java new file mode 100644 index 0000000..096b1b1 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/StateAddMoveNode.java @@ -0,0 +1,110 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.Point; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.MoveNodeAction; +import org.jalgo.module.dijkstra.actions.NewNodeAction; +import org.jalgo.module.dijkstra.gfx.NodeVisual; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.model.Position; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class represents the state, which collaborates with the mode + * {@link org.jalgo.module.dijkstra.gui.Controller#MODE_ADD_MOVE_NODE}. + * + * @author Alexander Claus + */ +public class StateAddMoveNode +extends GraphDisplayState { + + private Node draggedNode; + private Node highlightedNode; + + public StateAddMoveNode(GraphDisplay display, Controller controller) { + super(display, controller); + } + + @Override + public void mousePressed(Point p) { + Node clickedNode = display.findNode(p); + // finding a node means, that the user wants to drag it + if (clickedNode != null) { + draggedNode = clickedNode; + draggedNode.setActive(true); + draggedNode.getVisual().update(); + } + // finding no node means, that the user wants to create a new node + else try { + new NewNodeAction(controller, p, display.getSize()); + // if succeeded, there should be a node under mouse pointer + draggedNode = display.findNode(p); + if (draggedNode != null) { + draggedNode.setActive(true); + draggedNode.getVisual().update(); + } + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + + @Override + public void mouseReleased(Point p) { + // end of dragging + if (draggedNode != null) { + try { + // do not allow to move nodes away from screen! + new MoveNodeAction(controller, draggedNode, + new Position(new Point( + Math.min(Math.max(0, p.x), display.getWidth()), + Math.min(Math.max(0, p.y), display.getHeight())), + GraphDisplay.getScreenSize())); + draggedNode.getVisual().updateLocation( + GraphDisplay.getScreenSize()); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + draggedNode.setActive(false); + draggedNode.setHighlighted(true); + highlightedNode = draggedNode; + draggedNode.getVisual().update(); + draggedNode = null; + } + } + + @Override + public void mouseClicked(Point p) { + // this method has no effect + } + + @Override + public void mouseMoved(Point p) { + Node currentNode = display.findNode(p); + // recently selected node leaved + if (currentNode != highlightedNode && + highlightedNode != null) { + highlightedNode.setActive(false); + highlightedNode.setHighlighted(false); + highlightedNode.getVisual().update(); + } + highlightedNode = currentNode; + if (highlightedNode != null) { + highlightedNode.setHighlighted(true); + highlightedNode.getVisual().update(); + } + } + + @Override + public void mouseDragged(Point p) { + // do not allow to move nodes away from screen! + if (draggedNode != null) + ((NodeVisual)draggedNode.getVisual()).setCenter(new Point( + Math.min(Math.max(0, p.x), display.getWidth()), + Math.min(Math.max(0, p.y), display.getHeight()))); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.java b/src/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.java new file mode 100644 index 0000000..7a72948 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/StateRemoveEdge.java @@ -0,0 +1,90 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.Point; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.DeleteEdgeAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class represents the state, which collaborates with the mode + * {@link org.jalgo.module.dijkstra.gui.Controller#MODE_DELETE_EDGE}. + * + * @author Alexander Claus + */ +public class StateRemoveEdge +extends GraphDisplayState { + + private Edge selectedEdge; + + public StateRemoveEdge(GraphDisplay display, Controller controller) { + super(display, controller); + } + + @Override + public void mousePressed(Point p) { + Edge clickedEdge = display.findEdge(p); + if (clickedEdge != null) { + clickedEdge.setActive(true); + clickedEdge.getVisual().update(); + } + } + + @Override + public void mouseReleased(Point p) { + // sense of the following? -- alexander + Edge clickedEdge = display.findEdge(p); + if (clickedEdge != null) { + // here was the weight itself deactivated! - alexander + clickedEdge.setActive(false); + clickedEdge.getVisual().update(); + } + } + + @Override + public void mouseClicked(Point p) { + try { + Edge clickedEdge = display.findEdge(p); + if (clickedEdge != null) + new DeleteEdgeAction(controller, clickedEdge); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + + @Override + public void mouseMoved(Point p) { + Edge currentEdge = display.findEdge(p); + if (currentEdge != selectedEdge && + selectedEdge!= null) { + selectedEdge.setActive(false); + selectedEdge.setHighlighted(false); + selectedEdge.getVisual().update(); + } + selectedEdge = currentEdge; + if (selectedEdge != null) { + selectedEdge.setHighlighted(true); + selectedEdge.getVisual().update(); + } + } + + @Override + public void mouseDragged(Point p) { + Edge currentEdge = display.findEdge(p); + if (currentEdge != selectedEdge && + selectedEdge!= null) { + selectedEdge.setActive(false); + selectedEdge.setHighlighted(false); + selectedEdge.getVisual().update(); + } + selectedEdge = currentEdge; + if (selectedEdge != null) { + selectedEdge.setHighlighted(true); + selectedEdge.getVisual().update(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.java b/src/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.java new file mode 100644 index 0000000..fbd3bd6 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/StateRemoveNode.java @@ -0,0 +1,91 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.Point; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.DeleteNodeAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; +import org.jalgo.module.dijkstra.model.Node; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class represents the state, which collaborates with the mode + * {@link org.jalgo.module.dijkstra.gui.Controller#MODE_DELETE_NODE}. + * + * @author Alexander Claus + */ +public class StateRemoveNode +extends GraphDisplayState { + + private Node selectedNode; + + private Node toBeDeleted; + + public StateRemoveNode(GraphDisplay display, Controller controller) { + super(display, controller); + } + + @Override + public void mousePressed(Point p) { + toBeDeleted = display.findNode(p); + if (toBeDeleted != null) { + toBeDeleted.setActive(true); + toBeDeleted.getVisual().update(); + } + } + + @Override + public void mouseReleased(Point p) { + Node currentNode = display.findNode(p); + if (currentNode != null && currentNode == toBeDeleted) { + try { + new DeleteNodeAction(controller, toBeDeleted); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } + toBeDeleted = null; + } + + @Override + public void mouseClicked(Point p) { + // this method has no effect + } + + @Override + public void mouseMoved(Point p) { + Node currentNode = display.findNode(p); + // mouse leaved selected node + if (currentNode != selectedNode && selectedNode != null) { + selectedNode.setActive(false); + selectedNode.setHighlighted(false); + selectedNode.getVisual().update(); + } + selectedNode = currentNode; + // mouse entered currentNode + if (selectedNode != null) { + selectedNode.setHighlighted(true); + selectedNode.getVisual().update(); + } + } + + @Override + public void mouseDragged(Point p) { + Node currentNode = display.findNode(p); + // mouse leaved selectedNode + if (selectedNode != null && currentNode != selectedNode) { + selectedNode.setActive(false); + selectedNode.setHighlighted(false); + selectedNode.getVisual().update(); + } + selectedNode = currentNode; + // mouse entered currentNode + if (selectedNode != null) { + if (selectedNode == toBeDeleted) selectedNode.setActive(true); + selectedNode.setHighlighted(true); + selectedNode.getVisual().update(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.java b/src/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.java new file mode 100644 index 0000000..d92f97a --- /dev/null +++ b/src/org/jalgo/module/dijkstra/gui/event/ToolbarActionHandler.java @@ -0,0 +1,41 @@ +package org.jalgo.module.dijkstra.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import org.jalgo.module.dijkstra.actions.ActionException; +import org.jalgo.module.dijkstra.actions.RedoAction; +import org.jalgo.module.dijkstra.actions.UndoAction; +import org.jalgo.module.dijkstra.gui.Controller; +import org.jalgo.module.dijkstra.util.DefaultExceptionHandler; + +/** + * This class is responsible for handling clicks on toolbar buttons, namely: + * undo and redo. + * + * @author Alexander Claus + */ +public class ToolbarActionHandler +implements ActionListener { + + private final Controller controller; + + public ToolbarActionHandler(Controller controller) { + this.controller = controller; + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("undo")) try { + new UndoAction(controller); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + else if (e.getActionCommand().equals("redo")) try { + new RedoAction(controller); + } + catch (ActionException ex) { + new DefaultExceptionHandler(ex); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/model/BorderState.java b/src/org/jalgo/module/dijkstra/model/BorderState.java new file mode 100644 index 0000000..d1688e1 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/BorderState.java @@ -0,0 +1,91 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +// $Id$ + +package org.jalgo.module.dijkstra.model; + +import java.util.ArrayList; +import java.util.Iterator; + + + +/** + * BorderState is a container that associates a chosen + * node with a border list. + * + * @see DijkstraAlgorithm + * @see State + * @author Julian Stecklina + */ +public class BorderState implements Cloneable { + + private ArrayList border; + private Node chosen; + private Graph graph; + + /** + * @return Returns the graph. + */ + public Graph getGraph() { + return graph; + } + /** + * Gets the Border as ArrayList of {@link Edge}s. + * + * @return the Border value. + */ + public ArrayList getBorder() { + return border; + } + + /* (non-Javadoc) + * @see java.lang.Object#clone() + */ + public Object clone() { + ArrayList newBorder = new ArrayList(border.size()); + Iterator it = border.iterator(); + + while (it.hasNext()) { + newBorder.add(it.next()); + } + + return new BorderState(chosen.clone(), newBorder, graph); + } + + /** + * Gets the chosen Node. + * + * @return the Node + */ + public Node getChosen() { + return chosen; + } + + + /** Creates a BorderState object with the given contents. + * @param chosen the chosen node + * @param border an ArrayList of edges. + */ + BorderState(Node chosen, ArrayList border, Graph graph) { + this.border = border; + this.chosen = chosen; + this.graph = graph; + } +} diff --git a/src/org/jalgo/module/dijkstra/model/CVS/Entries b/src/org/jalgo/module/dijkstra/model/CVS/Entries new file mode 100644 index 0000000..dfcf8ec --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/CVS/Entries @@ -0,0 +1,8 @@ +/BorderState.java/1.3/Thu Jan 31 20:15:10 2008/-kk/ +/DijkstraAlgorithm.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/Edge.java/1.5/Thu Jan 31 20:15:10 2008/-kk/ +/Graph.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/GraphElement.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/Node.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/Position.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ +/State.java/1.4/Thu Jan 31 20:15:10 2008/-kk/ diff --git a/src/org/jalgo/module/dijkstra/model/CVS/Repository b/src/org/jalgo/module/dijkstra/model/CVS/Repository new file mode 100644 index 0000000..cd17b51 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/model diff --git a/src/org/jalgo/module/dijkstra/model/CVS/Root b/src/org/jalgo/module/dijkstra/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.java b/src/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.java new file mode 100644 index 0000000..f5bd0a5 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/DijkstraAlgorithm.java @@ -0,0 +1,463 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 21.05.2005 $Id$ + */ +package org.jalgo.module.dijkstra.model; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.main.util.Messages; + +/** + * @author Julian Stecklina + */ +public class DijkstraAlgorithm { + + /** + * INFINITY approximates the numerical infinity. :-) Special + * care should be taken not to present this value to the user. + */ + private static final int INFINITY = -1; + private Graph graph; + private Node startNode; + private State currentState; + private ArrayList stateList; + private ArrayList borderStates = new ArrayList(); + private Node currentlyChosen; + /** + * INVALID means that there is no next index. + */ + public static final int INVALID = -1; + + private void addNodeReference(State state, Node node) { + state.addStyledDescription(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Node") + node.getIndex()); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private interface NodeClosure { + void value(Node node); + } + + private interface EdgeClosure { + void value(Edge edge); + } + + // I miss optional and keyword parameters... and _real_ closures... + private void doAllNodes(NodeClosure closure) { + doAllNodes(closure, graph.getNodeList()); + } + + /** + * Something like Lisp's mapc for Java. Maps over all nodes in the given + * ArrayList. + * + * @param closure + * @param nodes + */ + private void doAllNodes(NodeClosure closure, List nodes) { + for (int i = 0; i < nodes.size(); i++) + closure.value((Node)nodes.get(i)); + } + + /** + * Maps over all edges in the given array. + * + * @param closure + * @param edges + */ + private void doAllEdges(EdgeClosure closure, List edges) { + for (Edge edge : edges) + closure.value(edge); + } + + /** + * Same as doAllEdges with explicit ArrayList parameter, but defaults to all + * edges. + * + * @param closure + */ + private void doAllEdges(EdgeClosure closure) { + doAllEdges(closure, graph.getEdgeList()); + } + + /** + * @param index The state to go to. + */ + public void gotoState(int index) { + currentState = stateList.get(index); + } + + /** + * Return the current count of states + */ + public int getStateCount() { + return (stateList == null) ? 0 : stateList.size(); + } + + public State getCurrentState() { + return currentState; + } + + private State createState(ArrayList border, String descr, boolean macro) { + return createState(border, descr, macro, null); + } + + private State createState(ArrayList border, String descr, boolean macro, + Node activeNode) { + return createState(border, descr, macro, activeNode, null); + } + + private State createState(ArrayList border, String descr, boolean macro, + Node activeNode, Edge skipEdge) { + // Update the border flag + Graph ngraph = (Graph)graph.clone(); + + for (Node node : ngraph.getNodeList()) { + Node oldNode = graph.findNode(node.getIndex()); + node.setBorder(border.contains(oldNode)); + if ((activeNode == oldNode) || (currentlyChosen == oldNode)) + node.setActive(true); + } + + Edge nskipEdge = (skipEdge != null) ? + ngraph.findEdge(ngraph.findNode(skipEdge.getStartNodeIndex()), + ngraph.findNode(skipEdge.getEndNodeIndex())) : null; + // Now we need to propagate all flags to the approprate nodes. + + for (Node node : ngraph.getNodeList()) { + Node pred = node.getPredecessor(); + // If we have a predeccessor, find the appropriate edge + if (pred != null) { + Edge edge = ngraph.findEdge(node, pred); + // and set the right flags. + if (edge != nskipEdge) { + edge.setFlags(node.getFlags()); + edge.setReversed(pred != edge.getStartNode()); + } + } + } + + State newState = new State(ngraph, descr, macro, + (ArrayList)borderStates.clone()); + stateList.add(newState); + + return newState; + } + + /** + * @param border The border represented as ArrayList + * @param node The node from which we complete the border. + */ + private void completeBorder(ArrayList border, Node node) { + border.remove(node); + + for (Edge edge : graph.getEdgeList()) { + Node from = edge.getStartNode(); + Node to = edge.getEndNode(); + Node other; + + // Check whether we got an edge that belongs to node. + // other will be set to the 'other' node. + if (from == node) { + other = to; + } + else if (to == node) { + other = from; + } + else continue; + + if (other.isChosen() == false) { + if (other.getDistance() == INFINITY) { + // do nothing + } + else if ((node.getDistance() + edge.getWeight()) < + other.getDistance()) { + // Conflict case ?! + other.setConflict(true); + // edge.setConflict(true); + edge.setActive(true); + edge.setBorder(true); + edge.setReversed(other == edge.getStartNode()); + State c1 = createState(border, "", //$NON-NLS-1$ + false, other, edge); + addNodeReference(c1, other); + c1.addDescription(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Is_over")); //$NON-NLS-1$ //$NON-NLS-2$ + addNodeReference(c1, node); + c1.addDescription(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Reachable_on_shorter_path")); //$NON-NLS-1$ //$NON-NLS-2$ + + edge.setActive(false); + // edge.setConflict(false); + edge.setBorder(false); + other.setConflict(false); + + } + else { + // Conflict case, but nothing to do + other.setConflict(true); + // edge.setConflict(true); + edge.setActive(true); + edge.setBorder(true); + edge.setReversed(other == edge.getStartNode()); + State c1 = createState(border, "", //$NON-NLS-1$ + false, other, edge); + + addNodeReference(c1, other); + c1.addDescription(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Reachable_over_existing_path_shorter")); //$NON-NLS-1$ //$NON-NLS-2$ + + edge.setActive(false); + // edge.setConflict(false); + edge.setBorder(false); + other.setConflict(false); + continue; + } + + // There is a shorter path to other via node + other.setPredecessor(node); + other.setDistance(node.getDistance() + edge.getWeight()); + if (!border.contains(other)) border.add(other); + + // Create state + State st1 = createState(border, Messages.getString( + "dijkstra", "DijkstraAlgorithm.New_node"), //$NON-NLS-1$ //$NON-NLS-2$ + false, other); + addNodeReference(st1, other); + } + } + } + + private ArrayList deepClone(ArrayList list) { + ArrayList newList = new ArrayList(list.size()); + + for (Edge edge : list) + newList.add(edge.clone()); + + return newList; + } + + private void newBorderState(Node chosen, ArrayList border) { + // We want to pass EDGEs not NODEs here! + ArrayList borderEdges = new ArrayList(); + + for (Node bnode : border) { + Node pred = bnode.getPredecessor(); + if (pred == null) { throw new RuntimeException(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Error_1")); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (bnode == pred) { throw new RuntimeException(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Error_2")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + Edge edge = graph.findEdge(pred, bnode); + borderEdges.add(edge); + } + + borderStates.add(new BorderState(chosen.clone(), + deepClone(borderEdges), (Graph)graph.clone())); + } + + /** + * This is the implementation of Dijkstra's algorithm to find the shortest + * paths in a graph as given in Vogler's script as of 2003. + * + * @param start the start node + */ + public void generateStates(Node start) { + // Tabula rasa + + stateList = new ArrayList(); + borderStates = new ArrayList(); + currentlyChosen = start; + + // Initial states + start.setStart(true); + + // Initialization: + // All nodes except start are not reachable. + for (Node node : graph.getNodeList()) { + if (node != start) { + node.setStart(false); + node.setPredecessor(null); + node.setChosen(false); + node.setDistance(INFINITY); + } + } + + // start is chosen + start.setPredecessor(null); + start.setDistance(0); + start.setChosen(true); + + // All nodes adjacent to start form the initial border. + // We do not use the border flag of the nodes, because that + // would be unwieldy. + ArrayList border = new ArrayList(); + currentState = createState(border, "", true, start); //$NON-NLS-1$ + addNodeReference(currentState, start); + currentState.addDescription(Messages.getString( + "dijkstra", "DijkstraAlgorithm.Choosed_as_start_node")); //$NON-NLS-1$ //$NON-NLS-2$ + + completeBorder(border, start); + newBorderState(start, border); + createState(border, Messages.getString( + "dijkstra", "DijkstraAlgorithm.Fringe_complete_for_start_node"), //$NON-NLS-1$ //$NON-NLS-2$ + true); + + // Compute paths from start + while (!border.isEmpty()) { + // We need to make this an array because Java is braindead. + final Node[] minimum = new Node[1]; + minimum[0] = null; + + NodeClosure minimize = new NodeClosure() { + + public void value(Node node) { + if ((minimum[0] == null) + || (minimum[0].getDistance() > node.getDistance())) { + minimum[0] = node; + } + + } + }; + + // Find v with minimal distance + doAllNodes(minimize, border); + Node v = minimum[0]; + + v.setChosen(true); + currentlyChosen = v; + + State state1 = createState(border, Messages.getString( + "dijkstra", "DijkstraAlgorithm.New_choosen"), true, v); //$NON-NLS-1$ //$NON-NLS-2$ + addNodeReference(state1, v); + + completeBorder(border, v); + newBorderState(v, border); + + createState(border, Messages.getString( + "dijkstra", "DijkstraAlgorithm.Fringe_complete"), true); //$NON-NLS-1$ //$NON-NLS-2$ + currentlyChosen = null; + border.remove(v); + } + + createState(border, Messages.getString( + "dijkstra", "DijkstraAlgorithm.Algorithm_finished"), true); //$NON-NLS-1$ //$NON-NLS-2$ + + // dumpResult(start); + } + + private void dumpResult(Node start) { + System.out.println("Dumping results for Node " //$NON-NLS-1$ + + start.getIndex()); + + for (Node node : graph.getNodeList()) { + System.out.println("Node " + node.getIndex() //$NON-NLS-1$ + + " distance = " + node.getDistance()); //$NON-NLS-1$ + for (Node pred = node; pred != null; pred = pred.getPredecessor()) + System.out.print("> Node " + pred.getIndex()); //$NON-NLS-1$ + System.out.println(); + } + } + + /** + * This constructor creates a new DijkstraAlgorithm object that will compute + * the shortest paths in the given graph. + * + * @param graph The graph we want our algorithm to operate on. + */ + public DijkstraAlgorithm(Graph graph) { + // Do we want to copy this graph? + this.graph = graph; + this.stateList = new ArrayList(); + } + + /** + * Returns the index of the current state. + * + * @return index of the current state + */ + public int getCurrentStateIndex() { + return stateList.indexOf(currentState); + } + + /** + * Returns the index of the next macro step. + * + * @return next index of macro state + */ + public int getNextMacroStepIndex() { + for (int i = getCurrentStateIndex() + 1; i < stateList.size(); i++) { + if (stateList.get(i).isMacro()) return i; + } + return INVALID; + } + + /** + * Returns the index of the previous macro step. + * + * @return previous index of macro state + */ + public int getPrevMacroStepIndex() { + for (int i = getCurrentStateIndex() - 1; i >= 0; i--) { + if (stateList.get(i).isMacro()) return i; + } + return INVALID; + } + + /** + * Returns the index of the next state. + * + * @return next index + */ + public int getNextStepIndex() { + int cur = getCurrentStateIndex(); + + if (cur + 1 == stateList.size()) return INVALID; + return getCurrentStateIndex() + 1; + } + + /** + * Returns the index of the previous state. + * + * @return previous index + */ + public int getPrevStepIndex() { + int cur = getCurrentStateIndex(); + + return (cur <= 0) ? INVALID : cur - 1; + } + + /** + * Returns the start node. + * + * @return start node + */ + public Node getStartNode() { + return startNode; + } +} diff --git a/src/org/jalgo/module/dijkstra/model/Edge.java b/src/org/jalgo/module/dijkstra/model/Edge.java new file mode 100644 index 0000000..ebaeb6f --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/Edge.java @@ -0,0 +1,250 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2005 + * + */ +package org.jalgo.module.dijkstra.model; + +import java.io.Serializable; + +import org.jalgo.module.dijkstra.gfx.EdgeVisual; + +/** + * @author Hannes Strass + * + * Represents an weighted edge between two nodes. + */ +public class Edge +extends GraphElement +implements Serializable, Comparable, Cloneable { + + private static final long serialVersionUID = 18238242054685159L; + + private Node startNode; + private Node endNode; + private int weight; + + /** + * Retrieves a copy of the current Edge. + */ + @Override + protected Edge clone() { + try { + Edge clone = (Edge)super.clone(); + clone.visual = new EdgeVisual(clone); + return clone; + } + catch (CloneNotSupportedException ex) { + throw new RuntimeException(ex); + } + } + + /** + * reversed specifies whether an edge needs to be drawn not + * from startNode to + * endNode, but the other way round. + * + */ + private boolean reversed = false; + + /** + * Get the Reversed value. + * + * @return the Reversed value. + */ + public boolean isReversed() { + return reversed; + } + + /** + * Set the Reversed value. + * + * @param newReversed The new Reversed value. + */ + public void setReversed(boolean newReversed) { + this.reversed = newReversed; + } + + /** + * creates a new Edge with default weight, sets changed-flag true + * + * @param startNode the start Node + * @param endNode the end Node + */ + public Edge(Node startNode, Node endNode) { + this(startNode, endNode, 5); + } + + /** + * creates a new Edge, sets changed-flag true + * + * @param startNode the start Node + * @param endNode the end Node + * @param weight the weight + */ + public Edge(Node startNode, Node endNode, int weight) { + // if index of startNode is greater than index of endNode, swap Nodes + if (startNode.getIndex() > endNode.getIndex()) { + this.startNode = endNode; + this.endNode = startNode; + } + else { + this.startNode = startNode; + this.endNode = endNode; + } + setWeight(weight); + this.setChanged(true); + + visual = new EdgeVisual(this); + } + + /** + * @param anotherEdge + * @return true, if both start- and endNode are equal and weight matches as + * well + */ + public boolean equals(Edge anotherEdge) { + return (startNode.getIndex() == anotherEdge.getStartNode().getIndex() && + // && this.weight == anotherEdge.getWeight() + endNode.getIndex() == anotherEdge.getEndNode().getIndex()); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Edge anotherEdge) { + if (this.startNode.getIndex() < anotherEdge.getStartNode().getIndex()) return -1; + if (this.startNode.getIndex() > anotherEdge.getStartNode().getIndex()) return 1; + if (this.endNode.getIndex() < anotherEdge.getEndNode().getIndex()) return -1; + if (this.endNode.getIndex() > anotherEdge.getEndNode().getIndex()) return 1; + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + return "Edge(" + startNode + ", " + weight + ", " + endNode + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + /** + * @return the start Node + */ + public Node getStartNode() { + return startNode; + } + + /** + * @return the end Node + */ + public Node getEndNode() { + return endNode; + } + + /** + * @return the weight + */ + public int getWeight() { + return weight; + } + + /** + * @return index of start Node + */ + public int getStartNodeIndex() { + return startNode.getIndex(); + } + + /** + * @return index of end Node + */ + public int getEndNodeIndex() { + if (endNode == null) throw new RuntimeException( + "This edge is without end node."); //$NON-NLS-1$ + return endNode.getIndex(); + } + + /** + * @return Edge as string according to Prof. Vogler's script: + * (startNodeIndex, weight, endNodeIndex) + */ + public String getText() { + if (!reversed) return "(" + startNode.getIndex() + "," + weight + "," + endNode.getIndex() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + return "(" + endNode.getIndex() + "," + weight + "," + startNode.getIndex() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + /** + * Creates a String suitable as description for the Algorithm stuff. Edges + * are represented as (to, distance/weight, form). + * + * @param distancep if true display the distance rather than weight. + * @return a string describing the edge. + */ + public String getAlgoText(boolean distancep, BorderState bdstate) { + boolean rev = false; + + Node fStart = bdstate.getGraph().findNode(startNode.getIndex()); + Node fEnd = bdstate.getGraph().findNode(endNode.getIndex()); + + if (fEnd.getPredecessor() == null) rev = true; + else rev = !(fStart.getIndex() == fEnd.getPredecessor().getIndex()); + + Node start = rev ? fEnd : fStart; + Node end = rev ? fStart : fEnd; + int dis = distancep ? end.getDistance() : weight; + + return "(" + end.getIndex() + "," + dis + "," + start.getIndex() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + + /** + * @param newStartNode the start Node to set + */ + public void setStartNode(Node newStartNode) { + this.startNode = newStartNode; + } + + /** + * @param newEndNode the end Node to set + */ + public void setEndNode(Node newEndNode) { + this.endNode = newEndNode; + } + + /** + * Sets the weight of this edge to the given weight. The value is clipped + * automatically to the range 0..99. + * + * @param newWeight the weight to set + */ + public void setWeight(int newWeight) { + this.weight = newWeight; + if (newWeight < 0) this.weight = 0; + if (newWeight > 99) this.weight = 99; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/model/Graph.java b/src/org/jalgo/module/dijkstra/model/Graph.java new file mode 100644 index 0000000..dd3019a --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/Graph.java @@ -0,0 +1,539 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2005 + * + */ +package org.jalgo.module.dijkstra.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * @author Hannes Strass, Martin Winter + * + * Represents a set of nodes and a set of edges. + * + */ +public class Graph implements Serializable, Cloneable { + + private static final long serialVersionUID = -5343300138161726312L; + + private List nodeList; + + private List edgeList; + + /** + * creates a new Graph with new, empty ArrayLists + */ + public Graph() { + nodeList = new ArrayList(); + edgeList = new ArrayList(); + } + + /** + * creates a Graph using given ArrayLists + * @param nodes the Node list + * @param edges the Edge list + */ + public Graph(List nodes, List edges) { + nodeList = nodes; + edgeList = edges; + } + + /** Finds the edge between two nodes. + * @param from + * @param to + * @return the node + */ + public Edge findEdge(Node from, Node to) { + for (int i = 0; i < edgeList.size(); i++) { + Edge edge = edgeList.get(i); + if (((edge.getStartNode().getIndex() == from.getIndex()) && + (edge.getEndNode().getIndex() == to.getIndex())) || + ((edge.getStartNode().getIndex() == to.getIndex()) && + (edge.getEndNode().getIndex() == from.getIndex()))) + return edge; + } + throw new RuntimeException("Graph structure is broken."); //$NON-NLS-1$ + } + + /** Finds the node with the given index or returns null. + * @param index + * @return a node or null + */ + public Node findNode(int index) { + Iterator it = nodeList.iterator(); + + while (it.hasNext()) { + Node node = (Node) it.next(); + + if (node.getIndex() == index) + return node; + } + + return null; + + } + + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Graph)) return false; + if (obj == null) return false; + Graph other = (Graph)obj; + return nodeList.equals(other.nodeList) && edgeList.equals(other.edgeList); + } + + + /* (non-Javadoc) + * @see java.lang.Object#clone() + * @author Julian Stecklina + */ + public Object clone() { + Graph newGraph = new Graph(); + + for (int i = 0; i < nodeList.size(); i++) + newGraph.addNode(nodeList.get(i).clone()); + + for (int i = 0; i < nodeList.size(); i++) { + Node n = newGraph.nodeList.get(i); + Node pred = n.getPredecessor(); + + // Deep copy means we must fix references! + if (pred != null) + n.setPredecessor(newGraph.findNode(pred.getIndex())); + } + + for (int i = 0; i < edgeList.size(); i++) + newGraph.addEdge(edgeList.get(i).clone()); + for (int i = 0; i < edgeList.size(); i++) { + Edge e = newGraph.edgeList.get(i); + Node from = e.getStartNode(); + Node to = e.getEndNode(); + + // Fix references again + e.setStartNode(newGraph.findNode(from.getIndex())); + e.setEndNode(newGraph.findNode(to.getIndex())); + } + + return newGraph; + } + + + public String toString() { + return "Graph: NodeList: " + getNodeListText() + "; EdgeList: " + getEdgeListText() + "."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + + /** Return next available index for a new node. + * + * @return next available index + */ + public int getNextNodeIndex() { + // Node indices are 1-based. + return nodeList.size() + 1; + } + + + /** + * adds a Node to the NodeList if it doesn't exist yet + * @param node the Node to add + * @return true, if Node has been added + */ + public boolean addNode(Node node) { + for (int i = 0; i < nodeList.size(); i++) { + if (nodeList.get(i).getIndex() == node.getIndex()) { + return false; + } + } + boolean returnValue = nodeList.add(node); + Collections.sort(nodeList); + return returnValue; + } + + + /** + * adds an Edge to the EdgeList if it doesn't exist yet + * @param edge the Edge to add + * @return true, if Edge has been added + */ + public boolean addEdge(Edge edge) { + Edge currentEdge; + + if (edge.getEndNodeIndex() == edge.getStartNodeIndex()) { + addNode(edge.getStartNode()); + return false; + } + + for (int i = 0; i < edgeList.size(); i++) // check if edge already exists + { + currentEdge = edgeList.get(i); + if (currentEdge.equals(edge)) { + int newWeight = edge.getWeight(); + if (newWeight == currentEdge.getWeight()) + return false; + currentEdge.setWeight(newWeight); + currentEdge.setChanged(true); + return true; + } + } + + for (int i = 0; i < nodeList.size(); i++) // check for duplicate Nodes + { + if (edge.getStartNode().getIndex() == nodeList.get(i).getIndex()) { + edge.setStartNode(nodeList.get(i)); + } + if (edge.getEndNode().getIndex() == nodeList.get(i).getIndex()) { + edge.setEndNode(nodeList.get(i)); + } + } + + boolean returnValue = edgeList.add(edge); + Collections.sort(edgeList); + + return returnValue; + } + + + /** + * @return the Edge list according to Prof. Vogler's script without leading and trailing braces + */ + public String getEdgeListText() { + StringBuffer returnValue = new StringBuffer(); + + if (edgeList.size() > 0) { + returnValue.append(edgeList.get(0).getText()); + } + for (int i = 1; i < edgeList.size(); i++) { + returnValue.append(", ").append(edgeList.get(i).getText()); //$NON-NLS-1$ + } + + return returnValue.toString(); + } + + + /** + * @return the Node list according to Prof. Vogler's script without leading and trailing braces + */ + public String getNodeListText() { + StringBuffer returnValue = new StringBuffer(); + + if (nodeList.size() > 0) { + returnValue.append(nodeList.get(0).getIndex()); + } + for (int i = 1; i < nodeList.size(); i++) { + returnValue.append(", ").append(nodeList.get(i).getIndex()); //$NON-NLS-1$ + } + + return returnValue.toString(); + } + + + /** Automaticly changes Node Positions and arranges Nodes in a circle with their indexes ascending clockwise. + * + * Call after replaceMissingNodes(). + * + * @return rescaled Graph (this) + */ + public Graph rescale() { + /* + * count nodes, calculate new positions, change positions + */ + double nodeAngle, newWorldX, newWorldY, addValue; + int numberOfNodes = nodeList.size(); + Position newPosition; + + addValue = ((numberOfNodes % 2) == 0) ? + ((Math.PI / numberOfNodes) + (Math.PI / 2)) : + (Math.PI / 2); + + if (numberOfNodes == 1) { + // Put single node in the center. + nodeList.get(0).setPosition(new Position(0.0, 0.0)); + } + else { + for (int i = 0; i < numberOfNodes; i++) { + // Arrange nodes clockwise, starting with node 1 top middle //left. + nodeAngle = i * ((-2) * Math.PI) / numberOfNodes + addValue; + newWorldX = Math.cos(nodeAngle) * 0.8; // Offset from edge of screen. + newWorldY = Math.sin(nodeAngle) * 0.8; + newPosition = new Position(newWorldX, newWorldY); + nodeList.get(i).setPosition(newPosition); + } + } + + return this; + } + + + /** + * The current implementation of the distance matrix editing composite does not + * support arbitrary Node indexes in the Node list, eg. you can't have a Node 1 and a Node 3 but no Node 2. + * + * This method checks the Nodes and if their indexes (and thus labels) differ from their position in the + * Node list, it changes the indexes. + * + * After calling this method you will have n Nodes with indexes from 1 to n in your Node list. + * + * Should be called before rescale(). + * + */ + public void replaceMissingNodes() { + int startNodeIndex, endNodeIndex; + Node currentNode; + Edge currentEdge; + ArrayList newNodes = new ArrayList(10); + ArrayList badNodes = new ArrayList(10); + + for (int i = 0; i < 10; i++) { + newNodes.add(null); + badNodes.add(null); + } + + for (int i = 0; i < nodeList.size(); i++) { + currentNode = nodeList.get(i); + if (currentNode.getIndex() == i + 1) { + // Node has correct index, do nothing + } else { + // wrong index, map Node to new index + badNodes.set(i, currentNode); + newNodes.set(i, new Node((i + 1), currentNode.getPosition())); + } + } + + for (int i = 0; i < newNodes.size(); i++) { + if (newNodes.get(i) != null) { + nodeList.set(i, newNodes.get(i)); + } + } + + for (int i = 0; i < edgeList.size(); i++) { + currentEdge = edgeList.get(i); + + startNodeIndex = badNodes.indexOf(currentEdge.getStartNode()); + if (startNodeIndex != -1) { + currentEdge.setStartNode(newNodes.get(startNodeIndex)); + } + + endNodeIndex = badNodes.indexOf(currentEdge.getEndNode()); + if (endNodeIndex != -1) { + currentEdge.setEndNode(newNodes.get(endNodeIndex)); + } + } + } + + + /** + * resets the Graph -- Node list and Edge list are cleared + */ + public void reset() { + nodeList.clear(); + edgeList.clear(); + } + + + /** + * @return the Node list + */ + public List getNodeList() { + return nodeList; + } + + + /** + * @return The start node of the graph or null + */ + public Node getStartNode() { + Iterator iter = getNodeList().iterator(); + while (iter.hasNext()) { + Node node = (Node) iter.next(); + if (node.isStart()) + return node; + } + return null; + } + + + /** + * @return the Edge list + */ + public List getEdgeList() { + return edgeList; + } + + + /** removes a Node from the Node list and all adjacent Edges from the Edge list + * @param nodeToDelete the Node to delete + * @return true, if Node actually existed in Node list and has been deleted. nothing is removed otherwise + */ + public boolean deleteNode(Node nodeToDelete) { + for (int i = 0; i <= nodeList.size(); i++) { + if (nodeList.get(i).getIndex() == nodeToDelete.getIndex()) { + /* + * FSt + * nodeList.remove(nodeToDelete); + * because somtimes the indices are equal, but the object pointers are different + */ + nodeList.remove(nodeList.get(i)); + //~FSt + + boolean stillHasEdges = true; + Edge currentEdge = null; + + //if nodeToDelete has adjacent Edges, delete them + while (stillHasEdges) { + stillHasEdges = false; + for (int j = 0; j < edgeList.size(); j++) { + if ((nodeToDelete.getIndex() == edgeList.get(j).getStartNode() + .getIndex()) + || (nodeToDelete.getIndex() == edgeList.get(j) + .getEndNode().getIndex())) { + currentEdge = edgeList.get(j); + stillHasEdges = true; + } + } + if (stillHasEdges) + this.deleteEdge(currentEdge); + } + return true; + } + } + + return false; + } + + + /** + * deletes an Edge from the Edge list. Note: after removing an Edge there might be a Node that is not connected to the Graph any more + * + * @param edgeToDelete the Edge to delete + * @return true, if Edge actually existed in Edge list and has been deleted + */ + public boolean deleteEdge(Edge edgeToDelete) { + for (int i = 0; i <= edgeList.size(); i++) { + if (edgeList.get(i).equals(edgeToDelete)) { + //edgeList.remove(edgeToDelete); + //FSt see deleteNode() for more information about this change + edgeList.remove(edgeList.get(i)); + return true; + } + } + return false; + } + + + /** + * sets changed-flags of all Nodes and all Edges false. call this before adding new Nodes and Edges + */ + public void setAllChangedFlagsFalse() { + for (Node node : nodeList) { + node.setChanged(false); + node.getVisual().update(); + } + for (Edge edge : edgeList) { + edge.setChanged(false); + edge.getVisual().update(); + } + } + + + /** + * Synchronizes this with anotherGraph -- ie. elements that are in anotherGraph + * but not in this, are added. Elements that are in this, but not in + * anotherGraph, are deleted from this. This method is basically needed because + * you can't create Edges in a Node list and new elements always carry the + * changed-flag, which should only be true for recently added elements. + * @param anotherGraph graph to synchronize with + * @param deleteNodes determines wether Nodes that are in this, but not in + * anotherGraph, shall be deleted + */ + public void synchronizeWith(Graph anotherGraph, boolean deleteNodes) { + /* direction 1: + * copy all Elements from anotherGraph into this. + * already existing elements should not be overwritten (changed-flag) + */ + + List anotherNodeList = anotherGraph.getNodeList(); // NOT ANOTHER NODE LIST! (coming to cinemas soon) + List anotherEdgeList = anotherGraph.getEdgeList(); + + for (int i = 0; i < anotherNodeList.size(); i++) { + this.addNode(anotherNodeList.get(i)); + } + for (int i = 0; i < anotherEdgeList.size(); i++) { + this.addEdge(anotherEdgeList.get(i)); + } + + /* direction 2: + * check if this contains elements that anotherGraph + * does not contain; if found, delete them + */ + + boolean deleteIt = true; + Node currentNode; + Edge currentEdge; + ArrayList nodesToDelete = new ArrayList(); + ArrayList edgesToDelete = new ArrayList(); + + for (int i = 0; i < nodeList.size(); i++) { + currentNode = nodeList.get(i); // get an element from this Graph + + for (int j = 0; j < anotherNodeList.size(); j++) { + if (currentNode.getIndex() == anotherNodeList.get(j).getIndex()) + deleteIt = false; + } + if (deleteIt) + nodesToDelete.add(currentNode); + //this.deleteNode(currentNode); + + deleteIt = true; + } + + for (int i = 0; i < edgeList.size(); i++) { + currentEdge = edgeList.get(i); // get an element from this Graph + + for (int j = 0; j < anotherEdgeList.size(); j++) { + if (currentEdge.equals(anotherEdgeList.get(j))) + deleteIt = false; + } + if (deleteIt) + edgesToDelete.add(currentEdge); + //this.deleteEdge(currentEdge); + + deleteIt = true; + } + + for (int i = 0; i < edgesToDelete.size(); i++) { + this.deleteEdge(edgesToDelete.get(i)); + } + + if (deleteNodes) { + for (int i = 0; i < nodesToDelete.size(); i++) { + this.deleteNode(nodesToDelete.get(i)); + } + } + } // (1,1,3),(3,2,5),(5,3,2),(2,4,4),(4,5,1)} +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/model/GraphElement.java b/src/org/jalgo/module/dijkstra/model/GraphElement.java new file mode 100644 index 0000000..2686fc7 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/GraphElement.java @@ -0,0 +1,219 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 18.05.2005 + * + */ +package org.jalgo.module.dijkstra.model; + +import java.io.Serializable; + +import org.jalgo.module.dijkstra.gfx.Visual; + +/** + * @author Hannes Strass, Martin Winter + * + * Abstract superclass of Node and Edge. Needed to define static flags. + * + */ +public abstract class GraphElement +implements Serializable { + + public static final int NONE = 0; + public static final int ACTIVE = 1; + public static final int BORDER = 2; + public static final int CHANGED = 4; + public static final int CHOSEN = 8; + public static final int CONFLICT = 16; + public static final int HIGHLIGHTED = 32; + public static final int START = 64; + + private boolean isActive; + private boolean isBorder; + private boolean isChanged; + /** + * @see java.lang.Object#toString() + * @author Frank Staudinger + */ + public String toString() + { + return "Flags: "+new Integer(getFlags())+";"+super.toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } + private boolean isChosen; + private boolean isConflict; + private boolean isHighlighted; + private boolean isStart; + + private int flags; + + protected Visual visual; + + /** Gets flags as integer. + * @return flags + */ + public int getFlags() + { + flags = NONE; + if (isActive) flags |= ACTIVE; + if (isBorder) flags |= BORDER; + if (isChanged) flags |= CHANGED; + if (isChosen) flags |= CHOSEN; + if (isConflict) flags |= CONFLICT; + if (isHighlighted) flags |= HIGHLIGHTED; + if (isStart) flags |= START; + return flags; + } + + /** Sets the flags as integer. + * @param newFlags the new flags to set + */ + public void setFlags(int newFlags) + { + isActive = ((newFlags & ACTIVE) > 0); + isBorder = ((newFlags & BORDER) > 0); + isChanged = ((newFlags & CHANGED) > 0); + isChosen = ((newFlags & CHOSEN) > 0); + isConflict = ((newFlags & CONFLICT) > 0); + isHighlighted = ((newFlags & HIGHLIGHTED) > 0); + isStart = ((newFlags & START) > 0); + + flags = newFlags; + } + + /** Checks whether the given element is "active". + */ + public boolean isActive() + { + return isActive; + } + + /** Checks whether the element belongs to the border. + */ + public boolean isBorder() + { + return isBorder; + } + + /** + * @return true if the element was recently changed. + */ + public boolean isChanged() + { + return isChanged; + } + + /** + * @return true if the element is a chosen one. + */ + public boolean isChosen() + { + return isChosen; + } + + /** + * @return true if the element is in conflict with something. + */ + public boolean isConflict() + { + return isConflict; + } + + /** + * @return true if the element shall be highlighted. + */ + public boolean isHighlighted() + { + return isHighlighted; + } + + /** + * @return true if the element is the start node. + */ + public boolean isStart() + { + return isStart; + } + + /** Sets the active property of the element. + * @param newActive + */ + public void setActive(boolean newActive) + { + isActive = newActive; + } + + /** Sets the border property of the element. + * @param newBorder + */ + public void setBorder(boolean newBorder) + { + isBorder = newBorder; + } + + /** Marks an object as recently changed or not. + * @param newChanged + */ + public void setChanged(boolean newChanged) + { + isChanged = newChanged; + } + + /** Sets the chosen property of the element. + * @param newChosen + */ + public void setChosen(boolean newChosen) + { + isChosen = newChosen; + } + + /** Sets the conflict property of the element. + * @param newConflict + */ + public void setConflict(boolean newConflict) + { + isConflict = newConflict; + } + + /** Marks the element as highlighted or normal. + * @param newHighlighted + */ + public void setHighlighted(boolean newHighlighted) + { + isHighlighted = newHighlighted; + } + + /** Marks the element as the start node or not. + * @param newStart + */ + public void setStart(boolean newStart) + { + isStart = newStart; + } + + /** + * Since all GraphElements are going to be displayed, each of + * them has a Visual component. + * + * @return the Visual component for this GraphElement + */ + public Visual getVisual() { + return visual; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/model/Node.java b/src/org/jalgo/module/dijkstra/model/Node.java new file mode 100644 index 0000000..ca712cf --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/Node.java @@ -0,0 +1,216 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2005 + * + */ +package org.jalgo.module.dijkstra.model; + +import java.io.Serializable; + +import org.jalgo.module.dijkstra.gfx.NodeVisual; +import org.jalgo.module.dijkstra.gui.components.GraphDisplay; + +/** + * Represents a Node which is characterized by its index, which is an integer + * between 1 and 9. + * + * @author Hannes Strass, Martin Winter + */ +public class Node +extends GraphElement +implements Serializable, Comparable, Cloneable { + + private static final long serialVersionUID = 3662600887046879993L; + private int index; + private Position position; + private Node predecessor; + private int distance; + + /** + * Retrieves a copy of the current Node. + */ + @Override + protected Node clone() { + try { + Node clone = (Node)super.clone(); + clone.visual = new NodeVisual(clone); + return clone; + } + catch (CloneNotSupportedException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Returns the distance from the start node. This is used by + * {@link DijkstraAlgorithm}. + * + * @return Returns the distance from the start node to this one. + */ + public int getDistance() { + return distance; + } + + /** + * Sets the distance from the start node. This is used by + * {@link DijkstraAlgorithm}. + * + * @param distance The distance to set. + */ + public void setDistance(int distance) { + this.distance = distance; + } + + /** + * Creates a Node with Position(0.0, 0.0) and given index, sets changed-flag + * true + * + * @param index the index + */ + public Node(int index) { + this(index, new Position(0, 0)); + } + + /** + * creates a node with given Position and given index, sets changed-flag + * true + * + * @param index the index + * @param position the Position + */ + public Node(int index, Position position) { + this.index = index; + this.position = position; + visual = new NodeVisual(this); + setChanged(true); // new Nodes are always changed + } + + /** + * @param anotherNode + * @return true, if indexes of this and anotherNode are equal + */ + public boolean equals(Node anotherNode) { + if (anotherNode == null) return false; + return (this.index) == anotherNode.getIndex(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + return "(Node " + index + ", " + position + ");" + super.toString(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + /** + * @return the index as String + */ + public String getLabel() { + return (String.valueOf(index)); + } + + /** + * @return the index + */ + public int getIndex() { + return index; + } + + /** + * @param newIndex the index to set + * @return true, if index is in range (from 1 to 9). index will not be set + * otherwise + */ + public boolean setIndex(int newIndex) { + if ((0 < newIndex) && (newIndex < 10)) { + this.index = newIndex; + return true; + } + + return false; + } + + /** + * @return The Position of the Node in the virtual "world coordinate system" + */ + public Position getPosition() { + return this.position; + } + + /** + * @return the predecessor of the node concerning shortest paths + */ + public Node getPredecessor() { + return this.predecessor; + } + + /** + * @return the shortest path as string + */ + public String getShortestPath() { + if (getPredecessor() != null) { + String strPath = getPredecessor().getShortestPath(); + if (strPath.length() == 0) return getPredecessor().getLabel(); + return strPath + "," + getPredecessor().getLabel(); //$NON-NLS-1$ + } + return ""; //$NON-NLS-1$ + } + + /** + * compares Nodes + * + * @param anotherNode Node to compare with + * @return -1 for less, 0 for equal and 1 for greater (this than + * anotherNode) + */ + public int compareTo(Node anotherNode) { + if (anotherNode.getIndex() < this.index) return 1; + if (anotherNode.getIndex() == this.index) return 0; + // (node.getIndex() > this.index) + return -1; + } + + /** + * Sets the position of this node on the screen. + * + * @param newPosition the new position + */ + public void setPosition(Position newPosition) { + this.position = newPosition; + ((NodeVisual)visual).setCenter( + newPosition.getScreenPoint(GraphDisplay.getScreenSize())); + } + + /** + * Sets the predecessor of a node. This forms the spanning graph where we + * extract the shortest paths. + * + * @param newPredecessor the predecessor to set + */ + public void setPredecessor(Node newPredecessor) { + this.predecessor = newPredecessor; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/model/Position.java b/src/org/jalgo/module/dijkstra/model/Position.java new file mode 100644 index 0000000..ecfc8df --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/Position.java @@ -0,0 +1,217 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 08.05.2005 + * + */ +package org.jalgo.module.dijkstra.model; + +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.geom.Point2D; +import java.io.Serializable; + +/** + * Defines a data structure which indicates the position of a {@link Node} in a virtual "world coordinate system". + *

          Note: The parameter "screenSize" does not mean the size of the entire screen; + * it refers to the area of the screen that represents the coordinate system and is to contrast with "worldSize". + * @author Hannes Strass, Martin Winter + */ +public class Position implements Serializable { + + private static final long serialVersionUID = 4599666519626602617L; + + // here no Point2D is used because of the lack of serializability + private double worldX; + private double worldY; + + /** + * Creates a new position using world coordinates as individual doubles. + * @param worldX horizontal coordinate, range -1 ... +1 inclusive + * @param worldY vertical coordinate, range -1 ... +1 inclusive + */ + public Position(double worldX, double worldY) { + this.worldX = worldX; + this.worldY = worldY; + } + + /** + * Creates a new position using screen coordinates and the size of the screen area as a Dimension. + * @param screenCoordinates point (pixels) of the position + * @param screenSize screen size as a dimension (see class description above) + */ + public Position(Point screenCoordinates, Dimension screenSize) { + setScreenCoordinates(screenCoordinates, screenSize); + } + + /** + * Creates a new position using screen coordinates and the size of the screen area as a Rectangle. + * Location of screenBounds is ignored. + * @param screenCoordinates point (pixels) of the position + * @param screenBounds screen size as a rectangle (see class description above) + */ + public Position(Point screenCoordinates, Rectangle screenBounds) { + this(screenCoordinates, screenBounds.getSize()); + } + + /** + * Sets screen coordinates and computes world coordinates. + * @param screenCoordinates point (pixels) of the position + * @param screenSize screen size as a dimension (see class description above) + */ + public void setScreenCoordinates(Point screenCoordinates, Dimension screenSize) { + // Copy screen coordinates as base for calculations. + worldX = screenCoordinates.getX(); + worldY = screenCoordinates.getY(); + + // Translate coordinates by the distance of the screen (area) center from the origin, + // so we get four quadrants with positive _and_ negative coordinates. + double horizontalOffset = screenSize.width / 2.0; // Must be double in case dimensions are odd. + double verticalOffset = screenSize.height / 2.0; + worldX -= horizontalOffset; + worldY -= verticalOffset; + + // Scale screen coordinates to world coordinate system (range -1 ... +1 inclusive). + worldX /= horizontalOffset; + worldY /= verticalOffset * -1.0; // Flip vertical coordinates. + } + + /** + * Sets screen coordinates and computes world coordinates. + * @param screenCoordinates point (pixels) of the position + * @param screenBounds screen size as a rectangle (see class description above) + */ + public void setScreenCoordinates(Point screenCoordinates, Rectangle screenBounds) { + setScreenCoordinates(screenCoordinates, screenBounds.getSize()); + } + + /** + * Returns the point on screen, computed from internal world coordinates and relative to screenSize. + * Performs operations symmetric to those of setScreenCoordinates(). + * @param screenSize screen size as a dimension (see class description above) + * @return point on screen (pixels) + */ + public Point getScreenPoint(Dimension screenSize) { + // Copy world coordinates as base for calculations. + // Passing worldCoordinates to the constructor of screenCoordinates + // would copy only integer values, not preciseX and preciseY! + Point2D screenCoordinates = new Point2D.Double(); + screenCoordinates.setLocation(worldX, worldY); + + // Scale world coordinates to screen coordinate system. + double horizontalOffset = screenSize.width / 2.0; // Must be doubles in case dimensions are odd. + double verticalOffset = screenSize.height / 2.0; + screenCoordinates.setLocation( + screenCoordinates.getX() * horizontalOffset, + screenCoordinates.getY() * verticalOffset * -1.0); // Flip vertical coordinates. + + // Translate coordinates by the distance of the screen (area) center from the origin, + // so we get only positive coordinates. + screenCoordinates.setLocation( + screenCoordinates.getX() + horizontalOffset, + screenCoordinates.getY() + verticalOffset); + + // Return integer coordinates. + Point integralScreenCoordinates = new Point( + (int)screenCoordinates.getX(), (int)screenCoordinates.getY()); + return integralScreenCoordinates; + } + + /** + * Returns the point on screen, computed from internal world coordinates and relative to screenSize. + * Performs operations symmetric to those of setScreenCoordinates(). + * @param screenBounds screen size as a rectangle (see class description above) + * @return point on screen (pixels) + */ + public Point getScreenPoint(Rectangle screenBounds) { + return getScreenPoint(screenBounds.getSize()); + } + + /** + * Sets world coordinates. + * Automatically clipped to the range -1 ... +1 inclusive. + * @param worldCoordinates world coordinates as a PrecisionPoint (double) + */ + public void setWorldCoordinates(Point2D worldCoordinates) { + setWorldX(worldCoordinates.getX()); + setWorldY(worldCoordinates.getY()); + } + + /** + * Sets horizontal world coordinate. + * Automatically clipped to the range -1 ... +1 inclusive. + * @param newWorldX world x coordinate as a double + */ + public void setWorldX(double newWorldX) { + worldX = Math.min(1, Math.max(-1, newWorldX)); + } + + /** + * Sets vertical world coordinate. + * Automatically clipped to the range -1 ... +1 inclusive. + * @param newWorldY world y coordinate as a double + */ + public void setWorldY(double newWorldY) { + worldY = Math.min(1, Math.max(-1, newWorldY)); + } + + /** + * Returns horizontal world coordinate. + * @return world x coordinate as a double + */ + public double getWorldX() { + return worldX; + } + + /** + * Returns vertical world coordinate. + * @return world y coordinate as a double + */ + public double getWorldY() { + return worldY; + } + + /** + * Returns true if world coordinates are in the range -1 ... +1 inclusive. + * @return true if world coordinates are in the range -1 ... +1 inclusive + */ + public boolean isInRange() { + return (-1 <= getWorldX()) && (getWorldX() <= 1) && (-1 <= getWorldY()) && (getWorldY() <= 1); + } + + /** + * Returns a string representation of this position, including its world coordinates. + */ + public String toString() { + return "Position (" + getWorldX() + ", " + getWorldY() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + /** + * Returns true if the world coordinates of this position and the argument are equal. + */ + public boolean equals(Object arg0) { + if (arg0.getClass().equals(getClass())) { + Position pos = (Position) arg0; + return ((pos.getWorldX() == getWorldX()) && (pos.getWorldY() == getWorldY())); + } + return false; + } +} diff --git a/src/org/jalgo/module/dijkstra/model/State.java b/src/org/jalgo/module/dijkstra/model/State.java new file mode 100644 index 0000000..1257778 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/model/State.java @@ -0,0 +1,152 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 21.05.2005 $Id$ + */ +package org.jalgo.module.dijkstra.model; + +import java.util.ArrayList; + +import org.jalgo.module.dijkstra.gui.Controller; + +/** + * @author Julian Stecklina + * + */ +public class State { + + private boolean isMacro; + private Graph graph; + private StringBuilder descHTMLCode; + + private ArrayList borderStates; + + /** + * Returns the list of {@link BorderState} objects. + * + * @return border state objects + */ + public ArrayList getBorderStates() { + return borderStates; + } + + /** + * Returns the path from the given node back to the start node. + * + * @return The list of nodes in the right order. (Start node is the first) + */ + public ArrayList getPath(Node node) { + ArrayList nodes = new ArrayList(); + + for (Node n = node; n != null; n = node.getPredecessor()) { + // Wow, this is wasteful. :) + nodes.add(0, n); + } + + return nodes; + } + + /** + * Appends descr to the end of the current description and set appropriate + * styles. + * + * @param descr + */ + public void addStyledDescription(String descr) { + descHTMLCode.append("").append(descr).append(""); + } + + public void addDescription(String descr) { + descHTMLCode.append(descr); + } + + /** + * @return a coloured version of the decription + */ + public String getDescriptionEx() { + StringBuilder htmlCode = new StringBuilder(descHTMLCode); + htmlCode.append(""); + return htmlCode.toString(); + } + + /** + * Creates a state object with the given parameters. This constructor does + * copy the passed graph. Care must be taken, that only structures are + * passed that are never changed again. + * + * @param graph The graph + * @param macro + */ + public State(Graph graph, String descr, boolean macro, + ArrayList borderStates) { + this.graph = graph; + for (Node node : graph.getNodeList()) { + node.getVisual().updateModel(node); + node.getVisual().setControllerMode(Controller.MODE_ALGORITHM); + node.getVisual().update(); + } + for (Edge edge : graph.getEdgeList()) { + edge.getVisual().updateModel(edge); + edge.getVisual().setControllerMode(Controller.MODE_ALGORITHM); + edge.getVisual().update(); + } + + descHTMLCode = new StringBuilder(""); + descHTMLCode.append(descr); + this.isMacro = macro; + this.borderStates = borderStates; + } + + /** + * Creates a new state object without discription. + * + * @see #State(Graph,String,boolean,ArrayList) + */ + public State(Graph graph, boolean macro, ArrayList borderStates) { + this(graph, "", macro, borderStates); //$NON-NLS-1$ + } + + /** + * @return Returns the isMacro. + */ + public boolean isMacro() { + return isMacro; + } + + /** + * Sets the macro property of this state. + * + * @param isMacro The value to set. + */ + public void setMacro(boolean isMacro) { + this.isMacro = isMacro; + } + + /** + * @return Returns the graph. + */ + public Graph getGraph() { + return graph; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/res.properties b/src/org/jalgo/module/dijkstra/res.properties new file mode 100644 index 0000000..0b0a464 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/res.properties @@ -0,0 +1 @@ +Module_logo=/dijkstra_pix/logo.gif HelpSet_Name=/help/jhelp/dijkstra_help.hs \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/util/CVS/Entries b/src/org/jalgo/module/dijkstra/util/CVS/Entries new file mode 100644 index 0000000..3fb7c3e --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/CVS/Entries @@ -0,0 +1,4 @@ +/DefaultExceptionHandler.java/1.2/Thu Jan 31 20:15:08 2008/-kk/ +/EdgeListParser.java/1.3/Thu Jan 31 20:15:08 2008/-kk/ +/NodeListParser.java/1.3/Thu Jan 31 20:15:08 2008/-kk/ +/ParsingException.java/1.2/Thu Jan 31 20:15:08 2008/-kk/ diff --git a/src/org/jalgo/module/dijkstra/util/CVS/Repository b/src/org/jalgo/module/dijkstra/util/CVS/Repository new file mode 100644 index 0000000..5e8ee47 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/dijkstra/util diff --git a/src/org/jalgo/module/dijkstra/util/CVS/Root b/src/org/jalgo/module/dijkstra/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.java b/src/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.java new file mode 100644 index 0000000..ccfed69 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/DefaultExceptionHandler.java @@ -0,0 +1,40 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 30.05.2005 09:24:47 + * + */ +package org.jalgo.module.dijkstra.util; + +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * @author Frank + * + */ + +public class DefaultExceptionHandler { + + public DefaultExceptionHandler(Exception e) { + e.printStackTrace(); + if (e.getMessage() == null) return; + JAlgoGUIConnector.getInstance().showErrorMessage(e.getMessage()); + } +} diff --git a/src/org/jalgo/module/dijkstra/util/EdgeListParser.java b/src/org/jalgo/module/dijkstra/util/EdgeListParser.java new file mode 100644 index 0000000..2c73380 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/EdgeListParser.java @@ -0,0 +1,225 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 07.05.2005 + * + */ +package org.jalgo.module.dijkstra.util; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.model.Edge; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; + + +/** + * The EdgeListParser class defines the functionality to create and modify a + * graph by an edge list. + * + * @author Hannes Straß + * + */ +public class EdgeListParser { + + private String edgeList; + private Graph newGraph; + private Graph retGraph; + + /** + * Creates an EdgeListParser. + */ + public EdgeListParser() { + edgeList = ""; //$NON-NLS-1$ + newGraph = new Graph(); + } + + private boolean setEdgeList(String newEdgeList) { + // remove leading and trailing space characters after each edit + edgeList = newEdgeList.trim(); + return edgeList.equals(""); //$NON-NLS-1$ + } + + /** + * Parses given Edge list and adds Nodes and Edges specified in list to + * given Graph. + * + * @param edgeListToParse the Edge list to parse + * @param graphToFill the graph, to which new elements are added + * @return The given graph containing new elements as specified in + * edgeListToParse + * @throws ParsingException + */ + public Graph getParsedEdgeList(String edgeListToParse, Graph graphToFill) + throws ParsingException { + retGraph = (Graph)graphToFill.clone(); + setEdgeList(edgeListToParse); + + /* + * enterEdgeList(); only needed if Edge list must start with "{" + */ + while (edgeList.startsWith("(")) //$NON-NLS-1$ + { + enterEdge(); + parseEdge(); + leaveEdge(); + if (edgeList.startsWith(",")) //$NON-NLS-1$ + { + nextEdge(); + } + } + /* + * leaveEdgeList(); only needed if Edge list must end with "}" + */ + + if (edgeList.equals("")) //$NON-NLS-1$ + { + newGraph.rescale(); + // only new elements should have the changed-flag + retGraph.setAllChangedFlagsFalse(); + retGraph.synchronizeWith(newGraph, false); + retGraph.replaceMissingNodes(); // + + newGraph.reset(); + return retGraph; + } + throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_error_1") + edgeList + "!"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + private void parseEdge() + throws ParsingException { + String start, end, weight; + Node startNode, endNode; + Edge edge; + + start = getStartNode(); + nextNode(); + weight = getWeight(); + nextNode(); + end = getEndNode(); + + /** + * check if all node indexes are numbers between 1 and 9 using regular + * expressions + */ + if (start.matches("[1-9]") //$NON-NLS-1$ + && end.matches("[1-9]") //$NON-NLS-1$ + && weight.matches("[0-9][0-9]*")) { //$NON-NLS-1$ + // creating "int"s from "String"s to the base 10 + startNode = new Node((Integer.valueOf(start, 10)).intValue()); + endNode = new Node((Integer.valueOf(end, 10)).intValue()); + edge = new Edge(startNode, endNode, + (Integer.valueOf(weight, 10)).intValue()); + + newGraph.addNode(startNode); + newGraph.addNode(endNode); + newGraph.addEdge(edge); + } + else { + // error handling + throw new ParsingException( + Messages.getString("dijkstra", "EdgeListParser.Syntax_error_2") //$NON-NLS-1$ //$NON-NLS-2$ + + start + ", " + weight + ", " + end + Messages.getString( //$NON-NLS-1$ //$NON-NLS-2$ + "dijkstra", "EdgeListParser.Syntax_error_3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + } + } + + private void enterEdgeList() + throws ParsingException { + if (edgeList.startsWith("{")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_1")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void leaveEdgeList() + throws ParsingException { + if (edgeList.startsWith("}")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_2")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void enterEdge() + throws ParsingException { + if (edgeList.startsWith("(")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_3")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void leaveEdge() + throws ParsingException { + if (edgeList.startsWith(")")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_4")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void nextEdge() + throws ParsingException { + if (edgeList.startsWith(",")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_5")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void nextNode() + throws ParsingException { + if (edgeList.startsWith(",")) setEdgeList(edgeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_hint_6")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private String getStartNode() + throws ParsingException { + if (edgeList.equals("")) //$NON-NLS-1$ + throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_error_4")); //$NON-NLS-1$ //$NON-NLS-2$ + + String n = edgeList.substring(0, 1); + setEdgeList(edgeList.substring(1)); + + return n; + } + + private String getEndNode() + throws ParsingException { + if (edgeList.equals("")) //$NON-NLS-1$ + throw new ParsingException(Messages.getString( + "dijkstra", "EdgeListParser.Syntax_error_5")); //$NON-NLS-1$ //$NON-NLS-2$ + + String n = edgeList.substring(0, 1); + setEdgeList(edgeList.substring(1)); + + return n; + } + + private String getWeight() { + String n = ""; //$NON-NLS-1$ + + while (!edgeList.startsWith(",") && edgeList.length() > 0) { //$NON-NLS-1$ + // weight can be longer than one character + n = n.concat(edgeList.substring(0, 1)); + setEdgeList(edgeList.substring(1)); + } + + return n; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/util/NodeListParser.java b/src/org/jalgo/module/dijkstra/util/NodeListParser.java new file mode 100644 index 0000000..cc064a4 --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/NodeListParser.java @@ -0,0 +1,141 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 12.05.2005 + * + */ +package org.jalgo.module.dijkstra.util; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.dijkstra.model.Graph; +import org.jalgo.module.dijkstra.model.Node; + + +/** + * The NodeListParser class defines the functionality to create and modify a + * graph by a node list. + * + * @author Hannes Straß + */ +public class NodeListParser { + + private String nodeList; + private Graph newGraph; + private Graph retGraph; + + /** + * Creates a NodeListParser. + */ + public NodeListParser() { + nodeList = ""; //$NON-NLS-1$ + newGraph = new Graph(); + } + + private boolean setNodeList(String newNodeList) { + nodeList = newNodeList.trim(); // remove leading and trailing space + // characters after each edit + return nodeList.equals(""); //$NON-NLS-1$ + } + + /** + * Parses given Node list and adds Nodes and Edges to given Graph. + * + * @param nodeListToParse Node list to parse + * @param graphToFill graph, to which specified Nodes are added + * @return changed graph + * @throws ParsingException + */ + public Graph getParsedNodeList(String nodeListToParse, Graph graphToFill) + throws ParsingException { + + retGraph = graphToFill; + setNodeList(nodeListToParse); + + /* + * enterNodeList(); only needed, if Node list must start with "{" + */ + + // get first Node if nodeList isn't empty + if (!nodeList.equals("")) getNode(); // //$NON-NLS-1$ + + while (nodeList.startsWith(",")) { //$NON-NLS-1$ + nextNode(); + getNode(); // creation of Node-object + } + /* + * leaveNodeList(); only needed, if Node list must end with "}" + */ + + if (nodeList.equals("")) { //$NON-NLS-1$ + // only new elements should have the changed-flag + retGraph.setAllChangedFlagsFalse(); + newGraph.rescale(); + retGraph.synchronizeWith(new Graph( + newGraph.getNodeList(), retGraph.getEdgeList()), true); + + retGraph.replaceMissingNodes(); + + return retGraph; + } + throw new ParsingException(Messages.getString( + "dijkstra", "NodeListParser.Syntax_error_1") + nodeList + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + private void enterNodeList() + throws ParsingException { + if (nodeList.startsWith("{")) setNodeList(nodeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "NodeListParser.Syntax_hint_1")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void leaveNodeList() + throws ParsingException { + if (nodeList.startsWith("}")) setNodeList(nodeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "NodeListParser.Syntax_hint_2")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void getNode() + throws ParsingException { + if (nodeList.equals("")) throw new ParsingException( //$NON-NLS-1$ + Messages.getString("dijkstra", "NodeListParser.Syntax_error_2")); //$NON-NLS-1$ //$NON-NLS-2$ + + String currentNode = nodeList.substring(0, 1); + setNodeList(nodeList.substring(1)); + + if (currentNode.matches("[1-9]")) //$NON-NLS-1$ + newGraph.addNode( + new Node((Integer.valueOf(currentNode, 10)).intValue())); + else throw new ParsingException(Messages.getString( + "dijkstra", "NodeListParser.Syntax_error_3") + currentNode //$NON-NLS-1$ //$NON-NLS-2$ + + Messages.getString("dijkstra", "NodeListParser.Syntax_hint_3")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + private void nextNode() + throws ParsingException { + if (nodeList.startsWith(",")) setNodeList(nodeList.substring(1)); //$NON-NLS-1$ + else throw new ParsingException(Messages.getString( + "dijkstra", "NodeListParser.Syntax_hint_4")); //$NON-NLS-1$ //$NON-NLS-2$ + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/dijkstra/util/ParsingException.java b/src/org/jalgo/module/dijkstra/util/ParsingException.java new file mode 100644 index 0000000..5b5ceea --- /dev/null +++ b/src/org/jalgo/module/dijkstra/util/ParsingException.java @@ -0,0 +1,51 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* + * Created on 08.05.2005 + * + */ +package org.jalgo.module.dijkstra.util; + +/** + * Defines an Exception which is thrown by the parsing classes when an parsing error occurs. + * + * @author Hannes Stra"s + * + */ +public class ParsingException extends Exception { + + private static final long serialVersionUID = 807340482223438215L; + + private String message; + + /** Creates a ParsingException containing the given message. + * @param message error message + */ + public ParsingException(String message) { + this.message = message; + } + + /* (non-Javadoc) + * @see java.lang.Throwable#getMessage() + */ + public String getMessage() { + return message; + } +} diff --git a/src/org/jalgo/module/ebnf/CVS/Entries b/src/org/jalgo/module/ebnf/CVS/Entries new file mode 100644 index 0000000..514bba8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/CVS/Entries @@ -0,0 +1,13 @@ +/MainController.java/1.3/Wed Oct 7 13:36:13 2009// +/ModuleConnector.java/1.2/Thu Jan 31 20:15:10 2008// +/ModuleInfo.java/1.2/Thu Jan 31 20:15:10 2008// +D/controller//// +/de.properties/1.1/Fri Aug 11 16:40:28 2006// +/en.properties/1.1/Fri Aug 11 16:40:28 2006// +D/gui//// +/jAlgoTabContrainerListener.java/1.2/Thu Jan 31 20:15:10 2008// +D/model//// +D/renderer//// +/res.properties/1.1/Fri Aug 11 16:40:29 2006// +/rootPaneListener.java/1.2/Thu Jan 31 20:15:10 2008// +D/util//// diff --git a/src/org/jalgo/module/ebnf/CVS/Repository b/src/org/jalgo/module/ebnf/CVS/Repository new file mode 100644 index 0000000..ad6b3f7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf diff --git a/src/org/jalgo/module/ebnf/CVS/Root b/src/org/jalgo/module/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/MainController.java b/src/org/jalgo/module/ebnf/MainController.java new file mode 100644 index 0000000..d087a78 --- /dev/null +++ b/src/org/jalgo/module/ebnf/MainController.java @@ -0,0 +1,476 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.FontFormatException; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.ebnf.EbnfController; +import org.jalgo.module.ebnf.controller.syndia.SynDiaController; +import org.jalgo.module.ebnf.controller.trans.TransController; +import org.jalgo.module.ebnf.controller.wordalgorithm.WordAlgorithmController; +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.GUIConstants; +import org.jalgo.module.ebnf.gui.StartAction; +import org.jalgo.module.ebnf.gui.StartScreen; +import org.jalgo.module.ebnf.gui.syndia.display.DisplayController; +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; + +/** + * + * @author Tom + * + */ +public class MainController implements GUIConstants { + + private enum Controller { + NONE, EBNF, SYNDIA, SYNDIADISPLAY, TRANS, WORD + } + + private Controller activeController = Controller.NONE; + + private ModuleConnector connector; + + private StartScreen startScreen; + + private JPanel contentPane; + + private EbnfController ebnfController; + + private TransController transController; + + private SynDiaController synDiaController; + + private DisplayController synDiaDisplayController; + + private WordAlgorithmController wordAlgoController; + + private Font ebnfFont; + + private StartAction startAction; + + private boolean isDialogOpen; + + private JMenu menu; + + private JToolBar toolBar; + + private JMenuBar menubar; + + private JMenuBar customMenubar; + + private List customMenuList; + + private List customMenuListBackup; + + public MainController(ModuleConnector connector) { + this.connector = connector; + + // install the main panel + JComponent rootPane = JAlgoGUIConnector.getInstance() + .getModuleComponent(connector); + rootPane.setLayout(new BorderLayout()); + contentPane = new JPanel(); + rootPane.addComponentListener(new rootPaneListener(this)); + rootPane.getParent().addContainerListener(new jAlgoTabContrainerListener(this)); + rootPane.add(contentPane, BorderLayout.CENTER); +// rootPane.addContainerListener(new rootPaneListener()); + customMenuList = new ArrayList(); + installToolbar(); + installMenu(); + importFont(); + EbnfFont.setFont(this.ebnfFont); + } + + public void installStartScreen() { + startScreen = new StartScreen(this); + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(startScreen, BorderLayout.CENTER); + setToolbarButtonsDisabled(); + connector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + contentPane.updateUI(); + contentPane.validate(); + } + + public void doLayout() { + contentPane.validate(); + } + + public boolean isDialogOpen() { + return isDialogOpen; + } + + public void update() { + doLayout(); + } + + /** + * Start EbnfInputMode. + */ + public void setEbnfInputMode(boolean transActive) { + + activeController = Controller.EBNF; + installToolbar(); + // System.out.println("Starte EbnfInput"); + startAction.setEnabled(true); + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + contentPane.setLayout(new BorderLayout()); + + if (!transActive) + ebnfController = new EbnfController(this, contentPane, connector); + else + ebnfController.switchToChoiceGUI(transActive); + + } + + /** + * Start or continue TransAlgorithm + * + * @param def + * the EbnfDefinition to transform + * @param restart + * indicates whether te controller should be (re)started or + * continued + */ + public void setTransMode(Definition def, boolean restart) { + + activeController = Controller.TRANS; + installToolbar(); + + // System.out.println("Starte TransAlgorithmus"); + + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + contentPane.setLayout(new BorderLayout()); + + if (restart) { + transController = new TransController(this, connector, contentPane, + def); + } else { + transController.switchToAlgorithm(); + } + } + + /** + * Start SynDiaDisplayMode. + */ + public void setSynDiaDisplayMode(SynDiaSystem sds) { + + activeController = Controller.SYNDIADISPLAY; + installToolbar(); + // System.out.println("Starte SynDiaDisplay"); + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + contentPane.setLayout(new BorderLayout()); + + synDiaDisplayController = new DisplayController(this, connector, + contentPane, sds); + + } + + /** + * Start SynDiaInputMode. + */ + public void setSynDiaInputMode(SynDiaSystem sds) { + + activeController = Controller.SYNDIA; + installToolbar(); + // System.out.println("Starte SynDiaInput"); + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + contentPane.setLayout(new BorderLayout()); + synDiaController = new SynDiaController(this, connector, sds, + contentPane); + + } + + /** + * Start SynDiaInputMode. + */ + public void setWordAlgoMode(SynDiaSystem sds) { + + // SynDiaSystem synDiaSystem1 = SynDiaSystemLibrary.getSynDiaSystem2(); + // synDiaSystem1.removeNullElems(); + installToolbar(); + contentPane.removeAll(); + contentPane.setBackground(STANDARD_BACKGROUND); + wordAlgoController = new WordAlgorithmController(this, connector, + contentPane, sds); + + } + + /** + * Sets up the toolbar. + */ + private void installToolbar() { + toolBar = JAlgoGUIConnector.getInstance().getModuleToolbar(connector); + toolBar.removeAll(); + startAction = new StartAction(this, connector); + toolBar.add(createToolbarButton(startAction)); + toolBar.validate(); + toolBar.repaint(); + } + + /** + * Add a menu in the j-Algo menubar. The function positions always the + * "help" menu at the end. + * + * @param newMenu - + * the new JMenu to be added + */ + public void addMenu(JMenu newMenu) { + customMenuList.add(newMenu); + JMenu helpMenu = menubar.getMenu(menubar.getMenuCount() - 1); + menubar.remove(helpMenu); + menubar.add(newMenu); + menubar.add(helpMenu); + menubar.validate(); + } + + /** + * This function removes everything ebnf-related in the menubar. This means + * everything except the "File" and the "Help" menu are removed. + * + */ + public void removeCustomMenu() { + if (menubar != null) { + customMenuListBackup = new ArrayList(customMenuList); + for (JMenu item : customMenuList) { + menubar.remove(item); + } + customMenubar = menubar; + customMenuList.clear(); + } + menubar.validate(); + } + + /** + * Creates a new ToolbarButton with the desired action. + */ + public JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton((Icon) a + .getValue(Action.SMALL_ICON), null, null); + button.setAction(a); + button.setText(""); + return button; + } + + /** + * Sets up the menu. + */ + private void installMenu() { + menu = JAlgoGUIConnector.getInstance().getModuleMenu(connector); + menu.setEnabled(false); + menubar = (JMenuBar) menu.getParent(); + customMenubar = menubar; + + // ((JMenu) (menubar.getComponent(0))).getMenuComponent(4).; + } + + public void setToolbarButtonsDisabled() { + startAction.setEnabled(false); + } + + /** + * This function imports our EBNFSans.TTF-Font and makes it accessable via + * the Font ebnfFont of the GUI.class + */ + public void importFont() { + // SwingUtilities.invokeLater( new Runnable() { + // public void run() + // { + try { + InputStream fontStream = Messages.getResourceURL("ebnf", + "Ebnf_Font").openStream(); // Stream der Font aus + // res-Ordner :) + Font onePoint = Font.createFont(Font.TRUETYPE_FONT, fontStream); + fontStream.close(); + Font ebnfFont = onePoint.deriveFont(Font.PLAIN, 18); + + this.ebnfFont = ebnfFont; + + // System.out.println("Font 'EBNFSans' initialized"); + } catch (FontFormatException e) { + System.err.println("FontFormaException: " + e.getMessage()); + System.exit(1); + } catch (IOException e) { + System.err.println("IOException: " + e.getMessage()); + System.exit(1); + } + } + + // } ); + // } + + public Font getEbnfFont() { + return ebnfFont; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + public void setDataFromFile(ByteArrayInputStream data) { + ObjectInputStream in = null; + try { + in = new ObjectInputStream(data); + try { + boolean isEbnf = (Boolean) in.readBoolean(); + + if (isEbnf) { + // load the EbnfInputModule + setEbnfInputMode(false); + // load the definition into the module + ebnfController.loadDefinition(in); + // Show the View-Panel + ebnfController.switchToChoiceGUI(false); + } else { + try { + SynDiaSystem system = (SynDiaSystem) in.readObject(); + if (system.isComplete()) { + system.removeNullElems(); + setSynDiaDisplayMode(system); + } else { + system.fillWithNullElems(); + setSynDiaInputMode(system); + } + } catch (Exception e) { + JAlgoGUIConnector + .getInstance() + .showErrorMessage( + Messages + .getString( + "ebnf", "SynDia.Error.LoadErrorInvalidDef")); //$NON-NLS-1$ //$NON-NLS-2$ + + } + + } // END if(isEbnf) + } // END try + catch (Exception e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("ebnf", "General.Error.LoadError")); //$NON-NLS-1$ //$NON-NLS-2$ + + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { } // ignore + } + } + + } + + public ByteArrayOutputStream getDataForFile() { + + if (activeController == Controller.EBNF) { + return ebnfController.saveDefinition(); + } else if (activeController == Controller.SYNDIADISPLAY) { + return synDiaDisplayController.saveSystem(); + + } else if (activeController == Controller.SYNDIA) { + return synDiaController.saveSystem(); + + } + return null; + } + + public JMenu getMenu() { + return menu; + } + + public JToolBar getToolBar() { + return toolBar; + } + + public JMenuBar getMenubar() { + return menubar; + } + + public JPanel getContentPane() { + return contentPane; + } + + public void setContentPane(JPanel contentPane) { + this.contentPane = contentPane; + } + + public void setMenubar(JMenuBar menubar) { + this.menubar = menubar; + } + + public JMenuBar getCustomMenubar() { + return customMenubar; + } + + public void setCustomMenubar(JMenuBar customMenubar) { + this.customMenubar = customMenubar; + } + + public List getCustomMenuListBackup() { + return customMenuListBackup; + } + + public void showErrorDialog(String message, boolean closeModule) { + JOptionPane.showMessageDialog(contentPane.getTopLevelAncestor(), + message, + Messages.getString("ebnf", "Ebnf.Error.Error"), + JOptionPane.ERROR_MESSAGE); + + JComponent rootPane = JAlgoGUIConnector.getInstance() + .getModuleComponent(connector); + + if (closeModule) { + System.out.println("critical error - closing module"); + ((JTabbedPane)rootPane.getParent()).remove(rootPane); + } + } +} diff --git a/src/org/jalgo/module/ebnf/ModuleConnector.java b/src/org/jalgo/module/ebnf/ModuleConnector.java new file mode 100644 index 0000000..795f572 --- /dev/null +++ b/src/org/jalgo/module/ebnf/ModuleConnector.java @@ -0,0 +1,88 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.jalgo.main.AbstractModuleConnector; + + +/** + * This class is the Interface to the jAlgo main module. It simply transfers + * any requests to the mainController of the EBNF module + * + * @author Tom Kazimiers, Johannes Mey + * + */ +public class ModuleConnector +extends AbstractModuleConnector { + + private MainController mainController; + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#init() + */ + @Override + public void init() { + + mainController = new MainController(this); // initialize a new GUIController + + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#run() + */ + @Override + public void run() { + mainController.installStartScreen(); + + // System.out.println("EBNF-Modul is running"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + @Override + public void setDataFromFile(ByteArrayInputStream data) { + // simply transfer the problem to the mainController + mainController.setDataFromFile(data); + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#getDataForFile() + */ + @Override + public ByteArrayOutputStream getDataForFile() { + // simply transfer the problem to the mainController + return mainController.getDataForFile(); + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#print() + */ + @Override + public void print() { + // here is no action performed in ebnf module + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/ModuleInfo.java b/src/org/jalgo/module/ebnf/ModuleInfo.java new file mode 100644 index 0000000..431df0b --- /dev/null +++ b/src/org/jalgo/module/ebnf/ModuleInfo.java @@ -0,0 +1,83 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) + instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return Messages.getString("ebnf", "Module_name"); + } + + public String getVersion() { + return Messages.getString("ebnf", "Module_version"); + } + + public String getAuthor() { + return Messages.getString("ebnf", "Module_authors"); + } + + public String getDescription() { + return Messages.getString("ebnf", "Module_description_1") + + System.getProperty("line.separator") + + Messages.getString("ebnf", "Module_description_2"); + } + + public URL getLogoURL() { + return Messages.getResourceURL("ebnf", "Module_logo"); + } + + public String getLicense() { + return Messages.getString("ebnf", "Module_license"); + } + + public URL getHelpSetURL() { + return Messages.getResourceURL("ebnf", "HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/controller/CVS/Entries b/src/org/jalgo/module/ebnf/controller/CVS/Entries new file mode 100644 index 0000000..fa2bbbf --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/CVS/Entries @@ -0,0 +1,4 @@ +D/ebnf//// +D/syndia//// +D/trans//// +D/wordalgorithm//// diff --git a/src/org/jalgo/module/ebnf/controller/CVS/Repository b/src/org/jalgo/module/ebnf/controller/CVS/Repository new file mode 100644 index 0000000..e0bb858 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller diff --git a/src/org/jalgo/module/ebnf/controller/CVS/Root b/src/org/jalgo/module/ebnf/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.java new file mode 100644 index 0000000..a6480b3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/AddRuleAction.java @@ -0,0 +1,50 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + + + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.Rule; +import org.jalgo.module.ebnf.util.IAction; + + +public class AddRuleAction implements IAction { + + Rule rule; + EbnfController controller; + + public AddRuleAction(EbnfController controller, Rule rule) { + this.rule = rule; + this.controller = controller; + } + + public void perform() throws DefinitionFormatException { + controller.getDefinition().addRule(rule); + } + + public void undo() throws DefinitionFormatException { + controller.getDefinition().removeRule(rule); + + } + } diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.java new file mode 100644 index 0000000..f5c643e --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/AddTerminalAction.java @@ -0,0 +1,65 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action for adding a terminal symbol + * + * @author Tom Kaimiers, Johannes Mey + * + */ +public class AddTerminalAction implements IAction { + + // the new terminal symbol + private ETerminalSymbol terminal; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * @param terminal + */ + public AddTerminalAction(EbnfController controller, ETerminalSymbol terminal) { + this.terminal = terminal; + this.controller = controller; + } + + /* (non-Javadoc) + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().addTerminal(terminal); + } + + /* (non-Javadoc) + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().removeTerminal(terminal); + } + } diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.java new file mode 100644 index 0000000..788b237 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/AddVariableAction.java @@ -0,0 +1,101 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action for adding variables + * + * @author Tom Kaimiers, Johannes Mey + * + */ +public class AddVariableAction implements IAction { + + // the variable that has been added + private EVariable variable; + + // the old StartVariable + private EVariable oldStartVar; + + // the new StartVariable + private EVariable newStartVar; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param name + * the name of the new variable + * @throws DefinitionFormatException + * if the name is not a valid symbol name + */ + public AddVariableAction(EbnfController controller, String name) + throws DefinitionFormatException { + + EVariable variable = null; + + // try to create a new EVariable; if this is not possible because + // of an invalid name, an exception is thrown + variable = new EVariable(name); + + this.variable = variable; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().addVariable(variable); + + this.oldStartVar = controller.getDefinition().getStartVariable(); + + if(oldStartVar==null) { + this.newStartVar = variable; + controller.getDefinition().setStartVariable(newStartVar); + } + else { + this.newStartVar = this.oldStartVar; + } + + + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().removeVariable(variable); + if (oldStartVar!=newStartVar) + controller.getDefinition().setStartVariable(oldStartVar); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Entries b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Entries new file mode 100644 index 0000000..5511bb8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Entries @@ -0,0 +1,12 @@ +/AddRuleAction.java/1.2/Thu Jan 31 20:15:11 2008// +/AddTerminalAction.java/1.2/Thu Jan 31 20:15:11 2008// +/AddVariableAction.java/1.2/Thu Jan 31 20:15:11 2008// +/DeleteRuleAction.java/1.2/Thu Jan 31 20:15:11 2008// +/DeleteTerminalAction.java/1.2/Thu Jan 31 20:15:11 2008// +/DeleteVariableAction.java/1.2/Thu Jan 31 20:15:11 2008// +/EbnfController.java/1.2/Thu Jan 31 20:15:11 2008// +/ModifyRuleAction.java/1.2/Thu Jan 31 20:15:11 2008// +/ModifyTerminalAction.java/1.2/Thu Jan 31 20:15:11 2008// +/ModifyVariableAction.java/1.2/Thu Jan 31 20:15:11 2008// +/SetStartVariableAction.java/1.2/Thu Jan 31 20:15:11 2008// +D/parser//// diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Repository b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Repository new file mode 100644 index 0000000..d9f7d4a --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/ebnf diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Root b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.java new file mode 100644 index 0000000..0294aad --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteRuleAction.java @@ -0,0 +1,72 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.Rule; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action to delete a rule + * + * @author Tom Kazimiers, Johannes Mey + * + */ +public class DeleteRuleAction implements IAction { + + // the deleted rule + private Rule rule; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param rule + * the rule to be deleted + */ + public DeleteRuleAction(EbnfController controller, Rule rule) { + this.rule = rule; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().addRule(rule); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().removeRule(rule); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.java new file mode 100644 index 0000000..d238e26 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteTerminalAction.java @@ -0,0 +1,73 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action to delete a terminal symbol + * + * @author Tom Kazimiers, Johannes Mey + * + */ +public class DeleteTerminalAction implements IAction { + + // The terminal Symbol that has been deleted + ETerminalSymbol terminal; + + // the controller that owns the definition + EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param terminal + * the terinal symbol to be deleted + */ + public DeleteTerminalAction(EbnfController controller, + ETerminalSymbol terminal) { + this.terminal = terminal; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().addTerminal(terminal); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().removeTerminal(terminal); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.java new file mode 100644 index 0000000..e50feb8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/DeleteVariableAction.java @@ -0,0 +1,106 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action to delete a variable + * + * @author Tom Kazimiers, Johannes Mey + * + */ + +public class DeleteVariableAction implements IAction { + + // the deleted variable + private EVariable variable; + + // the old StartVariable + private EVariable oldStartVar; + + // the new StartVariable + private EVariable newStartVar; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param variable + * the variable to be deleted + */ + public DeleteVariableAction(EbnfController controller, EVariable variable) { + this.variable = variable; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().addVariable(variable); + if (oldStartVar!=newStartVar) + controller.getDefinition().setStartVariable(oldStartVar); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + + + + // save the old startVar + this.oldStartVar = controller.getDefinition().getStartVariable(); + + // remove the Var + controller.getDefinition().removeVariable(variable); + + + if(oldStartVar==variable) { + if (controller.getDefinition().getVariables().size()!=0) { + this.newStartVar = controller.getDefinition().getVariables().get(0); + controller.getDefinition().setStartVariable(newStartVar); + } + else { + newStartVar = null; + } + } + + else { + this.newStartVar = this.oldStartVar; + } + + + + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/EbnfController.java b/src/org/jalgo/module/ebnf/controller/ebnf/EbnfController.java new file mode 100644 index 0000000..31361ee --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/EbnfController.java @@ -0,0 +1,675 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import java.awt.Cursor; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Observable; +import java.util.Observer; +import java.util.Stack; + +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.controller.ebnf.parser.EbnfParser; +import org.jalgo.module.ebnf.controller.ebnf.parser.ParseException; +import org.jalgo.module.ebnf.gui.ebnf.GuiController; +import org.jalgo.module.ebnf.gui.ebnf.RedoAction; +import org.jalgo.module.ebnf.gui.ebnf.RenderConstants; +import org.jalgo.module.ebnf.gui.ebnf.UndoAction; +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ESymbol; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.model.ebnf.Rule; +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.util.ActionStack; +import org.jalgo.module.ebnf.util.IAction; + +/** + * + * @author Tom Kazimiers, Johannes Mey + * + */ +public class EbnfController implements Observer { + + private EbnfParser parser; + + private ActionStack actionStack; + + private Definition definition; + + private MainController mainController; + + private ModuleConnector moduleConnector; + + private GuiController guiController; + + private JPanel contentPane; + + private boolean transActive; + + private JButton redoButton; + + private JButton undoButton; + + /** + * This Constructor creates an EBNF controller + * + * @param mainController + * @param contentPane + * @param moduleConnector + */ + public EbnfController(MainController mainController, JPanel contentPane, + ModuleConnector moduleConnector) { + contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + + transActive = false; + + this.definition = new Definition(); + this.mainController = mainController; + this.moduleConnector = moduleConnector; + this.contentPane = contentPane; + this.actionStack = new ActionStack(); + + // add this as an observer of the definition this is necessary to + // display the save status + definition.addObserver(this); + actionStack.addObserver(this); + guiController = new GuiController(this); + + installToolbar(); + + contentPane.setCursor(Cursor.getDefaultCursor()); + } + + /** + * Sets up the toolbar. + */ + private void installToolbar() { + JToolBar toolBar = JAlgoGUIConnector.getInstance().getModuleToolbar( + moduleConnector); + + UndoAction undoAction = new UndoAction(this); + undoButton = mainController.createToolbarButton(undoAction); + undoButton.setEnabled(false); + toolBar.addSeparator(); + toolBar.add(undoButton); + RedoAction redoAction = new RedoAction(this); + redoButton = mainController.createToolbarButton(redoAction); + + redoButton.setEnabled(false); + toolBar.add(redoButton); + + } + + // ----------------------------------------------------------------------------- + // Modification of the EBNF definition + // ----------------------------------------------------------------------------- + + /** + * Adds a terminal symbol to the definition + * + * @param name + * is the name of the new symbol + * @throws Exception + */ + public void addTerminal(String name) throws Exception { + + ETerminalSymbol terminal = null; + + // try to create a new ETerminalSymbol; if this is not possible because + // of an invalid name, false is returned + terminal = new ETerminalSymbol(name); + + // try to add the the terminal symbol to the definition, if this fails + // because of an existing symbol, false is returned + IAction action = new AddTerminalAction(this, terminal); + actionStack.perform(action); + + } + + /** + * Adds a variable to the definition + * + * @param name + * is the name of the new symbol + * @throws Exception + */ + public void addVariable(String name) throws Exception { + + // try to add the the variable to the definition, if this fails + // because of an existing symbol an exception is thrown + IAction action = new AddVariableAction(this, name); + actionStack.perform(action); + + } + + /** + * Adds a rule to the definition + * + * @param left + * is the variable on the left side of the rule + * @param right + * is the term on the right side of the rule + * @throws Exception + */ + public void addRule(EVariable left, String right) throws Exception { + + // Check if all brackets are correct + checkBrackets(right); + + // parse the right side of the rule + parser = new EbnfParser(this, right); + Term term = null; + try { + term = parser.parse(); + } catch (ParseException ex) { + throw new DefinitionFormatException(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.Error.ParseError")); //$NON-NLS-1$ + } + + // try to create the rule + Rule rule = new Rule(left, term); + + // try to add the rule to the definition + IAction action = new AddRuleAction(this, rule); + actionStack.perform(action); + + } + + /** + * Checks if all brackets in the term are correct and if alternative bars + * occur only in parentheses + * + * @param term + * the term to be ckecked + * @throws DefinitionFormatException + */ + private void checkBrackets(String term) throws DefinitionFormatException { + + Stack s = new Stack(); + + for (int i = 0; i < term.length(); i++) { + String tempChar = term.substring(i, i + 1); + if (tempChar.equals(String.valueOf(RenderConstants.LBRACE))) + s.push(tempChar); + else if (tempChar.equals(String.valueOf(RenderConstants.LBRACKET))) + s.push(tempChar); + else if (tempChar.equals(String + .valueOf(RenderConstants.LPARENTHESES))) + s.push(tempChar); + + else if (tempChar.equals(String.valueOf(RenderConstants.RBRACE))) { + String stackString = new String(); + try { + stackString = s.pop(); + } catch (Exception e) { + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (!stackString.equals(String.valueOf(RenderConstants.LBRACE))) + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$ //$NON-NLS-2$ + + } else if (tempChar + .equals(String.valueOf(RenderConstants.RBRACKET))) { + String stackString = new String(); + try { + stackString = s.pop(); + } catch (Exception e) { + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (!stackString.equals(String + .valueOf(RenderConstants.LBRACKET))) + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$//$NON-NLS-2$ + + } else if (tempChar.equals(String + .valueOf(RenderConstants.RPARENTHESES))) { + String stackString = new String(); + try { + stackString = s.pop(); + } catch (Exception e) { + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (!stackString.equals(String + .valueOf(RenderConstants.LPARENTHESES))) + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.BracketError")); //$NON-NLS-1$//$NON-NLS-2$ + + } else if (tempChar.equals(String + .valueOf(RenderConstants.ALTERNATIVE))) { + + String stackString = new String(); + try { + stackString = s.lastElement(); + } catch (Exception e) { + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.AlternativeError")); //$NON-NLS-1$//$NON-NLS-2$ + } + + if (!stackString.equals(String + .valueOf(RenderConstants.LPARENTHESES))) + throw new DefinitionFormatException(Messages.getString( + "ebnf", "Ebnf.Error.AlternativeError")); //$NON-NLS-1$//$NON-NLS-2$ + } + + } + + if (!s.isEmpty()) + throw new DefinitionFormatException(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.Error.BracketError")); //$NON-NLS-1$ + + } + + /** + * @param terminal + * @throws Exception + */ + public void deleteTerminal(ETerminalSymbol terminal) throws Exception { + + IAction action = new DeleteTerminalAction(this, terminal); + actionStack.perform(action); + + } + + /** + * @param variable + * @throws Exception + */ + public void deleteVariable(EVariable variable) throws Exception { + IAction action = new DeleteVariableAction(this, variable); + actionStack.perform(action); + + } + + /** + * @param rule + * @throws Exception + */ + public void deleteRule(Rule rule) throws Exception { + + IAction action = new DeleteRuleAction(this, rule); + actionStack.perform(action); + + } + + /** + * @param oldRule + * @param left + * @param right + * @throws Exception + */ + public void modifyRule(Rule oldRule, EVariable left, String right) + throws Exception { + + // Check if all brackets are correct + checkBrackets(right); + + parser = new EbnfParser(this, right); + Term term; + + try { + term = parser.parse(); + } catch (ParseException ex) { + throw new DefinitionFormatException(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.Error.ParseError")); //$NON-NLS-1$ + } + + Rule rule = new Rule(left, term); + + IAction action = new ModifyRuleAction(this, oldRule, rule); + actionStack.perform(action); + } + + /** + * @param oldTerminal + * @param newTerminal + * @throws Exception + */ + public void modifyTerminal(ETerminalSymbol oldTerminal, String newTerminal) + throws Exception { + + IAction action = new ModifyTerminalAction(this, oldTerminal, + newTerminal); + actionStack.perform(action); + + } + + /** + * @param oldVariable + * @param newVariable + * @throws Exception + */ + public void modifyVariable(EVariable oldVariable, String newVariable) + throws Exception { + IAction action = new ModifyVariableAction(this, oldVariable, + newVariable); + actionStack.perform(action); + + } + + public void switchToChoiceGUI(boolean transActive) { + this.transActive = transActive; + if (transActive) { + moduleConnector.setSaveStatus(SaveStatus.NO_CHANGES); + } + guiController.showChoiceGUI(transActive); + } + + public void switchToTransGUI() { + + mainController.removeCustomMenu(); + mainController.addMenu(mainController.getMenu()); + mainController.setTransMode(definition, !transActive); + } + + public void setStartVariable(EVariable startVar) throws Exception { + + IAction action = new SetStartVariableAction(this, startVar); + actionStack.perform(action); + + } + + // ----------------------------------------------------------------------------- + // File Management + // ----------------------------------------------------------------------------- + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + public void loadDefinition(ObjectInputStream in) { + try { + + definition = (Definition) in.readObject(); + definition.addObserver(this); + guiController.reloadObservers(); + + } catch (Exception e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString( + "ebnf", "Ebnf.Error.LoadErrorInvalidDef")); //$NON-NLS-1$ //$NON-NLS-2$ + + } + } + + public ByteArrayOutputStream saveDefinition() { + if (!guiController.isEditMode() && guiController.getStrictMode()) { + if (guiController.showSaveStrictModeDialog(false) == 1) { + setDefinitionStrict(); + } + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeBoolean(true); + objOut.writeObject(definition); + objOut.close(); + moduleConnector.setSaveStatus(SaveStatus.NO_CHANGES); + } catch (IOException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("ebnf", "Ebnf.Error.SaveError")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + return out; + } + + // ----------------------------------------------------------------------------- + // actionStack + // ----------------------------------------------------------------------------- + + public void redo() { + try { + actionStack.redo(); + } catch (Exception e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("ebnf", "Ebnf.Error.RedoImpossible")); //$NON-NLS-1$//$NON-NLS-2$ + e.printStackTrace(); + actionStack.toString(); + actionStack.clear(); + } + } + + public void undo() { + try { + actionStack.undo(); + } catch (Exception e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("ebnf", "Ebnf.Error.UndoImpossible")); //$NON-NLS-1$//$NON-NLS-2$ + e.printStackTrace(); + actionStack.toString(); + actionStack.clear(); + } + } + + // ----------------------------------------------------------------------------- + // Definition Check + // ----------------------------------------------------------------------------- + + /** + * Checks if a Definition is complete and gives additional warnings + * + * @return a String including the errors and warnings as HTML + */ + public String checkDefinition(boolean includeWarnings) { + + String checkResult = ""; + + // check if the definition has a start variable + if (definition.getStartVariable() == null) { + checkResult += Messages.getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoStartVar"); + includeWarnings = false; + } + + // check if the definition has a rule for every Variable + for (EVariable var : definition.getVariables()) { + if (definition.getRule(var) == null) { + checkResult += Messages.getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoRuleForVar_1") + + " " + + var + + " " + + Messages + .getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoRuleForVar_2"); + includeWarnings = false; + } + } + + if (includeWarnings) { + // check if all Variables are used + for (EVariable var : definition.getVariables()) { + if ((!occursInRightSide(var)) + && (!definition.getStartVariable().equals(var))) { + checkResult += Messages.getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoTermWithVar_1") + + " " + + var + + " " + + Messages + .getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoTermWithVar_2"); + } + } + + // check if all TerminalSymbols are used + for (ETerminalSymbol term : definition.getTerminals()) { + if (!occursInRightSide(term)) { + checkResult += Messages.getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoTermWithTS_1") + + " " + + term + + " " + + Messages + .getString("ebnf", + "Ebnf.Controller_DefinitionCheck_NoTermWithTS_2"); + } + } + + // Warshall-Algorithm + int dim = definition.getVariables().size(); + + boolean matrix[][] = new boolean[dim][dim]; + int startvar = -1; + + // building the distance matrix + for (int from = 0; from < dim; from++) { + if (definition.getVariables().get(from).equals( + definition.getStartVariable())) + startvar = from; + for (int to = 0; to < dim; to++) + try { + matrix[from][to] = definition.getRule( + definition.getVariables().get(from)).contains( + definition.getVariables().get(to)); + } catch (Exception e) { + matrix[from][to] = from == to; + } + } + + // the actual algorithm + for (int k = 0; k < dim; k++) + for (int i = 0; i < dim; i++) + for (int j = 0; j < dim; j++) + if (!matrix[i][j]) + matrix[i][j] = matrix[i][k] && matrix[k][j]; + + // print matrix (for test purposes only + // for (int i = 0;i= 0; to++) { + if (!matrix[startvar][to] + && definition + .getRule(definition.getVariables().get(to)) != null) { + checkResult += Messages + .getString("ebnf", + "Ebnf.Controller_DefinitionCheck_RuleNotReachable_1") + + " " + + definition.getVariables().get(to) + + " " + + Messages + .getString("ebnf", + "Ebnf.Controller_DefinitionCheck_RuleNotReachable_2"); + } + } + } + + return checkResult + ""; + } + + /** + * This is a helper method for the definition check. It checks if any rule + * of the definition contains the given symbol symbol + * + * @param symbol + * @return true if the defintion contains the symbol in a term of a rule + */ + public boolean occursInRightSide(ESymbol symbol) { + for (Rule rule : definition.getRules()) { + if (rule.getTerm().contains(symbol)) + return true; + } + return false; + } + + // ----------------------------------------------------------------------------- + // getters + // ----------------------------------------------------------------------------- + + public Definition getDefinition() { + return definition; + } + + public JPanel getContentPane() { + return contentPane; + } + + public MainController getMainController() { + return mainController; + } + + public GuiController getGuiController() { + return guiController; + } + + // ----------------------------------------------------------------------------- + // Observer Pattern + // ----------------------------------------------------------------------------- + + public void update(Observable o, Object arg) { + if (o.getClass().equals(Definition.class)) { + moduleConnector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + guiController.getEbnfController().setTransActive(false); + } else if (o.getClass().equals(ActionStack.class)) { + undoButton.setEnabled(actionStack.isUndoPossible()); + redoButton.setEnabled(actionStack.isRedoPossible()); + } + + } + + public boolean isTransActive() { + return transActive; + } + + public void setTransActive(boolean transActive) { + this.transActive = transActive; + } + + public void setDefinitionStrict() { + try { + this.definition = this.definition.getStrict(); + moduleConnector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } catch (DefinitionFormatException e) { + guiController.getInputPanel().showInfo( + Messages.getString("ebnf", + "Ebnf.Controller_MakeDefinitionStrictError"), true); + } + guiController.reloadObservers(); + definition.addObserver(this); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.java new file mode 100644 index 0000000..5868880 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyRuleAction.java @@ -0,0 +1,79 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.Rule; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action for repacing rules + * + * @author Tom Kaimiers, Johannes Mey + * + */ +public class ModifyRuleAction implements IAction { + + // the rule that has been replaced + private Rule oldRule; + + // the replacement rule + private Rule newRule; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param oldRule + * the rule to ne replaced + * @param newRule + * the new repacement rule + */ + public ModifyRuleAction(EbnfController controller, Rule oldRule, + Rule newRule) { + this.oldRule = oldRule; + this.newRule = newRule; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().replaceRule(oldRule, newRule); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().replaceRule(newRule, oldRule); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.java new file mode 100644 index 0000000..1b85753 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyTerminalAction.java @@ -0,0 +1,84 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action for changing terminal symbol names + * + * @author Tom Kaimiers, Johannes Mey + * + */ + +public class ModifyTerminalAction implements IAction { + + // the terminal symbol to be renamed + private ETerminalSymbol terminal; + + // the new name of the terminal symbol + private String newName; + + // the old name of the terminal symbol + private String oldName; + + // the controlelr that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param terminal + * the terminal symbol to be renamed + * @param newName + * the new name of the terminal symbol + */ + public ModifyTerminalAction(EbnfController controller, + ETerminalSymbol terminal, String newName) { + this.terminal = terminal; + this.oldName = terminal.getName(); + this.newName = newName; + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().renameSymbol(terminal, newName); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().renameSymbol(terminal, oldName); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.java new file mode 100644 index 0000000..7f2a8a3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/ModifyVariableAction.java @@ -0,0 +1,83 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action for changing variable names + * + * @author Tom Kaimiers, Johannes Mey + * + */ +public class ModifyVariableAction implements IAction { + + // the variable that is renamed + private EVariable variable; + + // the new name of the variable + private String newName; + + // the old name of the variable + private String oldName; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that owns the definition + * @param variable + * the variable to be renamed + * @param newName + * the new name of the variable + */ + public ModifyVariableAction(EbnfController controller, EVariable variable, + String newName) { + this.variable = variable; + this.newName = newName; + this.oldName = variable.getName(); + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().renameSymbol(variable, newName); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().renameSymbol(variable, oldName); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.java b/src/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.java new file mode 100644 index 0000000..0b1a8de --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/SetStartVariableAction.java @@ -0,0 +1,77 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.controller.ebnf; + +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.util.IAction; + +/** + * This is the action to set the start variable of the definition + * + * @author Tom Kaimiers, Johannes Mey + * + */ +public class SetStartVariableAction implements IAction { + + // the old startvariable + private EVariable oldStartVariable; + + // the new startvariable + private EVariable newStartVariable; + + // the controller that owns the definition + private EbnfController controller; + + /** + * @param controller + * the controller that own the definition + * @param startVariable + * the new startvariable + */ + public SetStartVariableAction(EbnfController controller, + EVariable startVariable) { + this.newStartVariable = startVariable; + this.oldStartVariable = controller.getDefinition().getStartVariable(); + this.controller = controller; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#perform() + */ + public void perform() throws DefinitionFormatException { + controller.getDefinition().setStartVariable(newStartVariable); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.util.IAction#undo() + */ + public void undo() throws DefinitionFormatException { + controller.getDefinition().setStartVariable(oldStartVariable); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Entries b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Entries new file mode 100644 index 0000000..73f5a6c --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Entries @@ -0,0 +1,7 @@ +/EbnfParser.java/1.1/Fri Aug 11 16:40:31 2006// +/EbnfParserConstants.java/1.1/Fri Aug 11 16:40:31 2006// +/EbnfParserTokenManager.java/1.1/Fri Aug 11 16:40:31 2006// +/ParseException.java/1.1/Fri Aug 11 16:40:31 2006// +/SimpleCharStream.java/1.1/Fri Aug 11 16:40:31 2006// +/Token.java/1.1/Fri Aug 11 16:40:31 2006// +/TokenMgrError.java/1.1/Fri Aug 11 16:40:31 2006// diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Repository b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Repository new file mode 100644 index 0000000..0ccbcbb --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/ebnf/parser diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Root b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.java new file mode 100644 index 0000000..2be39f7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParser.java @@ -0,0 +1,603 @@ +/* Generated By:JavaCC: Do not edit this line. EbnfParser.java */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +import org.jalgo.module.ebnf.model.ebnf.*; +import org.jalgo.module.ebnf.controller.ebnf.EbnfController; + +/** This is the parser for EBNF terms. It is automatically created by JavaCC + * + */ +public class EbnfParser implements EbnfParserConstants { + + private EbnfController ebnfController; + + public EbnfParser(EbnfController ebnfController, String term) { + this.ebnfController = ebnfController; + java.io.StringReader sr = new java.io.StringReader( term ); + java.io.Reader r = new java.io.BufferedReader( sr ); + jj_input_stream = new SimpleCharStream(r, 1, 1); + token_source = new EbnfParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + + /** + * + * @param symbols a String with parsed symbols + * @return a concatenation (or a simple term) of all terminal symbols and variables that are valid for this ebnf definition. + */ + private Term parseSymbols(String symbols) throws ParseException { + java.util.List termList = new java.util.ArrayList(); + boolean changed = true; + while (!symbols.equals("") && changed==true) { + changed = false; + for (EVariable var : ebnfController.getDefinition().getVariables()) { + if (symbols.startsWith(var.getName())) { + termList.add(var); + symbols = symbols.substring(var.getName().length()); + changed = true; + } + } + for (ETerminalSymbol terminal : ebnfController.getDefinition().getTerminals()) { + if (symbols.startsWith(terminal.getName())) { + termList.add(terminal); + symbols = symbols.substring(terminal.getName().length()); + changed = true; + } + } + if (!symbols.equals("") && changed==false) { + changed = ebnfController.getGuiController().showUnknownSymbolDialog(symbols); + + } + } + if (!symbols.equals("")) throw new ParseException(); + Term t = null; + try { + if (termList.size() == 1) { + t = termList.get(0); + } else { + t = new EConcatenation(termList); + } + } catch (DefinitionFormatException e) { + throw new ParseException(); + } + return t; + } + + final public Term parse() throws ParseException { + Term term; + term = term(); + jj_consume_token(0); + {if (true) return term;} + throw new Error("Missing return statement in function"); + } + + final public Term term() throws ParseException { + Token t; Term term; Term term2 = null; + if (jj_2_1(2)) { + term = repetition(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case L_REPETITION: + case L_PARENTHESES: + case L_OPTION: + case TERM: + term2 = term(); + break; + default: + jj_la1[0] = jj_gen; + ; + } + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + } + {if (true) return term;} + } else if (jj_2_2(2)) { + term = parentheses(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case L_REPETITION: + case L_PARENTHESES: + case L_OPTION: + case TERM: + term2 = term(); + break; + default: + jj_la1[1] = jj_gen; + ; + } + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + } + {if (true) return term;} + } else if (jj_2_3(2)) { + term = option(); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case L_REPETITION: + case L_PARENTHESES: + case L_OPTION: + case TERM: + term2 = term(); + break; + default: + jj_la1[2] = jj_gen; + ; + } + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + } + {if (true) return term;} + } else { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case TERM: + t = jj_consume_token(TERM); + term = parseSymbols(t.image); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case L_REPETITION: + case L_PARENTHESES: + case L_OPTION: + case TERM: + term2 = term(); + break; + default: + jj_la1[3] = jj_gen; + ; + } + if (term2!=null) { + try { + term = new EConcatenation(term, term2); + } catch (Exception e){ + {if (true) throw new ParseException();} + } + } + {if (true) return term;} + break; + default: + jj_la1[4] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + throw new Error("Missing return statement in function"); + } + + final public java.util.List specialTerm() throws ParseException { + Term term; + java.util.List terms = new java.util.ArrayList(); + java.util.List subTerms = new java.util.ArrayList(); + term = term(); + terms.add(term); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case BRANCH: + jj_consume_token(BRANCH); + subTerms = specialTerm(); + break; + default: + jj_la1[5] = jj_gen; + ; + } + terms.addAll(subTerms); + {if (true) return terms;} + {if (true) return terms;} + throw new Error("Missing return statement in function"); + } + + final public Term repetition() throws ParseException { + Term term; + jj_consume_token(L_REPETITION); + term = term(); + jj_consume_token(R_REPETITION); + ERepetition rep = null; + try { + rep = new ERepetition(term); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + {if (true) return rep;} + throw new Error("Missing return statement in function"); + } + + final public Term parentheses() throws ParseException { + java.util.List subTerms; + jj_consume_token(L_PARENTHESES); + subTerms = specialTerm(); + jj_consume_token(R_PARENTHESES); + if (subTerms.size() == 1){ + ECompoundTerm ct = null; + try { + ct = new ECompoundTerm(subTerms.get(0)); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + {if (true) return ct;} + } else { + EAlternative alt = null; + try { + alt = new EAlternative(subTerms); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + {if (true) return alt;} + } + throw new Error("Missing return statement in function"); + } + + final public Term option() throws ParseException { + Term term; + jj_consume_token(L_OPTION); + term = term(); + jj_consume_token(R_OPTION); + EOption opt = null; + try { + opt = new EOption(term); + } catch (Exception e) { + {if (true) throw new ParseException();} + } + {if (true) return opt;} + throw new Error("Missing return statement in function"); + } + + final private boolean jj_2_1(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_1(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(0, xla); } + } + + final private boolean jj_2_2(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_2(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(1, xla); } + } + + final private boolean jj_2_3(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_3(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(2, xla); } + } + + final private boolean jj_3R_1() { + if (jj_scan_token(L_REPETITION)) return true; + if (jj_3R_4()) return true; + return false; + } + + final private boolean jj_3_3() { + if (jj_3R_3()) return true; + return false; + } + + final private boolean jj_3_1() { + if (jj_3R_1()) return true; + return false; + } + + final private boolean jj_3R_4() { + Token xsp; + xsp = jj_scanpos; + if (jj_3_1()) { + jj_scanpos = xsp; + if (jj_3_2()) { + jj_scanpos = xsp; + if (jj_3_3()) { + jj_scanpos = xsp; + if (jj_3R_6()) return true; + } + } + } + return false; + } + + final private boolean jj_3R_3() { + if (jj_scan_token(L_OPTION)) return true; + if (jj_3R_4()) return true; + return false; + } + + final private boolean jj_3R_2() { + if (jj_scan_token(L_PARENTHESES)) return true; + if (jj_3R_5()) return true; + return false; + } + + final private boolean jj_3_2() { + if (jj_3R_2()) return true; + return false; + } + + final private boolean jj_3R_6() { + if (jj_scan_token(TERM)) return true; + return false; + } + + final private boolean jj_3R_5() { + if (jj_3R_4()) return true; + return false; + } + + public EbnfParserTokenManager token_source; + SimpleCharStream jj_input_stream; + public Token token, jj_nt; + private int jj_ntk; + private Token jj_scanpos, jj_lastpos; + private int jj_la; + public boolean lookingAhead = false; + private boolean jj_semLA; + private int jj_gen; + final private int[] jj_la1 = new int[6]; + static private int[] jj_la1_0; + static { + jj_la1_0(); + } + private static void jj_la1_0() { + jj_la1_0 = new int[] {0x12a0,0x12a0,0x12a0,0x12a0,0x1000,0x800,}; + } + final private JJCalls[] jj_2_rtns = new JJCalls[3]; + private boolean jj_rescan = false; + private int jj_gc = 0; + + public EbnfParser(java.io.InputStream stream) { + this(stream, null); + } + public EbnfParser(java.io.InputStream stream, String encoding) { + try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source = new EbnfParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + public void ReInit(java.io.InputStream stream) { + ReInit(stream, null); + } + public void ReInit(java.io.InputStream stream, String encoding) { + try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + public EbnfParser(java.io.Reader stream) { + jj_input_stream = new SimpleCharStream(stream, 1, 1); + token_source = new EbnfParserTokenManager(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + public void ReInit(java.io.Reader stream) { + jj_input_stream.ReInit(stream, 1, 1); + token_source.ReInit(jj_input_stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + public EbnfParser(EbnfParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + public void ReInit(EbnfParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 6; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + final private Token jj_consume_token(int kind) throws ParseException { + Token oldToken; + if ((oldToken = token).next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + if (token.kind == kind) { + jj_gen++; + if (++jj_gc > 100) { + jj_gc = 0; + for (int i = 0; i < jj_2_rtns.length; i++) { + JJCalls c = jj_2_rtns[i]; + while (c != null) { + if (c.gen < jj_gen) c.first = null; + c = c.next; + } + } + } + return token; + } + token = oldToken; + jj_kind = kind; + throw generateParseException(); + } + + static private final class LookaheadSuccess extends java.lang.Error { } + final private LookaheadSuccess jj_ls = new LookaheadSuccess(); + final private boolean jj_scan_token(int kind) { + if (jj_scanpos == jj_lastpos) { + jj_la--; + if (jj_scanpos.next == null) { + jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); + } else { + jj_lastpos = jj_scanpos = jj_scanpos.next; + } + } else { + jj_scanpos = jj_scanpos.next; + } + if (jj_rescan) { + int i = 0; Token tok = token; + while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } + if (tok != null) jj_add_error_token(kind, i); + } + if (jj_scanpos.kind != kind) return true; + if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; + return false; + } + + final public Token getNextToken() { + if (token.next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + jj_gen++; + return token; + } + + final public Token getToken(int index) { + Token t = lookingAhead ? jj_scanpos : token; + for (int i = 0; i < index; i++) { + if (t.next != null) t = t.next; + else t = t.next = token_source.getNextToken(); + } + return t; + } + + final private int jj_ntk() { + if ((jj_nt=token.next) == null) + return (jj_ntk = (token.next=token_source.getNextToken()).kind); + else + return (jj_ntk = jj_nt.kind); + } + + private java.util.Vector jj_expentries = new java.util.Vector(); + private int[] jj_expentry; + private int jj_kind = -1; + private int[] jj_lasttokens = new int[100]; + private int jj_endpos; + + private void jj_add_error_token(int kind, int pos) { + if (pos >= 100) return; + if (pos == jj_endpos + 1) { + jj_lasttokens[jj_endpos++] = kind; + } else if (jj_endpos != 0) { + jj_expentry = new int[jj_endpos]; + for (int i = 0; i < jj_endpos; i++) { + jj_expentry[i] = jj_lasttokens[i]; + } + boolean exists = false; + for (java.util.Enumeration e = jj_expentries.elements(); e.hasMoreElements();) { + int[] oldentry = (int[])(e.nextElement()); + if (oldentry.length == jj_expentry.length) { + exists = true; + for (int i = 0; i < jj_expentry.length; i++) { + if (oldentry[i] != jj_expentry[i]) { + exists = false; + break; + } + } + if (exists) break; + } + } + if (!exists) jj_expentries.addElement(jj_expentry); + if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; + } + } + + public ParseException generateParseException() { + jj_expentries.removeAllElements(); + boolean[] la1tokens = new boolean[13]; + for (int i = 0; i < 13; i++) { + la1tokens[i] = false; + } + if (jj_kind >= 0) { + la1tokens[jj_kind] = true; + jj_kind = -1; + } + for (int i = 0; i < 6; i++) { + if (jj_la1[i] == jj_gen) { + for (int j = 0; j < 32; j++) { + if ((jj_la1_0[i] & (1< jj_gen) { + jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; + switch (i) { + case 0: jj_3_1(); break; + case 1: jj_3_2(); break; + case 2: jj_3_3(); break; + } + } + p = p.next; + } while (p != null); + } catch(LookaheadSuccess ls) { } + } + jj_rescan = false; + } + + final private void jj_save(int index, int xla) { + JJCalls p = jj_2_rtns[index]; + while (p.gen > jj_gen) { + if (p.next == null) { p = p.next = new JJCalls(); break; } + p = p.next; + } + p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; + } + + static final class JJCalls { + int gen; + Token first; + int arg; + JJCalls next; + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.java new file mode 100644 index 0000000..c7d005f --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserConstants.java @@ -0,0 +1,34 @@ +/* Generated By:JavaCC: Do not edit this line. EbnfParserConstants.java */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +public interface EbnfParserConstants { + + int EOF = 0; + int L_REPETITION = 5; + int R_REPETITION = 6; + int L_PARENTHESES = 7; + int R_PARENTHESES = 8; + int L_OPTION = 9; + int R_OPTION = 10; + int BRANCH = 11; + int TERM = 12; + + int DEFAULT = 0; + + String[] tokenImage = { + "", + "\" \"", + "\"\\t\"", + "\"\\r\"", + "\"\\n\"", + "\"\\u300f\"", + "\"\\u3010\"", + "\"\\u3011\"", + "\"\\u3012\"", + "\"\\u300c\"", + "\"\\u300d\"", + "\"\\u300e\"", + "", + }; + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.java new file mode 100644 index 0000000..38d7f14 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/EbnfParserTokenManager.java @@ -0,0 +1,331 @@ +/* Generated By:JavaCC: Do not edit this line. EbnfParserTokenManager.java */ +package org.jalgo.module.ebnf.controller.ebnf.parser; +import org.jalgo.module.ebnf.model.ebnf.*; +import org.jalgo.module.ebnf.controller.ebnf.EbnfController; + +public class EbnfParserTokenManager implements EbnfParserConstants +{ + public java.io.PrintStream debugStream = System.out; + public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } +private final int jjStopStringLiteralDfa_0(int pos, long active0) +{ + switch (pos) + { + default : + return -1; + } +} +private final int jjStartNfa_0(int pos, long active0) +{ + return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); +} +private final int jjStopAtPos(int pos, int kind) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + return pos + 1; +} +private final int jjStartNfaWithStates_0(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_0(state, pos + 1); +} +private final int jjMoveStringLiteralDfa0_0() +{ + switch(curChar) + { + case 9: + return jjStartNfaWithStates_0(0, 2, 0); + case 10: + return jjStartNfaWithStates_0(0, 4, 0); + case 13: + return jjStartNfaWithStates_0(0, 3, 0); + case 32: + return jjStartNfaWithStates_0(0, 1, 0); + case 12300: + return jjStopAtPos(0, 9); + case 12301: + return jjStopAtPos(0, 10); + case 12302: + return jjStopAtPos(0, 11); + case 12303: + return jjStopAtPos(0, 5); + case 12304: + return jjStopAtPos(0, 6); + case 12305: + return jjStopAtPos(0, 7); + case 12306: + return jjStopAtPos(0, 8); + default : + return jjMoveNfa_0(0, 0); + } +} +private final void jjCheckNAdd(int state) +{ + if (jjrounds[state] != jjround) + { + jjstateSet[jjnewStateCnt++] = state; + jjrounds[state] = jjround; + } +} +private final void jjAddStates(int start, int end) +{ + do { + jjstateSet[jjnewStateCnt++] = jjnextStates[start]; + } while (start++ != end); +} +private final void jjCheckNAddTwoStates(int state1, int state2) +{ + jjCheckNAdd(state1); + jjCheckNAdd(state2); +} +private final void jjCheckNAddStates(int start, int end) +{ + do { + jjCheckNAdd(jjnextStates[start]); + } while (start++ != end); +} +private final void jjCheckNAddStates(int start) +{ + jjCheckNAdd(jjnextStates[start]); + jjCheckNAdd(jjnextStates[start + 1]); +} +static final long[] jjbitVec0 = { + 0xfffefffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec2 = { + 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec3 = { + 0xfffffffffff80fffL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +private final int jjMoveNfa_0(int startState, int curPos) +{ + int[] nextStates; + int startsAt = 0; + jjnewStateCnt = 1; + int i = 1; + jjstateSet[0] = startState; + int j, kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + kind = 12; + jjstateSet[jjnewStateCnt++] = 0; + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + kind = 12; + jjstateSet[jjnewStateCnt++] = 0; + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + MatchLoop: do + { + switch(jjstateSet[--i]) + { + case 0: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 12) + kind = 12; + jjstateSet[jjnewStateCnt++] = 0; + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +static final int[] jjnextStates = { +}; +private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) +{ + switch(hiByte) + { + case 0: + return ((jjbitVec2[i2] & l2) != 0L); + case 48: + return ((jjbitVec3[i2] & l2) != 0L); + default : + if ((jjbitVec0[i1] & l1) != 0L) + return true; + return false; + } +} +public static final String[] jjstrLiteralImages = { +"", null, null, null, null, "\u300f", "\u3010", "\u3011", "\u3012", "\u300c", +"\u300d", "\u300e", null, }; +public static final String[] lexStateNames = { + "DEFAULT", +}; +static final long[] jjtoToken = { + 0x1fe1L, +}; +static final long[] jjtoSkip = { + 0x1eL, +}; +protected SimpleCharStream input_stream; +private final int[] jjrounds = new int[1]; +private final int[] jjstateSet = new int[2]; +protected char curChar; +public EbnfParserTokenManager(SimpleCharStream stream){ + if (SimpleCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + input_stream = stream; +} +public EbnfParserTokenManager(SimpleCharStream stream, int lexState){ + this(stream); + SwitchTo(lexState); +} +public void ReInit(SimpleCharStream stream) +{ + jjmatchedPos = jjnewStateCnt = 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); +} +private final void ReInitRounds() +{ + int i; + jjround = 0x80000001; + for (i = 1; i-- > 0;) + jjrounds[i] = 0x80000000; +} +public void ReInit(SimpleCharStream stream, int lexState) +{ + ReInit(stream); + SwitchTo(lexState); +} +public void SwitchTo(int lexState) +{ + if (lexState >= 1 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; +} + +protected Token jjFillToken() +{ + Token t = Token.newToken(jjmatchedKind); + t.kind = jjmatchedKind; + String im = jjstrLiteralImages[jjmatchedKind]; + t.image = (im == null) ? input_stream.GetImage() : im; + t.beginLine = input_stream.getBeginLine(); + t.beginColumn = input_stream.getBeginColumn(); + t.endLine = input_stream.getEndLine(); + t.endColumn = input_stream.getEndColumn(); + return t; +} + +int curLexState = 0; +int defaultLexState = 0; +int jjnewStateCnt; +int jjround; +int jjmatchedPos; +int jjmatchedKind; + +public Token getNextToken() +{ + int kind; + Token specialToken = null; + Token matchedToken; + int curPos = 0; + + EOFLoop : + for (;;) + { + try + { + curChar = input_stream.BeginToken(); + } + catch(java.io.IOException e) + { + jjmatchedKind = 0; + matchedToken = jjFillToken(); + return matchedToken; + } + + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_0(); + if (jjmatchedKind != 0x7fffffff) + { + if (jjmatchedPos + 1 < curPos) + input_stream.backup(curPos - jjmatchedPos - 1); + if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) + { + matchedToken = jjFillToken(); + return matchedToken; + } + else + { + continue EOFLoop; + } + } + int error_line = input_stream.getEndLine(); + int error_column = input_stream.getEndColumn(); + String error_after = null; + boolean EOFSeen = false; + try { input_stream.readChar(); input_stream.backup(1); } + catch (java.io.IOException e1) { + EOFSeen = true; + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + if (curChar == '\n' || curChar == '\r') { + error_line++; + error_column = 0; + } + else + error_column++; + } + if (!EOFSeen) { + input_stream.backup(1); + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + } + throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); + } +} + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.java new file mode 100644 index 0000000..c5e9a7c --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/ParseException.java @@ -0,0 +1,192 @@ +/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +/** + * This exception is thrown when parse errors are encountered. + * You can explicitly create objects of this exception type by + * calling the method generateParseException in the generated + * parser. + * + * You can modify this class to customize your error reporting + * mechanisms so long as you retain the public fields. + */ +public class ParseException extends Exception { + + /** + * This constructor is used by the method "generateParseException" + * in the generated parser. Calling this constructor generates + * a new object of this type with the fields "currentToken", + * "expectedTokenSequences", and "tokenImage" set. The boolean + * flag "specialConstructor" is also set to true to indicate that + * this constructor was used to create this object. + * This constructor calls its super class with the empty string + * to force the "toString" method of parent class "Throwable" to + * print the error message in the form: + * ParseException: + */ + public ParseException(Token currentTokenVal, + int[][] expectedTokenSequencesVal, + String[] tokenImageVal + ) + { + super(""); + specialConstructor = true; + currentToken = currentTokenVal; + expectedTokenSequences = expectedTokenSequencesVal; + tokenImage = tokenImageVal; + } + + /** + * The following constructors are for use by you for whatever + * purpose you can think of. Constructing the exception in this + * manner makes the exception behave in the normal way - i.e., as + * documented in the class "Throwable". The fields "errorToken", + * "expectedTokenSequences", and "tokenImage" do not contain + * relevant information. The JavaCC generated code does not use + * these constructors. + */ + + public ParseException() { + super(); + specialConstructor = false; + } + + public ParseException(String message) { + super(message); + specialConstructor = false; + } + + /** + * This variable determines which constructor was used to create + * this object and thereby affects the semantics of the + * "getMessage" method (see below). + */ + protected boolean specialConstructor; + + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * followng this token will (therefore) be the first error token. + */ + public Token currentToken; + + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + + /** + * This method has the standard behavior when this object has been + * created using the standard constructors. Otherwise, it uses + * "currentToken" and "expectedTokenSequences" to generate a parse + * error message and returns it. If this object has been created + * due to a parse error, and you do not catch it (it gets thrown + * from the parser), then this method is called during the printing + * of the final stack trace, and hence the correct error message + * gets displayed. + */ + public String getMessage() { + if (!specialConstructor) { + return super.getMessage(); + } + StringBuffer expected = new StringBuffer(); + int maxSize = 0; + for (int i = 0; i < expectedTokenSequences.length; i++) { + if (maxSize < expectedTokenSequences[i].length) { + maxSize = expectedTokenSequences[i].length; + } + for (int j = 0; j < expectedTokenSequences[i].length; j++) { + expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" "); + } + if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { + expected.append("..."); + } + expected.append(eol).append(" "); + } + String retval = "Encountered \""; + Token tok = currentToken.next; + for (int i = 0; i < maxSize; i++) { + if (i != 0) retval += " "; + if (tok.kind == 0) { + retval += tokenImage[0]; + break; + } + retval += add_escapes(tok.image); + tok = tok.next; + } + retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; + retval += "." + eol; + if (expectedTokenSequences.length == 1) { + retval += "Was expecting:" + eol + " "; + } else { + retval += "Was expecting one of:" + eol + " "; + } + retval += expected.toString(); + return retval; + } + + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + + /** + * Used to convert raw characters to their escaped version + * when these raw version cannot be used as part of an ASCII + * string literal. + */ + protected String add_escapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.java new file mode 100644 index 0000000..c098a99 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/SimpleCharStream.java @@ -0,0 +1,439 @@ +/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +/** + * An implementation of interface CharStream, where the stream is assumed to + * contain only ASCII characters (without unicode processing). + */ + +public class SimpleCharStream +{ + public static final boolean staticFlag = false; + int bufsize; + int available; + int tokenBegin; + public int bufpos = -1; + protected int bufline[]; + protected int bufcolumn[]; + + protected int column = 0; + protected int line = 1; + + protected boolean prevCharIsCR = false; + protected boolean prevCharIsLF = false; + + protected java.io.Reader inputStream; + + protected char[] buffer; + protected int maxNextCharInd = 0; + protected int inBuf = 0; + protected int tabSize = 8; + + protected void setTabSize(int i) { tabSize = i; } + protected int getTabSize(int i) { return tabSize; } + + + protected void ExpandBuff(boolean wrapAround) + { + char[] newbuffer = new char[bufsize + 2048]; + int newbufline[] = new int[bufsize + 2048]; + int newbufcolumn[] = new int[bufsize + 2048]; + + try + { + if (wrapAround) + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + System.arraycopy(buffer, 0, newbuffer, + bufsize - tokenBegin, bufpos); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos += (bufsize - tokenBegin)); + } + else + { + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos -= tokenBegin); + } + } + catch (Throwable t) + { + throw new Error(t.getMessage()); + } + + + bufsize += 2048; + available = bufsize; + tokenBegin = 0; + } + + protected void FillBuff() throws java.io.IOException + { + if (maxNextCharInd == available) + { + if (available == bufsize) + { + if (tokenBegin > 2048) + { + bufpos = maxNextCharInd = 0; + available = tokenBegin; + } + else if (tokenBegin < 0) + bufpos = maxNextCharInd = 0; + else + ExpandBuff(false); + } + else if (available > tokenBegin) + available = bufsize; + else if ((tokenBegin - available) < 2048) + ExpandBuff(true); + else + available = tokenBegin; + } + + int i; + try { + if ((i = inputStream.read(buffer, maxNextCharInd, + available - maxNextCharInd)) == -1) + { + inputStream.close(); + throw new java.io.IOException(); + } + else + maxNextCharInd += i; + return; + } + catch(java.io.IOException e) { + --bufpos; + backup(0); + if (tokenBegin == -1) + tokenBegin = bufpos; + throw e; + } + } + + public char BeginToken() throws java.io.IOException + { + tokenBegin = -1; + char c = readChar(); + tokenBegin = bufpos; + + return c; + } + + protected void UpdateLineColumn(char c) + { + column++; + + if (prevCharIsLF) + { + prevCharIsLF = false; + line += (column = 1); + } + else if (prevCharIsCR) + { + prevCharIsCR = false; + if (c == '\n') + { + prevCharIsLF = true; + } + else + line += (column = 1); + } + + switch (c) + { + case '\r' : + prevCharIsCR = true; + break; + case '\n' : + prevCharIsLF = true; + break; + case '\t' : + column--; + column += (tabSize - (column % tabSize)); + break; + default : + break; + } + + bufline[bufpos] = line; + bufcolumn[bufpos] = column; + } + + public char readChar() throws java.io.IOException + { + if (inBuf > 0) + { + --inBuf; + + if (++bufpos == bufsize) + bufpos = 0; + + return buffer[bufpos]; + } + + if (++bufpos >= maxNextCharInd) + FillBuff(); + + char c = buffer[bufpos]; + + UpdateLineColumn(c); + return (c); + } + + /** + * @deprecated + * @see #getEndColumn + */ + + public int getColumn() { + return bufcolumn[bufpos]; + } + + /** + * @deprecated + * @see #getEndLine + */ + + public int getLine() { + return bufline[bufpos]; + } + + public int getEndColumn() { + return bufcolumn[bufpos]; + } + + public int getEndLine() { + return bufline[bufpos]; + } + + public int getBeginColumn() { + return bufcolumn[tokenBegin]; + } + + public int getBeginLine() { + return bufline[tokenBegin]; + } + + public void backup(int amount) { + + inBuf += amount; + if ((bufpos -= amount) < 0) + bufpos += bufsize; + } + + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + + public SimpleCharStream(java.io.Reader dstream, int startline, + int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.Reader dstream) + { + this(dstream, 1, 1, 4096); + } + public void ReInit(java.io.Reader dstream, int startline, + int startcolumn, int buffersize) + { + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + if (buffer == null || buffersize != buffer.length) + { + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + prevCharIsLF = prevCharIsCR = false; + tokenBegin = inBuf = maxNextCharInd = 0; + bufpos = -1; + } + + public void ReInit(java.io.Reader dstream, int startline, + int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + + public void ReInit(java.io.Reader dstream) + { + ReInit(dstream, 1, 1, 4096); + } + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, + int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException + { + this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, + int startcolumn) throws java.io.UnsupportedEncodingException + { + this(dstream, encoding, startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream, int startline, + int startcolumn) + { + this(dstream, startline, startcolumn, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException + { + this(dstream, encoding, 1, 1, 4096); + } + + public SimpleCharStream(java.io.InputStream dstream) + { + this(dstream, 1, 1, 4096); + } + + public void ReInit(java.io.InputStream dstream, String encoding, int startline, + int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException + { + ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn, int buffersize) + { + ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException + { + ReInit(dstream, encoding, 1, 1, 4096); + } + + public void ReInit(java.io.InputStream dstream) + { + ReInit(dstream, 1, 1, 4096); + } + public void ReInit(java.io.InputStream dstream, String encoding, int startline, + int startcolumn) throws java.io.UnsupportedEncodingException + { + ReInit(dstream, encoding, startline, startcolumn, 4096); + } + public void ReInit(java.io.InputStream dstream, int startline, + int startcolumn) + { + ReInit(dstream, startline, startcolumn, 4096); + } + public String GetImage() + { + if (bufpos >= tokenBegin) + return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); + else + return new String(buffer, tokenBegin, bufsize - tokenBegin) + + new String(buffer, 0, bufpos + 1); + } + + public char[] GetSuffix(int len) + { + char[] ret = new char[len]; + + if ((bufpos + 1) >= len) + System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); + else + { + System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, + len - bufpos - 1); + System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); + } + + return ret; + } + + public void Done() + { + buffer = null; + bufline = null; + bufcolumn = null; + } + + /** + * Method to adjust line and column numbers for the start of a token. + */ + public void adjustBeginLineColumn(int newLine, int newCol) + { + int start = tokenBegin; + int len; + + if (bufpos >= tokenBegin) + { + len = bufpos - tokenBegin + inBuf + 1; + } + else + { + len = bufsize - tokenBegin + bufpos + 1 + inBuf; + } + + int i = 0, j = 0, k = 0; + int nextColDiff = 0, columnDiff = 0; + + while (i < len && + bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) + { + bufline[j] = newLine; + nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; + bufcolumn[j] = newCol + columnDiff; + columnDiff = nextColDiff; + i++; + } + + if (i < len) + { + bufline[j] = newLine++; + bufcolumn[j] = newCol + columnDiff; + + while (i++ < len) + { + if (bufline[j = start % bufsize] != bufline[++start % bufsize]) + bufline[j] = newLine++; + else + bufline[j] = newLine; + } + } + + line = bufline[j]; + column = bufcolumn[j]; + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/Token.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/Token.java new file mode 100644 index 0000000..19ea4ee --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/Token.java @@ -0,0 +1,81 @@ +/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +/** + * Describes the input token stream. + */ + +public class Token { + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** + * beginLine and beginColumn describe the position of the first character + * of this token; endLine and endColumn describe the position of the + * last character of this token. + */ + public int beginLine, beginColumn, endLine, endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * Returns the image. + */ + public String toString() + { + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simlpy add something like : + * + * case MyParserConstants.ID : return new IDToken(); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use it in your lexical actions. + */ + public static final Token newToken(int ofKind) + { + switch(ofKind) + { + default : return new Token(); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.java b/src/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.java new file mode 100644 index 0000000..a147f2d --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/ebnf/parser/TokenMgrError.java @@ -0,0 +1,133 @@ +/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */ +package org.jalgo.module.ebnf.controller.ebnf.parser; + +public class TokenMgrError extends Error +{ + /* + * Ordinals for various reasons why an Error of this type can be thrown. + */ + + /** + * Lexical error occured. + */ + static final int LEXICAL_ERROR = 0; + + /** + * An attempt wass made to create a second instance of a static token manager. + */ + static final int STATIC_LEXER_ERROR = 1; + + /** + * Tried to change to an invalid lexical state. + */ + static final int INVALID_LEXICAL_STATE = 2; + + /** + * Detected (and bailed out of) an infinite loop in the token manager. + */ + static final int LOOP_DETECTED = 3; + + /** + * Indicates the reason why the exception is thrown. It will have + * one of the above 4 values. + */ + int errorCode; + + /** + * Replaces unprintable characters by their espaced (or unicode escaped) + * equivalents in the given string + */ + protected static final String addEscapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + + /** + * Returns a detailed message for the Error when it is thrown by the + * token manager to indicate a lexical error. + * Parameters : + * EOFSeen : indicates if EOF caused the lexicl error + * curLexState : lexical state in which this error occured + * errorLine : line number when the error occured + * errorColumn : column number when the error occured + * errorAfter : prefix that was seen before this error occured + * curchar : the offending character + * Note: You can customize the lexical error message by modifying this method. + */ + protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { + return("Lexical error at line " + + errorLine + ", column " + + errorColumn + ". Encountered: " + + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + + "after : \"" + addEscapes(errorAfter) + "\""); + } + + /** + * You can also modify the body of this method to customize your error messages. + * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not + * of end-users concern, so you can return something like : + * + * "Internal Error : Please file a bug report .... " + * + * from this method for such cases in the release version of your parser. + */ + public String getMessage() { + return super.getMessage(); + } + + /* + * Constructors of various flavors follow. + */ + + public TokenMgrError() { + } + + public TokenMgrError(String message, int reason) { + super(message); + errorCode = reason; + } + + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.java new file mode 100644 index 0000000..4dc13ea --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddBranchAction.java @@ -0,0 +1,53 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.NullElem; + +/** + * Action that adds a new branch from oldNullElem to + * rightNullElem. If it is removed (by clicking "undo") elements + * of a potemtial contained concatenation are re-inserted in their original + * concatenation. + * + * @author Michael Thiele + * + */ +public class AddBranchAction extends AddSynDiaElemAction { + + private java.util.List containedPath; + + private int rightNullElemIndex; + + /** + * @param oldNullElem + * the left NullElem (start of the branch) + * @param rightNullElem + * the right NullElem (end of the branch) + */ + public AddBranchAction(NullElem oldNullElem, NullElem rightNullElem) { + super(oldNullElem); + this.rightNullElemIndex = rightNullElem.getIndex(); + } + + public void perform() throws IllegalArgumentException, NoNullElemException { + if (!undo) { + containedPath = parent.addBranch(oldIndex, rightNullElemIndex); + } else { + + containedPath = parent.redoAddBranch(oldIndex, rightNullElemIndex); + } + + } + + public void undo() throws IllegalArgumentException, + ElementNotFoundException { + undo = true; + if (containedPath.size() > 1) { + parent.removeBranch(oldIndex + 1, true, false, false); + } else { + parent.removeBranch(oldIndex + 1, false, false, false); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.java new file mode 100644 index 0000000..0ec1040 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddRepetitionAction.java @@ -0,0 +1,55 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.NullElem; + +/** + * Action that adds a new repetition from oldNullElem to + * rightNullElem. If it is removed (by clicking "undo") elements + * of a potemtial contained concatenation are re-inserted in their original + * concatenation. + * + * @author Michael Thiele + * + */ +public class AddRepetitionAction extends AddSynDiaElemAction { + + private java.util.List containedPath; + + private int rightNullElemIndex; + + /** + * @param oldNullElem + * the left NullElem (start of the repetition) + * @param rightNullElem + * the right NullElem (end of the repetition) + */ + public AddRepetitionAction(NullElem oldNullElem, NullElem rightNullElem) { + super(oldNullElem); + this.rightNullElemIndex = rightNullElem.getIndex(); + } + + public void perform() throws IllegalArgumentException, NoNullElemException { + if (!undo) { + containedPath = parent + .addRepetition(oldIndex, rightNullElemIndex); + } else { + containedPath = parent + .redoAddRepetition(oldIndex, rightNullElemIndex); + } + } + + public void undo() throws IllegalArgumentException, + ElementNotFoundException { + undo = true; + if (containedPath.size() > 0) { + parent.removeRepetition( + oldIndex + 1, true, false, false); + } else { + parent.removeRepetition( + oldIndex + 1, false, false, false); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.java new file mode 100644 index 0000000..06ef38f --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaAction.java @@ -0,0 +1,58 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.util.IAction; + +/** + * Action that adds a syntax diagram to a syntax diagram system. + * + * @author Michael Thiele + * + */ +public class AddSynDiaAction implements IAction { + + private SynDiaSystem sds; + + private String name, oldStartDiagramName; + + private boolean startDiagram; + + private boolean undo; + + /** + * + * @param sds + * the syntax diagram system of the actual syntax diagram + * @param name + * the name for the new diagram + * @param startDiagram + * is true if new diagram will be the new start + * diagram + */ + public AddSynDiaAction(SynDiaSystem sds, String name, boolean startDiagram) { + this.sds = sds; + this.name = name; + this.startDiagram = startDiagram; + undo = false; + } + + public void perform() throws Exception { + if (!undo) + sds.addSyntaxDiagram(name); + else + sds.undoRemoveSyntaxDiagram(); + if (startDiagram) { + oldStartDiagramName = sds.getStartDiagram(); + sds.setStartDiagram(name); + } + } + + public void undo() throws Exception { + undo = true; + sds.removeSyntaxDiagram(name, false); + if (startDiagram) { + sds.setStartDiagram(oldStartDiagramName); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.java new file mode 100644 index 0000000..5211b56 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddSynDiaElemAction.java @@ -0,0 +1,34 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.util.IAction; + +/** + * An abstract class for all Actions that have to add elements in a + * concatenation. All actions can be undone by implementing the + * undo function from IAction. + * + * @author Michael Thiele + * + */ +public abstract class AddSynDiaElemAction implements IAction { + + protected int oldIndex; + + protected Concatenation parent; + + protected boolean undo; + + /** + * + * @param oldNullElem + * this NullElem is used to define where the new + * syntax diagram element has to be added. + */ + public AddSynDiaElemAction(NullElem oldNullElem) { + this.oldIndex = oldNullElem.getIndex(); + parent = (Concatenation) oldNullElem.getParent(); + undo = false; + } +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.java new file mode 100644 index 0000000..0052437 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddTerminalAction.java @@ -0,0 +1,42 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.NullElem; + +/** + * Action that adds a new terminal symbol at oldNullElem. + * + * @author Michael Thiele + * + */ +public class AddTerminalAction extends AddSynDiaElemAction { + + private String label; + + /** + * + * @param oldNullElem + * is needed to get the position where to insert + * @param label + * label of the terminal symbol + */ + public AddTerminalAction(NullElem oldNullElem, String label) { + super(oldNullElem); + this.label = label; + } + + public void perform() throws NoNullElemException { + if (!undo) { + parent.addTerminalSymbol(oldIndex, label); + } else { + parent.redoAddTerminal(oldIndex); + } + } + + public void undo() throws ElementNotFoundException { + undo = true; + parent.removeTerminalSymbol(oldIndex + 1); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.java new file mode 100644 index 0000000..6d5b1eb --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddVariableAction.java @@ -0,0 +1,48 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.NullElem; + +/** + * Action that adds a new variable at oldNullElem. + * + * @author Michael Thiele + * + */ +public class AddVariableAction extends AddSynDiaElemAction { + + private String label; + + private NullElem oldNullElem; + + /** + * + * @param oldNullElem + * is needed to get the position where to insert + * @param label + * label of the variable + */ + public AddVariableAction(NullElem oldNullElem, String label) { + super(oldNullElem); + this.oldNullElem = oldNullElem; + this.label = label; + } + + public void perform() throws NoNullElemException { + if (!undo) { + parent.addVariable(oldIndex, label); + } else { + parent.redoAddVariable(oldIndex); + } + oldNullElem.getMySyntaxDiagram().getMySynDiaSystem().addVariable(label); + } + + public void undo() throws ElementNotFoundException { + undo = true; + parent.removeVariable(oldIndex + 1); + oldNullElem.getMySyntaxDiagram().getMySynDiaSystem().removeVariable( + label); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.java b/src/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.java new file mode 100644 index 0000000..b6bb2ac --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/AddWordWrapAction.java @@ -0,0 +1,32 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.NullElem; + +/** + * Action that adds a new word wrap at oldNullElem. + * + * @author Michael Thiele + * + */ +public class AddWordWrapAction extends AddSynDiaElemAction { + + /** + * + * @param oldNullElem + * is needed to get the position where to insert + */ + public AddWordWrapAction(NullElem oldNullElem) { + super(oldNullElem); + } + + public void perform() throws NoNullElemException { + parent.addWordWrap(oldIndex); + } + + public void undo() throws ElementNotFoundException { + parent.removeWordWrap(oldIndex + 1); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/CVS/Entries b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Entries new file mode 100644 index 0000000..1659491 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Entries @@ -0,0 +1,19 @@ +/AddBranchAction.java/1.1/Fri Aug 11 16:40:27 2006// +/AddRepetitionAction.java/1.1/Fri Aug 11 16:40:27 2006// +/AddSynDiaAction.java/1.1/Fri Aug 11 16:40:28 2006// +/AddSynDiaElemAction.java/1.1/Fri Aug 11 16:40:28 2006// +/AddTerminalAction.java/1.1/Fri Aug 11 16:40:28 2006// +/AddVariableAction.java/1.1/Fri Aug 11 16:40:27 2006// +/AddWordWrapAction.java/1.1/Fri Aug 11 16:40:28 2006// +/DeleteBranchAction.java/1.1/Fri Aug 11 16:40:27 2006// +/DeleteRepetitionAction.java/1.1/Fri Aug 11 16:40:28 2006// +/DeleteSynDiaElemAction.java/1.1/Fri Aug 11 16:40:28 2006// +/DeleteSyntaxDiagramAction.java/1.1/Fri Aug 11 16:40:27 2006// +/DeleteTerminalAction.java/1.1/Fri Aug 11 16:40:27 2006// +/DeleteVariableAction.java/1.1/Fri Aug 11 16:40:28 2006// +/DeleteWordWrapAction.java/1.1/Fri Aug 11 16:40:27 2006// +/RenameElementAction.java/1.1/Fri Aug 11 16:40:28 2006// +/RenameSyntaxDiagramAction.java/1.1/Fri Aug 11 16:40:27 2006// +/RenameTerminalAction.java/1.1/Fri Aug 11 16:40:27 2006// +/RenameVariableAction.java/1.1/Fri Aug 11 16:40:28 2006// +/SynDiaController.java/1.1/Fri Aug 11 16:40:27 2006// diff --git a/src/org/jalgo/module/ebnf/controller/syndia/CVS/Repository b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Repository new file mode 100644 index 0000000..578f8e6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/syndia diff --git a/src/org/jalgo/module/ebnf/controller/syndia/CVS/Root b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.java new file mode 100644 index 0000000..a23f336 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteBranchAction.java @@ -0,0 +1,76 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.*; + +/** + * Action that deletes a branch. + * + * @author Michael Thiele + * + */ +public class DeleteBranchAction extends DeleteSynDiaElemAction { + + private Branch deletedBranch; + + private boolean left, right; + + private int endLeft; + + /** + * Initializes the Action. + * + * @param deletedBranch + * the branch to delete + * @param left + * true if the left (upper) path has to be + * preserved + * @param right + * true if the right (lower) path has to be + * preserved + */ + public DeleteBranchAction(Branch deletedBranch, boolean left, boolean right) { + this.deletedBranch = deletedBranch; + this.left = left; + this.right = right; + // pre-initialize endLeft, because elements in the branch could be + // deleted + endLeft = deletedBranch.getLeft().getNumberOfElems() - 1; + } + + public void perform() throws IllegalArgumentException, + ElementNotFoundException { + NullElem newNullElem = ((Concatenation) deletedBranch.getParent()) + .deleteBranch(deletedBranch, left, right); + index = newNullElem.getIndex(); + } + + public void undo() throws IllegalArgumentException, NoNullElemException { + if (left == false && right == false) { + ((Concatenation) deletedBranch.getParent()).undoDeleteBranch(index, + index); + } else { + if (left == true) { + ((Concatenation) deletedBranch.getParent()).undoDeleteBranch( + index, endLeft + index); + } else { + ((Concatenation) deletedBranch.getParent()).undoDeleteBranch( + index, index); + // now delete all elements, that are in the right side of the + // branch, but also in the parent concatenation + Concatenation rightSide = (Concatenation) deletedBranch + .getRight(); + // do not delete NullElems - that's done in the remove function + for (int i = 1; i < rightSide.getNumberOfElems(); i = i + 2) { + SynDiaElem sde = rightSide.getSynDiaElem(i); + try { + ((Concatenation) deletedBranch.getParent()) + .removeSynDiaElemCompletely(sde); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + } + } + } + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.java new file mode 100644 index 0000000..8cbcc82 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteRepetitionAction.java @@ -0,0 +1,75 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.*; + +/** + * Action that deletes a repetition. + * + * @author Michael Thiele + * + */ +public class DeleteRepetitionAction extends DeleteSynDiaElemAction { + + private Repetition deletedRepetition; + + private boolean left, right; + + private int endLeft; + + /** + * Initializes the Action. + * + * @param deletedRepetition + * the repetition to delete + * @param left + * true if the left (upper) path has to be + * preserved + * @param right + * true if the right (lower) path has to be + * preserved + */ + public DeleteRepetitionAction(Repetition deletedRepetition, boolean left, + boolean right) { + this.deletedRepetition = deletedRepetition; + this.left = left; + this.right = right; + endLeft = deletedRepetition.getLeft().getNumberOfElems() - 1; + } + + public void perform() throws IllegalArgumentException, + ElementNotFoundException { + NullElem newNullElem = ((Concatenation) deletedRepetition.getParent()) + .deleteRepetition(deletedRepetition, left, right); + index = newNullElem.getIndex(); + } + + public void undo() throws IllegalArgumentException, NoNullElemException { + if (left == false && right == false) { + ((Concatenation) deletedRepetition.getParent()) + .undoDeleteRepetition(index, index); + } else { + if (left == true) { + ((Concatenation) deletedRepetition.getParent()) + .undoDeleteRepetition(index, endLeft + index); + } else { + ((Concatenation) deletedRepetition.getParent()) + .undoDeleteRepetition(index, index); + // now delete all elements, that are in the right side of the + // branch, but also in the parent concatenation + Concatenation rightSide = (Concatenation) deletedRepetition + .getRight(); + // do not delete NullElems - that's done in the remove function + for (int i = 1; i < rightSide.getNumberOfElems(); i = i + 2) { + SynDiaElem sde = rightSide.getSynDiaElem(i); + try { + ((Concatenation) deletedRepetition.getParent()) + .removeSynDiaElemCompletely(sde); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + } + } + } + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.java new file mode 100644 index 0000000..196ca64 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteSynDiaElemAction.java @@ -0,0 +1,19 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.util.IAction; + +/** + * An abstract class for all actions that have to delete elements from a + * concatenation. + * + * @author Michael Thiele + * + */ +public abstract class DeleteSynDiaElemAction implements IAction { + + /** + * Is saved to re-insert at the right place. + */ + protected int index; + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.java new file mode 100644 index 0000000..97501de --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteSyntaxDiagramAction.java @@ -0,0 +1,34 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.util.IAction; + +/** + * Action that deletes a syntax diagram. + * + * @author Michael Thiele + * + */ +public class DeleteSyntaxDiagramAction implements IAction { + + private SyntaxDiagram syntaxDiagram; + + /** + * + * @param syntaxDiagram + * the syntax diagram to delete + */ + public DeleteSyntaxDiagramAction(SyntaxDiagram syntaxDiagram) { + this.syntaxDiagram = syntaxDiagram; + } + + public void perform() throws Exception { + syntaxDiagram.getMySynDiaSystem().removeSyntaxDiagram( + syntaxDiagram.getName(), true); + } + + public void undo() throws Exception { + syntaxDiagram.getMySynDiaSystem().undoDeleteSyntaxDiagram(); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.java new file mode 100644 index 0000000..4b22983 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteTerminalAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.*; + +/** + * Action that deletes a terminal symbol. + * + * @author Michael Thiele + * + */ +public class DeleteTerminalAction extends DeleteSynDiaElemAction { + + private TerminalSymbol deletedTerminal; + + /** + * Initializes the Action. + * + * @param deletedTerminal + * the terminal symbol to delete + */ + public DeleteTerminalAction(TerminalSymbol deletedTerminal) { + this.deletedTerminal = deletedTerminal; + } + + public void perform() throws ElementNotFoundException { + NullElem newNullElem = ((Concatenation) deletedTerminal.getParent()) + .deleteTerminal(deletedTerminal); + index = newNullElem.getIndex(); + } + + public void undo() throws NoNullElemException { + ((Concatenation) deletedTerminal.getParent()) + .undoDeleteTerminal(index); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.java new file mode 100644 index 0000000..0b7e338 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteVariableAction.java @@ -0,0 +1,43 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.*; + +/** + * Action that deletes a variable. + * + * @author Michael Thiele + * + */ +public class DeleteVariableAction extends DeleteSynDiaElemAction { + + private Variable deletedVariable; + + private SynDiaSystem sds; + + /** + * Initializes the Action. + * + * @param deletedVariable + * the variable to delete + * @param sds + * a syntax diagram system + */ + public DeleteVariableAction(Variable deletedVariable, SynDiaSystem sds) { + this.deletedVariable = deletedVariable; + this.sds = sds; + } + + public void perform() throws ElementNotFoundException { + NullElem newNullElem = ((Concatenation) deletedVariable.getParent()) + .deleteVariable(deletedVariable); + index = newNullElem.getIndex(); + sds.removeVariable(deletedVariable.getLabel()); + } + + public void undo() throws NoNullElemException { + ((Concatenation) deletedVariable.getParent()) + .undoDeleteVariable(index); + sds.addVariable(deletedVariable.getLabel()); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.java b/src/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.java new file mode 100644 index 0000000..a6be961 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/DeleteWordWrapAction.java @@ -0,0 +1,35 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.*; + +/** + * Action that deletes a word wrap. + * + * @author Michael Thiele + * + */ +public class DeleteWordWrapAction extends DeleteSynDiaElemAction { + + private WordWrap deletedWordWrap; + + /** + * Initializes the Action. + * + * @param deletedWordWrap + * the word wrap to delete + */ + public DeleteWordWrapAction(WordWrap deletedWordWrap) { + this.deletedWordWrap = deletedWordWrap; + } + + public void perform() throws ElementNotFoundException { + NullElem newNullElem = ((Concatenation) deletedWordWrap.getParent()) + .removeWordWrap(deletedWordWrap); + index = newNullElem.getIndex(); + } + + public void undo() throws NoNullElemException { + ((Concatenation) deletedWordWrap.getParent()).addWordWrap(index); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.java b/src/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.java new file mode 100644 index 0000000..ca6e2c1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/RenameElementAction.java @@ -0,0 +1,26 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.util.IAction; + +/** + * Abstract class for renaming elements in a syntax diagram system. + * + * @author Michael Thiele + * + */ +public abstract class RenameElementAction implements IAction { + + protected String newLabel; + + protected String oldLabel; + + /** + * + * @param newLabel + * the new label for the syntax diagram element + */ + public RenameElementAction(String newLabel) { + this.newLabel = newLabel; + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.java b/src/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.java new file mode 100644 index 0000000..f31495a --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/RenameSyntaxDiagramAction.java @@ -0,0 +1,50 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; + +/** + * Action that renames an existing syntax diagram. + * + * @author Michael Thiele + * + */ +public class RenameSyntaxDiagramAction extends RenameElementAction { + + private SyntaxDiagram sd; + + private boolean setStartDiagram; + + private String oldStartDiagram; + + /** + * + * @param sd + * the syntax diagram to rename + * @param newLabel + * the new label for this syntax diagram + * @param setStartDiagram + * is true if this diagram will be new start + * diagram + */ + public RenameSyntaxDiagramAction(SyntaxDiagram sd, String newLabel, + boolean setStartDiagram) { + super(newLabel); + this.sd = sd; + this.setStartDiagram = setStartDiagram; + oldStartDiagram = sd.getMySynDiaSystem().getStartDiagram(); + oldLabel = sd.getName(); + } + + public void perform() throws Exception { + sd.setName(newLabel); + if (setStartDiagram) + sd.getMySynDiaSystem().setStartDiagram(sd.getName()); + } + + public void undo() throws Exception { + sd.setName(oldLabel); + if (setStartDiagram) + sd.getMySynDiaSystem().setStartDiagram(oldStartDiagram); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.java b/src/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.java new file mode 100644 index 0000000..cec4e31 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/RenameTerminalAction.java @@ -0,0 +1,36 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; + +/** + * Action that renames a terminal symbol. + * + * @author Michael Thiele + * + */ +public class RenameTerminalAction extends RenameElementAction { + + private TerminalSymbol terminalSymbol; + + /** + * + * @param terminalSymbol + * the terminal symbol to rename + * @param newLabel + * the new label for this terminal symbol + */ + public RenameTerminalAction(TerminalSymbol terminalSymbol, String newLabel) { + super(newLabel); + this.terminalSymbol = terminalSymbol; + oldLabel = terminalSymbol.getLabel(); + } + + public void perform() throws Exception { + terminalSymbol.setLabel(newLabel); + } + + public void undo() throws Exception { + terminalSymbol.setLabel(oldLabel); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.java b/src/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.java new file mode 100644 index 0000000..1d83de2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/RenameVariableAction.java @@ -0,0 +1,42 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import org.jalgo.module.ebnf.model.syndia.Variable; + +/** + * Action that renames a variable. + * + * @author Michael Thiele + * + */ +public class RenameVariableAction extends RenameElementAction { + + private Variable variable; + + /** + * + * @param variable + * the variable to rename + * @param newLabel + * the new label for this variable + */ + public RenameVariableAction(Variable variable, String newLabel) { + super(newLabel); + this.variable = variable; + oldLabel = variable.getLabel(); + } + + public void perform() throws Exception { + variable.setLabel(newLabel); + variable.getMySyntaxDiagram().getMySynDiaSystem().addVariable(newLabel); + variable.getMySyntaxDiagram().getMySynDiaSystem().removeVariable( + oldLabel); + } + + public void undo() throws Exception { + variable.setLabel(oldLabel); + variable.getMySyntaxDiagram().getMySynDiaSystem().removeVariable( + newLabel); + variable.getMySyntaxDiagram().getMySynDiaSystem().addVariable(oldLabel); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/syndia/SynDiaController.java b/src/org/jalgo/module/ebnf/controller/syndia/SynDiaController.java new file mode 100644 index 0000000..f96bac3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/syndia/SynDiaController.java @@ -0,0 +1,493 @@ +package org.jalgo.module.ebnf.controller.syndia; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JPanel; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.gui.syndia.GuiController; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.syndia.WordWrap; +import org.jalgo.module.ebnf.util.ActionStack; + +/** + * This class is the controller for syntax diagram input. The + * add/remove-functions just create a new IAction, which perform the task. They + * are called by the SynDiaMouseListener.
          + * The controller can save syntax diagram systems. + * + * @author Michael Thiele + */ +public class SynDiaController implements Observer { + + private MainController mainController; + + private ModuleConnector connector; + + private GuiController guiController; + + private ActionStack actionStack; + + private SynDiaSystem synDiaSystem; + + /** + * Constructor that initializes the controller. A new + * GuiController and ActionStack are created. + * + * @param mainController + * the jalgo main controller + * @param connector + * the jalgo module connector + * @param synDiaSystem + * model for a syntax diagram system + * @param rootPane + * the main panel from j-algo. + */ + public SynDiaController(MainController mainController, + ModuleConnector connector, SynDiaSystem synDiaSystem, + JPanel rootPane) { + this.mainController = mainController; + this.connector = connector; + this.synDiaSystem = synDiaSystem; + actionStack = new ActionStack(); + guiController = new GuiController(this, connector, rootPane); + synDiaSystem.addObserver(guiController.getDrawPanel()); + synDiaSystem.addObserver(this); + } + + /** + * Switches to syntax diagram view. + * + */ + public void switchToSynDiaView() { + synDiaSystem.removeNullElems(); + mainController.setSynDiaDisplayMode(synDiaSystem); + } + + /** + * Performs an undo action. + * + */ + public void undo() { + if (actionStack.isUndoPossible()) { + try { + actionStack.undo(); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog(Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + } + + /** + * Performs a redo action. + * + */ + public void redo() { + if (actionStack.isRedoPossible()) { + try { + actionStack.redo(); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog(Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + } + + /** + * Adds a syntax diagram to the syntax diagram system. + * + * @param name + * the name of the new syntax diagram + * @param setStartDiagram + * is true if new diagram will be start diagram + */ + public void addSyntaxDiagram(String name, boolean setStartDiagram) { + try { + actionStack.perform(new AddSynDiaAction(synDiaSystem, name, + setStartDiagram)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Renames a syntax diagram. + * + * @param sd + * the syntax diagram to rename + * @param newLabel + * the new name for the syntax diagram + * @param setStartDiagram + * true if the syntax diagram should be start + * diagram + */ + public void renameSyntaxDiagram(SyntaxDiagram sd, String newLabel, + boolean setStartDiagram) { + try { + actionStack.perform(new RenameSyntaxDiagramAction(sd, newLabel, + setStartDiagram)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Renames a terminal symbol. + * + * @param terminalSymbol + * the terminal symbol to rename + * @param newLabel + * the new label for the terminal symbol + */ + public void renameTerminal(TerminalSymbol terminalSymbol, String newLabel) { + try { + actionStack.perform(new RenameTerminalAction(terminalSymbol, + newLabel)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Adds a terminal symbol at the given position. + * + * @param nullElem + * is needed to locate where to insert + * @param label + * the label of the terminal symbol + */ + public void addTerminal(NullElem nullElem, String label) { + try { + actionStack.perform(new AddTerminalAction(nullElem, label)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Renames a variable. + * + * @param variable + * the variable to rename + * @param newLabel + * the new label for the variable + */ + public void renameVariable(Variable variable, String newLabel) { + try { + actionStack.perform(new RenameVariableAction(variable, newLabel)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Adds a variable at the given position. + * + * @param nullElem + * is needed to locate where to insert + * @param label + * the label of the variable + */ + public void addVariable(NullElem nullElem, String label) { + try { + actionStack.perform(new AddVariableAction(nullElem, label)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Adds a repetition at the given position. + * + * @param nullElemBegin + * is needed to locate where to insert the begin of the + * repetition + * @param nullElemEnd + * is needed to locate where to insert the end of the repetition + */ + public void addRepetition(NullElem nullElemBegin, NullElem nullElemEnd) { + try { + actionStack.perform(new AddRepetitionAction(nullElemBegin, + nullElemEnd)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Adds a branch at the given position. + * + * @param nullElemBegin + * is needed to locate where to insert the begin of the branch + * @param nullElemEnd + * is needed to locate where to insert the end of the branch + */ + public void addBranch(NullElem nullElemBegin, NullElem nullElemEnd) { + try { + actionStack + .perform(new AddBranchAction(nullElemBegin, nullElemEnd)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Adds a manual word wrap at the given position. + * + * @param nullElem + * is needed to locate where to insert the word wrap + */ + public void addWordWrap(NullElem nullElem) { + try { + actionStack.perform(new AddWordWrapAction(nullElem)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Removes a syntax diagram of a syntax diagram system. + * + * @param syntaxDiagram + * the syntax diagram to remove + * @throws Exception + */ + public void removeSyntaxDiagram(SyntaxDiagram syntaxDiagram) + throws Exception { + actionStack.perform(new DeleteSyntaxDiagramAction(syntaxDiagram)); + synDiaSystem.notifyObservers(); + } + + /** + * Removes a terminal symbol of the syntax diagram system. + * + * @param deletedTerminal + * the terminal symbol to delete + */ + public void removeTerminal(TerminalSymbol deletedTerminal) { + try { + actionStack.perform(new DeleteTerminalAction(deletedTerminal)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Removes a variable of the syntax diagram system. + * + * @param deletedVariable + * the variable to delete + */ + public void removeVariable(Variable deletedVariable) { + try { + actionStack.perform(new DeleteVariableAction(deletedVariable, + synDiaSystem)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Removes a manual word wrap of the syntax diagram system. + * + * @param deletedWordWrap + * the word wrap to delete + */ + public void removeWordWrap(WordWrap deletedWordWrap) { + try { + actionStack.perform(new DeleteWordWrapAction(deletedWordWrap)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Removes a repetition of the syntax diagram system. + * + * @param deletedRepetition + * the repetition to delete + * @param left + * true if the left (upper) path has to be + * preserved + * @param right + * true if the right (lower) path has to be + * preserved + */ + public void removeRepetition(Repetition deletedRepetition, boolean left, + boolean right) { + try { + actionStack.perform(new DeleteRepetitionAction(deletedRepetition, + left, right)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Removes a branch of the syntax diagram system. + * + * @param deletedBranch + * the branch to delete + * @param left + * true if the left (upper) path has to be + * preserved + * @param right + * true if the right (lower) path has to be + * preserved + */ + public void removeBranch(Branch deletedBranch, boolean left, boolean right) { + try { + actionStack.perform(new DeleteBranchAction(deletedBranch, left, + right)); + synDiaSystem.notifyObservers(); + } catch (Exception e) { + mainController.showErrorDialog( + Messages.getString("ebnf", + "SynDiaEditor.Error_InternalError") + + Messages.getString("ebnf", + "SynDiaEditor.Error_Appendix"), false); + } + } + + /** + * Returns the syntax diagram system. + * + * @return the syntax diagram system + */ + public SynDiaSystem getSynDiaSystem() { + return synDiaSystem; + } + + /** + * Returns the main controller. + * + * @return the main controller + */ + public MainController getMainController() { + return mainController; + } + + /** + * Returns the action stack. + * + * @return the action stack + */ + public ActionStack getActionStack() { + return actionStack; + } + + /** + * Saves the actual syntax diagram system into a file. + * + * @return a ByteArrayOutputStream + */ + public ByteArrayOutputStream saveSystem() { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeBoolean(false); + objOut.writeObject(synDiaSystem); + objOut.close(); + connector.setSaveStatus(SaveStatus.NO_CHANGES); + } catch (IOException e) { + JAlgoGUIConnector.getInstance().showErrorMessage( + Messages.getString("ebnf", "SynDia.Error.SaveError")); + } + + return out; + } + + public void update(Observable o, Object arg) { + if (o instanceof SynDiaSystem) { + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/trans/CVS/Entries b/src/org/jalgo/module/ebnf/controller/trans/CVS/Entries new file mode 100644 index 0000000..10a7f9b --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/CVS/Entries @@ -0,0 +1,3 @@ +/TransAlgorithm.java/1.1/Fri Aug 11 16:40:27 2006// +/TransController.java/1.1/Fri Aug 11 16:40:27 2006// +/TransStep.java/1.1/Fri Aug 11 16:40:27 2006// diff --git a/src/org/jalgo/module/ebnf/controller/trans/CVS/Repository b/src/org/jalgo/module/ebnf/controller/trans/CVS/Repository new file mode 100644 index 0000000..35c5220 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/trans diff --git a/src/org/jalgo/module/ebnf/controller/trans/CVS/Root b/src/org/jalgo/module/ebnf/controller/trans/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.java b/src/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.java new file mode 100644 index 0000000..24e7a81 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/TransAlgorithm.java @@ -0,0 +1,341 @@ +/** + * + */ +package org.jalgo.module.ebnf.controller.trans; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.EAlternative; +import org.jalgo.module.ebnf.model.ebnf.ECompoundTerm; +import org.jalgo.module.ebnf.model.ebnf.EConcatenation; +import org.jalgo.module.ebnf.model.ebnf.EOption; +import org.jalgo.module.ebnf.model.ebnf.ERepetition; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.model.ebnf.Rule; +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.NoNullElemException; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.trans.TransMap; + +/** + * @author Andre + * + */ +public class TransAlgorithm { + + private static TransMap transMap = null; + + /** + * this function transforms a Definition into an aquivalent + * SynDiaSystem + * @param ebnfDef + * @param tm an empty TransMap + * + * @return a SynDiaSystem + */ + + public static SynDiaSystem transformEbnf(Definition ebnfDef, TransMap tm) { + + transMap = tm; + + SynDiaSystem sds = new SynDiaSystem(); + + //Startvariable setzen + sds.setStartDiagram(ebnfDef.getStartVariable().getName()); + + // Variablenliste transformieren + for (EVariable ev : ebnfDef.getVariables()) { + + sds.addVariable(ev.getName()); + + } + + + // Reglen abarbeiten + + List ruleBuffer = new ArrayList(); + for (Rule rule : ebnfDef.getRules()) { + + if (sds.getStartDiagram().equals(rule.getName().getName())) { + sds.insertSyntaxDiagram(transformRule(rule, sds)); + } else { + ruleBuffer.add(rule); + } + } + for (Rule rule : ruleBuffer) + sds.insertSyntaxDiagram(transformRule(rule, sds)); + + return sds; + } + + /** + * Transforms a Rule into a SyntaxDiagram + * + * @param rule a Rule + * @return A SyntaxDiagram + */ + private static SyntaxDiagram transformRule(Rule rule, SynDiaSystem sds) { + + SyntaxDiagram sd = new SyntaxDiagram(rule.getName().getName(), sds); + + transformTerm(rule.getTerm(), sd.getRoot()); + + sd.removeNullElems(); + + return sd; + } + + /** + * Transforms a Term into a SynDiaElem and adds it to the SyntaxDiagram + * + * @param t A Term + * @param se A SynDiaElem + */ + private static void transformTerm(Term t, SynDiaElem se) { + try { + // + // Terminal Symbol + // + if (t.getClass() == ETerminalSymbol.class) { + + ETerminalSymbol et = (ETerminalSymbol) t; + if (se.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) se; + c.addTerminalSymbol(0, et.getName()); + transMap.put(c.getSynDiaElem(1), et); + + } + + // + // Variable + // + } else if (t.getClass() == EVariable.class) { + + EVariable ev = (EVariable) t; + if (se.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) se; + c.addVariable(0, ev.getName()); + transMap.put(c.getSynDiaElem(1), ev); + + } + + // + // Concatenation + // + } else if (t.getClass() == EConcatenation.class) { + + EConcatenation ec = (EConcatenation) t; + Concatenation c = (Concatenation) se; + int i = 0; + for (Term term : ec.getTerms()) { + + putTermInSynDia(term, c, 2 * i); + // TODO CHECK + transformTerm(term, c.getSynDiaElem(2 * i + 1)); + + i++; + } + transMap.put(c, t); + // + // Alternative + // + } else if (t.getClass() == EAlternative.class) { + + EAlternative ea = (EAlternative) t; + if (se.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) se; + c.addBranch(0, 0); + transMap.put(c.getSynDiaElem(1), ea); + + transformTerm(ea, c.getSynDiaElem(1)); + + } else if (se.getClass() == Branch.class) { + + Branch b = (Branch) se; + + transformTerm(ea.getTerms().get(0), b.getLeft()); + transformTerm(ea.getTerms().get(1), b.getRight()); + + } + + // + // Option + // + } else if (t.getClass() == EOption.class) { + + EOption eo = (EOption) t; + + if (se.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) se; + c.addBranch(0, 0); + transMap.put(c.getSynDiaElem(1), eo); + + transformTerm(eo, c.getSynDiaElem(1)); + + } else if (se.getClass() == Branch.class) { + + Branch b = (Branch) se; + + transformTerm(eo.getTerm(), b.getLeft()); + + } + // + // Repetition + // + } else if (t.getClass() == ERepetition.class) { + + ERepetition er = (ERepetition) t; + + if (se.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) se; + c.addRepetition(0, 0); + transMap.put(c.getSynDiaElem(1), er); + + transformTerm(er, c.getSynDiaElem(1)); + + } else if (se.getClass() == Repetition.class) { + + Repetition r = (Repetition) se; + + transformTerm(er.getTerm(), r.getRight()); + + } + // + // Compound Term + // + } else if (t.getClass() == ECompoundTerm.class) { + + ECompoundTerm ect = (ECompoundTerm) t; + + transformTerm(ect.getTerm(), se); + + } + } catch (NoNullElemException e) { + + System.out.println("Das war wohl kein Nullelement"); + + } + + } + + /** + * Creates a SynDiaElem of the given Term and puts this to the given + * Concatenation + * + * @param t the Term to transform + * @param c the Concatenation to put the SynDiaElem in + * @param index + */ + private static void putTermInSynDia(Term t, Concatenation c, int index) { + + try { + if (t.getClass() == ETerminalSymbol.class) { + ETerminalSymbol et = (ETerminalSymbol) t; + c.addTerminalSymbol(index, et.getName()); + transMap.put(c.getSynDiaElem(index + 1), t); + } else if (t.getClass() == EVariable.class) { + EVariable ev = (EVariable) t; + c.addVariable(index, ev.getName()); + transMap.put(c.getSynDiaElem(index + 1), t); + } else if (t.getClass() == EAlternative.class) { + c.addBranch(index, index); + transMap.put(c.getSynDiaElem(index + 1), t); + } else if (t.getClass() == EOption.class) { + c.addBranch(index, index); + transMap.put(c.getSynDiaElem(index + 1), t); + } else if (t.getClass() == ERepetition.class) { + c.addRepetition(index, index); + transMap.put(c.getSynDiaElem(index + 1), t); + } + + } catch (NoNullElemException e) { + System.out.println("Das war wohl kein Nullelement"); + } + + } + +// FIXME [Andre] TestEbnfDefinition, später auf jeden Fall löschen! + public static Definition getTestDef() { + + Definition ed = new Definition(); + try { + + EVariable start = new EVariable("Super Ingo"); + EVariable va = new EVariable("Nicht Diesel"); + + ETerminalSymbol a = new ETerminalSymbol("a"); + ETerminalSymbol b = new ETerminalSymbol("b"); + ETerminalSymbol c = new ETerminalSymbol("c"); + + ed.addTerminal(a); + ed.addTerminal(b); + ed.addTerminal(c); + + ed.addVariable(start); + ed.addVariable(va); + + ed.setStartVariable(va); + + // Regel S Seite 152 + List sconclist = new ArrayList(); + List sconclist2 = new ArrayList(); + + EOption salt = new EOption(b); + + sconclist2.add(c); + sconclist2.add(salt); + sconclist2.add(a); + EConcatenation sconc2 = new EConcatenation(sconclist2); + + ERepetition srep = new ERepetition(sconc2); + + sconclist.add(srep); + sconclist.add(va); + + EConcatenation sconc = new EConcatenation(sconclist); + + Rule rule1 = new Rule(start, sconc); + + // Regel A Seite 152 + List aconclist = new ArrayList(); + + aconclist.add(a); + aconclist.add(va); + aconclist.add(b); + + EConcatenation aconc = new EConcatenation(aconclist); + + ECompoundTerm acomp = new ECompoundTerm(aconc); + + EAlternative aalt = new EAlternative(acomp, a); + + Rule rule2 = new Rule(va, aalt); + + ed.addRule(rule1); + ed.addRule(rule2); + + } catch (DefinitionFormatException e) { + + System.out.println("irgendwas falsch hier"); + + } + + return ed; + } + + +} diff --git a/src/org/jalgo/module/ebnf/controller/trans/TransController.java b/src/org/jalgo/module/ebnf/controller/trans/TransController.java new file mode 100644 index 0000000..3bb9179 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/TransController.java @@ -0,0 +1,413 @@ +/** + * + */ + +package org.jalgo.module.ebnf.controller.trans; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JPanel; + +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.gui.trans.GUIController; +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.util.ActionStack; + +/** + * @author Andre + */ +public class TransController { + + /** + * Represents the Pane given by the TransController to draw on + */ + private JPanel contentPane; + + /** + * Represents the MainController of the EBNF module + */ + private MainController maincontroller; + + /** + * Represents the ModuleConnector of the EBNF module + */ + private ModuleConnector connector; + + /** + * Represents the GuiController of the trans-algorithm + */ + private GUIController guicontroller; + + /** + * Represents the EBNF definition to transform + */ + private Definition ebnfDef; + + /** + * Represents the later created SynDiaSystem + */ + private SynDiaSystem synDiaSystem; + + /** + * Represents the Map to see whether an element is transformed (null) or not + */ + private TransMap transMap; + + /** + * Represents a dataholder for the performed steps making it possible to + * undo steps + */ + private ActionStack actionStack; + + private AbstractAction startAction; + + /** + * Initializes the TransController + * + * @param maincontroller the MainController of the module + * @param connector the ModuleConnector of the module + * @param contentPane the Panel to draw on + * @param ebnfdef an Ebnf definition + */ + public TransController(MainController maincontroller, + ModuleConnector connector, JPanel contentPane, Definition ebnfdef) { + + this.maincontroller = maincontroller; + this.connector = connector; + this.contentPane = contentPane; + + this.actionStack = new ActionStack(); + + try { + this.ebnfDef = ebnfdef.getStrict(); + } catch (DefinitionFormatException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + this.transMap = new TransMap(); + + this.synDiaSystem = TransAlgorithm.transformEbnf(ebnfDef, transMap); + + guicontroller = new GUIController(this, connector); + + transMap.addObserver(guicontroller.getDrawPanel()); + transMap.addObserver(guicontroller.getControlPanel()); + } + + + /** + * Creates a JButton object without border and text, which + * can be used in JToolBars + * + * @return a JButton instance with the given + * Action + */ + public JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton((Icon) a + .getValue(Action.SMALL_ICON), null, null); + button.setAction(a); + button.setText(""); + return button; + } + + + /** + * A method to set another EBNF definition to transform. In standard case + * never used, but perhaps.. later... or so... or not + * + * @param ebnfdef + */ + public void setEbnfDefinition(Definition ebnfdef) { + + try { + this.ebnfDef = ebnfdef.getStrict(); + } catch (DefinitionFormatException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + this.synDiaSystem = new SynDiaSystem(ebnfdef.getStartVariable() + .getName()); + + this.synDiaSystem = TransAlgorithm.transformEbnf(ebnfDef, transMap); + + } + + public void switchToAlgorithm() { + + guicontroller.switchToAlgorithm(); + + } + + public void switchToSynDiaDisplay() { + + maincontroller.setSynDiaDisplayMode(synDiaSystem); + + } + + public void setEbnfInputMode() { + + maincontroller.setEbnfInputMode(true); + + } + + + /** + * A method just to get the contentPane + * + * @return The contentPane of the module + */ + public JPanel getContentPane() { + + return this.contentPane; + + } + + /** + * A method just to get the syntax diagram system + * + * @return A SynDiaSystem + */ + public SynDiaSystem getSynDiaSystem() { + + return this.synDiaSystem; + + } + + /** + * A method just to get the transMap + * + * @return A Map containing all associations from a syntax diagram element + * to the referred term + */ + public TransMap getTransMap() { + + return this.transMap; + + } + + + + /** Checks if there's at least one more step to perform + * @return True, if it is possible to perform at least one step + */ + public boolean hasNextStep() { + + for (SynDiaElem sde : transMap.keySet()) + if (transMap.get(sde) != null) return true; + + return false; + } + + /** This method searches for the next transformable term and returns it + * @return A Term, which is the next to be transformed + */ + public Term getTermFromNextStep() { + + for (SynDiaElem sde : transMap.keySet()) + + if (transMap.get(sde) != null) { + + return transMap.get(this.getLastPossibleParent(sde)); + } + + return null; + } + + /** This method searches for the next transformable term and returns it + * @return A Term, which is the next to be transformed + */ + public SynDiaElem getSdeFromNextStep() { + + for (SynDiaElem sde : transMap.keySet()) + + if (transMap.get(sde) != null) { + + return this.getLastPossibleParent(sde); + } + + return null; + } + + /** + * Searches for the next possible transformation step and performs it. If a + * redo is possible on the ActionStack, this step will be performed. + * + * @return True, if it was possible to perform the found step + */ + public boolean performNextStep() { + + for (SynDiaElem sde : transMap.keySet()) { + + if (transMap.get(sde) != null) { + + SynDiaElem newsde = getLastPossibleParent(sde); + + TransStep ts = new TransStep(newsde, transMap); + try { + + this.actionStack.perform(ts); + transMap.notifyObservers(); + + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + return true; + + } + //} + } + return false; + } + + /** + * @return true, if all steps are done + * + */ + public boolean performAllSteps() { + + while (actionStack.isRedoPossible()) { + + try { + actionStack.redo(); + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + } + + while (this.hasNextStep()) { + for (SynDiaElem sde : transMap.keySet()) { + + if (transMap.get(sde) != null) { + + SynDiaElem newsde = getLastPossibleParent(sde); + + TransStep ts = new TransStep(newsde, transMap); + try { + this.actionStack.perform(ts); + + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + break; + + } + } + } + transMap.notifyObservers(); + return true; + + } + + + /** + * This function looks for the last parent of a syntax + * diagram element, which is not transformed + * + * @param sde the child syntax diagram element + * @return the last possible not transformed parent + */ + public SynDiaElem getLastPossibleParent(SynDiaElem sde) { + + SynDiaElem parent = sde.getParent(); + if (transMap.get(parent) != null) + return getLastPossibleParent(parent); + + else + return sde; + + } + + /** Transforms the given syntax diagram element + * @param sde A syntax diagram element, which is to be transformed + * @return true, if the tranformation was possible + */ + public boolean performChosenStep(SynDiaElem sde) { + + TransStep ts = new TransStep(sde, transMap); + try { + this.actionStack.perform(ts); + transMap.notifyObservers(); + } + catch (Exception e) { + + System.out.println("es konnte kein perform durchgeführt werden"); + } + return true; + } + + public boolean redo() { + + if (actionStack.isRedoPossible()) { + + try { + actionStack.redo(); + transMap.notifyObservers(); + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + + return true; + } + + return false; + } + + + /** + * Undo the last TransStep which is to find on the ActionStack + * @return true + */ + public boolean undoStep() { + + try { + this.actionStack.undo(); + transMap.notifyObservers(); + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + return true; + + } + + /** + * Undoes all TransSteps which are to find on the ActionStack + * @return true + */ + public boolean undoAllSteps() { + + try { + while (actionStack.isUndoPossible()) + this.actionStack.undo(); + transMap.notifyObservers(); + } + catch (Exception e) { + + System.out.println("es konnte kein redo durchgeführt werden"); + } + + return true; + + } + + +} diff --git a/src/org/jalgo/module/ebnf/controller/trans/TransStep.java b/src/org/jalgo/module/ebnf/controller/trans/TransStep.java new file mode 100644 index 0000000..2e20722 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/trans/TransStep.java @@ -0,0 +1,58 @@ +/** + * + */ +package org.jalgo.module.ebnf.controller.trans; + +import org.jalgo.module.ebnf.util.IAction; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.ebnf.Term; + + +import java.util.Map; + + + +/** + * @author Andre + * + */ +public class TransStep implements IAction { + + /** + * Represents the element to be transformed + */ + SynDiaElem transElem; + /** + * Represents the term associated to the syntax diagram element + */ + Term transTerm; + /** + * the map where these associations are held + */ + TransMap transMap; + + + /** Initializes the paramaters + * @param sde A syntax diagram element + * @param transMap The transMap + */ + public TransStep(SynDiaElem sde, TransMap transMap) { + + this.transElem = sde; + this.transMap = transMap; + this.transTerm = transMap.get(sde); + } + + public void perform() { + + transMap.put(transElem, null); + + } + + public void undo() { + + transMap.put(transElem, transTerm); + + } +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.java new file mode 100644 index 0000000..d5926b6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/AlgorithmStartAction.java @@ -0,0 +1,81 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmAlreadyStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This class represents a step in the WordAlgorithm. The specific step is the + * begin of the algorithm. It's the first step. + * + * @author Claas Wilke + * + */ +public class AlgorithmStartAction extends WordAlgoAction { + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + */ + public AlgorithmStartAction(WordAlgoModel myModel, Boolean arg) { + super(myModel, arg); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmAlreadyStartedException { + if (!myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished()) { + // Start Algorithm + myModel.enableAlgorithmRunning(); + // Change Explanation + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_AlgorithmStart")); + // Change Position (if Diagram contains Elements) + if (myModel.getPosition() instanceof Concatenation) { + Concatenation actualConcat = (Concatenation) myModel + .getPosition(); + if (actualConcat.getNumberOfElems() > 0) { + myModel.setPosition(actualConcat.getSynDiaElem(0)); + myModel.disablePositionBehind(); + } else { + // Else the positions stays the same but is now behind the + // Concatenation. + myModel.setPosition(actualConcat); + myModel.enablePositionBehind(); + } + } + // Add second part toExplanation + isOnlyExitReachable(); + } else + throw new AlgorithmAlreadyStartedException( + "The Algorithm was already started."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Change Warning + myModel.setWarning(oldWarning); + // Change Position + myModel.setPosition(startPosition); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before undo of " + + "AlgorithmStartAction."); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Entries b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..f31459e --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Entries @@ -0,0 +1,12 @@ +/AlgorithmStartAction.java/1.1/Fri Aug 11 16:40:33 2006// +/JumpToDiagramAction.java/1.1/Fri Aug 11 16:40:33 2006// +/LeaveDiagramAction.java/1.1/Fri Aug 11 16:40:33 2006// +/ReturnToDiagramAction.java/1.1/Fri Aug 11 16:40:33 2006// +/SplitAction.java/1.1/Fri Aug 11 16:40:33 2006// +/TerminalAction.java/1.1/Fri Aug 11 16:40:33 2006// +/VariableAction.java/1.1/Fri Aug 11 16:40:33 2006// +/WordAlgoAction.java/1.1/Fri Aug 11 16:40:33 2006// +/WordAlgorithmController.java/1.1/Fri Aug 11 16:40:33 2006// +/WordGenerator.java/1.1/Fri Aug 11 16:40:33 2006// +/WordParser.java/1.1/Fri Aug 11 16:40:33 2006// +D/exceptions//// diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Repository b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..6f1f902 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/wordalgorithm diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Root b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.java new file mode 100644 index 0000000..0aa8cd3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/JumpToDiagramAction.java @@ -0,0 +1,116 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.Variable; + +/** + * This class represents a step in the WordAlgorithm. The specific step is a + * jump to another SyntaxDiagram. + * + * @author Claas Wilke + * + */ +public class JumpToDiagramAction extends WordAlgoAction { + + // Needed to rebuilt status after undo() + private boolean oldIsJumpToDiagram; + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + */ + public JumpToDiagramAction(WordAlgoModel myModel, SyntaxDiagram arg) { + super(myModel, arg); + + // Save status + oldIsJumpToDiagram = myModel.isJumpToDiagram(); + + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, + CantPerformStepException { + if (myModel.isAlgorithmRunning()) { + // Test if Diagram can be reached from actual Position. + // The Action warns if the user jumps to the wrong Diagram. + // (Just if warnings are enabled.) + if (myModel.getPosition() instanceof Variable + && myModel.isJumpToDiagram() + && !myModel.isPositionBehindElem()) { + // If Diagram can be reached, perform step. + SyntaxDiagram actualDiagram = (SyntaxDiagram) arg; + // Warning? + if (!actualDiagram.getName().equals( + ((Variable) startPosition).getLabel())) { + myModel.setWarning(Messages.getString("ebnf", + "WordAlgo.Warning_JumpToDiagram")); + throw new CantPerformStepException( + "The clicked Diagram not euqals to the name of " + + "the Variable left."); + } else + myModel.setWarning(""); + // Specifies, that the JumpToTheDiagram is finished. + // The algorithm can return to the Variable now. + myModel.disableJumpToDiagram(); + myModel.disableStackHighlighted(); + // Change Explanation + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_JumpToDiagram")); + // Change Position + Concatenation rootConcat = actualDiagram.getRoot(); + // Checkout if rootConcat contains elements. + // If true, new position is first Element in root Concat + if (rootConcat.getNumberOfElems() > 0) { + myModel.disablePositionBehind(); + myModel.setPosition(rootConcat.getSynDiaElem(0)); + } else { + // Else the positions stays the same but is now behind the + // Concatenation. + myModel.enablePositionBehind(); + myModel.setPosition(rootConcat); + } + } else + throw new CantPerformStepException( + "The clicked Diagram can not be reached."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before click on Diagram."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning()) { + // Undo running and finished status + super.undoBooleans(); + // Change Explanation + myModel.setExplanation(oldExplanation); + myModel.enableStackHighlighted(); + // Warnings ? + myModel.setWarning(oldWarning); + // Change Position + myModel.setPosition(startPosition); + if (myModel.isJumpToDiagram() != oldIsJumpToDiagram) { + if (oldIsJumpToDiagram) + myModel.enableJumpToDiagram(); + else + myModel.disableJumpToDiagram(); + } + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before redo click on Diagram."); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.java new file mode 100644 index 0000000..ee85eec --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/LeaveDiagramAction.java @@ -0,0 +1,137 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This class represents a step in the WordAlgorithm. The specific step is the + * leaving of a SyntaxDiagram. + * + * @author Claas Wilke + * + */ +public class LeaveDiagramAction extends WordAlgoAction { + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + */ + public LeaveDiagramAction(WordAlgoModel myModel, Variable arg) { + super(myModel, arg); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, Exception { + if (myModel.isAlgorithmRunning()) { + // Check if the end of the Diagram could be reached from + // the actual Position. + // if noElementReachable, leaving Diagram was already performed + if (myModel.isEndReached() && !myModel.isNoElementReachable()) { + // If End can be reached, perform step. + // Check if there is a return adress on the Stack + if (!myModel.isStackEmpty()) { + // If true, perform step leave a Diagram. + // Change Explanation + myModel + .setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramWithAdress")); + } else { + // If there is no adress on the Stack, the algorithm + // terminates. + // Terminate Algorithm + myModel.disableAlgorithmRunning(); + myModel.enableAlgorithmFinished(); + // , check if + // actual position is in StartDiagram. + SyntaxDiagram startDiagram = myModel + .getSynDiaSystem() + .getSyntaxDiagram( + myModel.getSynDiaSystem().getStartDiagram()); + // If the actual Element is in the StartDiagram, the + // algorithm terminates + // successfully. + if (myModel.isElementInDiagram(myModel.getPosition(), + startDiagram)) { + // Checkout if Word is completly generated. + if (myModel.getWord().equals("") + || myModel.getWord() + .equals(myModel.getOutput())) { + myModel + .setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagram")); + myModel.enableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithSuccess")); + } + // Else terminate also unsuccessfully + else { + myModel + .setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagram")); + myModel.disableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2")); + } + } + // Else the algorithm terminates with a fault. + else { + myModel + .setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagram")); + myModel.disableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess")); + } + } + // Change Position + myModel.enablePositionBehind(); + myModel.setPosition(myModel.getPosition().getMySyntaxDiagram() + .getRoot()); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + } else + throw new CantPerformStepException( + "The end of the actual Diagram is unreachable."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before leaving Diagram."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Enable algorithm (could be finished during perform()). + myModel.enableAlgorithmRunning(); + myModel.disableAlgorithmFinished(); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Change Warning + myModel.setWarning(oldWarning); + // Change Position + myModel.setPosition(startPosition); + // Change algorithm Status + myModel.disableAlgorithmFinished(); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started or finished before redo leaving Diagram."); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.java new file mode 100644 index 0000000..b1dd061 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/ReturnToDiagramAction.java @@ -0,0 +1,110 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import java.awt.Color; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This class represents a step in the WordAlgorithm. The specific step is the + * return from a SyntaxDiagram toanother pushed on the Stack + * before. + * + * @author Claas Wilke + * + */ +public class ReturnToDiagramAction extends WordAlgoAction { + + // need to have this step undone. + private Variable oldVarOnStack; + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + * @param aVar + * The Variable the algorithm should return to. + */ + public ReturnToDiagramAction(WordAlgoModel myModel, Variable aVar) { + super(myModel, aVar); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, + CantPerformStepException { + // Step can be just performed, if the algorithm is running and wasn't + // finished (successfully or not). + if (myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished()) { + // Check if the end of the Diagram could be reached from + // the actual Position. + // The Variable must be left before. Checked by isJumpToDiagram + // (true if not finished). Else throw an Exception + if (myModel.isEndReached() && !myModel.isJumpToDiagram()) { + // If End can be reached, perform step. + Variable actualVariable = (Variable) arg; + // Pop Variable from Stack + oldVarOnStack = myModel.popFromStack(); + // Warning? + if (actualVariable != oldVarOnStack) { + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Warning_ReturnToDiagram")); + myModel.enableStackHighlighted(Color.RED); + // repush Adress + myModel.pushToStack(oldVarOnStack); + throw new CantPerformStepException( + "The clicked Return adress doesn't euqal to the " + + "hightest Return adress on the Stack."); + } else + myModel.setWarning(""); + // Change Explanation + myModel + .setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_ReturnToDiagram")); + myModel.disableStackHighlighted(); + // Change Position + SynDiaElem positionNew = myModel + .getPositionBehind(actualVariable); + myModel.setPosition(positionNew); + // Add second part to Explanation + isOnlyExitReachable(); + } else + throw new CantPerformStepException( + "The clicked Variable is unreachable."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before click on Variable."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Change Stack + myModel.pushToStack(oldVarOnStack); + // Change Position + myModel.setPosition(startPosition); + // Warnings ? + myModel.setWarning(oldWarning); + // Change finished status + myModel.disableAlgorithmFinished(); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before redo click on Variable."); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.java new file mode 100644 index 0000000..1a50f56 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/SplitAction.java @@ -0,0 +1,92 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; + +/** + * This class represents a step in the WordAlgorithm. The specific step is a + * Click on an empty Concatenation in a Branch or Repetition. + * + * @author Claas Wilke + * + */ +public class SplitAction extends WordAlgoAction { + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + * @param parentElem + * The parenElem of the Concatenation clicked on. Could be a + * Repetition or a Branch. + * @param aConcat + * The Concatenation clicked on. + */ + public SplitAction(WordAlgoModel myModel, Concatenation aConcat) { + super(myModel, aConcat); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, + CantPerformStepException { + // Step can be just performed, if the algorithm is running and wasn't + // finished (successfully or not). + if (myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished()) { + Concatenation actualConcat = (Concatenation) arg; + // Test if Concatenation can be reached from actual Position + // and contains no SynDiaElems. + // Else throw Exception + if (myModel.isElementReachable(actualConcat) + && !myModel.isJumpToDiagram() + && actualConcat.getNumberOfElems() == 0) { + // If Concatenation can be reached, perform step. + + // Change Explanation + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_Split")); + + // Change Position + SynDiaElem positionNew = myModel + .getPositionBehind(actualConcat); + myModel.setPosition(positionNew); + // Add second part toExplanation + isOnlyExitReachable(); + } else + throw new CantPerformStepException( + "The clicked Concatenation is unreachable or is not empty."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before click on Concatenation."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Change Warning + myModel.setWarning(oldWarning); + // Change Position + myModel.setPosition(startPosition); + // Change FinishedStatus + myModel.disableAlgorithmFinished(); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before redo click on Concatenation."); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.java new file mode 100644 index 0000000..f3eadfc --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/TerminalAction.java @@ -0,0 +1,108 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; + +/** + * This class represents a step in the WordAlgorithm. The specific step is the + * passing of a TerminalSymbol. + * + * @author Claas Wilke + * + */ +public class TerminalAction extends WordAlgoAction { + + // This String saves the old output. Needed for undo-method. + protected final String oldOutput; + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + */ + public TerminalAction(WordAlgoModel myModel, TerminalSymbol arg) { + super(myModel, arg); + this.oldOutput = myModel.getOutput(); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, + CantPerformStepException { + // Step can be just performed, if the algorithm is running and wasn't + // finished (successfully or not). + if (myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished()) { + TerminalSymbol actualTerminal = (TerminalSymbol) arg; + // Test if TerminalSymbol can be reached from actual Position + // Else throw Exception + if (myModel.isElementReachable(actualTerminal) + && !myModel.isJumpToDiagram()) { + // If TerminalSymbol can be reached, perform step. + // Change Output + String tempOutput = myModel.getOutput(); + tempOutput = tempOutput + actualTerminal.getLabel(); + myModel.setOutput(tempOutput); + + // Change Explanation + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_Terminal")); + + + // Change Position + SynDiaElem positionNew = myModel + .getPositionBehind(actualTerminal); + myModel.setPosition(positionNew); + // Add second part toExplanation + isOnlyExitReachable(); + + // Warnings ? + // If inputword is not null and Output != Beginn of Input + // a warning is generated. + if (!myModel.getWord().equals("") + && !myModel.getWord().startsWith(myModel.getOutput())) { + myModel.setWarning(Messages.getString("ebnf", + "WordAlgo.Warning_Terminal")); + // The algorithm is finished unsuccessfully. + myModel.disableAlgorithmRunning(); + myModel.enableAlgorithmFinished(); + } else + myModel.setWarning(""); + + } else + throw new CantPerformStepException( + "The clicked TerminalSymbol is unreachable."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before click on TerminalSymbol."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Change Output + myModel.setOutput(oldOutput); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Warnings ? + myModel.setWarning(oldWarning); + // Change Position + myModel.setPosition(startPosition); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before redo click on Terminal."); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.java new file mode 100644 index 0000000..1309ecc --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/VariableAction.java @@ -0,0 +1,97 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.AlgorithmNotStartedException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.CantPerformStepException; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This class represents a step in the WordAlgorithm. The specific step is the + * passing of a Variable. + * + * @author Claas Wilke + * + */ +public class VariableAction extends WordAlgoAction { + + private boolean oldIsJumpToDiagram; + + /** + * Constructor which sets the Model and the argument, the + * WordAlgoAction should work with. + * + * @param myModel + * The WordAlgoAction should work with. + */ + public VariableAction(WordAlgoModel myModel, Variable arg) { + super(myModel, arg); + + oldIsJumpToDiagram = myModel.isJumpToDiagram(); + } + + /** + * This method performs the Action implemented by this + * WordAlgoAction. + */ + public void perform() throws AlgorithmNotStartedException, + CantPerformStepException { + // Step can be just performed, if the algorithm is running and wasn't + // finished (successfully or not). + if (myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished() + && !myModel.isJumpToDiagram()) { + Variable actualVariable = (Variable) arg; + // Test if Variable can be reached from actual Position + // Else throw Exception + if (myModel.isElementReachable(actualVariable)) { + // If VariableSymbol can be reached, perform step. + // Change Explanation + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.Explanation_Variable")); + // Change Stack + myModel.pushToStack(actualVariable); + myModel.enableStackHighlighted(); + // Change Position + myModel.setPosition(actualVariable); + myModel.disablePositionBehind(); + // Specifies, that the JumpToTheDiagram is not finished yet. + // The algorithm can't return to the Variable yet. + myModel.enableJumpToDiagram(); + } else + throw new CantPerformStepException( + "The clicked Variable is unreachable."); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before click on Variable."); + } + + /** + * This method can make the Action undone performed by this + * WordAlgoAction. + */ + public void undo() throws AlgorithmNotStartedException { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // Undo running and finished status + super.undoBooleans(); + // Change Explanation + myModel.setExplanation(oldExplanation); + // Change Warning + myModel.setWarning(oldWarning); + // Change Stack + myModel.popFromStack(); + myModel.disableStackHighlighted(); + // Specifies, that the JumpToTheDiagram is not finished yet. + // The algorithm can't return to the Variable yet. + if (myModel.isJumpToDiagram() != oldIsJumpToDiagram) { + if (oldIsJumpToDiagram) + myModel.enableJumpToDiagram(); + else + myModel.disableJumpToDiagram(); + } + // Change Position + myModel.setPosition(startPosition); + } else + throw new AlgorithmNotStartedException( + "The algorithm was not started before redo click on Variable."); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.java new file mode 100644 index 0000000..f6205e6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgoAction.java @@ -0,0 +1,185 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.util.IAction; + +/** + * The class WordAlgoAction represents an abstract Action + * performed during the WordAlgorithm. Each Action can be undone. Each + * WordAlgoAction has to know its model to perform changes. + * + * @author Claas Wilke + * + */ +public abstract class WordAlgoAction implements IAction { + + protected WordAlgoModel myModel; + + // The Position at which the algorihm was in the Diagram before this + // Action was performed. + protected final SynDiaElem startPosition; + + protected final boolean wasPositionBehindElem; + + protected final boolean oldRunningStatus; + + protected final boolean oldFinishedStatus; + protected final boolean oldFinishedWithSuccessStatus; + + // This String saves the old explanation. Needed for undo-method. + protected final String oldExplanation; + + // This String saves the old warning. Needed for undo-method. + protected final String oldWarning; + + // argument can be a SyntaxDiagram, a Variable or a TerminalSymbol. + protected Object arg; + + /** + * The Constructor constructs a new WordAlgoAction. Each + * WordAlgoAction has to know its model to perform changes. + * + * @param myModel + * The model, the WordAlgoAction will know. + * @param arg + * The argument, the WordAlgoAction should work + * with. Argument can be a SyntaxDiagram, a + * Variable or a TerminalSymbol. + */ + public WordAlgoAction(WordAlgoModel myModel, Object arg) { + this.myModel = myModel; + this.arg = arg; + // Saves some old values which can be resetted during undo() + this.startPosition = myModel.getPosition(); + this.oldExplanation = myModel.getExplanation(); + this.oldWarning = myModel.getWarning(); + this.wasPositionBehindElem = myModel.isPositionBehindElem(); + this.oldRunningStatus = myModel.isAlgorithmRunning(); + this.oldFinishedStatus = myModel.isAlgorithmFinished(); + this.oldFinishedWithSuccessStatus = myModel.isFinishedWithSuccess(); + + } + + /** + * The operation that should be performed by the WordAlgoAction. + * + */ + public void perform() throws Exception { + } + + /** + * The operation that can do the perform operation undone. + * + */ + public void undo() throws Exception { + } + + /** + * Method can be used to reset some booleans during undo. Booleans undone: + * algorithmRunngin status algorithmFinished status positionBehind element + * status + * + */ + public void undoBooleans() { + if (this.oldRunningStatus) + myModel.enableAlgorithmRunning(); + else + myModel.disableAlgorithmRunning(); + + if (this.oldFinishedStatus) + myModel.enableAlgorithmFinished(); + else + myModel.disableAlgorithmFinished(); + + if (this.wasPositionBehindElem) + myModel.enablePositionBehind(); + else + myModel.disablePositionBehind(); + + if (this.oldFinishedWithSuccessStatus) + myModel.enableFinishedWithSuccess(); + else + myModel.disableFinishedWithSuccess(); +} + + /** + * Method checks if only the exit of a Diagram can be reached from the + * actual position. If true, the leaving of the diagram is performed. A + * second part ist added to the Explanation, wether or not the Diagram must + * be left. + * + */ + protected void isOnlyExitReachable() { + if (myModel.isNoElementReachable() && myModel.isEndReached()) { + try { + // Perform a leaving of the diagram. + // Check if there is a return adress on the Stack + if (!myModel.isStackEmpty()) { + // If true, perform step leave a Diagram. + // Change Explanation + myModel.getExplanation(); + myModel + .setExplanation(myModel.getExplanation() + + "\n" + + Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramWithAdress")); + } else { + // If there is no adress on the Stack, the algorithm + // terminates. + // Terminate Algorithm + myModel.disableAlgorithmRunning(); + myModel.enableAlgorithmFinished(); + // , check if + // actual position is in StartDiagram. + SyntaxDiagram startDiagram = myModel + .getSynDiaSystem() + .getSyntaxDiagram( + myModel.getSynDiaSystem().getStartDiagram()); + // If the actual Element is in the StartDiagram, the + // algorithm terminates + // successfully. + if (myModel.isElementInDiagram(myModel.getPosition(), + startDiagram)) { + // Checkout if Word is completly generated. + if (myModel.getWord().equals("") + || myModel.getWord() + .equals(myModel.getOutput())) { + myModel.enableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithSuccess")); + } + // Else the algorithm terminates unsuccessfully. + else { + myModel.disableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2")); + } + } + // Else the algorithm terminates with a fault. + else { + myModel.disableFinishedWithSuccess(); + myModel + .setWarning(Messages.getString("ebnf", + "WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess")); + } + } + } catch (ElementNotFoundException e) { + // This exception is not handled. Cant happen during algorithm + // If the StartDiagram can't be getted, everything must have + // been wrong before. + } + + } else { + myModel.setExplanation(myModel.getExplanation() + "\n" + + Messages.getString("ebnf", + "WordAlgo.Explanation_ContinueDiagram")); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.java new file mode 100644 index 0000000..f81421e --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordAlgorithmController.java @@ -0,0 +1,883 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.InitializationFailedException; +import org.jalgo.module.ebnf.gui.wordalgorithm.GuiController; +import org.jalgo.module.ebnf.model.syndia.*; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.util.*; +import java.util.List; +import java.util.Observer; +import java.awt.Cursor; +import java.awt.Font; + +import javax.swing.JPanel; + +/** + * This controller manages the interaction between the Algorithm-GUI and the + * Algorithm-Model. + * + * It also controlls the algorithm by generating AlgorithmActions. + * + * @author Claas Wilke + */ +public class WordAlgorithmController { + + // ActionStack is used to push and pop Actions to have the possibility + // of having steps undone and redone during algorithm. + private ActionStack myActionStack; + + // Model during Algorithm (word, output, Stack etc) + private WordAlgoModel myModel; + + private MainController mainController; + + private ModuleConnector moduleConnector; + + // Used during mouseOver events. + // Needed to reconstruct the Explanations after MouseOver + private String oldExplanation; + + private String oldWarning; + + private boolean oldStackHighlightStatus; + + // Must have this reference to beware the guiController is not + // thrown into the GarbageCollector. + @SuppressWarnings("unused") + private GuiController guiController; + + // neded to parse Words end check if they only contain + // TerminalSymbols. + private WordParser myParser; + + /** + * Creates a new WordAlgorithmController + * + * @param mainController + * The MainController which controlles the + * EBNF-Module. Should be the Creator of this GuiController. + * @param moduleConnector + * The ModuleConnector. + * @param mySynDiaSystem + * The SynDiaSystem which should used during the algorithm. + * @throws InitiliazationFaildException if an error occurs + * during initialization. + */ + public WordAlgorithmController(MainController mainController, + ModuleConnector moduleConnector, SynDiaSystem mySynDiaSystem) + throws InitializationFailedException { + // The Attributes are initialized. + // If initialization fails, an Exception is thrown. + try { + myModel = new WordAlgoModel(mySynDiaSystem); + initialize(); + } catch (InitializationFailedException e) { + throw e; + } + + this.mainController = mainController; + this.moduleConnector = moduleConnector; + } + + /** + * Creates a new WordAlgorithmController with a GuiController. + * + * If initilization fails, the WordAlgorithmController is switching back to + * SynDiaView. + * + * @param mainController + * The MainController which controlles the + * EBNF-Module. Should be the Creator of this + * GuiController. + * @param moduleConnector + * The ModuleConnector. + * @param contentPane + * The JPanel the GuiController + * should use to paint its output. + * @param mySynDiaSystem + * The SynDiaSystem which should used during the algorithm. + */ + public WordAlgorithmController(MainController mainController, + ModuleConnector moduleConnector, JPanel contentPane, + SynDiaSystem mySynDiaSystem) { + + // Curser is changed to waiting + contentPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + + // The Attributes are initialized. + // If initialization fails, an Exception is thrown. + try { + myModel = new WordAlgoModel(mySynDiaSystem); + initialize(); + } catch (InitializationFailedException e) { + System.out.println(e.getMessage()); + System.out.println("Switch back to SynDiaView."); + guiController.switchToSynDiaView(); + } + + this.mainController = mainController; + this.moduleConnector = moduleConnector; + + // Disable saveSettings + this.moduleConnector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + + // Create GuiController + this.guiController = new GuiController(contentPane, mySynDiaSystem, + this); + + // Rechange Curser to default after initilization + contentPane + .setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + + /** + * Initializes the WordAlgorithmController. Used by the Constructor. + * + */ + private void initialize() { + // Creates a new ActionStack used during algorithm. + myActionStack = new ActionStack(); + + myParser = new WordParser(myModel); + + oldExplanation = ""; + oldWarning = ""; + oldStackHighlightStatus = false; + } + + /** + * This method returns the running status of the algorithm. + * + * @return True if Algorithm is already started. + */ + public Boolean isAlgorithmRunning() { + return myModel.isAlgorithmRunning(); + } + + /** + * This method returns the finished status of the algorithm. + * + * @return True if Algorithm is already finished. + */ + public Boolean isAlgorithmFinished() { + return myModel.isAlgorithmFinished(); + } + + /** + * This method returns the warnings status of the algorithm. + * + * @return True if warnings are enabled. + */ + public Boolean isWarningsOn() { + return myModel.isWarningsOn(); + } + + /** + * This method returns true, if a redo is possible. + * + * @return True if a redo is possible. + */ + public Boolean isRedoPossible() { + return myActionStack.isRedoPossible(); + } + + /** + * This method returns true, if a undo is possible. + * + * @return True if a undo is possible. + */ + public Boolean isUndoPossible() { + return myActionStack.isUndoPossible(); + } + + /** + * This method returns true, if the algorithm is during a Jump to a Diagram. + * + * @return True if the algorithm is during a Jumpt to a Diagram. + */ + public Boolean isJumpToDiagram() { + return myModel.isJumpToDiagram(); + } + + /** + * This method returns true, if the algorithm can reach the end of a + * Diagram. + * + * @return True if the algorithm can reach the end of a Diagram. + */ + public Boolean isEndReached() { + return myModel.isEndReached(); + } + + /** + * This method returns true, if the algorithm can only reach the end of a + * Diagram. + * + * @return True if the algorithm can only reach the end of a Diagram. + */ + public Boolean isOnlyEndReachable() { + return (myModel.isEndReached() && myModel.isNoElementReachable()); + } + + /** + * This method returns true, if the algorithm can reach a + * SynDiaElem. + * + * @param aSynDiaElem + * The SynDiaElem that should be reached + * @return True, if the algorithm can reach a SynDiaElem. + */ + public Boolean isElementReachable(SynDiaElem aSynDiaElem) { + return myModel.isElementReachable(aSynDiaElem); + } + + /** + * This method returns true, if the aSynDiaElem is in + * aDiagram. + * + * @param aSynDiaElem + * The SynDiaElem that should be in a + * aDiagram + * @param aDiagram + * The SyntaxDiagram, aSynDiaElem + * should be in. + * @return True, if the algorithm can reach a SynDiaElem. + */ + public Boolean isElementInDiagram(SynDiaElem aSynDiaElem, + SyntaxDiagram aDiagram) { + return myModel.isElementInDiagram(aSynDiaElem, aDiagram); + } + + /** + * This method returns true, if the actual position in behind an Element. + * + * @return True if the actual position in behind an Element. + */ + public Boolean isPositionBehindElem() { + return myModel.isPositionBehindElem(); + } + + /** + * This method returns true, if aWord is a String which only + * contains valid TerminalSymbols of the Controllers + * WordAlgoModel. + * + * @param word + * The String which should be checked. + * @return True if aWord only contains valid + * TerminalSymbols. + */ + public Boolean isWordValid(String aWord) { + return myParser.isWordValid(aWord); + } + + /** + * This method returns the word which should be generated by the algorithm. + * + * @return The word which should be generated + */ + public String getWord() { + return myModel.getWord(); + } + + /** + * This method returns the word which was already generated by the algoritm. + * + * @return The word which was already generated. + */ + public String getOutput() { + return myModel.getOutput(); + } + + /** + * This method returns the explanation of the actual algorithm step. + * + * @return The explanation of the actual step. + */ + public String getExplanation() { + return myModel.getExplanation(); + } + + /** + * This method returns the last warning generated by the algorithm. (Only if + * warnings are enabled). + * + * @return Last warning generated during algorithm. + */ + public String getWarning() { + return myModel.getWarning(); + } + + /** + * This method returns the actual position in a SyntaxDiagram during + * algorithm. + * + * @return Actual algorithm position in a SyntaxDiagram. + */ + public SynDiaElem getPosition() { + return myModel.getPosition(); + } + + /** + * This method returns the SynDiaSystem used by the algorithm. + * + * @return The SynDiaSystem used by the algorithm. + */ + public SynDiaSystem getSynDiaSystem() { + return myModel.getSynDiaSystem(); + } + + /** + * This method returns the return marks of all Variables pushed on the Stack + * starting with the oldest. + * + * @return List containing return marks (int). + */ + public List getAdressNumbersFromStack() { + return myModel.getAdressNumbersFromStack(); + } + + /** + * This method returns the adress number for a specific Variable used as + * return adress during the algorithm. + * + * @param var + * The Variable which return adress should be returned. + */ + public Number getAdressNumber(Variable var) { + return myModel.getAdressNumber(var); + } + + /** + * Returns the Font installed by the MainController to print + * EBNF-Definitions. + * + * @return Returns the Font installed by the MainController to print + * EBNF-Definitions. + */ + public Font getEbnfFont() { + return mainController.getEbnfFont(); + } + + /** + * Returns the ModuelConnector. + * + * @return Returns the ModuelConnector. + */ + public ModuleConnector getModuleConnector() { + return moduleConnector; + } + + /** + * Returns the MainController. + * + * @return Returns the MainController. + */ + public MainController getMainController() { + return mainController; + } + + /** + * This method enables warnings during algorithm. + */ + public void enableWarnings() { + myModel.enableWarnings(); + } + + /** + * This method disables warnings during algorithm. + * + */ + public void disableWarnings() { + myModel.disableWarnings(); + } + + /** + * This method sets the word which should be generated by the algorithm. + * + * @param word + * The word which should be generated. + */ + public void setWord(String word) { + myModel.setWord(word); + } + + /** + * This method adds an Observer to the ObserverList of the + * ActionStack. + * + * @param anObserver + * The Observer that should be added. + */ + public void addActionStackObserver(Observer anObserver) { + myActionStack.addObserver(anObserver); + } + + /** + * This method adds an Observer to the ObserverList of the + * Model used during algorithm. + * + * @param anObserver + * The Observer that should be added. + */ + public void addModelObserver(Observer anObserver) { + myModel.addObserver(anObserver); + } + + /** + * This method makes a step in the algorithm undone if possible. + * + * @return True, if Undo was peformed successfully. + */ + public boolean undo() { + try { + myActionStack.undo(); + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if undo is not possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method redoes a step in the algorithm if possible. + * + * @return True, if redo was peformed successfully. + */ + public boolean redo() { + try { + myActionStack.redo(); + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if undo is not possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This mehtod performs the firs step in the algorithm. It starts the + * algorihm + * + * @return True, if Step was peformed successfully. + */ + public boolean startAlgorithm() { + try { + AlgorithmStartAction anAction = new AlgorithmStartAction(myModel, + null); + myActionStack.perform(anAction); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs a jump back to a Diagram left before. The user can + * also return to a Diagram not pushed onto the Stack before. The algorithm + * will warn the user if warnings were enabled. + * + * @param aVariable + * The Variable the algorithm should return to. + * @return True, if Step was peformed successfully. + */ + public boolean returnToDiagram(Variable aVariable) { + try { + ReturnToDiagramAction anAction = new ReturnToDiagramAction(myModel, + aVariable); + myActionStack.perform(anAction); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs a jump during the algorithm from one Diagram + * toanother. The Action is pushed onto the ActionStack and + * can be made undone. The Action is just performed, if a jump is possible. + * + * @param aDiagram + * The Diagram, the algorithm should jump to. + * @return True, if Step was peformed successfully. + */ + public boolean jumpToDiagram(SyntaxDiagram aDiagram) { + try { + JumpToDiagramAction anAction = new JumpToDiagramAction(myModel, + aDiagram); + myActionStack.perform(anAction); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method implements the exit from a Diagram, if the actual Position is + * the end of a Diagram. + * + * @return True, if Step was peformed successfully. + */ + public boolean leaveDiagram() { + try { + LeaveDiagramAction anAction = new LeaveDiagramAction(myModel, null); + myActionStack.perform(anAction); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs the passing of a Variable during the + * Algorithm. The Action is pushed onto the ActionStack and + * can be made undone. The Action is just performed, if the Variable could + * be reached. + * + * @param aVar + * The Variable the algorithm should pass. + * @return True, if Step was peformed successfully. + */ + public boolean gotoVariable(Variable aVar) { + try { + VariableAction anAction = new VariableAction(myModel, aVar); + myActionStack.perform(anAction); + // OldExplanation must be changed + // To prevent wrong Explanation after MouseOver + this.oldExplanation = myModel.getExplanation(); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs the passing of a TerminalSymbol + * during the algorithm. The Action is pushed onto the + * ActionStack and can be made undone. The Action is just + * performed, if the Variable could be reached. + * + * @param aTerminal + * The TerminalSymbol the algorithm should pass. + * @return True, if Step was peformed successfully. + */ + public boolean gotoTerminal(TerminalSymbol aTerminal) { + try { + TerminalAction anAction = new TerminalAction(myModel, aTerminal); + myActionStack.perform(anAction); + // OldExplanation must be changed + // To prevent wrong Explanation after MouseOver + this.oldExplanation = myModel.getExplanation(); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs the passing of a Concatenation in a + * Branch or Repetition during the algorithm. + * The Action is pushed onto the ActionStack and can be made + * undone. The Action is just performed, if the Variable could be reached. + * + * @param aConcat + * The Concatenation clicked on. + * @return True, if Step was peformed successfully. + */ + public boolean gotoSplit(Concatenation aConcat) { + try { + SplitAction anAction = new SplitAction(myModel, aConcat); + myActionStack.perform(anAction); + // OldExplanation must be changed + // To prevent wrong Explanation after MouseOver + this.oldExplanation = myModel.getExplanation(); + // The Observers must be informed, that model has changed. + myModel.notifyObservers(); + return true; + } + // Exceptions are thrown by the ActionStack if startAlgorithm is not + // possible. + // These Exceptions arent handled. + catch (Exception e) { + myModel.notifyObservers(); + return false; + } + } + + /** + * This method performs an MouseOverEvent over a Variable a + * TerminalSymbol or a + * Concatenation>. (The Entry onto the Element) Changes + * the Explanation. + * + * @param myCaller + * The SynDiaElem which caused the MouseOverEvent. + * @param alternativeMode + * If true, if myCaller is a Variable, the + * MouseOverEvent is handled as a Event over a ReturnAdress. + * @return true if the Element of the MouseOverEvent could be reached. + * + */ + public boolean overElementEntry(SynDiaElem myCaller, boolean alternativeMode) { + + // Save oldExplanation for method overElementExit + oldExplanation = myModel.getExplanation(); + oldWarning = myModel.getWarning(); + oldStackHighlightStatus = myModel.isStackHighlighted(); + + boolean result = false; + + if (myCaller instanceof Variable) { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // If it is no return adress event + if (!alternativeMode) { + // If Element can be reached. + if (myModel.isElementReachable(myCaller) + && !myModel.isJumpToDiagram()) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_Variable")); + result = true; + } + } else { + if (isOnlyEndReachable() && !myModel.isJumpToDiagram()) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_ReturnAdress")); + myModel.enableStackHighlighted(); + result = true; + } + } + } + } + + if (myCaller instanceof TerminalSymbol) { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + // If Element can be reached. + if (myModel.isElementReachable(myCaller)) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_Terminal")); + result = true; + } + } + } + + if (myCaller instanceof Concatenation) { + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + Concatenation aConcat = (Concatenation) myCaller; + // If Element can be reached. + if (myModel.isElementReachable(myCaller) + && aConcat.getNumberOfElems() == 0) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_Split")); + result = true; + } + } + } + myModel.notifyObservers(); + return result; + + } + + /** + * This method performs an MouseOverEvent over a SyntaxDiagram. + * (The Entry onto the Element) Changes the Explanation. + * + * @param myCaller + * The SyntaxDiagram which caused the + * MouseOverEvent. + * @param alternativeMode + * If true, if myCaller is a Variable, the + * MouseOverEvent is handled as a Event over a ReturnAdress. + * @return true if the Element of the MouseOverEvent could be reached. + * + */ + @SuppressWarnings("static-access") + public boolean overElementEntry(SyntaxDiagram myCaller, + boolean alternativeMode) { + + // Save oldExplanation for method overElementExit + oldExplanation = myModel.getExplanation(); + oldWarning = myModel.getWarning(); + oldStackHighlightStatus = myModel.isStackHighlighted(); + + boolean result = false; + + if (myCaller instanceof SyntaxDiagram) { + if (myModel.isAlgorithmRunning()) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_Diagram")); + result = true; + } + } + + myModel.notifyObservers(); + return result; + + } + + /** + * This method performs an MouseOverEvent over the Exit of a + * SyntaxDiagram. (The Entry onto the Element) Changes the + * Explanation. + * + * @param myCaller + * The SyntaxDiagram which caused the + * MouseOverEvent. + * @return true if the Element of the MouseOverEvent can be reached. + */ + public boolean overSynDiaExitEntry(SyntaxDiagram myCaller) { + + // Save oldExplanation for method overElementExit + oldExplanation = myModel.getExplanation(); + + boolean result = false; + + // Algorithm must be runngin, end must be reachable but isn't reached + // yet + // and it must be the end of the diagram in which is the actual + // position. + if (myModel.isEndReached() && !isOnlyEndReachable()) { + if (myModel.isAlgorithmRunning() + && myModel.isElementInDiagram(myModel.getPosition(), + myCaller)) { + myModel.setExplanation(Messages.getString("ebnf", + "WordAlgo.MouseOver_DiagramExit")); + result = true; + } + } + + myModel.notifyObservers(); + return result; + + } + + /** + * This method performs an MouseOverEvent over a Variable or + * a TerminalSymbol, a + * Concatenation> or a SyntaxDiagram. + * (The Exit from the Element) Changes the Explanation. + * * + */ + public void overElementExit() { + + myModel.setExplanation(oldExplanation); + myModel.setWarning(oldWarning); + if (oldStackHighlightStatus) + myModel.enableStackHighlighted(); + else + myModel.disableStackHighlighted(); + myModel.notifyObservers(); + + } + + /** + * This method performs an MouseOverEvent over the end of a + * SyntaxDiagram. (The Exit from the Element) Changes the + * Explanation. + * + */ + public void overSynDiaExitExit() { + + myModel.setExplanation(oldExplanation); + myModel.notifyObservers(); + + } + + /** + * This method resets the algorithm. Throws InitializationFailedException if + * reinitialization fails. + * + * @throws InitializationFailedException + * if reinitialization fails. + */ + public void resetAlgorithm() throws InitializationFailedException { + try { + // ActionStack is cleared + myActionStack.clear(); + // and Model is reseted too. + myModel.reset(); + myModel.notifyObservers(); + } catch (InitializationFailedException e) { + System.out.println(e.getMessage()); + System.out + .println("Error occured during reset of Algorithm. Switch back to SynDiaView."); + guiController.switchToSynDiaView(); + } + } + + /** + * Performs a reswitch to SynDiaGui. + * + * Attention: This method does not reset the GUI. To reset the Gui, + * calle the GuiController which controlls the gui via his + * methos switchToSynDiaView(). + * + */ + public void switchToSynDiaView() { + // Switch to SynDiaView + mainController.setSynDiaDisplayMode(myModel.getSynDiaSystem()); + } + + /** + * Method can be used to set the Model status changed and notify its + * observers. + * + */ + public void notifyModelObservers() { + myModel.setModelChanged(); + myModel.notifyObservers(); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.java new file mode 100644 index 0000000..b74628a --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordGenerator.java @@ -0,0 +1,174 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import java.util.HashMap; +import java.util.Map; + +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.GenerateWordException; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; + +/** + * Generates a random word from a given syntax diagram system. + * + * @author Michael Thiele + * + */ +public class WordGenerator { + + private static int counter = 0; + + private SynDiaSystem sds; + + private String generatedWord; + + private Map repetitions; + + /** + * + * @param sds + * a syntax diagram system + */ + public WordGenerator(SynDiaSystem sds) { + this.sds = sds; + fillRepetitions(); + } + + private void fillRepetitions() { + repetitions = new HashMap(); + for (String name : sds.getLabelsOfVariables()) { + try { + Concatenation root = sds.getSyntaxDiagram(name).getRoot(); + fillRepetitions(root); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + System.exit(-1); + } + + } + } + + private void fillRepetitions(Concatenation concat) { + for (int i = 0; i < concat.getNumberOfElems(); i++) { + SynDiaElem sde = concat.getSynDiaElem(i); + if (sde instanceof Repetition) { + Repetition r = (Repetition) sde; + repetitions.put(r, 0.5); + fillRepetitions(r.getLeft()); + fillRepetitions(r.getRight()); + } else if (sde instanceof Branch) { + Branch b = (Branch) sde; + fillRepetitions(b.getLeft()); + fillRepetitions(b.getRight()); + } + } + } + + /** + * Starts the generator and returns a random word. + * + * @return a random word + * @throws GenerateWordException + */ + public String start() throws GenerateWordException { + try { + Concatenation root = sds.getSyntaxDiagram(sds.getStartDiagram()) + .getRoot(); + this.generatedWord = ""; + counter = 0; + this.walkThroughConcatenation(root); + return generatedWord; + } catch (ElementNotFoundException e) { + e.printStackTrace(); + System.exit(-1); + } + return null; + } + + private void walkThroughConcatenation(Concatenation concat) + throws GenerateWordException { + if (counter > 100 || generatedWord.length() > 120) + throw new GenerateWordException(); + // from the beginning to the end + for (int i = 0; i < concat.getNumberOfElems(); i++) { + SynDiaElem sde = concat.getSynDiaElem(i); + // TerminalSymbol - just add to generated word + if (sde instanceof TerminalSymbol) { + generatedWord += ((TerminalSymbol) sde).getLabel(); + counter++; + } + // Variable - jump to this diagram and walk through its root + else if (sde instanceof Variable) { + try { + Concatenation root = sds.getSyntaxDiagram( + ((Variable) sde).getLabel()).getRoot(); + walkThroughConcatenation(root); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + System.exit(-1); + } + } + // Branch - either take upper or lower path + else if (sde instanceof Branch) { + // lookahead, how much branches are on this way + double countUpper, countLower; + double chance; + Concatenation leftPath = ((Branch) sde).getLeft(); + Concatenation rightPath = ((Branch) sde).getRight(); + countUpper = countBranches(leftPath) + 1; + countLower = countBranches(rightPath) + 1; + if (countUpper > countLower) + chance = 1 - countLower / (countUpper + countLower); + else + chance = countUpper / (countLower + countUpper); + if (Math.random() < chance) { + // upper path + walkThroughConcatenation(leftPath); + } else { + // lower path + walkThroughConcatenation(rightPath); + } + } + // Repetition - take upper path and decide at the end whether to + // take lower path + else if (sde instanceof Repetition) { + walkThroughRepetition((Repetition) sde); + } + } + } + + private void walkThroughRepetition(Repetition r) + throws GenerateWordException { + Concatenation leftPath = r.getLeft(); + walkThroughConcatenation(leftPath); + if (Math.random() < repetitions.get(r)) { + // walk through lower path + Concatenation rightPath = r.getRight(); + walkThroughConcatenation(rightPath); + // set random value for repetition nearer to zero + if (repetitions.get(r) > 0) + repetitions.put(r, repetitions.get(r) - 0.1); + walkThroughRepetition(r); + } + } + + private double countBranches(Concatenation concat) { + double count = 0; + for (int i = 0; i < concat.getNumberOfElems(); i++) { + SynDiaElem sde = concat.getSynDiaElem(i); + if (sde instanceof Branch) { + Branch b = (Branch) sde; + count++; + count += countBranches(b.getLeft()); + count += countBranches(b.getRight()); + } + } + return count; + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.java new file mode 100644 index 0000000..8437abe --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/WordParser.java @@ -0,0 +1,59 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm; + +import java.util.List; + +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * Method Parses an Word and checks if its only contains valid TerminalSymbols. + * + * @author Claas Wilke + * + */ +public class WordParser { + + private WordAlgoModel myModel; + + /** + * Constructs a new WordParser + * + * @param myModel + * The WordAlgoModel which should be used to parse + * Words. + */ + public WordParser(WordAlgoModel myModel) { + + this.myModel = myModel; + + } + + /** + * Parses a String and checks if its only contains TeminalSymbols which are + * in the parsers model. + * + * @param word + * The word which should be parsed. + * @return True im word only contains TeminalSymbols which + * are in the parsers model. + */ + public boolean isWordValid(String symbols) { + List terminalList = myModel.getSynDiaSystem().getLabelsOfTerminals(); + boolean changed = true; + while (changed) { + changed = false; + for (String aTerminalName : terminalList) { + if (symbols.startsWith(aTerminalName)) { + symbols = symbols.substring(aTerminalName.length()); + changed = true; + } + } + } + // If all symbols were removed, the String contains only valid + // TerminalSymbols + if (!symbols.equals("")) { + return false; + } + return true; + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.java new file mode 100644 index 0000000..f89f903 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmAlreadyStartedException.java @@ -0,0 +1,32 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Exception thrown by the AlgorithmStartAction if the algorithm was already started + * before performing the AlgorithmStartAction. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class AlgorithmAlreadyStartedException extends Exception { + + /** + * Constructor without message + * + * + */ + public AlgorithmAlreadyStartedException() { + super(); + } + + /** + * Constructor with message + * + * @param message + * The message which should be thrown with the Exception. + */ + public AlgorithmAlreadyStartedException(String message) { + super(message); + } + + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.java new file mode 100644 index 0000000..9111789 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/AlgorithmNotStartedException.java @@ -0,0 +1,31 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Exception thrown by the WordAlgoAction if the algorithm was not started + * before performing the WordAlgoAction. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class AlgorithmNotStartedException extends Exception { + + /** + * Constructor without message + * + * + */ + public AlgorithmNotStartedException() { + super(); + } + + /** + * Constructor with message + * + * @param message + * The message which should be thrown with the Exception. + */ + public AlgorithmNotStartedException(String message) { + super(message); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Entries b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Entries new file mode 100644 index 0000000..51dc5d2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Entries @@ -0,0 +1,6 @@ +/AlgorithmAlreadyStartedException.java/1.1/Fri Aug 11 16:40:31 2006// +/AlgorithmNotStartedException.java/1.1/Fri Aug 11 16:40:31 2006// +/CantPerformStepException.java/1.1/Fri Aug 11 16:40:31 2006// +/GenerateWordException.java/1.1/Fri Aug 11 16:40:31 2006// +/InconsistentDiagramSystemException.java/1.1/Fri Aug 11 16:40:31 2006// +/InitializationFailedException.java/1.1/Fri Aug 11 16:40:31 2006// diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Repository b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Repository new file mode 100644 index 0000000..0a885f0 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Root b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.java new file mode 100644 index 0000000..be1e84e --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/CantPerformStepException.java @@ -0,0 +1,31 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Exception thrown by the WordAlgoAction if there was a problem during + * performing the step represented by the WordAlgoAction. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class CantPerformStepException extends Exception { + + /** + * Constructor without message + * + * + */ + public CantPerformStepException() { + super(); + } + + /** + * Constructor with message + * + * @param message + * The message which should be thrown with the Exception. + */ + public CantPerformStepException(String message) { + super(message); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.java new file mode 100644 index 0000000..2fd400f --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/GenerateWordException.java @@ -0,0 +1,18 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Is thrown if no valid word could be generated. + * + * @author Michael Thiele + * + */ @SuppressWarnings("serial") +public class GenerateWordException extends Exception { + + /** + * + */ + public GenerateWordException() { + super(); + } + +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.java new file mode 100644 index 0000000..9f75778 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InconsistentDiagramSystemException.java @@ -0,0 +1,29 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Exception thrown by the method generateAdresses of the WordAlgorithmController. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class InconsistentDiagramSystemException extends Exception { + + /** + * Constructor without message + * + * + */ + public InconsistentDiagramSystemException() { + super(); + } + + /** + * Constructor with message + * + * @param message + * The message which should be thrown with the Exception. + */ + public InconsistentDiagramSystemException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.java b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.java new file mode 100644 index 0000000..ec746d7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/controller/wordalgorithm/exceptions/InitializationFailedException.java @@ -0,0 +1,29 @@ +package org.jalgo.module.ebnf.controller.wordalgorithm.exceptions; + +/** + * Exception thrown by the method initialize of the WordAlgorithmController. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class InitializationFailedException extends Exception { + + /** + * Constructor without message + * + * + */ + public InitializationFailedException() { + super(); + } + + /** + * Constructor with message + * + * @param message + * The message which should be thrown with the Exception. + */ + public InitializationFailedException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/de.properties b/src/org/jalgo/module/ebnf/de.properties new file mode 100644 index 0000000..346442f --- /dev/null +++ b/src/org/jalgo/module/ebnf/de.properties @@ -0,0 +1,224 @@ +Module_name=EBNF / Syntax-Diagramme +Module_version=1.0 +Module_authors=Tom Kazimier, Johannes Mey, Michael Thiele, Andr\u00E9 Viergutz, Claas Wilke +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt EBNF-Terme sowie Syntaxdiagramme. +Module_description_2=Es wird der trans()-Algorithmus unterst\u00FCtzt und es ist m\u00F6glich, W\u00F6rter interaktiv zu erzeugen. + +ModuleConnector.No_valid_EBNF_file=Keine g\u00FCltige EBNF- bzw. Syntax-Diagramm-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist m\u00F6glicherweise besch\u00E4digt. +GUIController.Wish_to_change_to_EBNF_mode=M\u00F6chten Sie jetzt in den EBNF - Modus wechseln? + +Show_start_screen=Startbildschirm anzeigen +Show_start_screen_tooltip=\u00D6ffnet den Startbildschirm +Wish_to_discard=M\u00F6chten Sie Ihre \u00C4nderungen verwerfen? +Wish_to_show_Startscreen=M\u00F6chten Sie den Startbildschirm wirklich anzeigen? + +SynDiaModel.NoNullElemException=Fehler beim Einf\u00FCgen in ein Syntaxdiagramm: Am angegebenen Index befindet sich kein NullElement +SynDiaModel.BeginEndException=begin - end < 0 oder (begin - end) % 2 != 0 +SynDiaModel.LeftAndRightPathException=Beim L\u00F6schen einer Verzweigung/Wiederholung ist es nicht m\u00F6glich, den oberen und unteren Pfad zu erhalten! +SynDiaModel.ElementNotFoundException=An dieser Stelle befindet sich kein zu entfernendes Element. +SynDiaModel.DeleteStartDiagramException=Das Startdiagramm darf nicht gel\u00F6scht werden! +SynDiaModel.EmptyNameExeption=Namen f\u00FCr Variablen/Terminalsymbole d\u00FCrfen nicht leer sein. + +Trans.UndoAll=Alle Schritte r\u00FCckg\u00E4ngig machen +Trans.Undo=Den letzten Schritt r\u00FCckg\u00E4ngig machen +Trans.Perform=Den n\u00E4chstm\u00F6glichen Schritt ausf\u00FChren +Trans.PerformAll=Den Algorithmus bis zum Ende ausf\u00FChren +Trans.ShowHelp=Hervorhebung des n\u00E4chsten Schrittes ein/ausschalten + +Trans.Finished=Der Algorithmus ist beendet +Trans.Beachte_top=Achtung: Der Eingang des Diagramms befindet sich auf +Trans.Beachte_bottom=der rechten Seite! +Trans.Sei=Sei +Trans.FirstAd=Fahre mit der Maus \u00FCber ein trans()-Element +Trans.SecondAd=Bei Klick darauf wird der angezeigte, bzw. n\u00E4chste Schritt ausgef\u00FChrt + +Border_Control=Kontrollbereich +Border_Draw=Anzeige der Diagramme +Border_Explanation=Hinweise zum Algorithmus + +SynDia.Control_FitToSize=Gr\u00F6\u00DFe automatisch anpassen an / ausschalten +SynDia.Control_Stairs=Treppenstrukturen ein-/ausblenden +SynDia.Control_ToEbnf=
          EBNF-Definition
          ansehen/bearbeiten
          +SynDia.Control_ToSynDiaDisplay=
          Zur Syntaxdiagramm-
          anzeige wechseln
          +SynDia.Control_ToSynDiaInput=
          Zum Syntaxdiagramm-
          editor wechseln
          +SynDia.Control_ToWordAlgo=
          Zum R\u00FCcksprung-
          algorithmus wechseln
          +SynDia.Control_Save=Hinweis +SynDia.Control_SaveText=Wollen Sie das Diagramm speichern, bevor Sie den Algorithmus ausf\u00FChren? + +Ebnf.Controller_DefinitionCheck_NoStartVar=FEHLER: Die Definition hat keine Startvariable
          +Ebnf.Controller_DefinitionCheck_NoRuleForVar_1=FEHLER: Die Variable +Ebnf.Controller_DefinitionCheck_NoRuleForVar_2=hat keine zugeh\u00F6rige Regel
          +Ebnf.Controller_DefinitionCheck_NoTermWithVar_1=WARNUNG: Die Variable +Ebnf.Controller_DefinitionCheck_NoTermWithVar_2=kommt in keinem Term einer Regel vor
          +Ebnf.Controller_DefinitionCheck_NoTermWithTS_1=WARNUNG: Das Terminalsymbol +Ebnf.Controller_DefinitionCheck_NoTermWithTS_2=kommt in keinem Term einer Regel vor
          +Ebnf.Controller_DefinitionCheck_RuleNotReachable_1=WARNUNG: Die Regel +Ebnf.Controller_DefinitionCheck_RuleNotReachable_2=kann nie erreicht werden
          +Ebnf.Controller_DefinitionCheck_NotBinaryAlt=WARNUNG: Die Definition beinhaltet nicht bin\u00E4r geklammerte Alternative-Regeln
          +Ebnf.Controller_MakeDefinitionStrictError=FEHLER: Die Definition konnte leider nicht bin\u00E4r geklammert werden! + +Ebnf.ChoicePanel_EbnfNotBinary=Die Definition ist noch nicht
          bin\u00E4r geklammert! Dies ist

          n\u00F6tig um trans() auszuf\u00FChren! +Ebnf.ChoicePanel_EbnfIsBinary=Die Definition ist bin\u00E4r geklammert.
          Der trans()-Algorithmus

          kann gestartet werden. +Ebnf.ChoicePanel_Border=Bitte W\u00E4hlen Sie... +Ebnf.ChoicePanel_transNotActiveButton=

          trans()-Algorithmus
          anwenden
          +Ebnf.ChoicePanel_transActiveButton=
          Zur\u00FCck zum
          trans()-Algorithmus
          +Ebnf.ChoicePanel_editButton=
          Definition
          \u00FCberarbeiten
          +Ebnf.ChoicePanel_strictButton=
          Definition
          bin\u00E4r klammern
          +Ebnf.ChoicePanel_strictButton2=
          Bin\u00E4re Klammerung
          wieder entfernen
          +Ebnf.ChoicePanel_SaveStrictMode=M\u00F6chten Sie die bin\u00E4re Klammerung in Ihrer Definition speichern? +Ebnf.ChoicePanel_StrictMode=Bin\u00E4re Klammerung beibehalten + +Ebnf.PopupMenu_Edit=bearbeiten +Ebnf.PopupMenu_Rename=umbenennen +Ebnf.PopupMenu_Delete=l\u00F6schen +Ebnf.PopupMenu_SetAsStartRule=als Startregel setzen +Ebnf.PopupMenu_SetAsStartVar=als Startvariable setzen + +Ebnf.DefinitionCorrect=Die Definition is korrekt und vollst\u00E4ndig +Ebnf.CheckDefinition=\u00DCberpr\u00FCfung der Definition +Ebnf.Add=Hinzuf\u00FCgen +Ebnf.Edit=Bearbeiten +Ebnf.Undo=R\u00FCckg\u00E4ngig +Ebnf.33=Symbol: +Ebnf.Change=\u00C4ndern +Ebnf.Cancel=Abbrechen +Ebnf.Insert=Einf\u00FCgen +Ebnf.cancel=Abbrechen +Ebnf.Input_StartVar=Startvariable + +Ebnf.Input_Undo=Die letzte \u00C4nderung r\u00FCckg\u00E4ngig machen +Ebnf.Input_Redo=Die letzte \u00C4nderung wieder herstellen + +Ebnf.RuleIsCorrect=Die von Ihnen eingegebene Regel ist korrekt. + +Ebnf.Input_CheckDefinitionButton=
          Defintion
          pr\u00FCfen
          +Ebnf.Input_InputFinishedButton=
          Eingabe
          beenden
          +Ebnf.Input_RulesBorder=Regeln +Ebnf.Input_TerminalBorder=Terminalsymbole + +Ebnf.Input_Undo=Macht die letzte Aktion r\u00FCckg\u00E4ngig. +Ebnf.Input_Redo=Stellt Vorzustand her. +Ebnf.terminal=Terminalsymbol +Ebnf.variable=Variable +Ebnf.symbol=Das Symbol +Ebnf.isUnknown=konnte nicht zugeordnet werden.
          Es kann aber einer Menge hinzugef\u00FCgt werden. + +Ebnf.Error_NoValidVarName=FEHLER: Ung\u00FCltiger Variablen-Name! +Ebnf.Error_NoValidTermrName=FEHLER: Ung\u00FCltiger Terminalsymbol-Name! +Ebnf.Error_NoValidRule=FEHLER: Die eingebene Regel ist ung\u00FCltig! + +Ebnf.Error.Error=FEHLER: +Ebnf.FurtherChars=weitere Sonderzeichen +Ebnf.Error.Undefined=FEHLER: Operation konnte nicht ausgef\u00FChrt werden! +Ebnf.Error.StartVarNull=FEHLER: Es muss eine Variable der Definition als Startvariable gesetzt werden! +Ebnf.Error.StartVarNotInDef=FEHLER: Die neue Startvariable ist nicht in der Definition vorhanden! +Ebnf.Error.InvalidNameInDef=konnte wegen \u00DCberschneidungen mit anderen Symbolnamen der Definition nicht hinzugef\u00FCgt werden! +Ebnf.Error.InvalidSymbolName=ist kein g\u00FCltiger Symbolname! +Ebnf.Error.SymbolOccoursInRule=kommt noch in Regeln vor und kann deshalb nicht gel\u00F6scht werden! +Ebnf.Error.NotASymbol=ist kein Symbol der Definition +Ebnf.Error.NotATerminalSymbol=ist kein Terminalsymbol +Ebnf.Error.NotAVariable=ist keine Variable +Ebnf.Error.NotARuleReplace=FEHLER: Die Regel ist keine Regel der Definition und kann daher nicht ersetzt werden. +Ebnf.Error.RuleIsNull=FEHLER: Die Regel ist leer und kann deshalb nicht hinzugef\u00FCgt werden! +Ebnf.Error.RuleAlreadyExists=Fehler: Es gibt bereits eine Regel f\u00FCr die Variable +Ebnf.Error.ReplacementRuleIsNull=FEHLER: Die neue Regel ist leer und kann deshalb nicht die alte regel ersetzten! +Ebnf.Error.Replacement=Die Regel kann nicht ersetzt werden: +Ebnf.Error.ParseError=FEHLER: Die Regel ist ung\u00FCltig! +Ebnf.Error.BracketError=FEHLER: Die Regel ist falsch geklammert! +Ebnf.Error.AlternativeError=FEHLER: Es kommt ein Alternativstrich au\u00DFerhalb von runden Klammern vor! +Ebnf.Error.StillErrorsInDef=Leider enth\u00E4lt die von Ihnen eingegebene Definition noch Fehler: +Ebnf.Error.SaveError=Beim Speichern der Definition ist ein Fehler aufgetreten +Ebnf.Error.LoadError=Beim Laden der Definition ist ein Fehler aufgetreten +Ebnf.Error.LoadErrorInvalidDef=Die gew\u00E4hlte Datei enth\u00E4lt keine g\u00FCltige EBNF-Definition + +Ebnf.Error.UndoImpossible=Das R\u00FCckg\u00E4ngigmachen der Aktion ist leider nicht m\u00F6glich +Ebnf.Error.RedoImpossible=Das Wiederherstellen der Aktion ist leider nicht m\u00F6glich + +General.Error.LoadError=Beim Laden des Syntaxdiagramms ist ein Fehler aufgetreten + +SynDia.Error.SaveError=Beim Speichern des Syntaxdiagramms ist ein Fehler aufgetreten +SynDia.Error.LoadError=Beim Laden des Syntaxdiagramms ist ein Fehler aufgetreten +SynDia.Error.LoadErrorInvalidDef=Die gew\u00E4hlte Datei enth\u00E4lt kein g\u00FCltiges Syntaxdiagramm + +SynDiaEditor.Error_InternalError=Beim Bearbeiten des Syntaxdiagrammsystems ist ein Fehler aufgetreten. +SynDiaEditor.Error_Appendix=Es wird empfohlen, das aktuelle Modul zu schlie\u00DFen und einen alten Speicherstand zu laden. + +SynDiaEditor.PopupNote_Border=Hinweis +SynDiaEditor.PopupNote_DoNotDeleteStartDiagram=
          Das Startdiagramm darf
          nicht gel\u00F6scht werden!
          +SynDiaEditor.PopupIncomplete_Top=
          Folgende Variablen haben
          kein zugeh\u00F6riges Diagramm:
          + +SynDiaEditor.NameOfDiagram=Name des Diagramms +SynDiaEditor.ChangeNameOfDiagram=Bitte keinen leeren Namen +SynDiaEditor.DiagramAlreadyExists=Name existiert schon! + +SynDiaEditor.Undo=Macht die letzte Aktion r\u00FCckg\u00E4ngig. +SynDiaEditor.Redo=Stellt Vorzustand her. + +SynDiaEditor.ToolTip_AddSynDia=Einf\u00FCgen eines neuen Syntaxdiagramms +SynDiaEditor.ToolTip_Edit=Editieren von Syntaxdiagramm-, Variablen- und Terminalsymbolnamen +SynDiaEditor.ToolTip_Delete=L\u00F6schen von Syntaydiagrammelementen oder leeren Diagrammen +SynDiaEditor.ToolTip_AddTerminal=Einf\u00FCgen eines Terminalsymbols an einer Raute +SynDiaEditor.ToolTip_AddVariable=Einf\u00FCgen einer Variable an einer Raute +SynDiaEditor.ToolTip_AddBranch=Einf\u00FCgen einer Verzweigung: 1. Rechtsklick befestigt Anfang; 2.Rechtsklick das Ende +SynDiaEditor.ToolTip_AddRepetition=Einf\u00FCgen einer Wiederholung: 1. Rechtsklick befestigt Anfang; 2.Rechtsklick das Ende + +WordAlgo.BgName=word + +WordAlgo.Explanation_BeforeStart=Geben Sie ein Wort ein, das sie generieren wollen, und klicken Sie auf den Button 'Algorithmus Starten', um den Algorithmus zu beginnen. Sie k\u00F6nnen auch kein Wort eingeben, um die Erzeugung beliebiger W\u00F6rter zu \u00FCben. +WordAlgo.Explanation_AlgorithmStart=Bevor der Algorithmus abl\u00E4uft, wird der Ausgang jeder Variable mit einer Marke versehen. Der Algorithmus beginnt am Eingang des Startdiagrammes. +WordAlgo.Explanation_JumpToDiagram=Sprung in das Diagramm, dessen Name die Variable trug. +WordAlgo.Explanation_LeaveDiagram=Das Diagramm wurde verlassen. +WordAlgo.Explanation_LeaveDiagramWithAdress=Wenn noch eine Ruecksprungadresse auf dem Keller liegt, dann klicke die R\u00FCcksprungmarke der Variable an, die mit dieser Adresse gekennzeichnet ist. +WordAlgo.Explanation_LeaveDiagramFinishWithSuccess=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller und der Ausgang des Startdiagrammes wurde ereicht. Der Algorithmus endet erfolgreich. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller, aber der Ausgang des Startdiagrammes wurde nicht ereicht. Der Algorithmus endet nicht erfolgreich. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2=Es liegt keine R\u00FCcksprungadresse mehr auf dem Keller, aber das erzeugte Wort entspricht nicht dem eingegebenen. Der Algorithmus endet nicht erfolgreich. +WordAlgo.Explanation_ReturnToDiagram=Die R\u00FCcksprungadresse wurde vom Keller entfernt und der R\u00FCcksprung vollzogen. +WordAlgo.Explanation_Split= +WordAlgo.Explanation_Terminal=Das im Terminalzeichen enthaltene Symbol wurde ans Ende des erzeugten Wortes angeh\u00E4ngt. +WordAlgo.Explanation_Variable=Die R\u00FCcksprungadresse der Variable wurde auf den Keller gelegt. \nKlicke jetzt auf das Syntaxdiagramm, dessen Name in der angeklickten Variable notiert ist. +WordAlgo.Explanation_ContinueDiagram=Setze den Weg durch das Diagram fort. Klicke dazu auf ein TerminalSymbol, eine Variable oder einen leeren Pfad, der erreicht werden kann. + +WordAlgo.Warning_JumpToDiagram=Der Name des betretenen Syntaxdiagrammes stimmt nicht mit dem Name der verlassenen Variable \u00FCberein. Der Sprung wird nicht durchgef\u00FChrt. +WordAlgo.Warning_ReturnToDiagram=Die ausgew\u00E4hlte R\u00FCcksprungadresse stimmt nicht mit der obersten R\u00FCcksprungadresse vom Keller \u00FCberein. +WordAlgo.Warning_Terminal=Das erzeugte Wort kann nicht mehr zum eingegebenen Wort fuehren. Der Algorithmus wird beendet. +WordAlgo.Warning_WordNotValid=Das eingebene Wort ist ung\u00FCltig! +WordAlgo.Warning_WordNotValidToolTip=Es d\u00FCrfen nur Terminalsymbole verwendet werden, die auch in den Diagrammen enthalten sind. + +WordAlgo.MouseOver_Variable=Diese Variable kann erreicht werden. Klicke, um den Weg zu dieser Variable zu w\u00E4hlen. +WordAlgo.MouseOver_ReturnAdress=Klicke, um zu dieser Variable zur\u00FCck zu springen. +WordAlgo.MouseOver_Terminal=Dieses Terminalsymbol kann erreicht werden. Klicke, um den Weg zu diesem TerminalSymbol zu w\u00E4hlen. +WordAlgo.MouseOver_Diagram=Klicke, um zu diesem Diagram zu Springen. +WordAlgo.MouseOver_DiagramExit=Der Ausgang des Diagrammes kann erreicht werden. Klicke, um das Diagram zu verlassen. +WordAlgo.MouseOver_Split=Diese Verzweigung kann erreicht werden. Klicke, um diese Verzweigung zu passieren. + +WordAlgo.GuiControlPanel_Description=Steuerung +WordAlgo.GuiControlPanel_StartLabel=
          Algorithmus
          starten
          +WordAlgo.GuiControlPanel_StopLabel=
          Algorithmus
          zur\u00FCcksetzen
          +WordAlgo.GuiControlPanel_RandomWordLabel=
          Erzeuge
          Zufallswort
          +WordAlgo.GuiControlPanel_StartTooltip=Startet den Algorithmus. +WordAlgo.GuiControlPanel_StopTooltip=Setzt den Algorithmus auf den Anfang zur\u00FCck. +WordAlgo.GuiControlPanel_RandomWordTooltip=Erzeugt ein Zufallswort, das mit dem Algorithmus generiert werden kann. +WordAlgo.GuiControlPanel_FinishSuccess=Der Algorithmus wurde erfolgreich beendet. +WordAlgo.GuiControlPanel_FinishUnsuccess=Der Algorithmus wurde fehlerhaft beendet. +WordAlgo.GuiControlPanel_RandomWordError=Fehler bei Worterzeugung. + +WordAlgo.GuiExplanationPanel_Description=Erkl\u00E4rung +WordAlgo.GuiStackPanel_Description=Keller + +WordAlgo.ToolBar_Undo=Den letzten Schritt r\u00FCckg\u00E4ngig machen +WordAlgo.ToolBar_Redo=Den letzten Schritt wiederherstellen + +WordAlgo.Menu_Title=R\u00FCcksprung-Algorithmus +WordAlgo.Menu_Start=Algorithmus starten +WordAlgo.Menu_Reset=Algorithmus zur\u00FCcksetzen +WordAlgo.Menu_Undo=Schritt r\u00FCckg\u00E4ngig +WordAlgo.Menu_Redo=Schritt wiederherstellen +WordAlgo.Menu_UndoAll=Alle Schritte R\u00FCckg\u00E4ngig +WordAlgo.Menu_RedoAll=Alle Schritte wiederherstellen +WordAlgo.Menu_Exit=Algorithmus verlassen +InputPanel.next=Weiter +InputPanel.Variables=Variablen +InputPanel.insertlpar=( einf\u00FCgen diff --git a/src/org/jalgo/module/ebnf/en.properties b/src/org/jalgo/module/ebnf/en.properties new file mode 100644 index 0000000..8af4954 --- /dev/null +++ b/src/org/jalgo/module/ebnf/en.properties @@ -0,0 +1,224 @@ +Module_name=EBNF / Syntax-Diagramme +Module_version=1.0 +Module_authors=Tom Kazimier, Johannes Mey, Michael Thiele, André Viergutz, Claas Wilke +Module_license=GNU General Public License +Module_description_1=This module handles EBNF definitions and syntax diagrams. +Module_description_2=The trans() algorithm and interactvive word creation are supported. + +ModuleConnector.No_valid_EBNF_file=This is not a valid EBNF definition or syntax diagram file. +ModuleConnector.Loading_error=Error loading the file. +ModuleConnector.File_damaged=The file is possibly damaged. +GUIController.Wish_to_change_to_EBNF_mode=Do you want to switch to EBNF mode? + +Show_start_screen=Show selcome screen +Show_start_screen_tooltip=Shows the selcome screen +Wish_to_discard=Do you wish to discard your changes? +Wish_to_show_Startscreen=Do you really want to show the start screen? + +SynDiaModel.NoNullElemException=Error inserting into the diagram: At the given index is no null element +SynDiaModel.BeginEndException=begin - end < 0 or (begin - end) % 2 != 0 +SynDiaModel.LeftAndRightPathException=It is impossible to keep the the upper or lower path when deleting a branch or repetition +SynDiaModel.ElementNotFoundException=There is no removable element at this position! +SynDiaModel.DeleteStartDiagramException=The start diagram can not be removed! +SynDiaModel.EmptyNameExeption=Variable and terminal symbol names must not be empty! + +Trans.UndoAll=Undo all steps +Trans.Undo=Undo the last step +Trans.Perform=Perform the next possible step +Trans.PerformAll=Complete the algorithm +Trans.ShowHelp=Switch accentuation of the next algorithm step on/off + +Trans.Finished=The algorithm has finished +Trans.Beachte_top=Attention: Enter the repetition at the right side! +Trans.Beachte_bottom= +Trans.Sei=Be +Trans.FirstAd=Move the mouse over a trans()-element +Trans.SecondAd=By clicking this, the next transformation step will be performed + +Border_Control=control area +Border_Draw=diagram display +Border_Explanation=algorithm advices + +SynDia.Control_FitToSize=automatically fit to size on/off +SynDia.Control_Stairs=show/hide stairs in syntax diagrams +SynDia.Control_ToEbnf=
          View/edit
          EBNF definition
          +SynDia.Control_ToSynDiaDisplay=
          To syntax
          diagram display
          +SynDia.Control_ToSynDiaInput=
          To syntax
          diagram editor
          +SynDia.Control_ToWordAlgo=
          To word
          algorithm
          +SynDia.Control_Save=Asvise +SynDia.Control_SaveText=Would you like to save the diagram before starting the algorithm? + +Ebnf.Controller_DefinitionCheck_NoStartVar=ERROR: the definition has no start variable
          +Ebnf.Controller_DefinitionCheck_NoRuleForVar_1=ERROR: The variable +Ebnf.Controller_DefinitionCheck_NoRuleForVar_2=has no associated rule
          +Ebnf.Controller_DefinitionCheck_NoTermWithVar_1=WARNING: The variable +Ebnf.Controller_DefinitionCheck_NoTermWithVar_2=appears in no term of any rule
          +Ebnf.Controller_DefinitionCheck_NoTermWithTS_1=WARNING: The terminal symbol +Ebnf.Controller_DefinitionCheck_NoTermWithTS_2=appears in no term of any rule
          +Ebnf.Controller_DefinitionCheck_RuleNotReachable_1=WARNING: The rule +Ebnf.Controller_DefinitionCheck_RuleNotReachable_2=can not be reached
          +Ebnf.Controller_DefinitionCheck_NotBinaryAlt=WARNING: The definition includes not binary bracketed alternative rules
          +Ebnf.Controller_MakeDefinitionStrictError=ERROR: The definition could not be bracketed binary! + +Ebnf.ChoicePanel_EbnfNotBinary=The definition hast not been

          made binary yet! This is
          necessary to execute trans()! +Ebnf.ChoicePanel_EbnfIsBinary=The definition is bracketed binary.

          The trans() algorithm

          could be started. +Ebnf.ChoicePanel_Border=Please choose... +Ebnf.ChoicePanel_transNotActiveButton=

          Do
          trans() algorithm
          +Ebnf.ChoicePanel_transActiveButton=
          Back to
          trans() algorithm
          +Ebnf.ChoicePanel_editButton=
          Overwork
          definition
          +Ebnf.ChoicePanel_strictButton=
          Bracket
          definition binary
          +Ebnf.ChoicePanel_strictButton2=
          Remove binary
          binary brackets
          +Ebnf.ChoicePanel_SaveStrictMode=Do you wish to save the binary brackets in your definition? +Ebnf.ChoicePanel_StrictMode=Keep binary brackets + +Ebnf.PopupMenu_Edit=Edit +Ebnf.PopupMenu_Rename=Rename +Ebnf.PopupMenu_Delete=Delete +Ebnf.PopupMenu_SetAsStartRule=Set as start rule +Ebnf.PopupMenu_SetAsStartVar=Set as start variable + +Ebnf.DefinitionCorrect=The definition is correct and complete. +Ebnf.CheckDefinition=Check of definition +Ebnf.Add=Add +Ebnf.Edit=Edit +Ebnf.Undo=Undo +Ebnf.33=Symbol: +Ebnf.Change=Change +Ebnf.Cancel=Cancel +Ebnf.Insert=Insert +Ebnf.cancel=Cancel +Ebnf.Input_StartVar=start variable + +Ebnf.Input_Undo=Undoes the latest change +Ebnf.Input_Redo=Redo + +Ebnf.RuleIsCorrect=The rule you inserted is accurate. + +Ebnf.Input_CheckDefinitionButton=
          Check
          definition
          +Ebnf.Input_InputFinishedButton=
          Input
          finished
          +Ebnf.Input_RulesBorder=Rules +Ebnf.Input_TerminalBorder=Terminal symbols + +Ebnf.Input_Undo=Undoes the last action. +Ebnf.Input_Redo=Redoes the last action. +Ebnf.terminal=Terminal symbol +Ebnf.variable=Variable +Ebnf.symbol=The Symbol +Ebnf.isUnknown=could not be assigned properly.
          It is possible to assign it to a set of the definition. + +Ebnf.Error_NoValidVarName=ERROR: Illegal variable name! +Ebnf.Error_NoValidTermrName=ERROR: Illegal terminalsymbol name! +Ebnf.Error_NoValidRule=ERROR: The entered rule is illegal! + +Ebnf.Error.Error=ERROR: +Ebnf.FurtherChars=further special characters +Ebnf.Error.Undefined=ERROR: Operation could not be done! +Ebnf.Error.StartVarNull=ERROR: A variable of the definition must be set as start variable! +Ebnf.Error.StartVarNotInDef=ERROR: The new start variable is not part of the definition! +Ebnf.Error.InvalidNameInDef=could not be added to the definition because of an overlapping with other symbols! +Ebnf.Error.InvalidSymbolName=is no valid symbol name! +Ebnf.Error.SymbolOccoursInRule=still occurs in rules and could therefore not be deleted!! +Ebnf.Error.NotASymbol=is no symbol of the definition +Ebnf.Error.NotATerminalSymbol=is no terminal symbol +Ebnf.Error.NotAVariable=is no variable +Ebnf.Error.NotARuleReplace=ERROR: The rule is not part of the definition and could therefore not be replaced! +Ebnf.Error.RuleIsNull=ERROR: The rule is empty and could therefore not be added! +Ebnf.Error.RuleAlreadyExists=ERROR: There is already a rule for this variable! +Ebnf.Error.ReplacementRuleIsNull=ERROR: The new rule is empty and can't therefore replace the old one! +Ebnf.Error.Replacement=The rule can not be replaced: +Ebnf.Error.ParseError=ERROR: The rule is invalid! +Ebnf.Error.BracketError=ERROR: The rule ist not bracketed properly! +Ebnf.Error.AlternativeError=ERROR: An alternative bar occurs outside of a a pair of parentheses! +Ebnf.Error.StillErrorsInDef=Unfortunately there are still mistakes in your definition: +Ebnf.Error.SaveError=An error occured on saving the definiton +Ebnf.Error.LoadError=An error occured on loading the definitonn +Ebnf.Error.LoadErrorInvalidDef=The chosen file does not include a valid EBNF definition + +Ebnf.Error.UndoImpossible=Unfortunately the undo of this action is not possible +Ebnf.Error.RedoImpossible=Unfortunately the redo of this action is not possible + +General.Error.LoadError=An error occured on loading the syntax diagram system + +SynDia.Error.SaveError=An error occured on saving the syntax diagram system +SynDia.Error.LoadError=An error occured on loading the syntax diagram system +SynDia.Error.LoadErrorInvalidDef=The file does not contain a valid syntax diagram system + +SynDiaEditor.Error_InternalError=An error occured on editing the syntax diagram system. +SynDiaEditor.Error_Appendix=It is recommended to close the active module and to reload an older save point. + +SynDiaEditor.PopupNote_Border=Hint +SynDiaEditor.PopupNote_DoNotDeleteStartDiagram=
          The start diagram
          must not be deleted!
          +SynDiaEditor.PopupIncomplete_Top=
          These variables do
          not have a diagram:
          + +SynDiaEditor.NameOfDiagram=name of the diagram +SynDiaEditor.ChangeNameOfDiagram=no empty name please +SynDiaEditor.DiagramAlreadyExists=name already exists + +SynDiaEditor.Undo=undoes last action +SynDiaEditor.Redo=redoes last undone action + +SynDiaEditor.ToolTip_AddSynDia=insert a new syntax diagram +SynDiaEditor.ToolTip_Edit=edit syntax diagrams, variables and terminal symbol names +SynDiaEditor.ToolTip_Delete=delete syntax diagram elements and empty diagrams +SynDiaEditor.ToolTip_AddTerminal=insert a terminal symbol at a rhombus +SynDiaEditor.ToolTip_AddVariable=insert a variable at a rhombus +SynDiaEditor.ToolTip_AddBranch=insert a branch: 1st click fixes beginning; 2nd click the end +SynDiaEditor.ToolTip_AddRepetition=insert a repetition: 1st click fixes beginning; 2nd click the end + +WordAlgo.BgName=word + +WordAlgo.Explanation_BeforeStart=Enter a word you want to generate and click the button 'Start algorithm' to start the algorithm. You can also start the algorithm without entering a word. +WordAlgo.Explanation_AlgorithmStart=Before the algorithm starts, each variable gets its own return adress. The algorithm starts at the beginning of the start diagram. +WordAlgo.Explanation_JumpToDiagram=Jump to the diagram which has the same name than the left variable. +WordAlgo.Explanation_LeaveDiagram=The algorithm has left the diagram. +WordAlgo.Explanation_LeaveDiagramWithAdress=If there is still a return adress on the stack, click the return adress from the variable which return adress equals the highest adress on the stack. +WordAlgo.Explanation_LeaveDiagramFinishWithSuccess=There is no return adress on the stack anymore and the exit of the start diagram has been reached. The algorithm terminates with success. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess=There is no return adress on the stack anymore, but the exit of the start diagram has not been reached. The algorithm terminates without succes. +WordAlgo.Explanation_LeaveDiagramFinishWithoutSuccess2=Ther is no return adress on the stack anymore, but the enterred word wasn't generated. The algorithm terminates without success. +WordAlgo.Explanation_ReturnToDiagram=The return adress was popped from the stack. The algorithm returned to the diagram. +WordAlgo.Explanation_Split= +WordAlgo.Explanation_Terminal=The symbol of the terminal symbol was added to the output. +WordAlgo.Explanation_Variable=The return adress of the variable was pushed onto the stack.\nClick onto the syntax diagram which has the same name than the left Variable to jump to the diagram. +WordAlgo.Explanation_ContinueDiagram=Click on a terminal symbol, a variable or a empty branch to continue the way through the syntax diagram. + +WordAlgo.Warning_JumpToDiagram=The name of the clicked diagram does not euqal to the name of the left variable. The jump was not performed. +WordAlgo.Warning_ReturnToDiagram=The clicked return adress does not equal to the name of the highest return adress on the stack. The return was not performed. +WordAlgo.Warning_Terminal=The generated output can not become the entered word anymore. Algorithm terminates without success. +WordAlgo.Warning_WordNotValid=The entered word is not valid. +WordAlgo.Warning_WordNotValidToolTip=A valid word can only contain terminal symbols which are also in at least on of the syntax diagrams. + +WordAlgo.MouseOver_Variable=This variable can be reached. Click to go to the variable. +WordAlgo.MouseOver_ReturnAdress=Click to return to this return adress. +WordAlgo.MouseOver_Terminal=This terminal symbol can be reached. Click to pass the terminal symbol. +WordAlgo.MouseOver_Diagram=Click, to jump to this syntax diagram. +WordAlgo.MouseOver_DiagramExit=The exit of the syntax diagram can be reached. Click to leave the diagram. +WordAlgo.MouseOver_Split=This branch can be reached. Click to pass the branch. + +WordAlgo.GuiControlPanel_Description=Control +WordAlgo.GuiControlPanel_StartLabel=
          Start
          algorithm
          +WordAlgo.GuiControlPanel_StopLabel=
          Reset
          algorithm
          +WordAlgo.GuiControlPanel_RandomWordLabel=
          Generate a
          random word
          +WordAlgo.GuiControlPanel_StartTooltip=Starts the algorithm. +WordAlgo.GuiControlPanel_StopTooltip=Resets the algorithm to the beginning. +WordAlgo.GuiControlPanel_RandomWordTooltip=Generates a random word which can be also generated by the algorithm. +WordAlgo.GuiControlPanel_FinishSuccess=The algorithm terminated successfully. +WordAlgo.GuiControlPanel_FinishUnsuccess=The algorithm terminated unsuccessfully. +WordAlgo.GuiControlPanel_RandomWordError=Error during word generation. + +WordAlgo.GuiExplanationPanel_Description=Explanation +WordAlgo.GuiStackPanel_Description=Stack + +WordAlgo.ToolBar_Undo=Undo the last step +WordAlgo.ToolBar_Redo=Redo the last step + +WordAlgo.Menu_Title=Word-Algorithm +WordAlgo.Menu_Start=Start algorithm +WordAlgo.Menu_Reset=Reset algorithm +WordAlgo.Menu_Undo=Undo the last step +WordAlgo.Menu_Redo=Redo the last step +WordAlgo.Menu_UndoAll=Undo all steps +WordAlgo.Menu_RedoAll=Redo all steps +WordAlgo.Menu_Exit=Leave algorithm +InputPanel.next=Nect +InputPanel.Variables=Variablen +InputPanel.insertlpar=add ( \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/CVS/Entries b/src/org/jalgo/module/ebnf/gui/CVS/Entries new file mode 100644 index 0000000..93e1afb --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/CVS/Entries @@ -0,0 +1,11 @@ +/EbnfFont.java/1.2/Thu Jan 31 20:15:09 2008// +/FontNotInitializedException.java/1.2/Thu Jan 31 20:15:09 2008// +/GUIConstants.java/1.2/Thu Jan 31 20:15:09 2008// +/StartAction.java/1.2/Thu Jan 31 20:15:09 2008// +/StartButton.java/1.2/Thu Jan 31 20:15:09 2008// +/StartScreen.java/1.2/Thu Jan 31 20:15:09 2008// +/StartScreenActionHandler.java/1.2/Thu Jan 31 20:15:09 2008// +D/ebnf//// +D/syndia//// +D/trans//// +D/wordalgorithm//// diff --git a/src/org/jalgo/module/ebnf/gui/CVS/Repository b/src/org/jalgo/module/ebnf/gui/CVS/Repository new file mode 100644 index 0000000..d6f0af6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui diff --git a/src/org/jalgo/module/ebnf/gui/CVS/Root b/src/org/jalgo/module/ebnf/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/EbnfFont.java b/src/org/jalgo/module/ebnf/gui/EbnfFont.java new file mode 100644 index 0000000..fd2c838 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/EbnfFont.java @@ -0,0 +1,59 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui; + +import java.awt.Font; + +/** + * @author Andre + * + */ +public class EbnfFont { + + /** + * the font to display EbnfTerms + */ + private static Font ebnfFont = null; + + /** + * @param ebnffont + */ + public static void setFont(Font ebnffont) { + + ebnfFont = ebnffont; + + } + + /** This method returns the Font if it is initialized + * @return The ebnfFont to display EbnfTerms + * @throws FontNotInitializedException This Exception is thrown, if the font is not initialized yet + */ + public static Font getFont() + throws FontNotInitializedException { + + if (ebnfFont != null) + return ebnfFont; + else + throw(new FontNotInitializedException("Font is not initialized yet")); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/FontNotInitializedException.java b/src/org/jalgo/module/ebnf/gui/FontNotInitializedException.java new file mode 100644 index 0000000..7590390 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/FontNotInitializedException.java @@ -0,0 +1,40 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui; + +/** + * @author Andre + * + */ +public class FontNotInitializedException extends Exception { + + private static final long serialVersionUID = 1L; + + public FontNotInitializedException() { + super(); + } + + public FontNotInitializedException(String message) { + super(message); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/GUIConstants.java b/src/org/jalgo/module/ebnf/gui/GUIConstants.java new file mode 100644 index 0000000..26bc92b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/GUIConstants.java @@ -0,0 +1,87 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.05.2005 */ +package org.jalgo.module.ebnf.gui; + +import java.awt.Color; +import java.awt.Font; + +/** + * The interface Constants is a collection of several constant values, + * used in the GUI implementation of the AVL module. + * + * @author Tom Kazimiers + */ +public interface GUIConstants { + + /*------------------------display modes--------------------------*/ + /** Indicates, that display is tuned for working on a pc screen. */ + public static final int PC_MODE = 0; + /** Indicates, that display is tuned for working on a beamer. */ + public static final int BEAMER_MODE = 1; + + /*------------------------validity states-------------------------*/ + /** Indicates a valid input value. */ + public final static int VALID_INPUT = 0; + /** Indicates that input is no integer. */ + public final static int NO_INTEGER = 1; + /** Indicates that input value is out of the acceptable range. */ + public final static int NOT_IN_RANGE = 2; + /** Indicates that input is empty. */ + public final static int INPUT_EMPTY = 3; + + /*------------------------------colors----------------------------*/ + /** The background color in standard layout. */ + public final static Color STANDARD_BACKGROUND = new Color(238, 238, 238); + /** The background color in the START screen. */ + public final static Color START_SCREEN_BACKGROUND = new Color(53, 153, 51); + /** The font color in the START screen. */ + public final static Color START_SCREEN_FOREGROUND = new Color(254, 215, 0); + /** The highlight color for various parts of the module. */ + public final static Color HIGHLIGHT_COLOR = new Color(254, 215, 0); + + public final static Color MOUSEOVER_COLOR = new Color(200, 200, 200); + + public final static Color ERROR_COLOR = new Color(200, 50, 20); /*------------------------------fonts-----------------------------*/ + /** The font used in the START screen. */ + public static final Font START_SCREEN_FONT = + new Font("Tahoma", Font.PLAIN, 16); + public final static Color TEXT_COLOR = new Color(254, 254, 254); + /** The standart background color for colored backgrounds*/ + public final static Color STANDARD_COLOR_BACKGROUND = new Color(250,250,240); + /** The standart color for text in the background*/ + public final static Color STANDARD_COLOR_BACKGROUND_TEXT = new Color(248, 244, 230); + + /*------------------------visualization modes---------------------*/ + /** Indicates that automatical visualisation animation is selected. */ + public static final int AUTOMATICAL = 0; + /** Indicates that stepwise visualisation is selected. */ + public static final int STEPWISE = 1; + /** Indicates that no visualisation is selected. */ + public static final int NO_VISUALIZATION = 2; + + /*--------------------------message types-------------------------*/ + /** Indicates that displayed message is reset. */ + public static final int NO_MESSAGE = 0; + /** Indicates a message to be an error message. */ + public static final int ERROR_MESSAGE = 1; + /** Indicates a message to be an information message. */ + public static final int INFORMATION_MESSAGE = 2; +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/StartAction.java b/src/org/jalgo/module/ebnf/gui/StartAction.java new file mode 100644 index 0000000..d651ac9 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/StartAction.java @@ -0,0 +1,102 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.gui; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.DialogConstants; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; + +/** + * The class StartAction defines an Action which could + * be added to ToolBar- and Menu-Buttons. This action asks the user to discard his/her + * changes to switch to the StartScreen. If "No" is chosen nothing will happen, if + * "yes" he/she is taken to the StartScreen. + * + * @author Tom Kazimiers + */ +public class StartAction +extends AbstractAction { + + /** + * + */ + private static final long serialVersionUID = -1675559376688011664L; + private MainController maincontroller; + private ModuleConnector connector; + + /** + * Constructs a StartAction object with the given + * references. + * + * @param controller the GUIController instance of the EBNF module + */ + public StartAction(MainController controller, ModuleConnector connector) { + this.maincontroller = controller; + this.connector = connector; + putValue(NAME, Messages.getString("ebnf", "Show_start_screen")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "ebnf", "Show_start_screen_tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("ebnf", "Module_logo"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + if (connector.getSaveStatus() == SaveStatus.CHANGES_TO_SAVE) { + switch (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("ebnf", "Wish_to_discard"), + DialogConstants.YES_NO_CANCEL_OPTION)) { + case DialogConstants.YES_OPTION: + maincontroller.installStartScreen(); + break; + case DialogConstants.NO_OPTION: + JAlgoGUIConnector.getInstance().newModuleInstanceByName( + Messages.getString("ebnf", "Module_name")); + break; + case DialogConstants.CANCEL_OPTION: + return; + } + } else { + switch (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("ebnf", "Wish_to_show_Startscreen"), + DialogConstants.YES_NO_OPTION)) { + case DialogConstants.YES_OPTION: + maincontroller.installStartScreen(); + break; + case DialogConstants.NO_OPTION: + return; + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/StartButton.java b/src/org/jalgo/module/ebnf/gui/StartButton.java new file mode 100644 index 0000000..c2457f7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/StartButton.java @@ -0,0 +1,90 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.04.2005 */ +package org.jalgo.module.ebnf.gui; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +/** + * The class StartButton represents a rollover-enabled graphical + * button with a description, which can be displayed on mouse hovering. + * + * @author Tom Kazimiers + */ +public class StartButton +extends JToggleButton { + + private static final long serialVersionUID = -1924541401853204950L; + private final ImageIcon desc; + + /** + * Constructs a StartButton object with the given parameters. + * The description string is represented as a bitmap image, because of better + * layout on different platforms and the missing antialiasing of text on Swing + * components. + * + * @param defaultIcon the icon, which is displayed, when button is not selected + * @param rolloverIcon the icon, which is displayed on mouse hovering + * @param description the description string as image + * @param actionCommand the action command + * @param action an event handler implementing ActionListener + * and MouseListener + */ + public StartButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + ImageIcon description, String actionCommand, + StartScreenActionHandler action) { + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + //the standard rollover mechanism isn't used because of the following bug: + //click on an button holds the rollover state so that 2nd opening + //of welcome screen still highlights the button, even if mouse is not over + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + desc = description; + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension( + getIcon().getIconWidth(), + getIcon().getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(action); + } + + /** + * Retrieves the description of this WelcomeButton as image. + * + * @return the description string as image + */ + public ImageIcon getDescription() { + return desc; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/StartScreen.java b/src/org/jalgo/module/ebnf/gui/StartScreen.java new file mode 100644 index 0000000..bb51b40 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/StartScreen.java @@ -0,0 +1,158 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 25.05.2005 */ +package org.jalgo.module.ebnf.gui; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.ebnf.MainController; + +/** + * Class StartScreen represents a screen with three buttons, + * where the user can choose what to do. The buttons are rollover enabled and a + * description of the selected task is displayed. + * + * @author Tom Kazimiers + */ +public class StartScreen extends JPanel implements GUIConstants { + + /** + * + */ + private static final long serialVersionUID = -9085830968372916356L; + + private StartScreenActionHandler action; + + // components + private StartButton loadButton; + private StartButton ebnfButton; + private StartButton syndiaButton; + private JLabel descriptionLabel; + /** + * Constructs a StartScreen object with the given + * reference. + * + * @param gui the GUIController instance + */ + public StartScreen(MainController gui) { + action = new StartScreenActionHandler(gui, this); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + + String lang = Settings.getString("main", "Language"); + if (!lang.equals("de")) lang = "en"; + loadButton = new StartButton( + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_load")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_load_rollover")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_load_description_"+lang)), + "load", action); + ebnfButton = new StartButton( + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_ebnf")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_ebnf_rollover")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_ebnf_description_"+lang)), + "startEbnfInput", action); + syndiaButton = new StartButton( + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_syndia")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_syndia_rollover")), + new ImageIcon( + Messages.getResourceURL("ebnf", "Start_syndia_description_"+lang)), + "startSynDiaInput", action); + + descriptionLabel = new JLabel(); + descriptionLabel.setSize(399,40); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(START_SCREEN_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(loadButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(ebnfButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(syndiaButton); + + + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + } + + /** + * Displays the given description-image on the screen. + * + * @param desc the task description string + */ + public void setDescription(Icon desc) { + descriptionLabel.setIcon(desc); + descriptionLabel.updateUI(); + } + + /** + * Sets the enabled status of the buttons. If the given value is + * false, also the description string is removed from the + * screen. + * + * @param b true, if the buttons should be enabled, + * false otherwise + */ + public void setButtonsEnabled(boolean b) { + loadButton.setEnabled(b); + ebnfButton.setEnabled(b); + syndiaButton.setEnabled(b); + if (!b) setDescription(null); + } + + /** + * Draws the background with a beautyful color ;o). Normally there would be + * the background color set with setBackground(..), but, under + * linux (GTK) this has no effect. So this is a workaround... + */ + @Override + protected void paintComponent(Graphics g) { + g.setColor(START_SCREEN_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/StartScreenActionHandler.java b/src/org/jalgo/module/ebnf/gui/StartScreenActionHandler.java new file mode 100644 index 0000000..9131f6c --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/StartScreenActionHandler.java @@ -0,0 +1,119 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 15.04.2005 */ +package org.jalgo.module.ebnf.gui; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; + +/** + * The class WelcomeScreenActionHandler is an event handler for + * the StartScreen class. It handles button clicks and mouse + * events for rollover mechanism. + * + * @author Tom Kazimiers + */ +public class StartScreenActionHandler implements ActionListener, MouseListener { + + private MainController maincontroller; + private StartScreen screen; + + /** + * Constructs a WelcomeScreenActionHandler object with the + * given references. + * + * @param gui the GUIController instance + * @param screen the WelcomeScreen instance, for which this + * event handler is used + */ + public StartScreenActionHandler(MainController gui, org.jalgo.module.ebnf.gui.StartScreen screen) { + this.maincontroller = gui; + this.screen = screen; + } + + /** + * Handles button clicks. + */ + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("load")) //$NON-NLS-1$ + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + else if (e.getActionCommand().equals("startEbnfInput")) { //$NON-NLS-1$ + maincontroller.setEbnfInputMode(false); + } + else if (e.getActionCommand().equals("startSynDiaInput")) { //$NON-NLS-1$ + maincontroller.setSynDiaInputMode(new SynDiaSystem("S")); + screen.setButtonsEnabled(false); + } + + ((StartButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** + * Causes the event source button to highlight and to display its + * description string on screen. + */ + public void mouseEntered(MouseEvent e) { + StartButton source = (StartButton)e.getSource(); + if (!source.isEnabled()) return; + source.setSelected(true); + screen.setDescription(source.getDescription()); + } + + /** + * Causes the event source button to be displayed normally and to remove the + * description string from the screen. + */ + public void mouseExited(MouseEvent e) { + ((StartButton)e.getSource()).setSelected(false); + screen.setDescription(null); + } + + /** + * This method has no effect. + */ + public void mouseClicked(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + public void mousePressed(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + public void mouseReleased(MouseEvent e) { + // This method has no effect + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Entries b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Entries new file mode 100644 index 0000000..254d234 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Entries @@ -0,0 +1,17 @@ +/ChoicePanel.java/1.2/Thu Jan 31 20:15:01 2008// +/ChoicePanelActionListener.java/1.2/Thu Jan 31 20:15:01 2008// +/EbnfButton.java/1.2/Thu Jan 31 20:15:01 2008// +/EbnfRenderer.java/1.2/Thu Jan 31 20:15:01 2008// +/EbnfTextField.java/1.2/Thu Jan 31 20:15:01 2008// +/EditDefinitionActionListener.java/1.2/Thu Jan 31 20:15:01 2008// +/EditRuleActionListener.java/1.2/Thu Jan 31 20:15:01 2008// +/GuiController.java/1.2/Thu Jan 31 20:15:01 2008// +/HeaderViewPanel.java/1.2/Thu Jan 31 20:15:01 2008// +/InputPanel.java/1.2/Thu Jan 31 20:15:01 2008// +/ModifyDefinitionActionListener.java/1.2/Thu Jan 31 20:15:01 2008// +/RedoAction.java/1.2/Thu Jan 31 20:15:01 2008// +/RenderConstants.java/1.2/Thu Jan 31 20:15:01 2008// +/RuleViewPanel.java/1.2/Thu Jan 31 20:15:01 2008// +/TermPanel.java/1.2/Thu Jan 31 20:15:01 2008// +/UndoAction.java/1.2/Thu Jan 31 20:15:01 2008// +/ViewPanelSizeListener.java/1.2/Thu Jan 31 20:15:01 2008// diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Repository b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Repository new file mode 100644 index 0000000..262e772 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/ebnf diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Root b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.java b/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.java new file mode 100644 index 0000000..a291fe1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanel.java @@ -0,0 +1,200 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.Graphics; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JToggleButton; + +import org.jalgo.main.util.Messages; + + +/** + * + * @author Tom + * + */public class ChoicePanel extends JPanel { + + + /** + * + */ + private static final long serialVersionUID = 1L; + private GuiController guiController; + private ImageIcon redLightIcon; + private ImageIcon greenLightIcon; + private JLabel infoLight; + private JLabel infoLabel; + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JPanel ChoicePanel; + private javax.swing.JPanel buttonPanel; + private javax.swing.JButton editButton; + private javax.swing.JButton transButton; + private JToggleButton strictButton; + // End of variables declaration//GEN-END:variables + + public ChoicePanel(GuiController guicontroller) { + this.guiController = guicontroller; + initComponents(); + initActionListeners(); + } + + public void checkIfDefIsStrict() { + + if (!guiController.getEbnfController().getDefinition().isStrict() && !guiController.getStrictMode()) { + //the definition is not strict + infoLight.setIcon(redLightIcon); + infoLabel.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_EbnfNotBinary")); + infoLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); + transButton.setEnabled(false); + } else { + // the definition is strict + infoLight.setIcon(greenLightIcon); + infoLabel.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_EbnfIsBinary")); + infoLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); + transButton.setEnabled(true); + } + buttonPanel.validate(); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + initializeButtons(); + + redLightIcon = new ImageIcon(Messages.getResourceURL("ebnf", "Light_Red")); + greenLightIcon = new ImageIcon(Messages.getResourceURL("ebnf", "Light_Green")); + + infoLabel = new JLabel(); + infoLight = new JLabel(); + + checkIfDefIsStrict(); + + ChoicePanel = new javax.swing.JPanel(); + + org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel); + buttonPanel.setLayout(buttonPanelLayout); + buttonPanelLayout.setHorizontalGroup( + buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup() + .add(infoLight) + .add(5,5,5) + .add(infoLabel) + .addContainerGap(0, Short.MAX_VALUE) + .add(editButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 155, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(strictButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 155, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) + .add(transButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 155, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addContainerGap(5,5) + ) + ); + buttonPanelLayout.setVerticalGroup( + buttonPanelLayout.createSequentialGroup() + .add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) + .add(buttonPanelLayout.createSequentialGroup() + .add(5,5,5) + .add(infoLight)) + .add(buttonPanelLayout.createSequentialGroup() + .add(5,5,5) + .add(infoLabel)) + .add(transButton) + .add(strictButton) + .add(editButton)) + .addContainerGap(5, 5) + ); + + org.jdesktop.layout.GroupLayout ChoicePanelLayout = new org.jdesktop.layout.GroupLayout(ChoicePanel); + ChoicePanel.setLayout(ChoicePanelLayout); + ChoicePanelLayout.setHorizontalGroup( + ChoicePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanelLayout.createSequentialGroup() + .addContainerGap() + .add(buttonPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + ChoicePanelLayout.setVerticalGroup( + ChoicePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanelLayout.createSequentialGroup() + .addContainerGap() + .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); + setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(layout.createSequentialGroup() + .add(ChoicePanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) + .add(ChoicePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + ); + } + + private void initializeButtons() { + buttonPanel = new javax.swing.JPanel(); + transButton = new javax.swing.JButton(); + editButton = new javax.swing.JButton(); + strictButton = new JToggleButton(); + + buttonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, Messages.getString("ebnf", "Ebnf.ChoicePanel_Border"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); + transButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + setTransButtonText(); + editButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + editButton.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_editButton")); + + strictButton.setFont(new java.awt.Font("Tahoma", 0, 14)); + strictButton.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_strictButton")); + } + + public void setTransButtonText() { + if (guiController.getEbnfController().isTransActive()) + transButton.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_transActiveButton")); + else + transButton.setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_transNotActiveButton")); + + } + private void initActionListeners() { + transButton.addActionListener(guiController.choicePanelActionListener); + transButton.setActionCommand("switchtotransgui"); + strictButton.addActionListener(guiController.choicePanelActionListener); + strictButton.setActionCommand("strictdefinition"); + editButton.addActionListener(guiController.choicePanelActionListener); + editButton.setActionCommand("editdefinition"); + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.java b/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.java new file mode 100644 index 0000000..9b7e7fe --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/ChoicePanelActionListener.java @@ -0,0 +1,77 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JToggleButton; + +import org.jalgo.main.util.Messages; + +/** + * + * @author Tom + * + */public class ChoicePanelActionListener implements ActionListener { + + private GuiController guiController; + + public ChoicePanelActionListener(GuiController guiController) { + this.guiController = guiController; + } + + /** + * The actions for the three buttons on top are defined and proceeded here + * + */public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("switchtotransgui")) { + guiController.setEditMode(false); + guiController.getEbnfController().switchToTransGUI(); + } else if (e.getActionCommand().equals("editdefinition")) { + if (guiController.getStrictMode() && !guiController.getEbnfController().getDefinition().isStrict()) { + int saveStrictMode = guiController.showSaveStrictModeDialog(true); + if (saveStrictMode == -1) return; + else if (saveStrictMode == 1) { + guiController.getEbnfController().setDefinitionStrict(); + } + } + guiController.setStrictMode(false); + guiController.setEditMode(true); + guiController.getRuleViewPanel().removeAll(); + guiController.getRuleViewPanel().drawRules(); + guiController.showInputGUI(); + } else if (e.getActionCommand().equals("strictdefinition")) { + boolean strictmode = guiController.getStrictMode(); + if (!((JToggleButton)e.getSource()).isSelected()) { + ((JToggleButton)e.getSource()).setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_strictButton")); + } else { + ((JToggleButton)e.getSource()).setText(Messages.getString("ebnf", "Ebnf.ChoicePanel_strictButton2")); + } + guiController.setStrictMode(((JToggleButton)e.getSource()).isSelected()); + guiController.getRuleViewPanel().removeAll(); + guiController.getRuleViewPanel().drawRules(); + guiController.getRuleViewPanel().repaint(); + } + + } + } diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.java b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.java new file mode 100644 index 0000000..84834cc --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfButton.java @@ -0,0 +1,47 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import javax.swing.JButton; + +public class EbnfButton extends JButton { + + /** + * + */ + private static final long serialVersionUID = 4129615363333244759L; + + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D)g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + super.paintComponent(g); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.java b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.java new file mode 100644 index 0000000..cbc2bd5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfRenderer.java @@ -0,0 +1,175 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.ebnf.model.ebnf.*; + +public class EbnfRenderer { + + /** + * Creates a String using the meta symbols form the ebnfsans font. if + * renderStrict is set to true the definition renders the alternatives as if + * they were binary. The added parentheses are highlighted. + * + * @param term the term to be redered + * @param renderStrict includes parentheses to make the definition strict + * @return the rendered output-string + */ + public static String toRenderString(Term term, boolean renderStrict, String delimiter) { + String renderString = new String(); + if (term == null) + return ""; + + if (term instanceof ETerminalSymbol) { + return ((ETerminalSymbol) term).getName(); + } else if (term instanceof EVariable) { + return ((EVariable) term).getName(); + } else if (term instanceof EOption) { + renderString = String.valueOf(RenderConstants.LBRACKET); + renderString += toRenderString(((EOption) term).getTerm(), + renderStrict, delimiter); + renderString += String.valueOf(RenderConstants.RBRACKET); + return renderString; + } else if (term instanceof ERepetition) { + renderString = String.valueOf(RenderConstants.LBRACE); + renderString += toRenderString(((ERepetition) term).getTerm(), + renderStrict, delimiter); + renderString += String.valueOf(RenderConstants.RBRACE); + return renderString; + } else if (term instanceof ECompoundTerm) { + renderString = String.valueOf(RenderConstants.LPARENTHESES); + renderString += toRenderString(((ECompoundTerm) term).getTerm(), + renderStrict, delimiter); + renderString += String.valueOf(RenderConstants.RPARENTHESES); + return renderString; + } else if (term instanceof EConcatenation) { + + for (Term concatTerm : term.getTerms()) + renderString += toRenderString(concatTerm, renderStrict, delimiter) + delimiter; + return renderString; + } else if ((term instanceof EAlternative) && !renderStrict) { + Term altTerm; + renderString = String.valueOf(RenderConstants.LPARENTHESES); + for (int i = 0; i < term.getTerms().size(); i++) { + altTerm = term.getTerms().get(i); + renderString += toRenderString(altTerm, renderStrict, delimiter); + if (i != term.getTerms().size() - 1) + renderString += String.valueOf(RenderConstants.ALTERNATIVE); + } + renderString += RenderConstants.RPARENTHESES; + return renderString; + } else if (term instanceof EAlternative && renderStrict) { + Term altTerm; + + renderString += String.valueOf(RenderConstants.LPARENTHESES); + altTerm = term.getTerms().get(0); + renderString += toRenderString(altTerm, renderStrict, delimiter); + renderString += String.valueOf(RenderConstants.ALTERNATIVE); + + for (int i = 1; i < term.getTerms().size() - 1; i++) { + + renderString += String.valueOf(RenderConstants.LPARENTHESES_M); + altTerm = term.getTerms().get(i); + renderString += toRenderString(altTerm, renderStrict, delimiter); + renderString += String.valueOf(RenderConstants.ALTERNATIVE); + + } + + altTerm = term.getTerms().get(term.getTerms().size() - 1); + renderString += toRenderString(altTerm, renderStrict, delimiter); + + for (int i = 0; i < term.getTerms().size() - 2; i++) { + renderString += String.valueOf(RenderConstants.RPARENTHESES_M); + + } + renderString += RenderConstants.RPARENTHESES; + return renderString; + } + + return renderString; + } + + /** + * @param term the term to be redered + * @param renderStrict includes parentheses to make the definition strict + * @return the rendered output-string-list + */ + public static List toRenderStringList(Term term, + boolean renderStrict) { + + List stringList = new ArrayList(); + + if (term == null) + stringList.add(""); + + if (term instanceof ETerminalSymbol) { + + stringList.add(((ETerminalSymbol) term).getName()); + + } else if (term instanceof EVariable) { + + stringList.add(((EVariable) term).getName()); + + } else if (term instanceof EOption) { + stringList.add(String.valueOf(RenderConstants.LBRACKET)); + stringList.add(toRenderString(((EOption) term).getTerm(), + renderStrict, "")); + stringList.add(String.valueOf(RenderConstants.RBRACKET)); + + } else if (term instanceof ERepetition) { + stringList.add(String.valueOf(RenderConstants.LBRACE)); + stringList.add(toRenderString(((ERepetition) term).getTerm(), + renderStrict, "")); + stringList.add(String.valueOf(RenderConstants.RBRACE)); + + } else if (term instanceof ECompoundTerm) { + stringList.add(String.valueOf(RenderConstants.LPARENTHESES)); + stringList.add(toRenderString(((ECompoundTerm) term).getTerm(), + renderStrict, "")); + stringList.add(String.valueOf(RenderConstants.RPARENTHESES)); + + } else if (term instanceof EConcatenation) { + + for (Term concatTerm : term.getTerms()) + stringList.add(toRenderString(concatTerm, renderStrict, "")); + + } else if (term instanceof EAlternative) { + Term altTerm; + stringList.add(String.valueOf(RenderConstants.LPARENTHESES)); + for (int i = 0; i < term.getTerms().size(); i++) { + altTerm = term.getTerms().get(i); + stringList.add(toRenderString(altTerm, renderStrict, "")); + if (i != term.getTerms().size() - 1) + stringList.add(String.valueOf(RenderConstants.ALTERNATIVE)); + } + stringList.add(String.valueOf(RenderConstants.RPARENTHESES)); + + } + + return stringList; + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.java b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.java new file mode 100644 index 0000000..039af9b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/EbnfTextField.java @@ -0,0 +1,222 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.geom.Rectangle2D; + +import javax.swing.JTextField; +import javax.swing.text.BadLocationException; + +import org.jalgo.module.ebnf.gui.GUIConstants; + +/**The class EbndTextField extends an JTextField to add some RenderingHints and + * makes it possible to highlight our EBNF-Symbols and their counterpart + * @author Tom Kazimiers + * + */ +public class EbnfTextField extends JTextField { + + /** + * + */ + private static final long serialVersionUID = 1L; + private int movecount = 0; + private int nextpos = 0; + private int margin_left; + private int margin_top; + private int caretPos = 0; + private EbnfTextField me = null; + + String strOpening = String.valueOf(RenderConstants.LBRACE)+String.valueOf(RenderConstants.LBRACKET)+String.valueOf(RenderConstants.LPARENTHESES); + String strClosing = String.valueOf(RenderConstants.RBRACE)+String.valueOf(RenderConstants.RBRACKET)+String.valueOf(RenderConstants.RPARENTHESES); + + public EbnfTextField() { + me = this; + initializeTimer(); + } + + + public EbnfTextField(String text) + { + super(text); + } + + /**This function initializes the timer t which is responsible for repainting the textfield. + * At the moment t does this every 200ms with a check if the caret has moved for more then one + * field. + * + * + */private void initializeTimer() { + javax.swing.Timer t = new javax.swing.Timer( 150, new ActionListener() { + public void actionPerformed( ActionEvent e ) { + if ((movecount != caretPos) || (movecount - 1 != caretPos) || (movecount + 1 != caretPos)) { + me.repaint(); + } +// SwingUtilities.invokeLater( new Runnable() { +// public void run() { +// guiController.cancelRule(); +// }} ); + } + }); + t.start(); + } + + @Override + protected void paintComponent(Graphics g) + { + // Unicode-Mappings: "\u300C" = [, "\u300D" = ], "\u300E" = |", + // "\u300F" = (, " \u3010" = ), " \u3011" = {, "\u3012" = } + // 3014 und 3015 sind nochmal () für die generierten Klammern + + Graphics2D g2 = (Graphics2D)g; + caretPos = this.getCaretPosition(); + + String text = " "; + + + if (caretPos>0) { + try { + text = this.getText(caretPos - 1, 1); + } catch (BadLocationException e) { + // should not occur because of the if-clause + } + } + + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + super.paintComponent(g); + + if (strClosing.contains(text)) { //Bracket is closing + margin_left = getInsets().left; + margin_top = getInsets().top; + nextpos = findNextChaaracterPos(caretPos, text, false); + if (nextpos >= 0) { + g2.setColor(GUIConstants.START_SCREEN_BACKGROUND); + g2.draw(findCorrectCharacterPos(nextpos)); + } else { + g2.setColor(GUIConstants.ERROR_COLOR); + } + + g2.draw(findCorrectCharacterPos(caretPos)); + movecount = caretPos; + + } else if (strOpening.contains(text)) { // Bracket is opening + margin_left = getInsets().left; + margin_top = getInsets().top; + nextpos = findNextChaaracterPos(caretPos, text, true); + if (nextpos >= 0) { + g2.setColor(GUIConstants.START_SCREEN_BACKGROUND); + g2.draw(findCorrectCharacterPos(nextpos)); + } else { + g2.setColor(GUIConstants.ERROR_COLOR); + } + + g2.draw(findCorrectCharacterPos(caretPos)); + movecount = caretPos; + } + + + + } + + /**The function findCorrectCharacterPos generates a fitting rectangle for + * out brackets, parenth. and braces. + * + * @param pos is the character-position in the TextField + * @return the correct rectangel is returned + */private Rectangle2D findCorrectCharacterPos(int pos) { + Font font = this.getFont(); + FontMetrics metrics = getFontMetrics( font ); + Rectangle2D rect; + int position = 0; + int width = 0; + + try { + + position = margin_left + metrics.stringWidth(this.getText(0, pos-1)) - 1; + width = metrics.stringWidth(this.getText(pos-1, 1)); + } catch (BadLocationException e) { + // This appears to be no serious error, so it can be ignored + } + + rect = new Rectangle2D.Float(position, margin_top + 1, width + 3, 26); + + return rect; + } + + /**This function finds the correct closing or opening bracket/parenth./brace for an correspondending + * closing/opening one. + * + * @param pos is the start position to search from + * @param searchtext is the String of the bracket/parenth./brace to look for + * @param fromlefttoright should be set to true if the clicket bracket/.../... is opening, otherwise falses + * @return the position of the found matching bracket/.../... is given back + */private int findNextChaaracterPos(int pos, String searchtext, boolean fromlefttoright) { + String nextbracket = ""; + String text = this.getText(); + int counter = 0; + if (searchtext.equals(String.valueOf(RenderConstants.LBRACKET))) nextbracket = String.valueOf(RenderConstants.RBRACKET); + else if (searchtext.equals(String.valueOf(RenderConstants.LBRACE))) nextbracket = String.valueOf(RenderConstants.RBRACE); + else if (searchtext.equals(String.valueOf(RenderConstants.LPARENTHESES))) nextbracket = String.valueOf(RenderConstants.RPARENTHESES); + else if (searchtext.equals(String.valueOf(RenderConstants.RBRACKET))) nextbracket = String.valueOf(RenderConstants.LBRACKET); + else if (searchtext.equals(String.valueOf(RenderConstants.RBRACE))) nextbracket = String.valueOf(RenderConstants.LBRACE); + else if (searchtext.equals(String.valueOf(RenderConstants.RPARENTHESES))) nextbracket = String.valueOf(RenderConstants.LPARENTHESES); + + if (fromlefttoright) { + for(int i=pos;i=0; i--) { + if ((text.substring(i,i+1).equals(nextbracket)) && (counter == 0)) { + return i+1; + } else if (text.substring(i,i+1).equals(searchtext)) { + counter++; + } else if ((text.substring(i,i+1).equals(nextbracket)) && (counter != 0)) { + counter--; + } + } + } + + // if no counterpart is found -1 is returned + return -1; + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.java b/src/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.java new file mode 100644 index 0000000..7b7ad7e --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/EditDefinitionActionListener.java @@ -0,0 +1,218 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.ebnf.TermPanel.Type; +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.ebnf.ESymbol; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; + +/** + * + * @author Tom + * + */public class EditDefinitionActionListener implements ActionListener, MouseListener, PopupMenuListener{ + + private ESymbol symbol; + private GuiController guiController; + private boolean menuOpen; + + private TermPanel mouseoverPanel; + + private JPopupMenu pMenu; + private JMenuItem edititem = new JMenuItem(Messages.getString("ebnf", "Ebnf.PopupMenu_Edit")); + private JMenuItem deleteitem = new JMenuItem(Messages.getString("ebnf", "Ebnf.PopupMenu_Delete")); + private JMenuItem startitem = new JMenuItem(Messages.getString("ebnf", "Ebnf.PopupMenu_SetAsStartRule")); + private JMenuItem startvar = new JMenuItem(Messages.getString("ebnf", "Ebnf.PopupMenu_SetAsStartVar")); + + public EditDefinitionActionListener(GuiController guiController) { + this.guiController = guiController; + + edititem.addActionListener(this); + deleteitem.addActionListener(this); + startitem.addActionListener(this); + startvar.addActionListener(this); + + pMenu = new JPopupMenu(); + + pMenu.addPopupMenuListener(this); + + + + pMenu.add(edititem); + pMenu.add(deleteitem); + pMenu.add(startitem); + } + + public void actionPerformed(ActionEvent e) { + Definition definition = guiController.getEbnfController().getDefinition(); + try { + if (mouseoverPanel.type == Type.VARIABLE) { // our currently clicked Panel is a variable + if(e.getSource().equals(deleteitem)) { // delete variable action + guiController.getEbnfController().deleteVariable((EVariable)symbol); + } else if(e.getSource().equals(edititem)) { // edit variable action + guiController.editVariable((EVariable)symbol, mouseoverPanel); + } else if(e.getSource().equals(startvar)) { // change startVar + guiController.getEbnfController().setStartVariable((EVariable)symbol); + } + } else if (mouseoverPanel.type == Type.TERMINALSYMBOL){ // our currently clicked Panel is a terminalsymbol + if(e.getSource().equals(deleteitem)) { // delete terminal action + guiController.getEbnfController().deleteTerminal((ETerminalSymbol)symbol); + } else if(e.getSource().equals(edititem)) { // edit terminal action + guiController.editTerminal((ETerminalSymbol)symbol, mouseoverPanel); + } + } else if (mouseoverPanel.type == Type.RULE) { // our currently clicked Panel is a rule + if(e.getSource().equals(deleteitem)) { // delete rule action + guiController.getEbnfController().deleteRule(definition.getRule((EVariable)symbol)); + } else if(e.getSource().equals(edititem)) { // edit rule action + guiController.editRule(definition.getRule((EVariable)symbol), mouseoverPanel); + } else if(e.getSource().equals(startitem)) { // change startVar + guiController.getEbnfController().setStartVariable((EVariable)symbol); + } + } + } catch (Exception ex) { + guiController.getInputPanel().showInfo(Messages.getString("ebnf", "Ebnf.Error.Undefined"), true); + ex.printStackTrace(); + } +// System.out.println("Action: " + e.getSource()); +// System.out.println(guiController.getEbnfController().getDefinition().toString()); +// System.out.println("----"); + } + + public void mouseClicked(MouseEvent e) { + // This mehthod is not used here, but has to exist due to the interface + } + + public void mousePressed(MouseEvent e) { + // This mehthod is not used here, but has to exist due to the interface + } + + public void mouseEntered(MouseEvent e) { + if (guiController.isEditMode()) { + if(!menuOpen) { + mouseoverPanel = ((TermPanel)e.getComponent()); + mouseoverPanel.setMouseOver(true); + } + } + + } + + public void mouseExited(MouseEvent e) { + if (guiController.isEditMode()) { + if (!menuOpen) { + mouseoverPanel.setMouseOver(false); + } + } + } + + public void mouseReleased(MouseEvent e) { + + if (guiController.isEditMode()) { + mouseEntered(e); + //remove StartVariable-related menu entries + pMenu.remove(startitem); + pMenu.remove(startvar); + symbol = mouseoverPanel.getSymbol(); + + //and check if (other) StartVariable related menu entries should be added + if (mouseoverPanel.type == Type.VARIABLE) { // VARIABLE + //check if the variable is allowed to be deleted + if (guiController.getEbnfController().occursInRightSide(symbol) + || (guiController.getEbnfController().getDefinition().getRule((EVariable)symbol) != null)) + deleteitem.setEnabled(false); + else + deleteitem.setEnabled(true); + + edititem.setText(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.PopupMenu_Rename")); + if (guiController.getCurrentlyEditedVariable() == null){ + edititem.setEnabled(true); + + } else { + deleteitem.setEnabled(false); + edititem.setEnabled(false); + } + + pMenu.add(startvar); + } else if (mouseoverPanel.type == Type.RULE) { // RULES + + + edititem.setText(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.PopupMenu_Edit")); + if (guiController.getCurrentlyEditedRule() == null){ + deleteitem.setEnabled(true); + edititem.setEnabled(true); + } else { + deleteitem.setEnabled(false); + edititem.setEnabled(false); + } + + pMenu.add(startitem); + } else if (mouseoverPanel.type == Type.TERMINALSYMBOL) { // TERMINALSYMBOL + if (guiController.getEbnfController().occursInRightSide(symbol)) + deleteitem.setEnabled(false); + else + deleteitem.setEnabled(true); + + edititem.setText(Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.PopupMenu_Rename")); + if (guiController.getCurrentlyEditedTerminal() == null) { + edititem.setEnabled(true); + } else { + deleteitem.setEnabled(false); + edititem.setEnabled(false); + } + } + + //show menu + pMenu.show(e.getComponent(), e.getX(), e.getY()); + } + } + + + + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + menuOpen = true; + + } + + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + menuOpen = false; + mouseoverPanel.setMouseOver(false); + } + + public void popupMenuCanceled(PopupMenuEvent e) { + // This mehthod is not used here, but has to exist due to the interface + } + } diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.java b/src/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.java new file mode 100644 index 0000000..4d70e8e --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/EditRuleActionListener.java @@ -0,0 +1,54 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * + * @author Tom + * + */public class EditRuleActionListener implements ActionListener { + + private GuiController guiController; + + public EditRuleActionListener(GuiController controller) { + this.guiController = controller; + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("ebnfParentLeft")) guiController.getInputPanel().addSpecialChar("\u3011"); + else if (e.getActionCommand().equals("ebnfParentRight")) guiController.getInputPanel().addSpecialChar("\u3012"); + else if (e.getActionCommand().equals("ebnfBar")) guiController.getInputPanel().addSpecialChar("\u300E"); + else if (e.getActionCommand().equals("ebnfBraceRight")) guiController.getInputPanel().addSpecialChar("\u3010"); + else if (e.getActionCommand().equals("ebnfBraceLeft")) guiController.getInputPanel().addSpecialChar("\u300F"); + else if (e.getActionCommand().equals("ebnfBracketLeft")) guiController.getInputPanel().addSpecialChar("\u300C"); + else if (e.getActionCommand().equals("ebnfBracketRight")) guiController.getInputPanel().addSpecialChar("\u300D"); + else if (e.getActionCommand().equals("ebnfLess")) guiController.getInputPanel().addSpecialChar("\u3008"); + else if (e.getActionCommand().equals("ebnfMore")) guiController.getInputPanel().addSpecialChar("\u3009"); + + else if (e.getActionCommand().equals("inputfinished")) guiController.showChoiceGUI(guiController.getEbnfController().isTransActive()); + else if (e.getActionCommand().equals("checkdefinition")) guiController.showWarningsDialog(true, true); + } + + } diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/GuiController.java b/src/org/jalgo/module/ebnf/gui/ebnf/GuiController.java new file mode 100644 index 0000000..853c18b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/GuiController.java @@ -0,0 +1,941 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.ebnf.EbnfController; +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.GUIConstants; +import org.jalgo.module.ebnf.model.ebnf.DefinitionFormatException; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; +import org.jalgo.module.ebnf.model.ebnf.Rule; + +/** The GUIController is responsible for the creation of the EBNF-GUI and for + * handeling input + * + * @author Tom Kazimiers, Johannes Mey + * + */ +public class GuiController implements Observer{ + + +// ----------------------------------------------------------------------------- +// class variables +// ----------------------------------------------------------------------------- + + + private static final long serialVersionUID = 1L; + + // GUI Components + private JScrollPane definitionHeaderViewScrollPanel; + + private JScrollPane definitionRulesViewScrollPanel; + + private JSplitPane definitionViewPanel; + + private ChoicePanel choicePanel; + + private RuleViewPanel ruleViewPanel; + + private HeaderViewPanel headerViewPanel; + + private InputPanel inputPanel; + + private org.jdesktop.layout.GroupLayout contentPaneLayout; + + private EbnfController ebnfController; + + private JPanel contentPane; + + private Rule currentlyEditedRule; + + private TermPanel currentlyEditedRulePanel; + + private EVariable currentlyEditedVariable; + + private ETerminalSymbol currentlyEditedTerminal; + + private TermPanel currentlyEditedVariablePanel; + + private TermPanel currentlyEditedTerminalPanel; + + // state variables + private boolean newUnknownSymbolAdded; + + private boolean editMode; + + private boolean strictMode; + + private Font ebnfFont; // stores our later initlized EbnfSans.TTF Font + + // Action Listeners + EditRuleActionListener editRuleActionListener; + + ModifyDefinitionActionListener modifyDefinitionActionListener; + + EditDefinitionActionListener editDefinitionActionListener; + + ChoicePanelActionListener choicePanelActionListener; + + ViewPanelSizeListener viewPanelSizeListener; + + private JMenu editMenu; + + private JMenu insertMenu; + + private JMenuItem menuUndo; + + private JMenuItem menuParenthLeft; + + private JMenuItem menuParenthRight; + + private JMenuItem menuParenthBar; + + private JMenuItem menuBracketLeft; + + private JMenuItem menuBracketRight; + + private JMenuItem menuBraceLeft; + + private JMenuItem menuBraceRight; + + private JMenuItem menuLess; + + private JMenuItem menuMore; + +// ----------------------------------------------------------------------------- +// constructor +// ----------------------------------------------------------------------------- + + + /** + * + * @param ebnfController + */ + public GuiController(EbnfController ebnfController) { + + this.ebnfController = ebnfController; + this.contentPane = ebnfController.getContentPane(); + editMode = true; + + try { + this.ebnfFont = EbnfFont.getFont(); + } catch (FontNotInitializedException e) { + // if the right font could not be found use the "sans" font + this.ebnfFont = new Font("Sans", Font.PLAIN, 18); //$NON-NLS-1$ + e.printStackTrace(); + } + + // initialize the ActionListeners + editRuleActionListener = new EditRuleActionListener(this); + modifyDefinitionActionListener = new ModifyDefinitionActionListener( + this); + editDefinitionActionListener = new EditDefinitionActionListener(this); + choicePanelActionListener = new ChoicePanelActionListener(this); + viewPanelSizeListener = new ViewPanelSizeListener(this); + + // create panels + inputPanel = new InputPanel(this); + ruleViewPanel = new RuleViewPanel(this); + headerViewPanel = new HeaderViewPanel(this); + choicePanel = new ChoicePanel(this); + + // initalize panels + + inputPanel.setEbnfFont(ebnfFont); + installMenu(); + initComponents(false); + reloadObservers(); + } + +// ----------------------------------------------------------------------------- +// initialization methods +// ----------------------------------------------------------------------------- + + /** + * This method is called from within the constructor to initialize the form. + */ + private void initComponents(boolean transActive) { + + contentPaneLayout = new org.jdesktop.layout.GroupLayout(contentPane); + contentPane.setLayout(contentPaneLayout); + + if (transActive) { + choicePanel.checkIfDefIsStrict(); + contentPaneLayout.setHorizontalGroup(contentPaneLayout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING).add( + choicePanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE).add(definitionViewPanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 795, + Short.MAX_VALUE)); + + contentPaneLayout + .setVerticalGroup(contentPaneLayout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING) + .add( + contentPaneLayout + .createSequentialGroup() + .add( + choicePanel, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.UNRELATED) + .add( + definitionViewPanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE))); + } else { + definitionViewPanel = new JSplitPane(); + definitionViewPanel.addComponentListener(viewPanelSizeListener); + + definitionHeaderViewScrollPanel = new JScrollPane( + ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + definitionRulesViewScrollPanel = new JScrollPane(); + + definitionViewPanel.setDividerLocation(95); + definitionViewPanel + .setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); + definitionViewPanel + .setTopComponent(definitionHeaderViewScrollPanel); + definitionViewPanel + .setBottomComponent(definitionRulesViewScrollPanel); + + contentPaneLayout.setHorizontalGroup(contentPaneLayout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING).add( + inputPanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE).add(definitionViewPanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 795, + Short.MAX_VALUE)); + + contentPaneLayout + .setVerticalGroup(contentPaneLayout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING) + .add( + contentPaneLayout + .createSequentialGroup() + .add( + inputPanel, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.UNRELATED) + .add( + definitionViewPanel, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE))); + } + definitionHeaderViewScrollPanel.setViewportView(headerViewPanel); + definitionRulesViewScrollPanel.setViewportView(ruleViewPanel); + + contentPane.validate(); + contentPane.repaint(); + + } + +// ----------------------------------------------------------------------------- +// gui control methods +// ----------------------------------------------------------------------------- + + /** + * Installs our own Menu in the j-Algo MenuBar + * + */ + private void installMenu() { + ebnfController.getMainController().removeCustomMenu(); + editMenu = new JMenu(Messages.getString("ebnf", "Ebnf.Edit")); //$NON-NLS-1$ //$NON-NLS-2$ + insertMenu = new JMenu(Messages.getString("ebnf", "Ebnf.Insert")); //$NON-NLS-1$ //$NON-NLS-2$ + ebnfController.getMainController().addMenu(editMenu); + ebnfController.getMainController().addMenu(insertMenu); + + menuUndo = new JMenuItem(Messages.getString("ebnf", "Ebnf.Undo")); //$NON-NLS-1$ //$NON-NLS-2$ + editMenu.add(menuUndo); + + menuParenthLeft = new JMenuItem("( - Alt+U"); //$NON-NLS-1$ + menuParenthLeft.setActionCommand("ebnfParentLeft"); //$NON-NLS-1$ + menuParenthLeft.addActionListener(editRuleActionListener); + insertMenu.add(menuParenthLeft); + + menuParenthRight = new JMenuItem(") - Alt+O"); //$NON-NLS-1$ + menuParenthRight.setActionCommand("ebnfParentRight"); //$NON-NLS-1$ + menuParenthRight.addActionListener(editRuleActionListener); + insertMenu.add(menuParenthRight); + + menuParenthBar = new JMenuItem("| - Alt+I"); //$NON-NLS-1$ + menuParenthBar.setActionCommand("ebnfBar"); //$NON-NLS-1$ + menuParenthBar.addActionListener(editRuleActionListener); + insertMenu.add(menuParenthBar); + + menuBracketLeft = new JMenuItem("[ - Alt+8"); //$NON-NLS-1$ + menuBracketLeft.setActionCommand("ebnfBracketLeft"); //$NON-NLS-1$ + menuBracketLeft.addActionListener(editRuleActionListener); + insertMenu.add(menuBracketLeft); + + menuBracketRight = new JMenuItem("] - Alt+9"); //$NON-NLS-1$ + menuBracketRight.setActionCommand("ebnfBracketRight"); //$NON-NLS-1$ + menuBracketRight.addActionListener(editRuleActionListener); + insertMenu.add(menuBracketRight); + + menuBraceLeft = new JMenuItem("{ - Alt+7"); //$NON-NLS-1$ + menuBraceLeft.setActionCommand("ebnfBraceLeft"); //$NON-NLS-1$ + menuBraceLeft.addActionListener(editRuleActionListener); + insertMenu.add(menuBraceLeft); + + menuBraceRight = new JMenuItem("} - Alt+0"); //$NON-NLS-1$ + menuBraceRight.setActionCommand("ebnfBraceRight"); //$NON-NLS-1$ + menuBraceRight.addActionListener(editRuleActionListener); + insertMenu.add(menuBraceRight); + +// JMenu menu = new JMenu(Messages.getString("ebnf", "Ebnf.FurtherChars")); //$NON-NLS-1$ //$NON-NLS-2$ +// +// menuLess = new JMenuItem("<"); //$NON-NLS-1$ +// menuLess.setActionCommand("ebnfLess"); //$NON-NLS-1$ +// menuLess.addActionListener(editRuleActionListener); +// menu.add(menuLess); +// +// menuMore = new JMenuItem(">"); //$NON-NLS-1$ +// menuMore.setActionCommand("ebnfMore"); //$NON-NLS-1$ +// menuMore.addActionListener(editRuleActionListener); +// menu.add(menuMore); +// +// insertMenu.add(menu); + } + + + /** + * Adds the Observers in the GUI to thedefinition again. Thisis necessary + * when a new Definition is loaded; additionally the Observers are updated + */ + public void reloadObservers() { + ebnfController.getDefinition().addObserver(inputPanel); + ebnfController.getDefinition().addObserver(headerViewPanel); + ebnfController.getDefinition().addObserver(ruleViewPanel); + ebnfController.getDefinition().addObserver(this); + + this.update(null,null); + inputPanel.update(null, null); + headerViewPanel.update(null, null); + ruleViewPanel.update(null, null); + } + + + /** + * @param transActive + */ + public void showChoiceGUI(boolean transActive) { + + ruleViewPanel.setFactor(0.2); + ruleViewPanel.setDisplayName("display"); //$NON-NLS-1$ + + if (!transActive) { + if (!showWarningsDialog(false, false)) + return; + editMode = false; + //System.out.println("Showing ChoiceGUI"); //$NON-NLS-1$ + choicePanel.checkIfDefIsStrict(); + choicePanel.setTransButtonText(); + contentPaneLayout.replace(inputPanel, choicePanel); + contentPane.repaint(); + contentPane.validate(); + } else { + //System.out.println("Showing ChoiceGUI [coming from trans()]"); //$NON-NLS-1$ + setStrictMode(true); + choicePanel.setTransButtonText(); + installMenu(); + if (editMode) { + editMode = false; + contentPaneLayout.replace(inputPanel, choicePanel); + choicePanel.checkIfDefIsStrict(); + getRuleViewPanel().removeAll(); + getRuleViewPanel().drawRules(); + contentPane.repaint(); + contentPane.validate(); + } else { + editMode = false; + initComponents(true); + } + } + + } + + /** + * + * + */ + public void showInputGUI() { + editMode = true; + ruleViewPanel.setFactor(0.22); + ruleViewPanel.setDisplayName("editor"); //$NON-NLS-1$ + // System.out.println("Showing InputGUI"); //$NON-NLS-1$ + contentPaneLayout.replace(choicePanel, inputPanel); + contentPane.repaint(); + } + + public boolean isEditMode() { + return editMode; + } + + /** + * The method repositionDivider sets the divider position of + * the split pane to the given value + * + * @param pos + */ + void repositionDivider(int pos) { + definitionViewPanel.setDividerLocation(pos); + } + + /** + * + * @return + */ + public boolean getStrictMode() { + + return strictMode; + } + + ChoicePanel getChoicePanel() { + return choicePanel; + } + + HeaderViewPanel getHeaderViewPanel() { + return headerViewPanel; + } + + public InputPanel getInputPanel() { + return inputPanel; + } + + RuleViewPanel getRuleViewPanel() { + return ruleViewPanel; + } + + void setRuleViewPanel(RuleViewPanel ruleViewPanel) { + this.ruleViewPanel = ruleViewPanel; + } + + public EbnfController getEbnfController() { + return ebnfController; + } + + JPanel getContentPane() { + return contentPane; + } + + + void setEditMode(boolean editMode) { + this.editMode = editMode; + } + + /** + * @param strictMode + * The strictMode to set. + */ + void setStrictMode(boolean strictMode) { + this.strictMode = strictMode; + choicePanel.checkIfDefIsStrict(); + } + + // popup menu functions for rules + void editRule(Rule rule, TermPanel tPanel) { + if (currentlyEditedRule == null) { + inputPanel.setEditRuleActionCommand(true); + currentlyEditedRule = rule; + currentlyEditedRulePanel = tPanel; + tPanel.setHighlighted(true); + inputPanel.editRule(rule); + ruleViewPanel.editRule(tPanel); + } + } + + void cancelRule() { + if (currentlyEditedRule != null) { + inputPanel.setEditRuleActionCommand(false); + currentlyEditedRulePanel.setHighlighted(false); + inputPanel.cancelRule(); + currentlyEditedRule = null; + currentlyEditedRulePanel = null; + inputPanel.update(null, null); + } + } + + void changeRule() { + if (currentlyEditedRule != null) { + try { + ebnfController.modifyRule(currentlyEditedRule, + currentlyEditedRule.getName(), + inputPanel.addRuleRightSideTextbox.getText()); + } catch (Exception e) { + inputPanel.showInfo(e.getMessage(), true); + } + inputPanel.setEditRuleActionCommand(false); + try { + currentlyEditedRulePanel.setHighlighted(false); + } catch (Exception e ) { + // no idea why there was an exception here + } + inputPanel.cancelRule(); + currentlyEditedRule = null; + currentlyEditedRulePanel = null; + inputPanel.update(null, null); + } + } + + // popup menu functions for terminalsymbols + void editTerminal(ETerminalSymbol terminal, TermPanel tPanel) { + if (currentlyEditedTerminal == null) { + inputPanel.setEditTerminalActionCommand(true); + currentlyEditedTerminal = terminal; + currentlyEditedTerminalPanel = tPanel; + tPanel.setHighlighted(true); + inputPanel.editTerminal(terminal); + } + } + + void cancelTerminal() { + if (currentlyEditedTerminal != null) { + inputPanel.setEditTerminalActionCommand(false); + currentlyEditedTerminalPanel.setHighlighted(false); + inputPanel.cancelTerminal(); + currentlyEditedTerminal = null; + currentlyEditedTerminalPanel = null; + } + } + + void changeTerminal() { + + if (currentlyEditedTerminal != null) { + try { + ebnfController.modifyTerminal(currentlyEditedTerminal, + inputPanel.addTerminalTextField.getText()); + } catch (Exception e) { + inputPanel.showInfo(e.getMessage(), true); + } + inputPanel.setEditTerminalActionCommand(false); + currentlyEditedTerminalPanel.setHighlighted(false); + inputPanel.cancelTerminal(); + currentlyEditedTerminal = null; + currentlyEditedTerminalPanel = null; + } + } + + // popup menu functions for variables + void editVariable(EVariable variable, TermPanel tPanel) { + if (currentlyEditedVariable == null) { + inputPanel.setEditVariableActionCommand(true); + currentlyEditedVariable = variable; + currentlyEditedVariablePanel = tPanel; + tPanel.setHighlighted(true); + inputPanel.editVariable(variable); + } + } + + void cancelVariable() { + if (currentlyEditedVariable != null) { + inputPanel.setEditVariableActionCommand(false); + currentlyEditedVariablePanel.setHighlighted(false); + inputPanel.cancelVariable(); + currentlyEditedVariable = null; + currentlyEditedVariablePanel = null; + } + } + + void changeVariable() { + if (currentlyEditedVariable != null) { + try { + ebnfController.modifyVariable(currentlyEditedVariable, + inputPanel.addVariableTextField.getText()); + } catch (Exception e) { + inputPanel.showInfo(e.getMessage(), true); + } + inputPanel.setEditVariableActionCommand(false); + currentlyEditedVariablePanel.setHighlighted(false); + inputPanel.cancelVariable(); + currentlyEditedVariable = null; + currentlyEditedVariablePanel = null; + } + } + + + + public boolean showUnknownSymbolDialog(String unknownSymbols) { + + JDialog unknownSymbolDialog = new JDialog((JFrame) contentPane + .getTopLevelAncestor(), true); + JButton terminalButton = new javax.swing.JButton(); + JButton variableButton = new javax.swing.JButton(); + JButton cancelButton = new javax.swing.JButton(); + JLabel infoTextLabel = new javax.swing.JLabel(); + JLabel symbolLabel = new javax.swing.JLabel(); + JTextField newSymbolTextField = new javax.swing.JTextField(); + + unknownSymbolDialog + .setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + newSymbolTextField.setText("jTextField1"); //$NON-NLS-1$ + + infoTextLabel + .setText(""+Messages.getString("ebnf", "Ebnf.symbol")+ " " //$NON-NLS-1$ + + unknownSymbols + + " "+Messages.getString("ebnf", "Ebnf.isUnknown")+ ""); //$NON-NLS-1$ + + terminalButton.setText(Messages.getString("ebnf", "Ebnf.terminal")); //$NON-NLS-1$ //$NON-NLS-2$ + + variableButton.setText(Messages.getString("ebnf", "Ebnf.variable")); //$NON-NLS-1$ //$NON-NLS-2$ + + cancelButton.setText(Messages.getString("ebnf", "Ebnf.cancel")); //$NON-NLS-1$ //$NON-NLS-2$ + + symbolLabel.setText(Messages.getString("ebnf", "Ebnf.33")); //$NON-NLS-1$ //$NON-NLS-2$ + + newSymbolTextField.setText(unknownSymbols); + + // reset the unknownSymbolAdded-switch + this.newUnknownSymbolAdded = false; + + // add the actionlisteners + cancelButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + ((JButton) e.getSource()).getTopLevelAncestor().setVisible( + false); + + } + }); + + class AddVariableListener implements ActionListener { + + EbnfController ebnfController; + + JTextField symbolText; + + GuiController guiController; + + public AddVariableListener(EbnfController ebnfController, + JTextField symbolText, GuiController controller) { + this.ebnfController = ebnfController; + this.symbolText = symbolText; + this.guiController = controller; + } + + public void actionPerformed(ActionEvent e) { + try { + ebnfController.addVariable(symbolText.getText()); + } catch (DefinitionFormatException ex) { + guiController.getInputPanel().showInfo(ex.getMessage(), true); + } catch (Exception ex) { + Toolkit.getDefaultToolkit().beep(); + } + + + guiController.newUnknownSymbolAdded = true; + + ((JButton) e.getSource()).getTopLevelAncestor().setVisible( + false); + + } + } + + class AddTerminalListener implements ActionListener { + + EbnfController ebnfController; + + JTextField symbolText; + + GuiController guiController; + + public AddTerminalListener(EbnfController ebnfController, + JTextField symbolText, GuiController controller) { + this.ebnfController = ebnfController; + this.symbolText = symbolText; + this.guiController = controller; + } + + public void actionPerformed(ActionEvent e) { + + try { + ebnfController.addTerminal(symbolText.getText()); + } catch (DefinitionFormatException ex) { + guiController.getInputPanel().showInfo(ex.getMessage(), true); + } catch (Exception ex) { + Toolkit.getDefaultToolkit().beep(); + } + + guiController.newUnknownSymbolAdded = true; + + ((JButton) e.getSource()).getTopLevelAncestor().setVisible( + false); + + } + } + + variableButton.addActionListener(new AddVariableListener( + ebnfController, newSymbolTextField, this)); + terminalButton.addActionListener(new AddTerminalListener( + ebnfController, newSymbolTextField, this)); + + org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout( + unknownSymbolDialog.getContentPane()); + unknownSymbolDialog.getContentPane().setLayout(layout); + layout + .setHorizontalGroup(layout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING) + .add( + layout + .createSequentialGroup() + .addContainerGap() + .add( + layout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING) + .add( + newSymbolTextField, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + 301, + Short.MAX_VALUE) + .add(infoTextLabel) + .add( + layout + .createSequentialGroup() + .add( + variableButton) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.RELATED) + .add( + terminalButton) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.RELATED, + 28, + Short.MAX_VALUE) + .add( + cancelButton)) + .add(symbolLabel)) + .addContainerGap())); + layout + .setVerticalGroup(layout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.LEADING) + .add( + layout + .createSequentialGroup() + .addContainerGap() + .add(infoTextLabel) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.RELATED) + .add(symbolLabel) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.RELATED) + .add( + newSymbolTextField, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + org.jdesktop.layout.LayoutStyle.RELATED, + org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .add( + layout + .createParallelGroup( + org.jdesktop.layout.GroupLayout.BASELINE) + .add(terminalButton) + .add(variableButton) + .add(cancelButton)) + .addContainerGap())); + + unknownSymbolDialog.pack(); + + + unknownSymbolDialog.setLocation(contentPane.getTopLevelAncestor().getX() + (contentPane.getTopLevelAncestor().getWidth()-unknownSymbolDialog.getWidth())/2, + contentPane.getTopLevelAncestor().getX() + (contentPane.getTopLevelAncestor().getHeight()-unknownSymbolDialog.getHeight())/2); + unknownSymbolDialog.setAlwaysOnTop(true); + unknownSymbolDialog.setVisible(true); + + return this.newUnknownSymbolAdded; + } + + public int showSaveStrictModeDialog(boolean withCancelButton) { + int ok; + + if (withCancelButton) + ok = JOptionPane.showConfirmDialog(null, Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.ChoicePanel_SaveStrictMode"), Messages.getString( //$NON-NLS-1$ + "ebnf", "Ebnf.ChoicePanel_StrictMode"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.YES_NO_CANCEL_OPTION); + else + ok = JOptionPane.showConfirmDialog(null, Messages.getString("ebnf", //$NON-NLS-1$ + "Ebnf.ChoicePanel_SaveStrictMode"), Messages.getString( //$NON-NLS-1$ + "ebnf", "Ebnf.ChoicePanel_StrictMode"), //$NON-NLS-1$ //$NON-NLS-2$ + JOptionPane.YES_NO_OPTION); + if (ok == JOptionPane.YES_OPTION) + return 1; + if (ok == JOptionPane.NO_OPTION) + return 0; + return -1; + } + + public boolean showWarningsDialog(boolean includeWarnings, + boolean showWinIfCorrect) { + + JDialog warningDialog = new JDialog(); + JButton okButton = new javax.swing.JButton(); + JLabel infoTextLabel = new javax.swing.JLabel(); + JLabel warningLabel = new JLabel(); + JPanel warningTextPane = new javax.swing.JPanel(); + JScrollPane scrollPane = new JScrollPane(); + + warningDialog + .setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); + warningTextPane.setAutoscrolls(true); + warningTextPane.setBackground(GUIConstants.STANDARD_COLOR_BACKGROUND); + warningDialog.setModal(true); + + scrollPane.setViewportView(warningTextPane); + + infoTextLabel + .setText(""+Messages.getString("ebnf", "Ebnf.Error.StillErrorsInDef")+""); + + + okButton.setText("Ok"); + + String warnings = ebnfController.checkDefinition(includeWarnings); + + // add the actionlisteners + okButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + ((JButton) e.getSource()).getTopLevelAncestor().setVisible( + false); + + } + }); + + warningDialog.setLayout(new BorderLayout(0, 0)); + + warningDialog.add(infoTextLabel, BorderLayout.NORTH); + warningDialog.add(scrollPane, BorderLayout.CENTER); + warningDialog.add(okButton, BorderLayout.SOUTH); + + warningDialog.setLocationByPlatform(true); + + if (warnings.equals("")) { //$NON-NLS-1$ + if (!showWinIfCorrect) + return true; + infoTextLabel + .setText(Messages.getString("ebnf", "Ebnf.RuleIsCorrect")); //$NON-NLS-1$ //$NON-NLS-2$ + warningTextPane.setPreferredSize(new Dimension(300, warningLabel + .getHeight())); + warningDialog.setPreferredSize(new Dimension(400, 100)); + + scrollPane.setVisible(false); + warningDialog.pack(); + + warningDialog.setLocation(contentPane.getTopLevelAncestor().getX() + (int) (contentPane.getTopLevelAncestor().getWidth()-warningDialog.getWidth())/2, + contentPane.getTopLevelAncestor().getX() + (int)(contentPane.getTopLevelAncestor().getHeight()-warningDialog.getHeight())/2); + + + warningDialog.setVisible(true); + warningDialog.setAlwaysOnTop(true); + + warningDialog.validate(); + return true; + } else { + warningTextPane.setVisible(true); + warningLabel.setText(warnings); + warningTextPane.setPreferredSize(new Dimension(warningLabel + .getPreferredSize().width, + warningLabel.getPreferredSize().height + 10)); + warningTextPane.add(warningLabel); + warningDialog.setSize(400, 150); + warningDialog.pack(); + + warningDialog.setLocation(contentPane.getTopLevelAncestor().getX() + (int) (contentPane.getTopLevelAncestor().getWidth()-warningDialog.getWidth())/2, + contentPane.getTopLevelAncestor().getX() + (int)(contentPane.getTopLevelAncestor().getHeight()-warningDialog.getHeight())/2); + + warningDialog.setVisible(true); + warningDialog.setAlwaysOnTop(true); + warningDialog.validate(); + return false; + } + + } + + Rule getCurrentlyEditedRule() { + return currentlyEditedRule; + } + + ETerminalSymbol getCurrentlyEditedTerminal() { + return currentlyEditedTerminal; + } + + EVariable getCurrentlyEditedVariable() { + return currentlyEditedVariable; + } + + public void update(Observable o, Object arg) { + + if (!ebnfController.getDefinition().getRules().contains(currentlyEditedRule)) + cancelRule(); + if (!ebnfController.getDefinition().getVariables().contains(currentlyEditedVariable)) + cancelVariable(); + if (!ebnfController.getDefinition().getTerminals().contains(currentlyEditedTerminal)) + cancelTerminal(); + + } +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.java b/src/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.java new file mode 100644 index 0000000..df4d91d --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/HeaderViewPanel.java @@ -0,0 +1,336 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.util.ArrayList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JPanel; +import javax.swing.UIManager; + +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.GUIConstants; +import org.jalgo.module.ebnf.gui.ebnf.TermPanel.Type; +import org.jalgo.module.ebnf.model.ebnf.Definition; +import org.jalgo.module.ebnf.model.ebnf.ESymbol; +import org.jalgo.module.ebnf.model.ebnf.ETerminalSymbol; +import org.jalgo.module.ebnf.model.ebnf.EVariable; + +/** + * This is the upper panel of the definition view, it shows the header of the + * definition: the tupel and the variable and terminal symbol sets + * + * @author Tom, Johannes + * + */ +public class HeaderViewPanel extends JPanel implements Observer { + + private static final long serialVersionUID = 1L; + + // the GuiController which is needed to get the Definition + private GuiController guiController; + + // This is panel which displays the start variable + private TermPanel startVarTermPanel; + + // these are the panels that display the variables + private List variables; + + // these are the panels that display the terminal symbols + private List terminals; + + // the height of the EBNF font + private int stringHeight; + + // the width of the list of variables + private int variableSetWidth; + + // the width of the list of terminal symbols + private int terminalSetWidth; + + // the horizontal position of the variable set + private int variableSetX; + + /** Creates new form HeaderViewPanel */ + public HeaderViewPanel(GuiController guicontroller) { + + // save the guiController reference + this.guiController = guicontroller; + + // initialize the font + try { + this.setFont(EbnfFont.getFont()); + } catch (FontNotInitializedException e) { + // if the right font could not be found use the "sans" font + this.setFont(new Font("Sans", Font.PLAIN, 18)); + e.printStackTrace(); + } + + stringHeight = getFont().getSize(); + + // initialize the actionListener + this.addComponentListener(guicontroller.viewPanelSizeListener); + + variableSetX = getStringWidth("V = {") + 12; + + // set a null layout + this.setLayout(null); + + // draw the header; this is the central function + drawHeader(); + } + + /** + * @return the String height of the Ebnf font + */ + public int getStringHeight() { + return stringHeight; + } + + /** + * @param string the string to be measured + * @return the width of the string + */ + private int getStringWidth(String string) { + FontMetrics metrics = getFontMetrics(this.getFont()); + return metrics.stringWidth(string); + } + + /** + * this function draws the panels of the definition header. it is called + * whenever the definition changes. note that it does not draw the rest + * of the panel; this is done in paintComponent() + */ + public void drawHeader() { + + // temporarily store the definition + Definition definition = guiController.getEbnfController().getDefinition(); + + // clear the panel + this.removeAll(); + + // clear the variable and terminal symbol lists + this.variables = new ArrayList(); + this.terminals = new ArrayList(); + +// ----------------------------------------------------------------------------- +// draw the start variable +// ----------------------------------------------------------------------------- + // create a termpanel with the size of the start variable and add it to + // the header view panel and place it + ESymbol startVar = definition.getStartVariable(); + String tempString = EbnfRenderer.toRenderString(startVar, false, ""); + startVarTermPanel = new TermPanel(this, tempString, startVar, + getStringWidth(tempString), stringHeight); + startVarTermPanel.type = Type.VARIABLE; + this.add(startVarTermPanel); + startVarTermPanel.setLocation(getStringWidth("E = (V, \u03a3, "), 4); + +// ----------------------------------------------------------------------------- +// draw the variables +// ----------------------------------------------------------------------------- + + List variables = definition.getVariables(); + tempString = ""; + + // initialize the width with 0 + variableSetWidth = 0; + + for (int i = 0; i < variables.size(); i++) { + this.variables.add(new TermPanel(this, variables.get(i).getName(), + variables.get(i), + getStringWidth(variables.get(i).getName()), stringHeight)); + this.variables.get(i).setLocation(variableSetX + variableSetWidth, + stringHeight + 15); + this.variables.get(i).type = Type.VARIABLE; + this.variables.get(i).addMouseListener( + guiController.editDefinitionActionListener); + this.add(this.variables.get(i)); + variableSetWidth = variableSetWidth + + this.variables.get(i).getWidth() + getStringWidth(", "); + + } + +// ----------------------------------------------------------------------------- +// draw the terminal symbols +// ----------------------------------------------------------------------------- + + List terminals = definition.getTerminals(); + terminalSetWidth = 0; + + for (int i = 0; i < terminals.size(); i++) { + this.terminals.add(new TermPanel(this, terminals.get(i).getName(), + terminals.get(i), + getStringWidth(terminals.get(i).getName()), stringHeight)); + this.terminals.get(i).setLocation(variableSetX + terminalSetWidth, + 2 * stringHeight + 25); + this.terminals.get(i).type = Type.TERMINALSYMBOL; + this.terminals.get(i).addMouseListener( + guiController.editDefinitionActionListener); + this.add(this.terminals.get(i)); + terminalSetWidth = terminalSetWidth + + this.terminals.get(i).getWidth() + getStringWidth(", "); + + } + + // finally, validate and repaint to show the changes + this.validate(); + this.repaint(); + } + + + + /* (non-Javadoc) + * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) + */ + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + + g2.clearRect(0, 0, getWidth(), getHeight()); + g2.setColor(GUIConstants.STANDARD_COLOR_BACKGROUND); + g2.fillRect(0, 0, getWidth(), getHeight()); + + super.paintComponents(g); + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + g2.setColor(Color.BLACK); + g2.setFont(getFont()); + + // draw the first header-line with the startsymbol + if (startVarTermPanel != null) { + g2.drawString("E = (V, \u03a3, ", 10, stringHeight + 5); + g2.drawString(", R)", getStringWidth("E = (V, \u03a3, ") + + startVarTermPanel.getWidth(), stringHeight + 5); + } + + // draw the second line with the definitions variables + g2.drawString("V = {", 10, 2 * stringHeight + 15); + + for (int i = 0; i < variables.size() - 1; i++) { + g2.drawString(",", variables.get(i).getX() + + variables.get(i).getWidth(), 2 * stringHeight + 15); + } + g2.drawString("}", variableSetX + variableSetWidth, + 2 * stringHeight + 15); + + // draw the third line with terminalsymbols + g2.drawString("\u03a3 = {", 10, 3 * stringHeight + 25); + + for (int i = 0; i < terminals.size() - 1; i++) { + g2.drawString(",", terminals.get(i).getX() + + terminals.get(i).getWidth(), 3 * stringHeight + 25); + } + g2.drawString("}", variableSetX + terminalSetWidth, + 3 * stringHeight + 25); + } + + /* (non-Javadoc) + * @see java.util.Observer#update(java.util.Observable, java.lang.Object) + */ + public void update(Observable o, Object arg) { + drawHeader(); + manageScrollBars(); + } + + /** + * This function manages the scrollbars, i.e. it shows them exactly when + * necessary + */ + public void manageScrollBars() { + int terminalSize = 0; + int variableSize = 0; + int startTermSize = 0; + int scrollBarHeight = Integer.parseInt(UIManager.get("ScrollBar.width") + .toString()); + + if (terminals.size() > 0) + terminalSize = 20 + + terminals.get(terminals.size() - 1).getLocation().x + + terminals.get(terminals.size() - 1).getWidth(); + + if (variables.size() > 0) + variableSize = 20 + + variables.get(variables.size() - 1).getLocation().x + + variables.get(variables.size() - 1).getWidth(); + + if (startVarTermPanel != null) + startTermSize = 30 + startVarTermPanel.getLocation().x + + startVarTermPanel.getWidth(); + if (terminalSize >= this.getWidth()) { + this.setPreferredSize(new Dimension(terminalSize, + 95 + scrollBarHeight)); + guiController.repositionDivider(95 + scrollBarHeight); + this.revalidate(); + } else if (variableSize >= this.getWidth()) { + this.setPreferredSize(new Dimension(variableSize, + 95 + scrollBarHeight)); + guiController.repositionDivider(95 + scrollBarHeight); + this.revalidate(); + } else if (startTermSize >= this.getWidth()) { + this.setPreferredSize(new Dimension(startTermSize, + 95 + scrollBarHeight)); + guiController.repositionDivider(95 + scrollBarHeight); + this.revalidate(); + } else { + int i = 0; + int b = this.getParent().getWidth(); + if (terminalSize > variableSize) { + if (terminalSize > startTermSize) + i = terminalSize; + else + i = startTermSize; + } else { + if (variableSize > startTermSize) + i = variableSize; + else + i = startTermSize; + } + if (i rulePanels; + private int margin_x; + private int margin_y; + private int ruleColumnWidth; + private int rowHeight; + private int stringHeight; + private double factor; + private String displayName; + + + + + + /** Creates new form RuleViewPanel */ + public RuleViewPanel(GuiController guicontroller) { + this.guiController = guicontroller; + try { + this.setFont(EbnfFont.getFont()); + } catch (FontNotInitializedException e) { + // if the right font could not be found use the "sans" font + this.setFont(new Font("Sans", Font.PLAIN, 18)); + e.printStackTrace(); + } + this.setLayout(null); + this.addComponentListener(guicontroller.viewPanelSizeListener); + this.setAutoscrolls(true); + this.addMouseWheelListener(this); + stringHeight = getFont().getSize(); + margin_y = 5; + margin_x = 40; + + factor = 0.22; + displayName = "editor"; + } + + /** + * Draws the rules on the RuleViewPanel. + */ + public void drawRules() { + String term; + String variable; + this.removeAll(); + ruleColumnWidth = 0; + rowHeight = stringHeight + 10; + List rules = new ArrayList(); + List distances = new ArrayList(); + rulePanels = new ArrayList(); + + for(Rule rule : guiController.getEbnfController().getDefinition().getRules()) { + rules.add(rule); + + variable = EbnfRenderer.toRenderString(rule.getName(), false, ""); + term = EbnfRenderer.toRenderString(rule.getTerm(), guiController.getStrictMode(), " "); + + if (ruleColumnWidth < getStringWidth(variable)) ruleColumnWidth = getStringWidth(variable); + + TermPanel tPanel = new TermPanel(this, variable+" ::= "+term, rule.getName(), + getStringWidth(variable+" ::= "+term), stringHeight); + this.rulePanels.add(tPanel); + + distances.add(getStringWidth(variable)); + + tPanel.addMouseListener(guiController.editDefinitionActionListener); + tPanel.type = Type.RULE; + } + + for(int i=0; i ruleSize) + ruleSize = i; + ruleHeight =+ tPanel.getLocation().y + tPanel.getHeight(); + } + this.setPreferredSize(new Dimension(ruleSize, ruleHeight)); + this.revalidate(); + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public void setFactor(double factor) { + this.factor = factor; + } + + public void mouseWheelMoved(MouseWheelEvent e) { + javax.swing.JScrollBar scrollbar = ((JScrollPane)this.getParent().getParent()).getVerticalScrollBar(); + + if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { + int totalScrollAmount = + e.getUnitsToScroll() * 4; + scrollbar.setValue(scrollbar.getValue() + totalScrollAmount); + } + } +} diff --git a/src/org/jalgo/module/ebnf/gui/ebnf/TermPanel.java b/src/org/jalgo/module/ebnf/gui/ebnf/TermPanel.java new file mode 100644 index 0000000..10b8471 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/ebnf/TermPanel.java @@ -0,0 +1,119 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf.gui.ebnf; + +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import javax.swing.JComponent; + +import org.jalgo.module.ebnf.gui.GUIConstants; +import org.jalgo.module.ebnf.model.ebnf.ESymbol; + + /**This class represents a JComponent in which EBNF-Elements got drawn. + * + * @author Tom + * + */public class TermPanel extends JComponent { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String name; + private int strheight; + private ESymbol symbol; + public enum Type { RULE, VARIABLE, TERMINALSYMBOL } + public Type type; + private boolean highlighted; + private boolean mouseover; + + + + public TermPanel(JComponent parent, String renderString, ESymbol symbol, int strwidth, int strheight) { + this.symbol = symbol; + this.name = renderString; + this.strheight = strheight; + this.setSize(strwidth+2, strheight+8); + setFont(parent.getFont()); + setLayout(null); + highlighted = false; + mouseover = false; + } + + + private int getStringWidth(String string) { + FontMetrics metrics = getFontMetrics( this.getFont() ); + return metrics.stringWidth(string); + } + + @Override + protected void paintComponent(Graphics g) { + + Graphics2D g2 = (Graphics2D)g; + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + + if (highlighted) g2.setColor(GUIConstants.HIGHLIGHT_COLOR); + else if (mouseover)g2.setColor(GUIConstants.MOUSEOVER_COLOR); + else g2.setColor(GUIConstants.STANDARD_COLOR_BACKGROUND); + g2.fillRoundRect(0,0,getWidth(), getHeight(), 10, 10); + g2.setFont(getFont()); + + for(int i=0;itrue
          if you want to autosize. + */ + public void setAutoSize(boolean autosize) { + drawPanel.setAutoSize(autosize); + if (autosize) + drawPanel.update(null, null); + this.drawScrollPane.validate(); + } + + /** + * Sets the Zoomers value + * + * @param size + * new size + */ + public void setZoomerValue(int size) { + controlPanel.setZoomerValue(size); + } + + /** + * Returns the drawPanel. + * + * @return the drawPanel + */ + public DrawPanel getDrawPanel() { + return drawPanel; + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/CVS/Entries b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Entries new file mode 100644 index 0000000..468a2fc --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Entries @@ -0,0 +1,16 @@ +/AbstractSDGuiController.java/1.1/Fri Aug 11 16:40:32 2006// +/ChangeBoldListener.java/1.1/Fri Aug 11 16:40:32 2006// +/ChangeColorToGreenListener.java/1.1/Fri Aug 11 16:40:33 2006// +/ChangeColorToRedListener.java/1.1/Fri Aug 11 16:40:32 2006// +/ChangeEditModeMenu.java/1.1/Fri Aug 11 16:40:32 2006// +/ChangeFillColorToListener.java/1.1/Fri Aug 11 16:40:32 2006// +/DeleteDiagramListener.java/1.1/Fri Aug 11 16:40:32 2006// +/DeleteElemListener.java/1.1/Fri Aug 11 16:40:32 2006// +/EditorControlPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/EditorDrawPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/GuiController.java/1.1/Fri Aug 11 16:40:33 2006// +/OkActionListener.java/1.1/Fri Aug 11 16:40:32 2006// +/RedoAction.java/1.1/Fri Aug 11 16:40:32 2006// +/SynDiaMouseListener.java/1.1/Fri Aug 11 16:40:32 2006// +/UndoAction.java/1.1/Fri Aug 11 16:40:32 2006// +D/display//// diff --git a/src/org/jalgo/module/ebnf/gui/syndia/CVS/Repository b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Repository new file mode 100644 index 0000000..e4eca8d --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/syndia diff --git a/src/org/jalgo/module/ebnf/gui/syndia/CVS/Root b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.java b/src/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.java new file mode 100644 index 0000000..aae5af1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/ChangeBoldListener.java @@ -0,0 +1,34 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Font; +import java.awt.event.MouseEvent; + +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.module.ebnf.renderer.elements.RenderName; + +/** + * MouseListener for RenderName in edit mode. + * + * @author Michael Thiele + * + */ +public class ChangeBoldListener extends MouseInputAdapter { + + /** + * If mouse enters RenderName change fontStyle to BOLD+ITALIC. + */ + public void mouseEntered(MouseEvent e) { + ((RenderName)e.getComponent()).setFontStyle(Font.BOLD | Font.ITALIC); + ((RenderName)e.getComponent()).repaint(); + } + + /** + * If mouse exits RenderName change fontStyle back to ITALIC. + */ + public void mouseExited(MouseEvent e) { + ((RenderName)e.getComponent()).setFontStyle(Font.ITALIC); + ((RenderName)e.getComponent()).repaint(); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.java b/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.java new file mode 100644 index 0000000..ee5f613 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToGreenListener.java @@ -0,0 +1,32 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.MouseEvent; + +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.module.ebnf.renderer.elements.RenderNullElem; + +/** + * MouseListener that changes color of NullElems to green if mouse enters it. + * + * @author Michael Thiele + * + */ +public class ChangeColorToGreenListener extends MouseInputAdapter { + + /** + * If mouse enters, change color of NullElem to green. + */ + public void mouseEntered(MouseEvent e) { + ((RenderNullElem) e.getComponent()) + .setColor(RenderNullElem.HIGHLIGHT_GREEN); + } + + /** + * If mouse exits, change color back to standard color. + */ + public void mouseExited(MouseEvent e) { + ((RenderNullElem) e.getComponent()) + .setColor(RenderNullElem.STANDARD_COLOR_GREY); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.java b/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.java new file mode 100644 index 0000000..fa90c2f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/ChangeColorToRedListener.java @@ -0,0 +1,32 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.MouseEvent; + +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.module.ebnf.renderer.elements.RenderNullElem; + +/** + * MouseListener that changes color of NullElems to red if mouse enters it. + * + * @author Michael Thiele + * + */ +public class ChangeColorToRedListener extends MouseInputAdapter { + + /** + * If mouse enters, change color of NullElem to red. + */ + public void mouseEntered(MouseEvent e) { + ((RenderNullElem) e.getComponent()) + .setColor(RenderNullElem.HIGHLIGHT_COLOR); + } + + /** + * If mouse exits, change color back to standard color. + */ + public void mouseExited(MouseEvent e) { + ((RenderNullElem) e.getComponent()) + .setColor(RenderNullElem.STANDARD_COLOR_GREY); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.java b/src/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.java new file mode 100644 index 0000000..aaeb141 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/ChangeEditModeMenu.java @@ -0,0 +1,122 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseListener; + +import javax.swing.ImageIcon; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; + +/** + * A popup menu to change the edit mode in the syntax diagram editor. It is + * ActionListener for all menu items. + * + * @author Michael Thiele + * + */ +public class ChangeEditModeMenu extends JPopupMenu implements ActionListener { + + private static final long serialVersionUID = 3596209418605843774L; + + private GuiController guiController; + + private MouseListener myStatusUpdater; + + /** + * Initalizes the popup menu. + * + * @param guiController + */ + public ChangeEditModeMenu(GuiController guiController) { + this.guiController = guiController; + + this.setBackground(Color.WHITE); + + JMenuItem modeEdit = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeEdit_Image"))); + modeEdit.addActionListener(this); + add(modeEdit); + + JMenuItem modeDelete = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeDelete_Image"))); + modeDelete.addActionListener(this); + add(modeDelete); + + this.addSeparator(); + + JMenuItem modeAddTerminal = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeAddTerminal_Image"))); + modeAddTerminal.addActionListener(this); + add(modeAddTerminal); + + JMenuItem modeAddVariable = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeAddVariable_Image"))); + modeAddVariable.addActionListener(this); + add(modeAddVariable); + + JMenuItem modeBranch = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeAddBranch_Image"))); + modeBranch.addActionListener(this); + add(modeBranch); + + JMenuItem modeRepetition = new JMenuItem(new ImageIcon(Messages + .getResourceURL("ebnf", "ModeAddRepetition_Image"))); + modeRepetition.addActionListener(this); + add(modeRepetition); + + this.myStatusUpdater = StatusLineUpdater.getInstance(); + + modeEdit.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_Edit")); + modeEdit.addMouseListener(myStatusUpdater); + modeDelete.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_Delete")); + modeDelete.addMouseListener(myStatusUpdater); + modeAddTerminal.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddTerminal")); + modeAddTerminal.addMouseListener(myStatusUpdater); + modeAddVariable.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddVariable")); + modeAddVariable.addMouseListener(myStatusUpdater); + modeBranch.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddBranch")); + modeBranch.addMouseListener(myStatusUpdater); + modeRepetition.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddRepetition")); + modeRepetition.addMouseListener(myStatusUpdater); + + } + + /** + * Changes the edit mode if a menu button was pressed. + */ + public void actionPerformed(ActionEvent e) { + String event = e.getSource().toString(); + // a bad trick to know which element was clicked: getSource contains the + // path of the image -> is also in Messages.getResourceURL(...) + if (event.contains(Messages.getResourceURL("ebnf", "ModeEdit_Image") + .toString())) { + guiController.setModeEdit(); + } else if (event.contains(Messages.getResourceURL("ebnf", + "ModeAddTerminal_Image").toString())) { + guiController.setModeAddTerminal(); + } else if (event.contains(Messages.getResourceURL("ebnf", + "ModeAddVariable_Image").toString())) { + guiController.setModeAddVariable(); + } else if (event.contains(Messages.getResourceURL("ebnf", + "ModeAddBranch_Image").toString())) { + guiController.setModeAddBranch(); + } else if (event.contains(Messages.getResourceURL("ebnf", + "ModeAddRepetition_Image").toString())) { + guiController.setModeAddRepetition(); + } else if (event.contains(Messages.getResourceURL("ebnf", + "ModeDelete_Image").toString())) { + guiController.setModeDelete(); + } + } +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.java b/src/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.java new file mode 100644 index 0000000..f9aa8a6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/ChangeFillColorToListener.java @@ -0,0 +1,34 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.MouseEvent; + +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * MouseListener that highlights terminal symbols and variables. + * + * @author Michael Thiele + * + */ +public class ChangeFillColorToListener extends MouseInputAdapter { + + /** + * Changes the color to blue if mouse enters this element. + */ + public void mouseEntered(MouseEvent e) { + ((RenderElement) e.getComponent()) + .setColor(RenderElement.HIGHLIGHT_BLUE); + } + + /** + * Changes the color back to standard fill color if mouse exits this + * element. + */ + public void mouseExited(MouseEvent e) { + ((RenderElement) e.getComponent()) + .setColor(RenderElement.STANDARD_FILL_COLOR); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.java b/src/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.java new file mode 100644 index 0000000..e98b50a --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/DeleteDiagramListener.java @@ -0,0 +1,92 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Component; +import java.awt.event.MouseEvent; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.module.ebnf.gui.syndia.display.SynDiaPanel; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * MouseListener that paints a border around syntax diagrams in delete mode. + * + * @author Michael Thiele + * + */ +public class DeleteDiagramListener extends MouseInputAdapter { + + private GuiController guiController; + + /** + * + * @param guiController + * the guiController this Listener belongs to + */ + public DeleteDiagramListener(GuiController guiController) { + this.guiController = guiController; + } + + /** + * If mouse enters, paint a red border around syntax diagram. + */ + public void mouseEntered(MouseEvent e) { + Component c = e.getComponent(); + if (c instanceof SynDiaPanel) { + ((SynDiaPanel) e.getComponent()).setBorder(BorderFactory + .createLineBorder(RenderElement.HIGHLIGHT_COLOR, 3)); + } else { + ((SynDiaPanel) e.getComponent().getParent()) + .setBorder(BorderFactory.createLineBorder( + RenderElement.HIGHLIGHT_COLOR, 3)); + } + } + + /** + * If mouse exits, set border back to standard (no border). + */ + public void mouseExited(MouseEvent e) { + Component c = e.getComponent(); + if (c instanceof SynDiaPanel) { + ((SynDiaPanel) e.getComponent()).setBorder(BorderFactory + .createEmptyBorder()); + } else { + ((SynDiaPanel) e.getComponent().getParent()) + .setBorder(BorderFactory.createEmptyBorder()); + } + } + + /** + * If mouse is clicked, remove the diagram. + */ + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + Component c = e.getComponent(); + if (c instanceof SynDiaPanel) { + try { + guiController.getSynDiaController().removeSyntaxDiagram( + guiController.getRenderMap().get( + ((JPanel) c).getComponent(2)) + .getMySyntaxDiagram()); + } catch (IllegalArgumentException ex) { + guiController.ShowDoNotDeleteStartDiagram(); + } catch (Exception ex2) { + ex2.printStackTrace(); + } + } else { + try { + guiController.getSynDiaController().removeSyntaxDiagram( + guiController.getRenderMap().get( + c.getParent().getComponent(2)) + .getMySyntaxDiagram()); + } catch (IllegalArgumentException ex) { + guiController.ShowDoNotDeleteStartDiagram(); + } catch (Exception ex2) { + ex2.printStackTrace(); + } + } + } + } +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.java b/src/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.java new file mode 100644 index 0000000..de394dd --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/DeleteElemListener.java @@ -0,0 +1,298 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Component; +import java.awt.event.MouseEvent; +import java.util.Map; + +import javax.swing.event.MouseInputListener; + +import org.jalgo.module.ebnf.gui.trans.SynDiaElemNotFoundException; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.elements.RenderBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderNoStairBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderRepetition; +import org.jalgo.module.ebnf.renderer.elements.RenderSplit; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +/** + * Mouse- and MouseMotionListener that highlights branches and repetitions in + * delete mode. If mouse is clicked, it deletes the highlighted elements. + * + * @author Michael Thiele + * + */ +public class DeleteElemListener implements MouseInputListener { + + private GuiController guiController; + + private boolean top = false; + + private boolean in = true; + + /** + * Initalizes the listener. + * + * @param guiController + * the guiController, the listener belongs to + */ + public DeleteElemListener(GuiController guiController) { + this.guiController = guiController; + } + + private SynDiaElem getElem(Component component) { + Map renderMap = guiController.getRenderMap(); + if (renderMap.containsKey(component)) { + return renderMap.get(component); + } + return null; + } + + /** + * If the mosue is moved inside the component, this method checks if it is + * in the top part of the branch or repetition or the lower part of it. It + * highlights the actual path and all children of it. + */ + public void mouseMoved(MouseEvent e) { + + if (e.getComponent() instanceof RenderSplit) { + RenderSplit rb = (RenderSplit) e.getComponent(); + + if (e.getY() < 2 * guiController.getRenderRadius()) { + + if (!top || in) { + rb.setTopHighlight(true, RenderElement.HIGHLIGHT_COLOR); + rb.setBottomHighlight(false, RenderElement.STANDARD_COLOR); + // search for elements on that line, that have to be + // highlighted too + Concatenation concat; + // old highlighted elems back to "normal" + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getRight(); + } else { + concat = ((Repetition) getElem(rb)).getRight(); + } + changeHighlightMode(concat, false); + // highlight actual elems + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getLeft(); + } else { + concat = ((Repetition) getElem(rb)).getLeft(); + } + changeHighlightMode(concat, true); + top = true; + } + + } else { + + if (top || in) { + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(true, RenderElement.HIGHLIGHT_COLOR); + // search for elements on that line, that have to be + // highlighted too + Concatenation concat; + // old highlighted elems back to "normal" + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getLeft(); + } else { + concat = ((Repetition) getElem(rb)).getLeft(); + } + changeHighlightMode(concat, false); + // highlight actual elems + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getRight(); + } else { + concat = ((Repetition) getElem(rb)).getRight(); + } + changeHighlightMode(concat, true); + top = false; + } + } + in = false; + } + } + + public void mouseDragged(MouseEvent e) { + + } + + /** + * If mouse enters this element, change color for terminal symbols and + * variables and initialize branch and repetition highlighting. + */ + public void mouseEntered(MouseEvent e) { + + RenderElement re = (RenderElement) e.getComponent(); + if (re instanceof RenderSplit) { + in = true; + } else if (re instanceof RenderTerminal || re instanceof RenderVariable) { + re.setColor(RenderElement.HIGHLIGHT_COLOR); + } + } + + /** + * If mouse exits the element, change colors back to standard. + */ + public void mouseExited(MouseEvent e) { + + RenderElement re = (RenderElement) e.getComponent(); + if (re instanceof RenderSplit) { + RenderSplit rb = (RenderSplit) re; + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(false, RenderElement.STANDARD_COLOR); + // search for elements on that line, that have to be + // highlighted too + Concatenation concat; + if (top) { + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getLeft(); + } else { + concat = ((Repetition) getElem(rb)).getLeft(); + } + } else { + if (rb instanceof RenderBranch + || rb instanceof RenderNoStairBranch) { + concat = ((Branch) getElem(rb)).getRight(); + } else { + concat = ((Repetition) getElem(rb)).getRight(); + } + } + changeHighlightMode(concat, false); + } else if (re instanceof RenderTerminal || re instanceof RenderVariable) { + re.setColor(RenderElement.STANDARD_FILL_COLOR); + } + + } + + public void mousePressed(MouseEvent e) { + + } + + public void mouseReleased(MouseEvent e) { + + } + + /** + * If mouse is clicked, delete all highlighted elements. + */ + public void mouseClicked(MouseEvent e) { + + if (e.getButton() == MouseEvent.BUTTON1) { + Component currentComponent = e.getComponent(); + if (currentComponent instanceof RenderBranch) { + if (top) { + guiController.getSynDiaController().removeBranch( + (Branch) getElem(currentComponent), false, true); + } else { + guiController.getSynDiaController().removeBranch( + (Branch) getElem(currentComponent), true, false); + } + } else if (currentComponent instanceof RenderRepetition) { + if (top) { + guiController.getSynDiaController() + .removeRepetition( + (Repetition) getElem(currentComponent), + false, true); + } else { + guiController.getSynDiaController() + .removeRepetition( + (Repetition) getElem(currentComponent), + true, false); + } + } + } + } + + /** + * @param sde + * a SynDiaElem finding itself in the RenderMap + * @return the render element representing the syntax diagram element in the + * model + * @throws SynDiaElemNotFoundException + */ + private RenderElement getReFromSde(SynDiaElem sde) + throws SynDiaElemNotFoundException { + Map renderMap = guiController.getRenderMap(); + if (renderMap.containsValue(sde)) { + for (RenderElement re : renderMap.keySet()) { + if (sde == renderMap.get(re)) + return re; + } + } + throw new SynDiaElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + + private void changeHighlightMode(Concatenation concat, boolean highlight) { + // no NullElems + for (int i = 1; i < concat.getNumberOfElems(); i = i + 2) { + SynDiaElem sde = concat.getSynDiaElem(i); + if (sde instanceof TerminalSymbol || sde instanceof Variable) { + try { + if (highlight) { + getReFromSde(sde).setColor( + RenderElement.HIGHLIGHT_COLOR); + } else { + getReFromSde(sde).setColor( + RenderElement.STANDARD_FILL_COLOR); + } + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + } else if (sde instanceof Branch) { + try { + if (highlight) { + ((RenderSplit) getReFromSde(sde)).setTopHighlight( + highlight, RenderElement.HIGHLIGHT_COLOR); + ((RenderSplit) getReFromSde(sde)).setBottomHighlight( + highlight, RenderElement.HIGHLIGHT_COLOR); + } else { + ((RenderSplit) getReFromSde(sde)).setTopHighlight( + highlight, RenderElement.STANDARD_COLOR); + ((RenderSplit) getReFromSde(sde)).setBottomHighlight( + highlight, RenderElement.STANDARD_COLOR); + } + // recursively call changeHighlightMode for children of a + // branch + changeHighlightMode(((Branch) sde).getLeft(), highlight); + changeHighlightMode(((Branch) sde).getRight(), highlight); + } catch (SynDiaElemNotFoundException e2) { + e2.printStackTrace(); + } + } else if (sde instanceof Repetition) { + try { + if (highlight) { + ((RenderSplit) getReFromSde(sde)).setTopHighlight( + highlight, RenderElement.HIGHLIGHT_COLOR); + ((RenderSplit) getReFromSde(sde)).setBottomHighlight( + highlight, RenderElement.HIGHLIGHT_COLOR); + } else { + ((RenderSplit) getReFromSde(sde)).setTopHighlight( + highlight, RenderElement.STANDARD_COLOR); + ((RenderSplit) getReFromSde(sde)).setBottomHighlight( + highlight, RenderElement.STANDARD_COLOR); + } + // recursively call changeHighlightMode for children of a + // repetition + changeHighlightMode(((Repetition) sde).getLeft(), highlight); + changeHighlightMode(((Repetition) sde).getRight(), + highlight); + } catch (SynDiaElemNotFoundException e2) { + e2.printStackTrace(); + } + } + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.java new file mode 100644 index 0000000..3789e64 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/EditorControlPanel.java @@ -0,0 +1,353 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JToggleButton; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.syndia.display.AbstractControlPanel; +import org.jalgo.module.ebnf.gui.syndia.display.DiagramSize; + +/** + * Control panel for the syntax diagram editor. Administrates all "mode + * buttons". + * + * @author Michael Thiele + */ +@SuppressWarnings("serial") +public class EditorControlPanel extends AbstractControlPanel { + + private JButton toSynDiaView = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToSynDiaDisplay")); + + private JToggleButton modeEdit = new JToggleButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.Edit"))); + + private JToggleButton modeAddTerminal = new JToggleButton(new ImageIcon( + Messages.getResourceURL("ebnf", "Icon.AddTerminal"))); + + private JToggleButton modeAddVariable = new JToggleButton(new ImageIcon( + Messages.getResourceURL("ebnf", "Icon.AddVariable"))); + + private JToggleButton modeAddBranch = new JToggleButton(new ImageIcon( + Messages.getResourceURL("ebnf", "Icon.AddBranch"))); + + private JToggleButton modeAddRepetition = new JToggleButton(new ImageIcon( + Messages.getResourceURL("ebnf", "Icon.AddRepetition"))); + + private JToggleButton modeDelete = new JToggleButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.Delete"))); + + private JButton addDiagram = new JButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.AddDiagram"))); + + private JToggleButton lastActiveButton = modeEdit; + + private AbstractSDGuiController controller; + + private ItemListener fitToSizeListener; + + private FocusAdapter zoomerFocusListener; + + private ChangeListener zoomerChangeListener; + + private ActionListener toSynDiaViewListener; + + private ActionListener modeEditListener; + + private ActionListener modeAddTerminalListener; + + private ActionListener modeAddVariableListener; + + private ActionListener modeAddBranchListener; + + private ActionListener modeAddRepetitionListener; + + private ActionListener modeDeleteListener; + + private ActionListener addDiagramListener; + + private MouseListener myStatusUpdater; + + /** + * Initializes the EditorControllPanel. + * + * @param controller + * the guiController this control panel belongs to. + */ + public EditorControlPanel(AbstractSDGuiController controller) { + this.controller = controller; + fitToSize.setSelected(false); + init(); + initListener(); + } + + /** + * Initializes the "mode buttons". + */ + private void init() { + + // elements + JLabel empty = new JLabel(" "); + JLabel empty2 = new JLabel(" "); + JLabel empty3 = new JLabel(" "); + + // JPanel right = new JPanel(); + right.setBackground(Color.WHITE); + right.add(toSynDiaView); + this.add(right, BorderLayout.EAST); + + modeEdit.setBackground(Color.WHITE); + modeDelete.setBackground(Color.WHITE); + modeAddTerminal.setBackground(Color.WHITE); + modeAddVariable.setBackground(Color.WHITE); + modeAddBranch.setBackground(Color.WHITE); + modeAddRepetition.setBackground(Color.WHITE); + addDiagram.setBackground(Color.WHITE); + + modeEdit.setFocusable(false); + modeDelete.setFocusable(false); + modeAddTerminal.setFocusable(false); + modeAddVariable.setFocusable(false); + modeAddBranch.setFocusable(false); + modeAddRepetition.setFocusable(false); + addDiagram.setFocusable(false); + + Insets insets = new Insets(1, 1, 1, 1); + modeEdit.setMargin(insets); + modeAddTerminal.setMargin(insets); + modeAddVariable.setMargin(insets); + modeAddBranch.setMargin(insets); + modeAddRepetition.setMargin(insets); + modeDelete.setMargin(insets); + addDiagram.setMargin(insets); + + modeEdit.setDisabledSelectedIcon(new ImageIcon(Messages.getResourceURL( + "ebnf", "Icon.SelectedEdit"))); + modeDelete.setDisabledSelectedIcon(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.SelectedDelete"))); + modeAddTerminal.setDisabledSelectedIcon(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.SelectedAddTerminal"))); + modeAddVariable.setDisabledSelectedIcon(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.SelectedAddVariable"))); + modeAddBranch.setDisabledSelectedIcon(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.SelectedAddBranch"))); + modeAddRepetition.setDisabledSelectedIcon(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.SelectedAddRepetition"))); + + addDiagram.setMnemonic(KeyEvent.VK_N); + modeEdit.setMnemonic(KeyEvent.VK_E); + modeDelete.setMnemonic(KeyEvent.VK_D); + modeAddTerminal.setMnemonic(KeyEvent.VK_T); + modeAddVariable.setMnemonic(KeyEvent.VK_V); + modeAddBranch.setMnemonic(KeyEvent.VK_B); + modeAddRepetition.setMnemonic(KeyEvent.VK_R); + + this.myStatusUpdater = StatusLineUpdater.getInstance(); + + addDiagram.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddSynDia")); + addDiagram.addMouseListener(myStatusUpdater); + modeEdit.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_Edit")); + modeEdit.addMouseListener(myStatusUpdater); + modeDelete.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_Delete")); + modeDelete.addMouseListener(myStatusUpdater); + modeAddTerminal.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddTerminal")); + modeAddTerminal.addMouseListener(myStatusUpdater); + modeAddVariable.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddVariable")); + modeAddVariable.addMouseListener(myStatusUpdater); + modeAddBranch.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddBranch")); + modeAddBranch.addMouseListener(myStatusUpdater); + modeAddRepetition.setToolTipText(Messages.getString("ebnf", + "SynDiaEditor.ToolTip_AddRepetition")); + modeAddRepetition.addMouseListener(myStatusUpdater); + + empty.setBackground(Color.WHITE); + left.add(empty); + left.add(addDiagram); + left.add(empty2); + left.add(modeEdit); + left.add(modeDelete); + left.add(empty3); + left.add(modeAddTerminal); + left.add(modeAddVariable); + left.add(modeAddBranch); + left.add(modeAddRepetition); + + this.add(left, BorderLayout.WEST); + + } + + private void enableLastButton(JToggleButton newButton) { + // enable last button again + lastActiveButton.setEnabled(true); + lastActiveButton.setSelected(false); + newButton.setSelected(true); + newButton.setEnabled(false); + lastActiveButton = newButton; + } + + private void checkListener() { + if (lastActiveButton == modeEdit) { + ((GuiController) controller).setChangeElemListenerBack(); + } else if (lastActiveButton == modeAddBranch + || lastActiveButton == modeAddRepetition) { + ((GuiController) controller).setNullElemColorListenerBack(); + } else if (lastActiveButton == modeDelete) { + ((GuiController) controller).setDeleteElemListenerBack(); + } + } + + private void initListener() { + + fitToSizeListener = new ItemListener() { + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + controller.setAutoSize(true); + } else { + controller.setAutoSize(false); + } + } + }; + fitToSize.addItemListener(fitToSizeListener); + + zoomerFocusListener = new FocusAdapter() { + public void focusGained(FocusEvent e) { + fitToSize.setSelected(false); + } + }; + zoomer.addFocusListener(zoomerFocusListener); + + zoomerChangeListener = new ChangeListener() { + public void stateChanged(ChangeEvent e) { + controller.resizeDrawPanel(zoomer.getValue()); + } + }; + zoomer.addChangeListener(zoomerChangeListener); + + toSynDiaViewListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + DiagramSize + .setFontSize(controller.getDrawPanel().getFontSize()); + ((GuiController) controller).switchToSynDiaView(); + } + }; + + toSynDiaView.addActionListener(toSynDiaViewListener); + + modeEditListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeEdit); + ((GuiController) controller).setModeEdit(); + } + }; + modeEdit.addActionListener(modeEditListener); + modeEdit.setSelected(true); + modeEdit.setEnabled(false); + + modeAddTerminalListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeAddTerminal); + ((GuiController) controller).setModeAddTerminal(); + } + }; + modeAddTerminal.addActionListener(modeAddTerminalListener); + + modeAddVariableListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeAddVariable); + ((GuiController) controller).setModeAddVariable(); + } + }; + modeAddVariable.addActionListener(modeAddVariableListener); + + modeAddBranchListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeAddBranch); + ((GuiController) controller).setModeAddBranch(); + } + }; + modeAddBranch.addActionListener(modeAddBranchListener); + + modeAddRepetitionListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeAddRepetition); + ((GuiController) controller).setModeAddRepetition(); + } + }; + modeAddRepetition.addActionListener(modeAddRepetitionListener); + + modeDeleteListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + checkListener(); + enableLastButton(modeDelete); + ((GuiController) controller).setModeDelete(); + } + }; + modeDelete.addActionListener(modeDeleteListener); + + addDiagramListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + ((GuiController) controller) + .showEditSynDiaName(null, 20, 20, Messages.getString( + "ebnf", "SynDiaEditor.NameOfDiagram")); + } + }; + addDiagram.addActionListener(addDiagramListener); + + } + + /** + * Is called, if the mode for editing has changed. + * + * @param newMode + * the new mode + */ + public void changeMode(int newMode) { + if (newMode == SynDiaMouseListener.MODE_EDIT && modeEdit.isEnabled()) { + enableLastButton(modeEdit); + } else if (newMode == SynDiaMouseListener.MODE_TERMINAL + && modeAddTerminal.isEnabled()) { + enableLastButton(modeAddTerminal); + } else if (newMode == SynDiaMouseListener.MODE_VARIABLE + && modeAddVariable.isEnabled()) { + enableLastButton(modeAddVariable); + } else if (newMode == SynDiaMouseListener.MODE_BRANCH + && modeAddBranch.isEnabled()) { + enableLastButton(modeAddBranch); + } else if (newMode == SynDiaMouseListener.MODE_REPETITION + && modeAddRepetition.isEnabled()) { + enableLastButton(modeAddRepetition); + } else if (newMode == SynDiaMouseListener.MODE_DELETE + && modeDelete.isEnabled()) { + enableLastButton(modeDelete); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.java new file mode 100644 index 0000000..b3c620f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/EditorDrawPanel.java @@ -0,0 +1,70 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Component; + +import javax.swing.JPanel; + +import org.jalgo.module.ebnf.gui.syndia.display.DrawPanel; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.renderer.SynDiaRenderer; + +/** + * DrawPanel for the syntax diagram editor. Sets synDiaMouseListener to + * synDiaPanels. + * + * @author Michael Thiele + * + */ +@SuppressWarnings("serial") +public class EditorDrawPanel extends DrawPanel { + + private SynDiaMouseListener synDiaMouseListener; + + /** + * Initializes the EditorDrawPanel. + * + * @param synDiaSystem + * the actual syntax diagram system + * @param dc + * the guiController the EditorDrawPanel belongs to + * @param synDiaRenderer + * the syntax diagram renderer for this EditorDrawPanel + */ + public EditorDrawPanel(SynDiaSystem synDiaSystem, + AbstractSDGuiController dc, SynDiaRenderer synDiaRenderer) { + super(synDiaSystem, dc, synDiaRenderer); + autoSize = false; + displayName = "editor"; + factor = 0.22; + } + + /** + * Sets the SynDiaMouseListener for all + * SynDiaPanels. + * + * @param synDiaMouseListener + * the synDiaMouseListener + */ + public void setMouseListener(SynDiaMouseListener synDiaMouseListener) { + this.synDiaMouseListener = synDiaMouseListener; + } + + /** + * Fills the synDiaPanelList with elements. Adds the + * synDiaMouseListener. + */ + public void drawSynDiaSystem(SynDiaSystem sds) { + super.drawSynDiaSystem(sds); + for (JPanel sdp : synDiaPanelList) { + sdp.setSize(sdp.getWidth(), sdp.getHeight() + + renderer.getRenderValues().radius + 2); + for (Component c : sdp.getComponents()) { + c.addMouseListener(synDiaMouseListener); + } + sdp.addMouseListener(synDiaMouseListener); + } + ((GuiController) controller).setRenderMap(renderMap); + ((GuiController) controller).hasBeenDrawn(); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/GuiController.java b/src/org/jalgo/module/ebnf/gui/syndia/GuiController.java new file mode 100644 index 0000000..6b725a3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/GuiController.java @@ -0,0 +1,1265 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.Map; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JToolBar; +import javax.swing.border.TitledBorder; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.controller.syndia.SynDiaController; +import org.jalgo.module.ebnf.gui.syndia.display.SynDiaPanel; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.EditorRenderer; +import org.jalgo.module.ebnf.renderer.RenderValues; +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderName; +import org.jalgo.module.ebnf.renderer.elements.RenderNullElem; +import org.jalgo.module.ebnf.renderer.elements.RenderSplit; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderTiledBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderTiledRepetition; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +/** + * The GuiController of the syntax diagram input. Administrates + * all GUI elements. Its DrawPanel is observer of the syntax + * diagram model to update the syntax diagram view. + * + * @author Michael Thiele + * + */ +public class GuiController extends AbstractSDGuiController { + + private SynDiaController synDiaController; + + private ModuleConnector connector; + + private Map renderMap; + + private RenderTiledBranch renderTiledBranch; + + private RenderTiledRepetition renderTiledRepetition; + + private JPanel rootPane; + + private SynDiaMouseListener synDiaMouseListener; + + private ChangeColorToGreenListener changeColorToGreenListener; + + private ChangeColorToRedListener changeColorToRedListener; + + private ChangeFillColorToListener changeFillColorToListener; + + private ChangeBoldListener changeBoldListener; + + private DeleteElemListener deleteElemListener; + + private DeleteDiagramListener deleteDiagramListener; + + private ChangeEditModeMenu changeEditModeMenu; + + private EditorRenderer synDiaRenderer; + + private JDialog dialogEdit; + + private JDialog dialogNew; + + private JDialog dialogSynDiaName; + + private JTextField newTextField; + + private JTextField editTextField; + + private JTextField synDiaNameTextField; + + private JPanel panel; + + private JCheckBox checkBox; + + private ItemListener checkBoxListener; + + private String oldLabel; + + private boolean setStartDiagram; + + private JButton okButton; + + private SynDiaElem currentSynDiaElem; + + private Component currentRenderElement; + + private SyntaxDiagram currentSyntaxDiagram; + + private int mode; + + private JDialog dialogNoStartDiagram; + + private JPanel popupIncomplete; + + private Cursor cursorBranch; + + private Cursor cursorRepetition; + + private Cursor cursorVariable; + + private Cursor cursorTerminal; + + private Cursor cursorDelete; + + private Cursor cursorEdit; + + private Cursor cursorBranchRight; + + private Cursor cursorRepetitionRight; + + private AbstractAction undoAction; + + private AbstractAction redoAction; + + private JDialog dialog; + + private int topOfDrawPanel, leftOfDrawPanel; + + /** + * Initializes the textFields, cursors, panels and mouse listener. + * + * @param synDiaController + * interface to the syntax diagram controller; is needed to + * change syntax diagram model + * @param connector + * the jalgo module connector + * @param rootPane + * the jalgo main panel + */ + public GuiController(SynDiaController synDiaController, + ModuleConnector connector, JPanel rootPane) { + this.synDiaController = synDiaController; + this.connector = connector; + this.rootPane = rootPane; + init(); + } + + /** + * Is called by the constructor. + * + */ + private void init() { + + // set cursor to "wait" + rootPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + + initToolbar(); + + ActionListener changeLabel = new ActionListener() { + public void actionPerformed(ActionEvent e) { + changeLabelOfElement(); + } + }; + + Font tahoma = new Font("Tahoma", Font.PLAIN, 15); + // ok-Button + okButton = new JButton("OK"); + okButton.addActionListener(new OkActionListener(this)); + okButton.setSize(25, 25); + okButton.setMargin(new Insets(1, 1, 1, 1)); + okButton.setVisible(true); + okButton.setFocusable(false); + + // dialogEdit: for changes in label names + dialogEdit = new JDialog((Frame) rootPane.getTopLevelAncestor(), true); + dialogEdit.setUndecorated(true); + dialogEdit.setFocusable(false); + JPanel panelEdit = new JPanel(); + panelEdit.setLayout(new BoxLayout(panelEdit, BoxLayout.X_AXIS)); + editTextField = new JTextField(); + editTextField.setFont(tahoma); + editTextField.addActionListener(changeLabel); + editTextField.addKeyListener(new KeyAdapter() { + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + dialogEdit.setVisible(false); + } + } + }); + panelEdit.add(editTextField); + panelEdit.add(okButton); + dialogEdit.setContentPane(panelEdit); + + // ok-Button + okButton = new JButton("OK"); + okButton.addActionListener(new OkActionListener(this)); + okButton.setSize(25, 25); + okButton.setMargin(new Insets(1, 1, 1, 1)); + okButton.setVisible(true); + okButton.setFocusable(false); + + // newTextField: for input of new terminal symbol or variable names + dialogNew = new JDialog((Frame) rootPane.getTopLevelAncestor(), true); + dialogNew.setUndecorated(true); + dialogNew.setFocusable(false); + JPanel panelNew = new JPanel(); + panelNew.setLayout(new BoxLayout(panelNew, BoxLayout.X_AXIS)); + newTextField = new JTextField(); + newTextField.setFont(tahoma); + newTextField.addActionListener(changeLabel); + newTextField.addKeyListener(new KeyAdapter() { + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + dialogNew.setVisible(false); + } + } + }); + panelNew.add(newTextField); + panelNew.add(okButton); + dialogNew.setContentPane(panelNew); + + // ok-Button + okButton = new JButton("OK"); + okButton.addActionListener(new OkActionListener(this)); + okButton.setSize(25, 25); + okButton.setMargin(new Insets(1, 1, 1, 1)); + okButton.setVisible(true); + okButton.setFocusable(false); + + // synDiaNameTextField + dialogSynDiaName = new JDialog((Frame) rootPane.getTopLevelAncestor(), + true); + dialogSynDiaName.setUndecorated(true); + // dialogSynDiaName.setUndecorated(true); + synDiaNameTextField = new JTextField(); + synDiaNameTextField.setFont(tahoma); + synDiaNameTextField.addActionListener(changeLabel); + synDiaNameTextField.addKeyListener(new KeyAdapter() { + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + dialogSynDiaName.setVisible(false); + } + } + }); + panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + int width = 100; + int height = 25; + int border = 15; + editTextField.setSize(width, height); + panel.setBackground(Color.WHITE); + panel.setVisible(true); + JLabel startDiagram = new JLabel("Startdiagramm"); + startDiagram.setBackground(Color.WHITE); + startDiagram.setSize(width, height); + startDiagram.setFont(new Font("Courier New", Font.PLAIN, 12)); + startDiagram.repaint(); + startDiagram.setVisible(true); + checkBox = new JCheckBox(); + checkBox.setEnabled(true); + checkBox.setBackground(Color.WHITE); + checkBox.setSize(height, height); + checkBox.repaint(); + checkBox.setVisible(true); + checkBoxListener = new ItemListener() { + public void itemStateChanged(ItemEvent arg0) { + setStartDiagram = ((JCheckBox)arg0.getSource()).isSelected(); + } + }; + + JPanel panel1 = new JPanel(); + panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS)); + panel1.setBackground(Color.WHITE); + panel1.add(synDiaNameTextField); + panel1.add(okButton); + + JPanel panel2 = new JPanel(); + panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS)); + panel2.setBackground(Color.WHITE); + panel2.add(startDiagram); + panel2.add(Box.createRigidArea(new Dimension(10, 0))); + panel2.add(checkBox); + + panel.add(panel1); + panel.add(panel2); + + panel.setSize(width + height + 2 * border, height * 2 + + (int) (border * 1.5)); + panel.validate(); + panel.repaint(); + dialogSynDiaName.setSize(panel.getSize()); + dialogSynDiaName.setContentPane(panel); + + // --- + renderTiledBranch = new RenderTiledBranch(); + renderTiledRepetition = new RenderTiledRepetition(); + + // renderer + synDiaRenderer = new EditorRenderer(); + + // scrollPane (from: DisplayController) + drawScrollPane = new JScrollPane(); + drawPanel = new EditorDrawPanel(synDiaController.getSynDiaSystem(), + this, synDiaRenderer); + controlPanel = new EditorControlPanel(this); + + // setting + rootPane.setBackground(Color.WHITE); + drawScrollPane.setBackground(Color.WHITE); + drawScrollPane.setViewportBorder(javax.swing.BorderFactory + .createLoweredBevelBorder()); + drawScrollPane.setViewportView(drawPanel); + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, rootPane + .getHeight() + - controlPanel.getPreferredSize().height)); + drawScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder( + null, Messages.getString("ebnf", "Border_Draw"), + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + controlPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, controlPanel + .getPreferredSize().height)); + + rootPane.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, + rootPane.getHeight() + - controlPanel.getPreferredSize().height)); + } + }); + + // layout + rootPane.setLayout(new BoxLayout(rootPane, BoxLayout.Y_AXIS)); + rootPane.add(controlPanel); + rootPane.add(drawScrollPane); + rootPane.validate(); + + // listener + changeColorToGreenListener = new ChangeColorToGreenListener(); + changeColorToRedListener = new ChangeColorToRedListener(); + changeFillColorToListener = new ChangeFillColorToListener(); + deleteElemListener = new DeleteElemListener(this); + changeBoldListener = new ChangeBoldListener(); + deleteDiagramListener = new DeleteDiagramListener(this); + + synDiaMouseListener = new SynDiaMouseListener(this, renderMap); + ((EditorDrawPanel) drawPanel).setMouseListener(synDiaMouseListener); + changeEditModeMenu = new ChangeEditModeMenu(this); + drawPanel.addMouseListener(synDiaMouseListener); + + // dialog "do not delete start diagram" + Font font = new Font("Tahoma", Font.PLAIN, 13); + dialogNoStartDiagram = new JDialog((Frame) rootPane + .getTopLevelAncestor(), true); + dialogNoStartDiagram.setVisible(false); + dialogNoStartDiagram.setUndecorated(true); + JPanel popupNote = new JPanel(); + popupNote.setLayout(new BoxLayout(popupNote, BoxLayout.Y_AXIS)); + popupNote.setBackground(Color.WHITE); + popupNote.setBorder(BorderFactory.createTitledBorder(null, Messages + .getString("ebnf", "SynDiaEditor.PopupNote_Border"), + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, font, Color.RED)); + JLabel doNotDeleteStartDiagram = new JLabel(Messages.getString("ebnf", + "SynDiaEditor.PopupNote_DoNotDeleteStartDiagram")); + doNotDeleteStartDiagram.setBackground(Color.WHITE); + doNotDeleteStartDiagram.setFont(font); + doNotDeleteStartDiagram.setAlignmentX(Component.CENTER_ALIGNMENT); + FontMetrics fm = doNotDeleteStartDiagram.getFontMetrics(font); + JButton okButton = new JButton("OK"); + okButton.setSize(25, 25); + okButton.setAlignmentX(Component.CENTER_ALIGNMENT); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + dialogNoStartDiagram.setVisible(false); + } + }); + popupNote.add(doNotDeleteStartDiagram); + popupNote.add(Box.createRigidArea(new Dimension(0, 10))); + popupNote.add(okButton); + popupNote.validate(); + popupNote.repaint(); + popupNote.addKeyListener(new KeyAdapter() { + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + dialogNoStartDiagram.setVisible(false); + } + } + }); + dialogNoStartDiagram.setContentPane(popupNote); + dialogNoStartDiagram.setSize(fm.stringWidth(doNotDeleteStartDiagram + .getText()) / 3, 100); + dialogNoStartDiagram.setLocationRelativeTo(rootPane); + + // popup incomplete + popupIncomplete = new JPanel(); + popupIncomplete.setVisible(false); + popupIncomplete.setLayout(new BoxLayout(popupIncomplete, + BoxLayout.Y_AXIS)); + popupIncomplete.setBackground(Color.WHITE); + popupIncomplete.setBorder(BorderFactory.createTitledBorder(null, + Messages.getString("ebnf", "SynDiaEditor.PopupNote_Border"), + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, font, Color.RED)); + + initCursor(); + + // set cursor back + rootPane.setCursor(Cursor.getDefaultCursor()); + + } + + private void initCursor() { + // cursor + cursorBranch = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", "Cursor_Branch")) + .getImage(), new Point(1, 2), "Cursor"); + cursorRepetition = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", + "Cursor_Repetition")).getImage(), new Point(1, 2), + "Cursor"); + cursorVariable = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages + .getResourceURL("ebnf", "Cursor_Variable")).getImage(), + new Point(1, 2), "Cursor"); + cursorTerminal = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages + .getResourceURL("ebnf", "Cursor_Terminal")).getImage(), + new Point(1, 2), "Cursor"); + cursorDelete = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", "Cursor_Delete")) + .getImage(), new Point(1, 2), "Cursor"); + cursorEdit = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", "Cursor_Edit")) + .getImage(), new Point(1, 2), "Cursor"); + cursorBranchRight = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", + "Cursor_BranchRight")).getImage(), new Point(1, 2), + "Cursor"); + cursorRepetitionRight = drawPanel.getToolkit().createCustomCursor( + new ImageIcon(Messages.getResourceURL("ebnf", + "Cursor_RepetitionRight")).getImage(), new Point(1, 2), + "Cursor"); + drawPanel.setCursor(cursorEdit); + } + + private void initToolbar() { + JToolBar toolBar = JAlgoGUIConnector.getInstance().getModuleToolbar( + connector); + toolBar.addSeparator(); + undoAction = new UndoAction(this); + toolBar.add(createToolbarButton(undoAction)); + redoAction = new RedoAction(this); + toolBar.add(createToolbarButton(redoAction)); + // redoAction.setEnabled(false); + // undoAction.setEnabled(false); + toolBar.validate(); + } + + /** + * Creates a JButton object without border and text, which + * can be used in JToolBars + * + * @return a JButton instance with the given + * Action + */ + private JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton((Icon) a + .getValue(Action.SMALL_ICON), null, null); + button.setAction(a); + button.setText(""); + return button; + } + + /** + * Switches to syntax diagram view. + * + */ + public void switchToSynDiaView() { + if (synDiaController.getSynDiaSystem().isComplete()) { + JToolBar toolBar = JAlgoGUIConnector.getInstance() + .getModuleToolbar(connector); + toolBar.removeAll(); + toolBar.validate(); + toolBar.repaint(); + synDiaController.switchToSynDiaView(); + } else { + ShowIncompleteSystem(); + } + } + + /** + * Sets a new render map. + * + * @param renderMap + * the new render map + */ + public void setRenderMap(Map renderMap) { + this.renderMap = renderMap; + } + + /** + * Sets a given cursor type. + * + * @param cursor + * name of the new cursor + */ + public void setCursor(String cursor) { + if (cursor.toLowerCase().equals("branch")) { + drawPanel.setCursor(cursorBranch); + } else if (cursor.toLowerCase().equals("repetition")) { + drawPanel.setCursor(cursorRepetition); + } else if (cursor.toLowerCase().equals("variable")) { + drawPanel.setCursor(cursorVariable); + } else if (cursor.toLowerCase().equals("terminal")) { + drawPanel.setCursor(cursorTerminal); + } else if (cursor.toLowerCase().equals("delete")) { + drawPanel.setCursor(cursorDelete); + } else if (cursor.toLowerCase().equals("edit")) { + drawPanel.setCursor(cursorEdit); + } else if (cursor.toLowerCase().equals("branchright")) { + drawPanel.setCursor(cursorBranchRight); + } else if (cursor.toLowerCase().equals("repetitionright")) { + drawPanel.setCursor(cursorRepetitionRight); + } + } + + /** + * Shows the popup menu, where you can choose the edit mode. + * + * @param x + * position where the contect menu should pop up + * @param y + * position where the contect menu should pop up + */ + public void showChangeEditModeMenu(int x, int y) { + changeEditModeMenu.show(drawPanel, x, y); + } + + /** + * Returns the syntax diagram controller. + * + * @return the syntax diagram controller + */ + public SynDiaController getSynDiaController() { + return synDiaController; + } + + /** + * Returns the renderMap of all syntax diagrams. + * + * @return the renderMap of all syntax diagrams + */ + public Map getRenderMap() { + return renderMap; + } + + /** + * NullElems loose their color listener and terminal symbols and variables + * get a new color listener. + * + */ + public void setChangeElemListener() { + for (RenderElement re : renderMap.keySet()) { + if (re instanceof RenderNullElem) { + re.removeMouseListener(changeColorToGreenListener); + } else if (re instanceof RenderVariable + || re instanceof RenderTerminal) { + re.addMouseListener(changeFillColorToListener); + } else if (re instanceof RenderName) { + re.addMouseListener(changeBoldListener); + } + } + } + + /** + * Sets all changes from setChangeElemListener() back. + * + */ + public void setChangeElemListenerBack() { + for (RenderElement re : renderMap.keySet()) { + if (re instanceof RenderNullElem) { + re.addMouseListener(changeColorToGreenListener); + } else if (re instanceof RenderVariable + || re instanceof RenderTerminal) { + re.removeMouseListener(changeFillColorToListener); + } else if (re instanceof RenderName) { + re.removeMouseListener(changeBoldListener); + } + } + } + + /** + * If mode is delete, remove listener for NullElems and add + * DeleteElemListener for all destroyable elements. + * + */ + public void setDeleteElemListener() { + // set NullElems to background, so that lines can be fully selected + for (RenderElement re : renderMap.keySet()) { + // remove listener for NullElems - they are not needed in delete + // mode + if (re instanceof RenderNullElem) { + re.removeMouseListener(changeColorToGreenListener); + re.getParent().setComponentZOrder(re, + re.getParent().getComponentCount() - 1); + } else if (!(re instanceof RenderBase)) { + re.addMouseListener(deleteElemListener); + re.addMouseMotionListener(deleteElemListener); + } + } + // search for empty diagrams + for (SynDiaPanel sdp : drawPanel.getSynDiaPanelList()) { + // 3 objects in empty diagram: name, base, 1 NullElem + if (sdp.getComponentCount() == 3) { + sdp.addMouseListener(deleteDiagramListener); + for (Component c : sdp.getComponents()) { + c.addMouseListener(deleteDiagramListener); + } + } + } + } + + /** + * Sets all listener back if there is a change from delete mode to another + * mode. + * + */ + public void setDeleteElemListenerBack() { + // set NullElems to foreground, so that they can be fully selected + for (RenderElement re : renderMap.keySet()) { + if (!(re instanceof RenderBase) || !(re instanceof RenderNullElem)) { + re.removeMouseListener(deleteElemListener); + re.removeMouseMotionListener(deleteElemListener); + } + // add listener for NullElems - they are needed now + if (re instanceof RenderNullElem) { + re.addMouseListener(changeColorToGreenListener); + re.getParent().setComponentZOrder(re, 0); + } + // if element is instance of RenderSplit it could be highlighted + if (re instanceof RenderSplit) { + ((RenderSplit) re).setTopHighlight(false, + RenderElement.STANDARD_COLOR); + ((RenderSplit) re).setBottomHighlight(false, + RenderElement.STANDARD_COLOR); + } + // if element is instance of RenderTerminal or RenderVariable it + // could be highlighted if it is part of an arm of a repetition + // or branch that is highlighted + else if (re instanceof RenderTerminal + || re instanceof RenderVariable) { + re.setColor(RenderElement.STANDARD_FILL_COLOR); + } + } + for (SynDiaPanel sdp : drawPanel.getSynDiaPanelList()) { + sdp.removeMouseListener(deleteDiagramListener); + for (Component c : sdp.getComponents()) { + c.removeMouseListener(deleteDiagramListener); + } + } + } + + /** + * Sets a new ColorListener for NullElems that are not on the same line. + * + * @param leftNullElem + * left side of the branch - the right side has to be at the same + * line + */ + public void setNullElemColorListener(NullElem leftNullElem) { + for (RenderElement re : renderMap.keySet()) { + if (re instanceof RenderNullElem) { + if (((NullElem) renderMap.get(re)).getLine() != leftNullElem + .getLine()) { + re.removeMouseListener(changeColorToGreenListener); + re.addMouseListener(changeColorToRedListener); + } + } + } + } + + /** + * Sets all ColorListener for NullElems back. + * + */ + public void setNullElemColorListenerBack() { + for (RenderElement re : renderMap.keySet()) { + if (re instanceof RenderNullElem) { + re.removeMouseListener(changeColorToRedListener); + // there are some listeners on green - remove them + re.removeMouseListener(changeColorToGreenListener); + re.addMouseListener(changeColorToGreenListener); + } + } + } + + /** + * Shows a popup window which says, that it is not allowed to delete the + * start diagram. + */ + public void ShowDoNotDeleteStartDiagram() { + dialogNoStartDiagram.setVisible(true); + } + + private void ShowIncompleteSystem() { + dialog = new JDialog((Frame) rootPane.getTopLevelAncestor(), true); + dialog.setVisible(false); + dialog.setBackground(Color.WHITE); + dialog.setLayout(new BoxLayout(dialog.getContentPane(), + BoxLayout.Y_AXIS)); + dialog.setUndecorated(true); + Font font = new Font("Tahoma", Font.PLAIN, 13); + JLabel incomplete = new JLabel(Messages.getString("ebnf", + "SynDiaEditor.PopupIncomplete_Top")); + incomplete.setBackground(Color.WHITE); + incomplete.setFont(font); + incomplete.setAlignmentX(Component.CENTER_ALIGNMENT); + popupIncomplete.add(incomplete); + popupIncomplete.add(Box.createRigidArea(new Dimension(0, 15))); + FontMetrics fm = incomplete.getFontMetrics(font); + popupIncomplete.setSize(fm.stringWidth(incomplete.getText()) / 3, 100); + JButton okButton = new JButton("OK"); + okButton.setSize(25, 25); + okButton.setAlignmentX(Component.CENTER_ALIGNMENT); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + dialog.setVisible(false); + popupIncomplete.removeAll(); + } + }); + int counter = 0; + SynDiaSystem sds = synDiaController.getSynDiaSystem(); + boolean loop = true; + for (String name : sds.getVariables()) { + if (loop) { + try { + sds.getSyntaxDiagram(name); + } catch (ElementNotFoundException e) { + counter++; + JLabel variable = new JLabel(name); + variable.setBackground(Color.WHITE); + variable.setAlignmentX(Component.CENTER_ALIGNMENT); + variable.setFont(font); + popupIncomplete.add(variable); + popupIncomplete.add(Box + .createRigidArea(new Dimension(0, 10))); + if (counter > 5) { + variable.setText("..."); + loop = false; + } + } + } + } + popupIncomplete.add(okButton); + popupIncomplete.setVisible(true); + popupIncomplete.validate(); + popupIncomplete.repaint(); + dialog.setContentPane(popupIncomplete); + dialog.setSize(popupIncomplete.getWidth(), popupIncomplete.getHeight() + + counter * 30); + dialog.setLocationRelativeTo(rootPane); + dialog.setVisible(true); + } + + /** + * Shows popup for editing syntax diagram names. + * + * @param sd + * the syntax diagram + * @param x + * position x + * @param y + * position y + * @param topLine + * text for the border + */ + public void showEditSynDiaName(SyntaxDiagram sd, int x, int y, + String topLine) { + this.currentSyntaxDiagram = sd; + setStartDiagram = false; + checkBox.setEnabled(true); + x -= drawPanel.getX(); + // if you want to edit + if (sd != null) { + // test, if this is the old startDiagram + synDiaNameTextField.setText(sd.getName()); + if (synDiaController.getSynDiaSystem().getStartDiagram().equals( + sd.getName())) { + setStartDiagram = true; + checkBox.setEnabled(false); + } + } else { + synDiaNameTextField.setText(""); + y -= drawPanel.getY(); + } + checkBox.setSelected(setStartDiagram); + checkBox.addItemListener(checkBoxListener); + oldLabel = synDiaNameTextField.getText(); + panel.setBorder(BorderFactory.createTitledBorder(null, topLine, + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION)); + panel.repaint(); + // fill topOfDrawPanel + leftOfDrawPanel + topOfDrawPanel = drawPanel.getLocationOnScreen().y; + leftOfDrawPanel = drawPanel.getLocationOnScreen().x; + synDiaNameTextField.requestFocus(); + synDiaNameTextField.selectAll(); + // set size to (0, 0) to get exactly the middle of the draw panel + dialogSynDiaName.setLocation(leftOfDrawPanel + x, topOfDrawPanel + y); + dialogSynDiaName.setVisible(true); + } + + /** + * Shows the text field for edit mode. + * + * @param x + * position where text field should pop up + * @param y + * position where text field should pop up + * @param synDiaElem + * is needed to save currentSynDiaElem + */ + public void showEditTextField(int x, int y, SynDiaElem synDiaElem) { + this.currentSynDiaElem = synDiaElem; + if (currentSynDiaElem instanceof TerminalSymbol) { + editTextField.setText(((TerminalSymbol) synDiaElem).getLabel()); + } else if (currentSynDiaElem instanceof Variable) { + editTextField.setText(((Variable) synDiaElem).getLabel()); + } + oldLabel = editTextField.getText(); + int additionalWidth = 40; + int width = editTextField.getFontMetrics(editTextField.getFont()) + .charsWidth(editTextField.getText().toCharArray(), 0, + editTextField.getText().toCharArray().length) + + additionalWidth; + if (width < 60) + width = 60; + int height = 25; + editTextField.setSize(width, height); + y += 1.2 * getRenderRadius() - 15; + dialogEdit.setSize(editTextField.getWidth() + 25, editTextField + .getHeight()); + // fill topOfDrawPanel + leftOfDrawPanel + topOfDrawPanel = drawPanel.getLocationOnScreen().y; + leftOfDrawPanel = drawPanel.getLocationOnScreen().x; + dialogEdit.setLocation(leftOfDrawPanel + x, topOfDrawPanel + y); + editTextField.requestFocus(true); + editTextField.selectAll(); + dialogEdit.setVisible(true); + } + + /** + * Shows the text field for creation of a new terminal symbol or variable. + * + * @param x + * position where text field should pop up + * @param y + * position where text field should pop up + * @param mode + * is used to save the mode (addTerminal or addVariable) to + * create right element when text is entered. + * @param currentRenderElement + * is needed to save currentRenderElement for later creation of a + * syntax diagram element (in + * actionPerformed(ActionEvent e)) + */ + public void showNewTextField(int x, int y, int mode, + Component currentRenderElement) { + this.currentRenderElement = currentRenderElement; + this.mode = mode; + if (mode == SynDiaMouseListener.MODE_TERMINAL) { + newTextField.setText("a"); + } else if (mode == SynDiaMouseListener.MODE_VARIABLE) { + newTextField.setText("A"); + } + oldLabel = newTextField.getText(); + int width = 60; + int height = 23; + newTextField.setSize(width, height); + y += 1.2 * getRenderRadius() - 15; + dialogNew.setSize(newTextField.getWidth() + 25, newTextField + .getHeight()); + // fill topOfDrawPanel + leftOfDrawPanel + topOfDrawPanel = drawPanel.getLocationOnScreen().y; + leftOfDrawPanel = drawPanel.getLocationOnScreen().x; + dialogNew.setLocation(leftOfDrawPanel + x, topOfDrawPanel + y); + newTextField.requestFocus(true); + newTextField.selectAll(); + dialogNew.setVisible(true); + } + + private void showTiledComponent(Component component, + Component leftRenderElement) { + int x = leftRenderElement.getX() + - synDiaRenderer.getRenderValues().radius; + int y = leftRenderElement.getY(); + int width = synDiaRenderer.getRenderValues().radius * 4; + int height = synDiaRenderer.getRenderValues().radius * 4; + component.setBounds(x, y, width, height); + if (component instanceof RenderTiledBranch) { + ((RenderTiledBranch) component).update(); + } else { + ((RenderTiledRepetition) component).update(); + } + component.setVisible(true); + leftRenderElement.getParent().add(component); + component.requestFocus(); + component.repaint(); + } + + /** + * Shows the tiled branch that is used to demonstrate where the new branch + * would be added. + * + * @param leftRenderElement + * is needed to compute location right + */ + public void showTiledBranch(Component leftRenderElement) { + renderTiledBranch.setRenderValues(synDiaRenderer.getRenderValues()); + showTiledComponent(renderTiledBranch, leftRenderElement); + } + + /** + * Hides the tiled branch. + * + */ + public void hideTiledBranch() { + renderTiledBranch.setVisible(false); + } + + /** + * Is called if the right end of the tiled branch is moved to somewhere new. + * + * @param begin + * position of the new left end of the tiled branch + * @param end + * position of the new right end of the tiled branch + */ + public void setNewTiledBranchEnd(int begin, int end) { + Rectangle bounds = renderTiledBranch.getBounds(); + if (begin <= end) { + bounds.width = end - bounds.x + 3 + * synDiaRenderer.getRenderValues().radius; + } else { + bounds.width = begin - end + 4 + * synDiaRenderer.getRenderValues().radius; + bounds.x = end - 1 * synDiaRenderer.getRenderValues().radius; + } + renderTiledBranch.setBounds(bounds); + renderTiledBranch.update(); + renderTiledBranch.repaint(); + } + + /** + * Is called if the height of the tiled branch has changed, because the + * tiled branch had been moved over new elements with greater or smaller + * dimensions. + * + * @param height + * the new height of the tiled branch + */ + public void setNewTiledBranchHeight(int height) { + Rectangle bounds = renderTiledBranch.getBounds(); + bounds.height = height; + renderTiledBranch.setBounds(bounds); + renderTiledBranch.update(); + renderTiledBranch.repaint(); + } + + /** + * Shows the tiled repetition that is used to demonstrate where the new + * repetition would be added. + * + * @param leftRenderElement + * is needed to compute location right + */ + public void showTiledRepetition(Component leftRenderElement) { + renderTiledRepetition.setRenderValues(synDiaRenderer.getRenderValues()); + showTiledComponent(renderTiledRepetition, leftRenderElement); + } + + /** + * Hdes the tiled branch. + * + */ + public void hideTiledRepetition() { + renderTiledRepetition.setVisible(false); + } + + /** + * Is called if the right end of the tiled repetition is moved to somewhere + * new. + * + * @param begin + * position of the new left end of the tiled repetition + * @param end + * position of the new right end of the tiled repetition + */ + public void setNewTiledRepetitionEnd(int begin, int end) { + Rectangle bounds = renderTiledRepetition.getBounds(); + if (begin <= end) { + bounds.width = end - bounds.x + 3 + * synDiaRenderer.getRenderValues().radius; + } else { + bounds.width = begin - end + 4 + * synDiaRenderer.getRenderValues().radius; + bounds.x = end - 1 * synDiaRenderer.getRenderValues().radius; + } + renderTiledRepetition.setBounds(bounds); + renderTiledRepetition.update(); + renderTiledRepetition.repaint(); + } + + /** + * Is called if the height of the tiled repetition has changed, because the + * tiled repetition had been moved over new elements with greater or smaller + * dimensions. + * + * @param height + * the new height of the tiled repetition + */ + public void setNewTiledRepetitionHeight(int height) { + Rectangle bounds = renderTiledRepetition.getBounds(); + bounds.height = height; + renderTiledRepetition.setBounds(bounds); + renderTiledRepetition.update(); + renderTiledRepetition.repaint(); + } + + /** + * Is called when syntax diagram panels were redrawn. + * + */ + public void hasBeenDrawn() { + setChangeElemListenerBack(); + // bad, bad smell... no time to change this :-( + if (drawPanel != null) { + if (drawPanel.getCursor().equals(cursorDelete)) { + setDeleteElemListener(); + } else if (drawPanel.getCursor().equals(cursorEdit)) { + setChangeElemListener(); + } + } + // update the toolbar (undo- and redo-buttons) + undoAction.setEnabled(synDiaController.getActionStack() + .isUndoPossible()); + redoAction.setEnabled(synDiaController.getActionStack() + .isRedoPossible()); + } + + /** + * Returns the renderRadius of the syntax diagram renderer. + * + * @return the renderRadius of the syntax diagram renderer + */ + public int getRenderRadius() { + return synDiaRenderer.getRenderValues().radius; + } + + /** + * Returns the render radius from the render values. + * + * @return the render radius from the render values + */ + public RenderValues getRenderValues() { + return synDiaRenderer.getRenderValues(); + } + + /** + * Is called when the user presses "Enter" or clicks on the "OK-Button" when + * editing a terminal symbol, variable or syntax diagram name. + * + */ + public void changeLabelOfElement() { + // user wants to change label of an existing terminal symobl or variable + if (dialogEdit.isVisible()) { + dialogEdit.setVisible(false); + if (editTextField.getText().trim().equals("") + || editTextField.getText().trim().equals(oldLabel)) + return; + if (this.currentSynDiaElem instanceof TerminalSymbol) { + synDiaController.renameTerminal( + (TerminalSymbol) currentSynDiaElem, editTextField + .getText()); + } else if (this.currentSynDiaElem instanceof Variable) { + synDiaController.renameVariable((Variable) currentSynDiaElem, + editTextField.getText()); + } + } + // user wants to create a new terminal symbol or variable + if (dialogNew.isVisible()) { + dialogNew.setVisible(false); + if (newTextField.getText().trim().equals("")) + return; + String text = newTextField.getText(); + if (mode == SynDiaMouseListener.MODE_TERMINAL) { + if (renderMap.containsKey(currentRenderElement)) { + NullElem nullElem = (NullElem) renderMap + .get(currentRenderElement); + synDiaController.addTerminal(nullElem, text.trim()); + } + } else if (mode == SynDiaMouseListener.MODE_VARIABLE) { + if (renderMap.containsKey(currentRenderElement)) { + NullElem nullElem = (NullElem) renderMap + .get(currentRenderElement); + synDiaController.addVariable(nullElem, text.trim()); + } + } + } + if (dialogSynDiaName.isVisible()) { + dialogSynDiaName.setVisible(false); + checkBox.removeItemListener(checkBoxListener); + // test, if there is already a diagram with the same name + for (String name : synDiaController.getSynDiaSystem() + .getLabelsOfVariables()) { + if (name.equals(synDiaNameTextField.getText().trim())) { + if (currentSyntaxDiagram != null && name.equals(oldLabel)) { + synDiaNameTextField.setText(oldLabel); + } else { + if (currentSyntaxDiagram != null) { + showEditSynDiaName( + currentSyntaxDiagram, + dialogSynDiaName.getX() - leftOfDrawPanel + + drawPanel.getX(), + dialogSynDiaName.getY() - topOfDrawPanel, + Messages + .getString("ebnf", + "SynDiaEditor.DiagramAlreadyExists")); + } else { + showEditSynDiaName( + currentSyntaxDiagram, + dialogSynDiaName.getX() - leftOfDrawPanel + + drawPanel.getX(), + dialogSynDiaName.getY() - topOfDrawPanel + + drawPanel.getY(), + Messages + .getString("ebnf", + "SynDiaEditor.DiagramAlreadyExists")); + + } + return; + } + } + } + if (synDiaNameTextField.getText().trim().equals("")) + return; + if (currentSyntaxDiagram != null) { + synDiaController.renameSyntaxDiagram(currentSyntaxDiagram, + synDiaNameTextField.getText().trim(), setStartDiagram); + } else { + synDiaController.addSyntaxDiagram(synDiaNameTextField.getText() + .trim(), setStartDiagram); + } + } + } + + /** + * Sets the mode to "edit". + * + */ + public void setModeEdit() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_EDIT); + setChangeElemListener(); + setCursor("edit"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_EDIT); + } + + /** + * Sets the mode to "add terminal". + * + */ + public void setModeAddTerminal() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_TERMINAL); + // setStatusLineTextForPanel("terminal"); + setCursor("terminal"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_TERMINAL); + } + + /** + * Sets the mode to "add variable". + * + */ + public void setModeAddVariable() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_VARIABLE); + // setStatusLineTextForPanel("variable"); + setCursor("variable"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_VARIABLE); + } + + /** + * Sets the mode to "add branch". + * + */ + public void setModeAddBranch() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_BRANCH); + setCursor("branch"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_BRANCH); + } + + /** + * Sets the mode to "add repetition". + * + */ + public void setModeAddRepetition() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_REPETITION); + setCursor("repetition"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_REPETITION); + } + + /** + * Sets the mode to "delete". + * + */ + public void setModeDelete() { + synDiaMouseListener.setMode(SynDiaMouseListener.MODE_DELETE); + setDeleteElemListener(); + setCursor("delete"); + ((EditorControlPanel) controlPanel) + .changeMode(SynDiaMouseListener.MODE_DELETE); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/OkActionListener.java b/src/org/jalgo/module/ebnf/gui/syndia/OkActionListener.java new file mode 100644 index 0000000..1c1df26 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/OkActionListener.java @@ -0,0 +1,34 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * ActionListener for the "OK-Button" that appears when editing terminal + * symbols, variables and syntay diagram names. + * + * @author Michael Thiele + * + */ +public class OkActionListener implements ActionListener { + + private GuiController guiController; + + /** + * Initializes the ActionListener. + * + * @param guiController + * the guiController for this listener + */ + public OkActionListener(GuiController guiController) { + this.guiController = guiController; + } + + /** + * Calls guiController.changeLabelOfElement(). + */ + public void actionPerformed(ActionEvent e) { + guiController.changeLabelOfElement(); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/RedoAction.java b/src/org/jalgo/module/ebnf/gui/syndia/RedoAction.java new file mode 100644 index 0000000..8ecf980 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/RedoAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; + +/** + * ActionListener for "redo-button" in the j-algo toolbar. + * + * @author Michael Thiele + * + */ +@SuppressWarnings("serial") +public class RedoAction extends AbstractAction { + + private GuiController guiController; + + /** + * Initializes the button. + * + * @param guiController + * the guiController - needed in actionPerformed() + */ + public RedoAction(GuiController guiController) { + super(); + this.guiController = guiController; + putValue(NAME, Messages.getString("ebnf", "SynDiaEditor.Redo")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", + "SynDiaEditor.Redo")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("main", + "Icon.Redo"))); + } + + /** + * Redoes an action. + */ + public void actionPerformed(ActionEvent arg0) { + guiController.getSynDiaController().redo(); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.java b/src/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.java new file mode 100644 index 0000000..0256abd --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/SynDiaMouseListener.java @@ -0,0 +1,414 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.Component; +import java.awt.event.MouseEvent; +import java.util.Map; + +import javax.swing.event.MouseInputAdapter; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.trans.SynDiaElemNotFoundException; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderName; +import org.jalgo.module.ebnf.renderer.elements.RenderNullElem; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +/** + * This class reacts to all sorts of mouse input. It contains information about + * the current mode (edit, insert variable, etc.) and status of docked elements. + * + * @author Michael Thiele + * + */ +public class SynDiaMouseListener extends MouseInputAdapter { + + final static int MODE_EDIT = 0; + + final static int MODE_TERMINAL = 1; + + final static int MODE_VARIABLE = 2; + + final static int MODE_REPETITION = 3; + + final static int MODE_BRANCH = 4; + + final static int MODE_WORDWRAP = 5; + + final static int MODE_DELETE = 6; + + private final int STATUS_NOTDOCKED = 0; + + private final int STATUS_LEFTDOCKED = 1; + + private int currentMode = MODE_EDIT; + + private int currentStatus = STATUS_NOTDOCKED; + + private NullElem leftNullElem; + + private GuiController guiController; + + private Map renderMap; + + /** + * Initializes the SynDiaMouseListener. + * + * @param guiController + * the guiController for this mouse listener + * @param renderMap + * the render map with the actual syntax diagram + */ + public SynDiaMouseListener(GuiController guiController, + Map renderMap) { + this.guiController = guiController; + this.renderMap = renderMap; + leftNullElem = null; + } + + private SynDiaElem getElem(Component component) { + if (renderMap.containsKey(component)) { + return renderMap.get(component); + } + return null; + } + + /** + * Sets the actual mode. Current status is set to "not docked". + * + * @param newMode + * the new mode to set + */ + public void setMode(int newMode) { + currentMode = newMode; + guiController.hideTiledBranch(); + guiController.hideTiledRepetition(); + currentStatus = STATUS_NOTDOCKED; + } + + public void mouseClicked(MouseEvent e) { + // if the right mouse button is pressed, the ChangeEditModeMenu pops + // up + if (e.getButton() == MouseEvent.BUTTON3) { + // set ChangeElemListener back if we were in edit mode + if (currentMode == MODE_EDIT) { + guiController.setChangeElemListenerBack(); + // if it pops up over a terminal symbol or variable you have to + // remove the color of this element + if (e.getComponent() instanceof RenderTerminal + || e.getComponent() instanceof RenderVariable) { + ((RenderElement) e.getComponent()) + .setColor(RenderElement.STANDARD_FILL_COLOR); + } + } + if (!(e.getComponent() instanceof RenderTerminal) + || !(e.getComponent() instanceof RenderVariable)) { + // set ColorListener back if there are some red now + if ((currentMode == MODE_BRANCH || currentMode == MODE_REPETITION) + && currentStatus == STATUS_LEFTDOCKED) { + guiController.setNullElemColorListenerBack(); + } + // set DeleteElemListener back if we were in delete mode + if (currentMode == MODE_DELETE) { + guiController.setDeleteElemListenerBack(); + } + // if popup is over RenderElement compute new position + if (e.getSource() instanceof RenderElement) { + guiController.showChangeEditModeMenu(e.getComponent() + .getX() + + e.getX() + e.getComponent().getParent().getX(), e + .getComponent().getY() + + e.getY() + e.getComponent().getParent().getY()); + } else { + guiController.showChangeEditModeMenu(e.getX(), e.getY()); + } + } + } + // a left-click + if (e.getButton() == MouseEvent.BUTTON1) { + Component currentComponent = e.getComponent(); + // MODE_EDIT + if (currentMode == MODE_EDIT) { + if (currentComponent instanceof RenderTerminal) { + guiController.showEditTextField(currentComponent.getX() + + currentComponent.getParent().getX(), + currentComponent.getY() + + currentComponent.getParent().getY(), + getElem(currentComponent)); + } else if (currentComponent instanceof RenderVariable) { + guiController.showEditTextField(currentComponent.getX() + + currentComponent.getParent().getX(), + currentComponent.getY() + + currentComponent.getParent().getY(), + getElem(currentComponent)); + } else if (currentComponent instanceof RenderName) { + // getCompontent(0) always has to be NullElem!!! + guiController.showEditSynDiaName(((SynDiaElem) renderMap + .get(currentComponent.getParent().getComponent(0))) + .getMySyntaxDiagram(), 20, e.getY() + + currentComponent.getParent().getY(), Messages + .getString("ebnf", "SynDiaEditor.NameOfDiagram")); + } + } + // MODE_TERMINAL + else if (currentMode == MODE_TERMINAL) { + if (currentComponent instanceof RenderNullElem) { + guiController.showNewTextField(currentComponent.getX() + + currentComponent.getParent().getX(), + currentComponent.getY() + + currentComponent.getParent().getY(), + currentMode, currentComponent); + } + } + // MODE_VARIABLE + else if (currentMode == MODE_VARIABLE) { + if (currentComponent instanceof RenderNullElem) { + guiController.showNewTextField(currentComponent.getX() + + currentComponent.getParent().getX(), + currentComponent.getY() + + currentComponent.getParent().getY(), + currentMode, currentComponent); + } + } + // MODE_WORDWRAP + else if (currentMode == MODE_WORDWRAP) { + if (currentComponent instanceof RenderNullElem) { + guiController.getSynDiaController().addWordWrap( + (NullElem) getElem(currentComponent)); + } + } + // MODE_BRANCH + else if (currentMode == MODE_BRANCH) { + if (currentComponent instanceof RenderNullElem) { + // if left side is already fixed, try to fix right side + if (currentStatus == STATUS_LEFTDOCKED) { + if (leftNullElem.getLine() == ((NullElem) getElem(e + .getComponent())).getLine()) { + NullElem rightNullElem = (NullElem) getElem(currentComponent); + if (leftNullElem.getIndex() <= rightNullElem + .getIndex()) { + guiController.getSynDiaController().addBranch( + leftNullElem, rightNullElem); + } else { + guiController.getSynDiaController().addBranch( + rightNullElem, leftNullElem); + } + guiController.hideTiledBranch(); + guiController.setCursor("branch"); + currentStatus = STATUS_NOTDOCKED; + } + } + // if this is the first click, save the left NullElem and + // set status to left docked + else if (currentStatus == STATUS_NOTDOCKED) { + currentStatus = STATUS_LEFTDOCKED; + leftNullElem = (NullElem) getElem(currentComponent); + guiController.setCursor("branchRight"); + guiController.setNullElemColorListener(leftNullElem); + guiController.showTiledBranch(currentComponent); + } + } + } + // MODE_REPETITION + else if (currentMode == MODE_REPETITION) { + if (currentComponent instanceof RenderNullElem) { + // if left side is already fixed, try to fix right side + if (currentStatus == STATUS_LEFTDOCKED) { + if (leftNullElem.getLine() == ((NullElem) getElem(e + .getComponent())).getLine()) { + NullElem rightNullElem = (NullElem) getElem(currentComponent); + if (leftNullElem.getIndex() <= rightNullElem + .getIndex()) { + guiController.getSynDiaController() + .addRepetition(leftNullElem, + rightNullElem); + } else { + guiController.getSynDiaController() + .addRepetition(rightNullElem, + leftNullElem); + } + guiController.hideTiledRepetition(); + guiController.setCursor("repetition"); + currentStatus = STATUS_NOTDOCKED; + } + } + // if this is the first click, save the left NullElem and + // set status to left docked + else if (currentStatus == STATUS_NOTDOCKED) { + currentStatus = STATUS_LEFTDOCKED; + leftNullElem = (NullElem) getElem(currentComponent); + guiController.setCursor("repetitionRight"); + guiController.setNullElemColorListener(leftNullElem); + guiController.showTiledRepetition(currentComponent); + } + } + } + // MODE_DELETE + else if (currentMode == MODE_DELETE) { + if (currentComponent instanceof RenderTerminal) { + guiController.getSynDiaController().removeTerminal( + (TerminalSymbol) getElem(currentComponent)); + } else if (currentComponent instanceof RenderVariable) { + guiController.getSynDiaController().removeVariable( + (Variable) getElem(currentComponent)); + } + } + } + } + + public void mouseEntered(MouseEvent e) { + Component currentComponent = e.getComponent(); + if (currentComponent instanceof RenderNullElem) { + if (currentMode == MODE_TERMINAL) { + // guiController.setToolTipTextForNullElems("terminal"); + } + if (currentStatus == STATUS_LEFTDOCKED) { + // test, if it is possible to move right end of branch or + // repetition to this position + if (leftNullElem.getLine() == ((NullElem) getElem(e + .getComponent())).getLine()) { + int begin = leftNullElem.getIndex(); + int end = ((NullElem) getElem(currentComponent)).getIndex(); + if (begin > end) { + int h = begin; + begin = end; + end = h; + } + int height = guiController.getRenderRadius() * 4; + if (begin != end) { + Concatenation concat = (Concatenation) getElem( + currentComponent).getParent(); + for (int i = begin + 1; i < end; i++) { + height = (int) Math.max(height, + getHeightFromElement(concat + .getSynDiaElem(i)) + + 1.5 + * guiController.getRenderRadius()); + } + } + if (currentMode == MODE_BRANCH) { + try { + guiController.setNewTiledBranchEnd(getReFromSde( + leftNullElem).getX(), e.getComponent() + .getX()); + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + guiController.setNewTiledBranchHeight(height); + } else { + try { + guiController.setNewTiledRepetitionEnd( + getReFromSde(leftNullElem).getX(), e + .getComponent().getX()); + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + guiController.setNewTiledRepetitionHeight(height); + } + } else { + try { + if (currentMode == MODE_BRANCH) { + guiController + .showTiledBranch(getReFromSde(leftNullElem)); + } else { + guiController + .showTiledRepetition(getReFromSde(leftNullElem)); + } + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + } + } + } + } + + public void mouseExited(MouseEvent e) { + if (currentStatus == STATUS_LEFTDOCKED) { + try { + if (currentMode == MODE_BRANCH) { + guiController.showTiledBranch(getReFromSde(leftNullElem)); + } else { + guiController + .showTiledRepetition(getReFromSde(leftNullElem)); + } + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + } + } + + /** + * Computes the height of a syntax diagram element. + * + * @param s + * the syntax diagram element + * @return the height of the element + */ + private int getHeightFromElement(SynDiaElem s) { + Component component = null; + int additionalHeight = 0; + int height = 0; + /* + * if the element is a branch or repetition there could be additional + * height through elements in the right side of these + * branches/repetitions + */ + if (s instanceof Branch || s instanceof Repetition) { + Concatenation c = null; + if (s instanceof Branch) + c = ((Branch) s).getRight(); + else if (s instanceof Repetition) + c = ((Repetition) s).getRight(); + for (int i = 0; i < c.getNumberOfElems(); i++) { + additionalHeight = Math.max(additionalHeight, + getHeightFromElement(c.getSynDiaElem(i)) - 2 + * guiController.getRenderRadius()); + } + } + try { + component = getReFromSde(s); + } catch (IndexOutOfBoundsException e1) { + e1.printStackTrace(); + } catch (SynDiaElemNotFoundException e1) { + e1.printStackTrace(); + } + height = Math.max(height, component.getHeight()) + additionalHeight; + return height; + } + + /** + * @param sde + * a SynDiaElem finding itself in the RenderMap + * @return the render element representing the syntax diagram element in the + * model + * @throws SynDiaElemNotFoundException + */ + private RenderElement getReFromSde(SynDiaElem sde) + throws SynDiaElemNotFoundException { + if (renderMap.containsValue(sde)) { + for (RenderElement re : renderMap.keySet()) { + if (sde == renderMap.get(re)) + return re; + } + } + throw new SynDiaElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + + /** + * Is used to set the render map to actual render map. + * + * @param renderMap + * the render map to update + */ + public void setRenderMap(Map renderMap) { + this.renderMap = renderMap; + } +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/UndoAction.java b/src/org/jalgo/module/ebnf/gui/syndia/UndoAction.java new file mode 100644 index 0000000..e82a9c4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/UndoAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.ebnf.gui.syndia; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; + +/** + * ActionListener for the "undo-Button" in the j-algo toolbar. + * + * @author Michael Thiele + * + */ +@SuppressWarnings("serial") +public class UndoAction extends AbstractAction { + + private GuiController guiController; + + /** + * Initializes the button. + * + * @param guiController + * the guiController - needed in actionPerformed() + */ + public UndoAction(GuiController guiController) { + super(); + this.guiController = guiController; + putValue(NAME, Messages.getString("ebnf", "SynDiaEditor.Undo")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", + "SynDiaEditor.Undo")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("main", + "Icon.Undo"))); + } + + /** + * Undoes last action. + */ + public void actionPerformed(ActionEvent arg0) { + guiController.getSynDiaController().undo(); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.java new file mode 100644 index 0000000..35f8edc --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/AbstractControlPanel.java @@ -0,0 +1,85 @@ +package org.jalgo.module.ebnf.gui.syndia.display; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.KeyEvent; + +import javax.swing.ImageIcon; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; + + /** + * @author Andre Viergutz + */ +public abstract class AbstractControlPanel extends JPanel { + + protected JPanel left; + protected JPanel right; + protected JSlider zoomer = new JSlider(JSlider.HORIZONTAL); + protected JToggleButton fitToSize = new JToggleButton(new ImageIcon(Messages.getResourceURL("ebnf", + "Icon.FitToSize"))); + + + /** + * Initializes the components + */ + public AbstractControlPanel() { + this.setBorder(javax.swing.BorderFactory.createTitledBorder( + null, Messages.getString("ebnf", "Border_Control"), + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + this.setBackground(Color.WHITE); + + this.left = new JPanel(); + left.setBackground(Color.WHITE); + this.right = new JPanel(); + right.setBackground(Color.WHITE); + + // settings + fitToSize.setMnemonic(KeyEvent.VK_Z); + fitToSize.setToolTipText(Messages.getString("ebnf", "SynDia.Control_FitToSize")); + fitToSize.addMouseListener(StatusLineUpdater.getInstance()); + fitToSize.setBorder(new EmptyBorder(3,3,3,3)); + fitToSize.setFocusPainted(false); + + zoomer.setMinimum(10); + zoomer.setMaximum(50); + zoomer.setValue(DiagramSize.getFontSize()); + zoomer.setPreferredSize(new Dimension(70, 20)); + zoomer.setBackground(Color.WHITE); + + // layout + this.setLayout(new BorderLayout(0,0)); + left.add(zoomer); + left.add(fitToSize); + this.add(left, BorderLayout.WEST); + this.add(right, BorderLayout.EAST); + + } + + + /** + * Sets the zoomer to the given value + * + * @param value An absolute int + */ + public void setZoomerValue(int value) { + if (value > zoomer.getMaximum()) + zoomer.setValue(zoomer.getMaximum()); + else if (value < zoomer.getMinimum()) + zoomer.setValue(zoomer.getMinimum()); + else + zoomer.setValue(value); + + } + + + + } diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Entries b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Entries new file mode 100644 index 0000000..8dffa97 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Entries @@ -0,0 +1,7 @@ +/AbstractControlPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/ControlPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/DiagramSize.java/1.1/Fri Aug 11 16:40:32 2006// +/DisplayController.java/1.1/Fri Aug 11 16:40:32 2006// +/DrawPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/IDrawPanel.java/1.1/Fri Aug 11 16:40:32 2006// +/SynDiaPanel.java/1.1/Fri Aug 11 16:40:32 2006// diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Repository b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Repository new file mode 100644 index 0000000..877e9d9 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/syndia/display diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Root b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.java new file mode 100644 index 0000000..95036f4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/ControlPanel.java @@ -0,0 +1,157 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.syndia.display; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.main.JAlgoMain; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.ModuleConnector; + +/** This is the control area for the syntax diagram display. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ControlPanel extends AbstractControlPanel { + + private JToggleButton noStairs = new JToggleButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.Stairs"))); + private JButton toWordAlgo = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToWordAlgo")); + private JButton toSynDia = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToSynDiaInput")); + private DisplayController controller; + private ModuleConnector connector; + + /** This is the constructor. + * + * @param dc The GuiController which handles the actions between the Panels + * @param connector The ModuleConnector for saving actions + */ + public ControlPanel(DisplayController dc, ModuleConnector connector) { + + super(); + this.controller = dc; + this.connector = connector; + init(); + initListener(); + + } + + /** + * Initializes the components + */ + public void init() { + + noStairs.setBorder(new EmptyBorder(3, 3, 3, 3)); + noStairs.setFocusPainted(false); + noStairs.setSelectedIcon(new ImageIcon(Messages.getResourceURL("ebnf", + "Icon.NoStairs"))); + noStairs.setToolTipText(Messages.getString("ebnf", "SynDia.Control_Stairs")); + noStairs.addMouseListener(StatusLineUpdater.getInstance()); + + left.add(noStairs); + JPanel right = new JPanel(); + right.setBackground(Color.WHITE); + right.add(toSynDia); + right.add(toWordAlgo); + this.add(right, BorderLayout.EAST); + + } + + /** + * Initializes all listeners on the Panel + */ + public void initListener() { + + fitToSize.addItemListener(new ItemListener() { + + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + + controller.setAutoSize(true); + + } else { + + controller.setAutoSize(false); + } + + } + + }); + + zoomer.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + fitToSize.setSelected(false); + } + }); + zoomer.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + controller.resizeDrawPanel(zoomer.getValue()); + + } + + }); + + noStairs.addItemListener(new ItemListener() { + + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + + controller.getDrawPanel().setStairs(false); + + } else { + + controller.getDrawPanel().setStairs(true); + + } + + controller.getDrawPanel().update(null, null); + + } + + }); + + toSynDia.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + DiagramSize + .setFontSize(controller.getDrawPanel().getFontSize()); + controller.switchToSynDiaInput(); + } + }); + + toWordAlgo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + + DiagramSize.setFontSize(controller.getDrawPanel().getFontSize()); + controller.setWordAlgoMode(); + } + + + }); + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.java b/src/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.java new file mode 100644 index 0000000..a1c570b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/DiagramSize.java @@ -0,0 +1,35 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.syndia.display; + +/** + * @author Andre Viergutz + */ +public class DiagramSize { + + private static int fontSize = 17; + + /** + * Sets the size of the Font. + * + * @param fsize + */ + public static void setFontSize(int fsize) { + + fontSize = fsize; + + } + + /** + * This functions returns the set font size. + * + * @return an int representing the size of the Font + */ + public static int getFontSize() { + + return fontSize; + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.java b/src/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.java new file mode 100644 index 0000000..5eca3c4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/DisplayController.java @@ -0,0 +1,154 @@ +package org.jalgo.module.ebnf.gui.syndia.display; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; + +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.MainController; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.gui.syndia.AbstractSDGuiController; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.renderer.WordAlgoRenderer; + +/** + * This class simply controls the display of a syntax diagram system as well as + * saving a definition. + * + * @author Andre Viergutz + */ +public class DisplayController extends AbstractSDGuiController { + + private MainController maincontroller; + private ModuleConnector connector; + protected SynDiaSystem synDiaSystem; + protected JPanel contentPane; + + /** + * This constructor initializes alle the GuiComponents + * + * @param controller The TransController which created this + * @param connector The ModuleConnector for saving actions + * @param contentP The pane to draw on + * @param sds The SynDiaSystem to draw + */ + + public DisplayController(MainController controller, + ModuleConnector connector, JPanel contentP, SynDiaSystem sds) { + + this.maincontroller = controller; + this.connector = connector; + this.contentPane = contentP; + this.synDiaSystem = sds; + + drawScrollPane = new JScrollPane(); + drawPanel = new DrawPanel(synDiaSystem, this, new WordAlgoRenderer()); + drawPanel.addComponentListener(new ComponentAdapter() { + + public void componentMoved(ComponentEvent e) { + + drawPanel.repaint(); + + } + + }); + + controlPanel = new ControlPanel(this, this.connector); + + // setting + contentPane.setBackground(Color.WHITE); + drawScrollPane.setBackground(Color.WHITE); + drawScrollPane.setViewportBorder(javax.swing.BorderFactory + .createLoweredBevelBorder()); + drawScrollPane.setViewportView(drawPanel); + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, + contentPane.getHeight() + - controlPanel.getPreferredSize().height)); + drawScrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder( + null, Messages.getString("ebnf", "Border_Draw"), + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + controlPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, controlPanel + .getPreferredSize().height)); + + contentPane.addComponentListener(new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, + contentPane.getHeight() + - controlPanel.getPreferredSize().height)); + } + }); + + switchToDisplay(); + + } + + /** + * Builds the Gui for the display of a SynDiaSystem + */ + public void switchToDisplay() { + + // layout + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));// layout); + + contentPane.add(controlPanel); + contentPane.add(drawScrollPane); + + contentPane.validate(); + contentPane.repaint(); + + connector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + } + + /** + * Switches to the syntax diagram editor + */ + public void switchToSynDiaInput() { + + synDiaSystem.fillWithNullElems(); + maincontroller.setSynDiaInputMode(synDiaSystem); + + } + + /** + * Switches to the word algorithm + */ + public void setWordAlgoMode() { + + maincontroller.setWordAlgoMode(synDiaSystem); + + } + + /** Saves a SynDiaSystem + * @return the ByteArrayOutputStream of the saved system + */ + public ByteArrayOutputStream saveSystem() { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeBoolean(false); + objOut.writeObject(synDiaSystem); + objOut.close(); + connector.setSaveStatus(SaveStatus.NO_CHANGES); + } catch (IOException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "ebnf", "SynDia.Error.SaveError")); //$NON-NLS-1$ //$NON-NLS-2$ + } + return out; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.java new file mode 100644 index 0000000..8c5f649 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/DrawPanel.java @@ -0,0 +1,365 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.syndia.display; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.module.ebnf.gui.syndia.AbstractSDGuiController; +import org.jalgo.module.ebnf.gui.trans.RenderElemNotFoundException; +import org.jalgo.module.ebnf.gui.trans.SynDiaElemNotFoundException; +import org.jalgo.module.ebnf.gui.syndia.display.SynDiaPanel; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.renderer.ReturnDiagram; +import org.jalgo.module.ebnf.renderer.SynDiaRenderer; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * This class is an inherition of a JPanel and represents a container of all + * SynDiaPanels + * + * @author Andre + */ +@SuppressWarnings("serial") +public class DrawPanel extends JPanel implements Observer, IDrawPanel, MouseWheelListener { + + protected SynDiaRenderer renderer; + protected List synDiaPanelList; + protected Map renderMap; + protected SynDiaSystem synDiaSystem; + protected AbstractSDGuiController controller; + protected boolean autoSize = false; + protected String displayName; + protected double factor; + + + /** + * Initializes all paramaters + * + * @param synDiaSystem the syntax diagram system to draw + * @param dc the DisplayController + * @param synDiaRenderer a SynDiaRenderer + */ + public DrawPanel(SynDiaSystem synDiaSystem, AbstractSDGuiController dc, + SynDiaRenderer synDiaRenderer) { + + displayName = "display"; + factor = 0.2; + this.setLayout(null); + this.controller = dc; + this.renderer = synDiaRenderer; + this.renderMap = new LinkedHashMap(); + this.synDiaSystem = synDiaSystem; + this.synDiaPanelList = new ArrayList(); + this.setBackground(BACKGROUND_COLOR); + this.addMouseWheelListener(this); + initListeners(); + + this.drawSynDiaSystem(this.synDiaSystem); + this.repaint(); + + } + + /** + * This method initializes all Listeners on the GUI elements + */ + public void initListeners() { + + this.addComponentListener(new ComponentAdapter() { + + public void componentResized(ComponentEvent e) { + + update(null, null); + + } + }); + + } + + /** + * Collects all SynDiaPanels for each SyntaxDiagram found and + * places it on the DrawPanel + * + * @param sds + */ + public void drawSynDiaSystem(SynDiaSystem sds) { + + int x = 30; + int y = 20; + + this.removeAll(); + this.synDiaPanelList.clear(); + this.renderMap.clear(); + for (String s : sds.getLabelsOfVariables()) { + + try { + SyntaxDiagram d = sds.getSyntaxDiagram(s); + + SynDiaPanel sdp; + sdp = this.getSyntaxDiagram(d); + sdp.repaint(); + this.synDiaPanelList.add(sdp); + this.add(sdp); + sdp.setVisible(true); + sdp.setLocation(x, y); + + y += sdp.getHeight() + 2 * renderer.getRenderValues().space; + } catch (ElementNotFoundException e) { + } + + } + this.repaint(); + + } + + /** + * Calculates the dimension of a Syntax Diagram + * + * @param sds + * @return The dimension of the Syntax Diagram System + */ + public Dimension getSynDiaSystemSize(SynDiaSystem sds) { + + int y = 20; + + int ret_width = 0; + int ret_height = 0; + + for (String s : sds.getLabelsOfVariables()) { + + try { + SyntaxDiagram d = sds.getSyntaxDiagram(s); + + Dimension dim = this.renderer.getDiagramSize(d); + + if (dim.width > ret_width) + ret_width = dim.width; + + ret_height = y + dim.height; + y += dim.height + 3 * renderer.getRenderValues().space; + } catch (ElementNotFoundException e) { + } + + } + return new Dimension(ret_width + 50, ret_height + 20); + + } + + /** + * Calculates a SynDiaPanel with the help of the TransRenderer + * + * @param sd A syntax diagram + * @return A JPanel containing the drawn SyntaxDiagram + */ + private SynDiaPanel getSyntaxDiagram(SyntaxDiagram sd) { + + SynDiaPanel p = new SynDiaPanel(); + ReturnDiagram rd = this.renderer.getRenderedDiagram(sd); + + for (RenderElement renderElem : rd.renderMap.keySet()) { + + // addListener(renderElem, new ColorChangeListener()); + p.add(renderElem); + renderElem.setVisible(true); + renderElem.repaint(); + + } + int width = rd.width; + if (1.3*this.renderer.getRenderValues().getWidthFromString(sd.getName()) > width) + width = (int) (1.3*this.renderer.getRenderValues().getWidthFromString( + sd.getName())); + + p.setSize(width, rd.height); + + this.renderMap.putAll(rd.renderMap); + + return p; + + } + + /** + * @param re + * the render element from that you want to get the mapped render + * element + * @return the syntax diagram element representing the render element in the + * model + * @throws RenderElemNotFoundException + */ + public SynDiaElem getSdeFromRe(RenderElement re) + throws RenderElemNotFoundException { + + if (renderMap.containsKey(re)) { + return renderMap.get(re); + } else { + throw new RenderElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + } + + /** + * @param sde + * a SynDiaElem finding itself in the RenderMap + * @return the render element representing the syntax diagram element in the + * model + * @throws SynDiaElemNotFoundException + */ + public RenderElement getReFromSde(SynDiaElem sde) + throws SynDiaElemNotFoundException { + + if (renderMap.containsValue(sde)) { + + for (RenderElement re : renderMap.keySet()) { + + if (sde == renderMap.get(re)) + return re; + + } + return null; + + } else { + throw new SynDiaElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + } + + /** + * This method sets the paramater autoSize deciding, whether the diagram + * size shall automatically fit to the screen size + * + * @param autosize + * true, if the diagram size shall automatically fit to the + * screen size + */ + public void setAutoSize(boolean autosize) { + + this.autoSize = autosize; + } + + /** + * A function instead of an Observer to rearrange the system by size + * + * @param size + * the size of the Font associated to the syntax diaram + */ + public void resizeSystem(int size) { + + renderer.getRenderValues().setFontSize(size); + + this.update(null, null); + + } + + /** + * This method returns the actual font size set in the RenderValues + * + * @return The actual font size set in the RenderValues + */ + public int getFontSize() { + + return this.renderer.getRenderValues().font.getSize(); + } + + /** Tells the Panel whether to render wi + * @param withStairs true, if stairs shall be displayed + */ + public void setStairs(boolean withStairs) { + + renderer.getRenderValues().withStairs = withStairs; + + } + + /** + * @param o + * @param arg + */ + public void update(Observable o, Object arg) { + + if (autoSize) { + + int size = renderer.getRenderValues().font.getSize(); + while ((this.getSynDiaSystemSize(synDiaSystem).width < this + .getParent().getWidth() || this + .getSynDiaSystemSize(synDiaSystem).height < this + .getParent().getHeight()) + && size < 50) { + + size++; + renderer.getRenderValues().setFontSize(size); + + } + + while ((this.getSynDiaSystemSize(synDiaSystem).width > this + .getParent().getWidth() || this + .getSynDiaSystemSize(synDiaSystem).height > this + .getParent().getHeight()) + && size > 10) { + + size--; + renderer.getRenderValues().setFontSize(size); + + } + + controller.setZoomerValue(size); + + } + + this.drawSynDiaSystem(synDiaSystem); + this.setPreferredSize(this.getSynDiaSystemSize(synDiaSystem)); + this.getParent().validate(); + + } + + /** This method returns a List containing all panels which represent a SyntaxDiagram + * @return a List containing all panels which represent a SyntaxDiagram + */ + public List getSynDiaPanelList() { + return synDiaPanelList; + } + + public void mouseWheelMoved(MouseWheelEvent e) { + javax.swing.JScrollBar scrollbar = ((JScrollPane)this.getParent().getParent()).getVerticalScrollBar(); + + if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { + int totalScrollAmount = + e.getUnitsToScroll() * 5; + scrollbar.setValue(scrollbar.getValue() + totalScrollAmount); + } + } + + public void paintComponent(Graphics g) { + + super.paintComponent(g); + + Graphics2D g2d = (Graphics2D) g; + int fontSize = (int) Math.round(factor * this.getParent().getWidth()); + Font f = new Font("Courier", Font.BOLD, fontSize); + + g2d.setFont(f); + g2d.setColor(FONT_COLOR); + int y = this.getParent().getHeight() + (int) Math.round(0.2 * fontSize); + g2d.rotate(-Math.PI * 7 / 180); + g2d.drawString(displayName, (int) (this.getParent().getWidth() + - renderer.getRenderValues().getWidthFromString(displayName, f) + - factor * 0.2 * this.getParent().getWidth()), y); + g2d.rotate(Math.PI * 7 / 180); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.java new file mode 100644 index 0000000..5f4fd92 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/IDrawPanel.java @@ -0,0 +1,26 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.syndia.display; + +import java.awt.Color; + +/** + * This class is an inherition of a JPanel and represents a container of all + * SynDiaPanels + * + * @author Andre + */ +public interface IDrawPanel { + +// new Color(225, 240, 210); + /** + * The background color of the DrawPanel + */ + public final static Color BACKGROUND_COLOR = new Color(250, 250, 240); + /** + * The label color of the DrawPanel + */ + public final static Color FONT_COLOR = new Color(248, 244, 230); + +} diff --git a/src/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.java b/src/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.java new file mode 100644 index 0000000..3942bea --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/syndia/display/SynDiaPanel.java @@ -0,0 +1,26 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.syndia.display; + +import javax.swing.JPanel; + + +/** + * @author Andre + * + */ +@SuppressWarnings("serial") +public class SynDiaPanel extends JPanel { + + /** + * The constructor sets the null layout und makes it transparent + */ + public SynDiaPanel() { + + this.setLayout(null); + this.setOpaque(false); + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/CVS/Entries b/src/org/jalgo/module/ebnf/gui/trans/CVS/Entries new file mode 100644 index 0000000..9f1ab58 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/CVS/Entries @@ -0,0 +1,9 @@ +/ControlPanel.java/1.1/Fri Aug 11 16:40:30 2006// +/DrawPanel.java/1.1/Fri Aug 11 16:40:30 2006// +/ExplanationFactory.java/1.1/Fri Aug 11 16:40:30 2006// +/ExplanationPanel.java/1.1/Fri Aug 11 16:40:30 2006// +/GUIController.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderElemNotFoundException.java/1.2/Thu Jan 31 20:15:12 2008// +/SynDiaElemNotFoundException.java/1.2/Thu Jan 31 20:15:12 2008// +D/event//// +D/explanations//// diff --git a/src/org/jalgo/module/ebnf/gui/trans/CVS/Repository b/src/org/jalgo/module/ebnf/gui/trans/CVS/Repository new file mode 100644 index 0000000..2caf9a2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/trans diff --git a/src/org/jalgo/module/ebnf/gui/trans/CVS/Root b/src/org/jalgo/module/ebnf/gui/trans/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/trans/ControlPanel.java b/src/org/jalgo/module/ebnf/gui/trans/ControlPanel.java new file mode 100644 index 0000000..da04697 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/ControlPanel.java @@ -0,0 +1,157 @@ +package org.jalgo.module.ebnf.gui.trans; + +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.syndia.display.AbstractControlPanel; +import org.jalgo.module.ebnf.gui.syndia.display.DiagramSize; +import org.jalgo.module.ebnf.model.trans.TransMap; + +/** + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ControlPanel extends AbstractControlPanel implements Observer { + + private JToggleButton noStairs = new JToggleButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.Stairs"))); + private JButton toEbnf = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToEbnf")); + private JButton toSynDia = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToSynDiaDisplay")); + private GUIController guicontroller; + + /** + * Initializes the components + * + * @param guicontroller the GuiController which aggregates this class + */ + public ControlPanel(GUIController guicontroller) { + + super(); + this.guicontroller = guicontroller; + + init(); + initListener(); + } + + /** + * Initializes the ControlPanel components + */ + public void init() { + + noStairs.setBorder(new EmptyBorder(3, 3, 3, 3)); + noStairs.setFocusPainted(false); + noStairs.setSelectedIcon(new ImageIcon(Messages.getResourceURL("ebnf", + "Icon.NoStairs"))); + noStairs.setToolTipText(Messages.getString("ebnf", "SynDia.Control_Stairs")); + toSynDia.setEnabled(false); + + // left.add(stairs); + left.add(noStairs); + right.setBackground(Color.WHITE); + right.add(toEbnf); + right.add(toSynDia); + + } + + /** + * Initializes all Listeners + */ + private void initListener() { + + fitToSize.addItemListener(new ItemListener() { + + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + + // zoomer.setEnabled(false); + guicontroller.setAutoSize(true); + guicontroller.updateDrawPanel(20); + + } else { + + // zoomer.setEnabled(true); + guicontroller.setAutoSize(false); + + } + + } + + }); + noStairs.addItemListener(new ItemListener() { + + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + + guicontroller.getDrawPanel().setStairs(false); + + } else { + + guicontroller.getDrawPanel().setStairs(true); + + } + + guicontroller.getDrawPanel().update(null, null); + + } + + }); + + zoomer.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + fitToSize.setSelected(false); + } + }); + zoomer.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + guicontroller.updateDrawPanel(zoomer.getValue()); + + } + + }); + + toSynDia.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + DiagramSize.setFontSize(guicontroller.getDrawPanel() + .getFontSize()); + guicontroller.switchToSynDiaDisplay(); + } + }); + + toEbnf.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + guicontroller.setEbnfInputMode(); + } + }); + + } + + public void update(Observable o, Object arg) { + + if (o instanceof TransMap) { + + toSynDia.setEnabled(((TransMap) o).isTransformed()); + + } + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/DrawPanel.java b/src/org/jalgo/module/ebnf/gui/trans/DrawPanel.java new file mode 100644 index 0000000..0b9fa0f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/DrawPanel.java @@ -0,0 +1,368 @@ +package org.jalgo.module.ebnf.gui.trans; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JPanel; + +import org.jalgo.module.ebnf.gui.GUIConstants; +import org.jalgo.module.ebnf.gui.syndia.display.IDrawPanel; +import org.jalgo.module.ebnf.gui.syndia.display.SynDiaPanel; +import org.jalgo.module.ebnf.gui.trans.event.TransListener; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.renderer.ReturnDiagram; +import org.jalgo.module.ebnf.renderer.TransRenderer; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderTrans; + +/** + * This class is an inherition of a JPanel and represents a container of all + * SynDiaPanels + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class DrawPanel extends JPanel implements Observer, IDrawPanel { + + private TransRenderer renderer; + + private List synDiaPanelList; + + private Map renderMap; + + private TransMap transMap; + + private SynDiaSystem synDiaSystem; + + // private TransListener translistener; + + private GUIController guicontroller; + + private boolean autoSize = false; + + /** + * Initializes all paramaters + * + * @param synDiaSystem the syntax diagram system to draw + * @param transMap the map conatining the informatin whether a syntax + * diagram element is transformed or not + * @param controller the GUIController which aggregates this class + */ + public DrawPanel(SynDiaSystem synDiaSystem, TransMap transMap, + GUIController controller) { + + this.setLayout(null); + this.renderer = new TransRenderer(); + this.renderMap = new LinkedHashMap(); + this.transMap = transMap; + this.synDiaSystem = synDiaSystem; + this.synDiaPanelList = new ArrayList(); + this.guicontroller = controller; + + this.setBackground(GUIConstants.STANDARD_COLOR_BACKGROUND); + + initListeners(); + + this.drawSynDiaSystem(this.synDiaSystem, transMap); + this.repaint(); + + } + + /** + * This method initializes all Listeners on the GUI elements + */ + public void initListeners() { + + this.addComponentListener(new ComponentAdapter() { + + public void componentResized(ComponentEvent e) { + if (autoSize) + update(null, null); + else + repaint(); + } + }); + + } + + /** + * Collects all SynDiaPanels for each SyntaxDiagram found and + * places it on the DrawPanel + * + * @param sds + * @param transMap + */ + public void drawSynDiaSystem(SynDiaSystem sds, TransMap transMap) { + + int x = 30; + int y = 20; + + this.removeAll(); + this.synDiaPanelList.clear(); + this.renderMap.clear(); + for (String s : sds.getLabelsOfVariables()) { + + try { + SyntaxDiagram d = sds.getSyntaxDiagram(s); + + SynDiaPanel sdp; + + sdp = this.getSyntaxDiagram(d, transMap); + sdp.repaint(); + this.synDiaPanelList.add(sdp); + this.add(sdp); + sdp.setVisible(true); + sdp.setLocation(x, y); + + y += sdp.getHeight() + 2 * renderer.getRenderValues().space; + } catch (ElementNotFoundException e) { + } + + } + this.repaint(); + + } + + /** + * Calculates the dimension of a Syntax Diagram + * + * @param sds + * @param transMap + * @return The dimension of the Syntax Diagram System + */ + public Dimension getSynDiaSystemSize(SynDiaSystem sds, TransMap transMap) { + + int y = 20; + + int ret_width = 0; + int ret_height = 0; + + for (String s : sds.getLabelsOfVariables()) { + + try { + SyntaxDiagram d = sds.getSyntaxDiagram(s); + + Dimension dim = this.renderer.getDiagramSize(d); + + if (dim.width > ret_width) + ret_width = dim.width; + + ret_height = y + dim.height; + y += dim.height + 3 * renderer.getRenderValues().space; + } catch (ElementNotFoundException e) { + } + + } + return new Dimension(ret_width + 50, ret_height + 20); + + } + + /** + * Calculates a SynDiaPanel with the help of the TransRenderer + * + * @param sd A syntax diagram + * @param transMap the transMap + * @return A JPanel containing the drawn SyntaxDiagram + */ + private SynDiaPanel getSyntaxDiagram(SyntaxDiagram sd, TransMap transMap) { + + SynDiaPanel p = new SynDiaPanel(); + ReturnDiagram rd = this.renderer.getRenderedDiagram(sd, transMap); + + for (RenderElement renderElem : rd.renderMap.keySet()) { + + if (renderElem instanceof RenderTrans) { + renderElem.addMouseListener(new TransListener(guicontroller, + transMap.get(rd.renderMap.get(renderElem)))); + } + + p.add(renderElem); + renderElem.setVisible(true); + renderElem.repaint(); + + } + + int width = rd.width; + if (this.renderer.getRenderValues().getWidthFromString(sd.getName()) > width) + width = this.renderer.getRenderValues().getWidthFromString( + sd.getName()); + + p.setSize(width, rd.height); + + this.renderMap.putAll(rd.renderMap); + + return p; + + } + + /** + * @param re the render element from that you want to get the mapped render + * element + * @return the syntax diagram element representing the render element in the + * model + * @throws RenderElemNotFoundException + */ + public SynDiaElem getSdeFromRe(RenderElement re) + throws RenderElemNotFoundException { + + if (renderMap.containsKey(re)) { + return renderMap.get(re); + } else { + throw new RenderElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + } + + /** + * @param sde a SynDiaElem finding itself in the RenderMap + * @return the render element representing the syntax diagram element in the + * model + * @throws SynDiaElemNotFoundException + */ + public RenderElement getReFromSde(SynDiaElem sde) + throws SynDiaElemNotFoundException { + + if (renderMap.containsValue(sde)) { + + for (RenderElement re : renderMap.keySet()) { + + if (sde == renderMap.get(re)) + return re; + + } + return null; + + } else { + throw new SynDiaElemNotFoundException( + "RenderElement existiert nicht in der Map"); + } + } + + /** + * This method sets the paramater autoSize deciding, whether the diagram + * size shall automatically fit to the screen size + * + * @param autosize true, if the diagram size shall automatically fit to the + * screen size + */ + public void setAutoSize(boolean autosize) { + + this.autoSize = autosize; + } + + /** + * A function instead of an Observer to rearrange the system by size + * + * @param size the size of the Font associated to the syntax diaram + */ + public void resizeSystem(int size) { + + renderer.getRenderValues().setFontSize(size); + + this.update(null, null); + + } + + /** + * This method returns the actual font size set in the RenderValues + * + * @return The actual font size set in the RenderValues + */ + public int getFontSize() { + + return this.renderer.getRenderValues().font.getSize(); + } + + /** Tells the Panel whether to render wi + * @param withStairs true, if stairs shall be displayed + */ + public void setStairs(boolean withStairs) { + + renderer.getRenderValues().withStairs = withStairs; + } + + /** + * @param o + * @param arg + */ + public void update(Observable o, Object arg) { + + if (autoSize) { + + int size = renderer.getRenderValues().font.getSize(); + while ((this.getSynDiaSystemSize(synDiaSystem, transMap).width < this + .getParent().getWidth() || this.getSynDiaSystemSize( + synDiaSystem, transMap).height < this.getParent() + .getHeight()) + && size < 50) { + + size++; + renderer.getRenderValues().setFontSize(size); + + } + + while ((this.getSynDiaSystemSize(synDiaSystem, transMap).width > this + .getParent().getWidth() || this.getSynDiaSystemSize( + synDiaSystem, transMap).height > this.getParent() + .getHeight()) + && size > 10) { + + size--; + renderer.getRenderValues().setFontSize(size); + + } + + guicontroller.getControlPanel().setZoomerValue(size); + + } + + this.drawSynDiaSystem(synDiaSystem, transMap); + this.setPreferredSize(this.getSynDiaSystemSize(synDiaSystem, transMap)); + guicontroller.validateComponents(); + if (guicontroller.isExplanationShown() && !transMap.isTransformed()) { + + guicontroller.setExplanationShow(true); + + } else { + + guicontroller.showExplanation(null); + + } + + } + + public void paintComponent(Graphics g) { + + super.paintComponent(g); + + Graphics2D g2d = (Graphics2D) g; + + int fsize = (int) Math.round(0.3*this.getParent().getWidth()); + Font trans = new Font("Courier", Font.BOLD, fsize); + + g2d.setFont(trans); + g2d.setColor(GUIConstants.STANDARD_COLOR_BACKGROUND_TEXT); + int y = this.getParent().getHeight() + (int) Math.round(0.2*fsize); + g2d.rotate(-Math.PI * 7/180); + g2d.drawString("trans", + this.getParent().getWidth() + - renderer.getRenderValues().getWidthFromString( + "trans", trans), y ); + g2d.rotate(Math.PI * 7/180); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.java b/src/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.java new file mode 100644 index 0000000..56b11fa --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/ExplanationFactory.java @@ -0,0 +1,61 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans; + +import java.awt.Font; + +import org.jalgo.module.ebnf.gui.trans.explanations.ExpAlt; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpConc; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpOpt; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpRep; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpTemp; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpTerminal; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpVar; +import org.jalgo.module.ebnf.gui.trans.explanations.Explanation; +import org.jalgo.module.ebnf.model.ebnf.*; + +/** + * @author Andre Viergutz + * + */ +public class ExplanationFactory { + + /** This factory creates an Explanation by getting a Term + * @param t The Term, to which the explanation is to be shown + * @param ebnffont + * @return an Explanation + */ + public static Explanation getExplanation(Term t, Font ebnffont) { + + + if (t instanceof ETerminalSymbol) { + + return new ExpTerminal(ebnffont); + + } else if (t instanceof EVariable) { + + return new ExpVar(ebnffont); + + } else if (t instanceof ERepetition) { + + return new ExpRep(ebnffont); + + } else if (t instanceof EOption) { + + return new ExpOpt(ebnffont); + + } else if (t instanceof EAlternative) { + + return new ExpAlt(ebnffont); + } else if (t instanceof EConcatenation) { + + return new ExpConc(ebnffont); + } + + return new ExpTemp(ebnffont); + + } + + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.java b/src/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.java new file mode 100644 index 0000000..43c1a4e --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/ExplanationPanel.java @@ -0,0 +1,76 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; + +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.trans.explanations.ExpFinish; +import org.jalgo.module.ebnf.gui.trans.explanations.Explanation; +import org.jalgo.module.ebnf.model.ebnf.Term; + +/** + * This Panel shows the Explanations to the transformation steps + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExplanationPanel extends JPanel { + + private Explanation explanation; + private Font ebnfFont; + + /** + * This is the constructor. It layouts the Panel + */ + public ExplanationPanel() { + + this.setLayout(null); + this.setBackground(Color.WHITE); + this.setPreferredSize(new Dimension(Short.MAX_VALUE, 150)); + this.setBorder(javax.swing.BorderFactory.createTitledBorder(null, + Messages.getString("ebnf", "Border_Explanation"), + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + try { + this.ebnfFont = EbnfFont.getFont().deriveFont(Font.PLAIN, 15f); + } catch (FontNotInitializedException e) { + System.out.println("DER EBNF-Font ist noch nicht initialisiert"); + } + + this.showExplanation(null, false); + + } + + /** + * This function displays an explanation by getting a Term and the + * information, whether the algorithm has finished or not + * + * @param t an Ebnf Term + * @param finish true, of the algorithm has finished + */ + public void showExplanation(Term t, boolean finish) { + + this.removeAll(); + if (finish) + explanation = new ExpFinish(ebnfFont); + else + explanation = ExplanationFactory.getExplanation(t, ebnfFont); + explanation.setLocation(10, 10); + explanation.setSize(this.getWidth() - 20, 140); + explanation.setVisible(true); + this.add(explanation); + this.repaint(); + + } + + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/GUIController.java b/src/org/jalgo/module/ebnf/gui/trans/GUIController.java new file mode 100644 index 0000000..f01eae0 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/GUIController.java @@ -0,0 +1,505 @@ +package org.jalgo.module.ebnf.gui.trans; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.ModuleConnector; +import org.jalgo.module.ebnf.controller.trans.TransController; +import org.jalgo.module.ebnf.gui.trans.event.PerformAction; +import org.jalgo.module.ebnf.gui.trans.event.PerformAllAction; +import org.jalgo.module.ebnf.gui.trans.event.ShowNextStepAction; +import org.jalgo.module.ebnf.gui.trans.event.UndoAction; +import org.jalgo.module.ebnf.gui.trans.event.UndoAllAction; +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderTrans; + +/** + * @author Andre Viergutz + */ +public class GUIController { + + private TransController transcontroller; + + private ModuleConnector connector; + + private JPanel contentPane; + + private DrawPanel drawPanel; + + private ExplanationPanel explanationPanel; + + private ControlPanel controlPanel; + + private JScrollPane drawScrollPane; + + private JPanel workPanel; + + private JButton showNextStepButton; + + private AbstractAction showNextStepAction; + + private AbstractAction performAction; + + private AbstractAction performAllAction; + + private AbstractAction undoAction; + + private AbstractAction undoAllAction; + + private boolean explanationShown = false; + + /** + * This constructor initializes alle the GuiComponents + * + * @param controller The TransController which created this + * @param connector The ModuleConnector from jAlgo + */ + + public GUIController(TransController controller, ModuleConnector connector) { + + this.transcontroller = controller; + this.connector = connector; + this.contentPane = controller.getContentPane(); + this.contentPane.addComponentListener(new ComponentAdapter() { + + public void componentResized(ComponentEvent e) { + + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, + contentPane.getHeight() + - controlPanel.getPreferredSize().height + - explanationPanel.getPreferredSize().height)); + + explanationPanel.revalidate(); + + } + + }); + + // this.installToolbar(); + this.init(); + + } + + /** + * This method is called from the constructor to layout the GUI + */ + public void init() { + + // init + + workPanel = new JPanel(); + explanationPanel = new ExplanationPanel(); + drawPanel = new DrawPanel(transcontroller.getSynDiaSystem(), + transcontroller.getTransMap(), this); + drawScrollPane = new JScrollPane(); + controlPanel = new ControlPanel(this); + + // setting + this.contentPane.setBackground(Color.WHITE); + drawScrollPane.setViewportBorder(javax.swing.BorderFactory + .createLoweredBevelBorder()); + drawScrollPane.setViewportView(drawPanel); + drawScrollPane.setPreferredSize(new Dimension(Short.MAX_VALUE, + contentPane.getHeight() + - controlPanel.getPreferredSize().height - 170)); + drawScrollPane.setMaximumSize(new Dimension(Short.MAX_VALUE, 200)); + + drawPanel.addComponentListener(new ComponentAdapter() { + + public void componentMoved(ComponentEvent e) { + + drawPanel.repaint(); + + } + + }); + + controlPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, controlPanel + .getPreferredSize().height)); + + workPanel.setLayout(new BoxLayout(workPanel, BoxLayout.Y_AXIS)); + workPanel.setBackground(Color.WHITE); + workPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, + Messages.getString("ebnf", "Border_Draw"), + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + workPanel.add(drawScrollPane); + workPanel.add(explanationPanel); + + switchToAlgorithm(); + + } + + /** + * Switches to the word algorithm + */ + public void switchToAlgorithm() { + + // layout + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));// layout); + + contentPane.add(controlPanel); + contentPane.add(workPanel); + + contentPane.validate(); + contentPane.repaint(); + + connector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + installToolbar(); + + } + + /** + * Switches to the syntax diagram display + */ + public void switchToSynDiaDisplay() { + + + transcontroller.switchToSynDiaDisplay(); + + } + + /** + * Switches back to the ebnf-display + */ + public void setEbnfInputMode() { + + + transcontroller.setEbnfInputMode(); + + } + + /** + * Sets up the toolbar. + */ + private void installToolbar() { + JToolBar toolBar = JAlgoGUIConnector.getInstance().getModuleToolbar( + connector); + + toolBar.addSeparator(); + + undoAllAction = new UndoAllAction(this); + toolBar.add(createToolbarButton(undoAllAction)); + undoAction = new UndoAction(this); + toolBar.add(createToolbarButton(undoAction)); + + showNextStepAction = new ShowNextStepAction(this, transcontroller); + showNextStepButton = createToolbarButton(showNextStepAction); + + toolBar.add(showNextStepButton); + + performAction = new PerformAction(this); + toolBar.add(createToolbarButton(performAction)); + performAllAction = new PerformAllAction(this); + toolBar.add(createToolbarButton(performAllAction)); + + toolBar.validate(); + updateToolbar(); + + } + + /** + * Creates a JButton object without border and text, which + * can be used in JToolBars + * + * @param a an Action associated to the created button + * @return a JButton instance with the given + * Action + */ + public JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton((Icon) a + .getValue(Action.SMALL_ICON), null, null); + button.setAction(a); + button.setText(""); + return button; + } + + /** + * Asks the TransController, if there is at least one step to perform + * + * @return true, if there are one or more steps to perform + */ + public boolean hasNextStep() { + + if (transcontroller.hasNextStep()) { + this.updateToolbar(); + return true; + } else + return false; + + } + + /** + * Tells the TransController to perform the next step chosen by the user + * + * @param re the RenderElement the user clicked on + * @return True, if it was possible to perform the chosen step + */ + public boolean performChosenStep(RenderElement re) { + + SynDiaElem se = this.getSynDiaElemFromRenderElem(re); + + if (transcontroller.performChosenStep(se)) { + this.updateToolbar(); + return true; + } else + return false; + } + + /** + * Tells the TransController to perform the next possible step. + * + * @return True, if it was possible to perform a step. + */ + public boolean performNextStep() { + + if (transcontroller.performNextStep()) { + this.updateToolbar(); + return true; + } else + return false; + + } + + /** + * Performs all possible steps. + * + * @return True, if it was possible to perform a step. + */ + public boolean performAllSteps() { + + if (transcontroller.performAllSteps()) { + this.updateToolbar(); + return true; + } else + return false; + + } + + /** + * Tells the TransController to undo the last executed step. + * + * @return True + */ + public boolean undoStep() { + + if (transcontroller.undoStep()) { + this.updateToolbar(); + return true; + } else + return false; + } + + /** + * Tells the TransController to undo the last executed step. + * + * @return True + */ + public boolean undoAllSteps() { + + transcontroller.undoAllSteps(); + this.updateToolbar(); + return true; + } + + /** + * Looks for the SynDiaElem which is associated to the given RenderElemnt + * + * @param re A RenderElement + * @return The associated SynDiaElem or null, if it was not found + */ + public SynDiaElem getSynDiaElemFromRenderElem(RenderElement re) { + + try { + + return drawPanel.getSdeFromRe(re); + + } catch (RenderElemNotFoundException e) { + + } + + return null; + } + + /** + * Looks for the SynDiaElem which is associated to the given RenderElemnt + * + * @param sde A SynDiaElem + * @return The associated SynDiaElem or null, if it was not found + */ + public RenderElement getRenderElemFromSynDiaElem(SynDiaElem sde) { + + try { + + return drawPanel.getReFromSde(sde); + + } catch (SynDiaElemNotFoundException e) { + + } + + return null; + } + + /** + * Looks and returns the next trans-element to render + * + * @return a RenderTrans + */ + public RenderTrans getNextRenderTrans() { + + SynDiaElem sde = transcontroller.getSdeFromNextStep(); + return (RenderTrans) getRenderElemFromSynDiaElem(sde); + + } + + /** + * Displays the explanation for the given Term + * + * @param t a Term of the ebnf-Definition + */ + public void showExplanation(Term t) { + + explanationPanel.showExplanation(t, !this.hasNextStep()); + + } + + /** + * Looks for and displays the next found explanation + */ + public void showNextExplanation() { + + Term t = transcontroller.getTermFromNextStep(); + explanationPanel.showExplanation(t, !this.hasNextStep()); + + } + + /** + * Updates the visibilitiy of the toolbar buttons + */ + public void updateToolbar() { + + TransMap tm = this.transcontroller.getTransMap(); + undoAllAction.setEnabled(!tm.isEbnf()); + undoAction.setEnabled(!tm.isEbnf()); + showNextStepAction.setEnabled(!tm.isTransformed()); + + if (explanationShown) { + showNextStepButton.setIcon(new ImageIcon(Messages.getResourceURL( + "main", "Icon.Advice_Selected"))); + } else { + showNextStepButton.setIcon(new ImageIcon(Messages.getResourceURL( + "main", "Icon.Advice"))); + } + performAction.setEnabled(!tm.isTransformed()); + performAllAction.setEnabled(!tm.isTransformed()); + + + } + + /** + * Updates the DrawPanel (where the SyntaxDiagrams are located). + * + * @param size The size of the Font associated to the SyntaxDiagram. Use + * size 0 if you don't want to change the size + */ + public void updateDrawPanel(int size) { + + drawPanel.resizeSystem(size); + this.validateComponents(); + + } + + /** + * This method validates all necessary components after a resize + */ + public void validateComponents() { + + this.drawScrollPane.validate(); + + } + + /** + * This method tells the guiController whether the DrawPanel should fit to + * size automatically or not + * + * @param autosize True, if auto size shall be activated + */ + public void setAutoSize(boolean autosize) { + + drawPanel.setAutoSize(autosize); + + } + + /** + * @return Returns the controlPanel. + */ + public ControlPanel getControlPanel() { + return controlPanel; + } + + /** + * @return Returns the drawPanel. + */ + public DrawPanel getDrawPanel() { + return drawPanel; + } + + /** + * This method sets the GUI, so that the next explanation is shown + * automatically. + * + * @param shown true, if the next explanation shall be shown automatically + */ + public void setExplanationShow(boolean shown) { + + if (this.hasNextStep()) { + if (shown) { + + this.showNextExplanation(); + RenderTrans te = this.getNextRenderTrans(); + te.changeColor(true); + te.showSeperated(true); + + } else { + + this.showExplanation(null); + RenderTrans te = this.getNextRenderTrans(); + te.changeColor(false); + te.showSeperated(false); + + } + } + + this.explanationShown = shown; + } + + /** + * This method tells the next explanation is shown automatically or not + * + * @return true, if shown automatically + */ + public boolean isExplanationShown() { + + return this.explanationShown; + } +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.java b/src/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.java new file mode 100644 index 0000000..badfc88 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/RenderElemNotFoundException.java @@ -0,0 +1,50 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.gui.trans; + +/** + * Exception is thrown if a syntax diagram element is not found in a + * concatenation. + * + * @author Michael Thiele + */ +@SuppressWarnings("serial") +public class RenderElemNotFoundException extends Exception { + + /** + * This constructor calls the super-constructor + */ + public RenderElemNotFoundException() { + super(); + } + + /** + * This constructor gets a String and directs it to the super-constructor + * + * @param message + */ + public RenderElemNotFoundException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.java b/src/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.java new file mode 100644 index 0000000..2492ad2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/SynDiaElemNotFoundException.java @@ -0,0 +1,50 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.gui.trans; + +/** + * Exception is thrown if a syntax diagram element is not found in a + * concatenation. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class SynDiaElemNotFoundException extends Exception { + + /** + * This constructor calls the super-constructor + */ + public SynDiaElemNotFoundException() { + super(); + } + + /** + * This constructor gets a String and directs it to the super-constructor + * + * @param message + */ + public SynDiaElemNotFoundException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Entries b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Entries new file mode 100644 index 0000000..031345f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Entries @@ -0,0 +1,6 @@ +/PerformAction.java/1.2/Thu Jan 31 20:15:01 2008// +/PerformAllAction.java/1.2/Thu Jan 31 20:15:01 2008// +/ShowNextStepAction.java/1.2/Thu Jan 31 20:15:01 2008// +/TransListener.java/1.1/Fri Aug 11 16:40:29 2006// +/UndoAction.java/1.2/Thu Jan 31 20:15:01 2008// +/UndoAllAction.java/1.2/Thu Jan 31 20:15:01 2008// diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Repository b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Repository new file mode 100644 index 0000000..eba753e --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/trans/event diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Root b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/PerformAction.java b/src/org/jalgo/module/ebnf/gui/trans/event/PerformAction.java new file mode 100644 index 0000000..567054d --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/PerformAction.java @@ -0,0 +1,71 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.trans.GUIController; + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class PerformAction extends AbstractAction { + + private GUIController gui; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + */ + public PerformAction(GUIController gui) { + super(); + this.gui = gui; + + putValue(NAME, Messages.getString("ebnf", "Trans.Perform")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", "Trans.Perform")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("main", + "Icon.Perform_step"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + + gui.performNextStep(); + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.java b/src/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.java new file mode 100644 index 0000000..7edc75b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/PerformAllAction.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.trans.GUIController; + + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class PerformAllAction +extends AbstractAction { + + private GUIController gui; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + */ + public PerformAllAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("ebnf", "Trans.PerformAll")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", "Trans.PerformAll")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Perform_all"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + + gui.performAllSteps(); + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.java b/src/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.java new file mode 100644 index 0000000..7370808 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/ShowNextStepAction.java @@ -0,0 +1,83 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.trans.TransController; +import org.jalgo.module.ebnf.gui.trans.GUIController; + + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ShowNextStepAction +extends AbstractAction { + + private GUIController controller; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + * @param controller the Controller instance of the AVL + * module + */ + public ShowNextStepAction(GUIController gui, TransController controller) { + super(); + this.controller = gui; + putValue(NAME, Messages.getString("ebnf", "Trans.ShowHelp")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", "Trans.ShowHelp")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Advice"))); + + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + + if (controller.isExplanationShown()) + controller.setExplanationShow(false); + else + controller.setExplanationShow(true); + + controller.getDrawPanel().repaint(); + controller.updateToolbar(); + + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/TransListener.java b/src/org/jalgo/module/ebnf/gui/trans/event/TransListener.java new file mode 100644 index 0000000..3b554d5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/TransListener.java @@ -0,0 +1,71 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import org.jalgo.module.ebnf.gui.trans.GUIController; +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.renderer.elements.RenderTrans; + +/** + * @author Andre + * + */ +public class TransListener extends MouseAdapter { + + private GUIController controller; + private Term term; + private boolean isExpShown; + + /** Initializes the controller + * @param controller the GuiController of the algorithm part + * @param t the Term to transform + */ + public TransListener(GUIController controller, Term t) { + + this.controller = controller; + this.term = t; + + } + + + public void mouseEntered(MouseEvent e) { + isExpShown = false; + if (controller.isExplanationShown()) { + + isExpShown = true; + controller.setExplanationShow(false); + + } + RenderTrans transelem = (RenderTrans) e.getComponent(); + transelem.showSeperated(true); + //transelem.changeColor(false); + + controller.showExplanation(term); + + } + public void mouseExited(MouseEvent e) { + + RenderTrans transelem = (RenderTrans) e.getComponent(); + transelem.showSeperated(false); + //transelem.changeColor(true); + + controller.showExplanation(null); + + if (isExpShown) + controller.setExplanationShow(true); + + } + public void mouseReleased(MouseEvent e) { + + controller.performChosenStep((RenderTrans) e.getComponent()); + controller.showExplanation(null); + if (isExpShown) + controller.setExplanationShow(true); + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/UndoAction.java b/src/org/jalgo/module/ebnf/gui/trans/event/UndoAction.java new file mode 100644 index 0000000..e884859 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/UndoAction.java @@ -0,0 +1,73 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.trans.GUIController; + + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class UndoAction +extends AbstractAction { + + private GUIController gui; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + */ + public UndoAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("ebnf", "Trans.Undo")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", "Trans.Undo")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_step"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + + gui.undoStep(); + + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.java b/src/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.java new file mode 100644 index 0000000..92097a5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/event/UndoAllAction.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 10.05.2005 */ +package org.jalgo.module.ebnf.gui.trans.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.trans.GUIController; + + +/** + * The class PerformAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * causes the currently running algorithm to perform a single step. + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class UndoAllAction +extends AbstractAction { + + private GUIController gui; + + /** + * Constructs a PerformAction object with the given + * references. + * + * @param gui the GUIController instance of the AVL module + */ + public UndoAllAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("ebnf", "Trans.UndoAll")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", "Trans.UndoAll")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_all"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + + gui.undoAllSteps(); + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Entries b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Entries new file mode 100644 index 0000000..f59985f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Entries @@ -0,0 +1,9 @@ +/ExpAlt.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpConc.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpFinish.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpOpt.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpRep.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpTemp.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpTerminal.java/1.1/Fri Aug 11 16:40:27 2006// +/ExpVar.java/1.1/Fri Aug 11 16:40:27 2006// +/Explanation.java/1.1/Fri Aug 11 16:40:27 2006// diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Repository b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Repository new file mode 100644 index 0000000..ed4f0de --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/trans/explanations diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Root b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.java new file mode 100644 index 0000000..12ae543 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpAlt.java @@ -0,0 +1,119 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpAlt extends Explanation { + + private Font ebnffont; + + private Arc2D.Double arc_left_top; + + private Arc2D.Double arc_right_top; + + private Arc2D.Double arc_left_bottom; + + private Arc2D.Double arc_right_bottom; + + private Line2D.Double line_top; + + private Line2D.Double line_bottom; + + private Line2D.Double line_left; + + private Line2D.Double line_right; + + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont The EbnfFont + */ + public ExpAlt(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + + + } + + public void paintComponent(Graphics g) { + + int radius = 15; + int x = 190; + int y = 40; + int width = 180; + int height = 50; + + arc_left_top = new Arc2D.Double(x, y, 2 * radius, 2 * radius, + 0, 90, Arc2D.OPEN); + arc_left_bottom = new Arc2D.Double(x + 2 * radius, y + height - 2 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + arc_right_top = new Arc2D.Double(x + width - 2 * radius, y, 2 * radius, + 2 * radius, 90, 90, Arc2D.OPEN); + arc_right_bottom = new Arc2D.Double(x + width - 4 * radius, y + height + - 2 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + + line_top = new Line2D.Double(x, y, x + width, y); + + line_bottom = new Line2D.Double(x + 3 * radius, y + height, x + width + - 3 * radius, y + height); + + line_left = new Line2D.Double(x + 2 * radius, y + radius, x + 2 * radius, y + + height - radius); + line_right = new Line2D.Double(x + width - 2 * radius, y + radius, x + + width - 2 * radius, y + height - radius); + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + //lines + g2d.setFont(ebnffont); + g2d.setColor(Color.BLACK); + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + + g2d.draw(line_top); + g2d.draw(line_bottom); + g2d.draw(line_left); + g2d.draw(line_right); + + g2d.setColor(Color.WHITE); + // trans element + + g2d.fillRoundRect(x + 3 * radius, y -radius, width - 6 * radius, 30, 30, 30); + g2d.fillRoundRect(x + 3 * radius, y + height - radius, width - 6 * radius, 30, 30, 30); + + g2d.setColor(Color.BLACK); + g2d.drawRoundRect(x + 3 * radius, y - radius, width - 6 * radius, 30, 30, 30); + g2d.drawRoundRect(x + 3 * radius, y + height - radius, width - 6 * radius, 30, 30, 30); + + g2d.drawString("trans(\u03b11)", x + 3 * radius + 15, y + 5 ); + g2d.drawString("trans(\u03b12)", x + 3 * radius + 15, y + height + 5 ); + + + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" \u03b11,\u03b12 \u2208 T(\u2211,V)", 10, 30); + g2d.drawString("\u2022 trans(\u3011\u03b11\u300e\u03b12\u3012) =", 50, 70); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.java new file mode 100644 index 0000000..79ad992 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpConc.java @@ -0,0 +1,88 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Line2D; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpConc extends Explanation { + + private Font ebnffont; + + + + private Line2D.Double line_left; + private Line2D.Double line_right; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpConc(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + + + } + + public void paintComponent(Graphics g) { + + int radius = 15; + int x = 170; + int y = 65; + int width = 120; + + line_left = new Line2D.Double(x, y, x + width, y); + line_right = new Line2D.Double(x + width + 2 * radius, y, x + 2*(width + radius), y); + + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + //lines + g2d.setFont(ebnffont); + g2d.setColor(Color.BLACK); + + g2d.draw(line_left); + g2d.draw(line_right); + + g2d.setColor(Color.WHITE); + // trans element + + g2d.fillRoundRect(x + radius, y -radius, width - 2 * radius, 30, 30, 30); + g2d.fillRoundRect(x + width + 3 * radius, y + - radius, width - 2 * radius, 30, 30, 30); + + + + g2d.setColor(Color.BLACK); + g2d.drawRoundRect(x + radius, y - radius, width - 2 * radius, 30, 30, 30); + g2d.drawRoundRect(x + width + 3 * radius, y - radius, width - 2 * radius, 30, 30, 30); + + + g2d.drawString("trans(\u03b11)", x + 2 * radius, y + 5 ); + g2d.drawString("...", x + width + 8, y+2); + g2d.drawString("trans(\u03b1n)", x + width + 4 * radius, y + 5 ); + + + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" \u03b11...\u03b1n \u2208 T(\u2211,V)", 10, 30); + g2d.drawString("\u2022 trans(\u03b11...\u03b1n) =", 50, 70); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.java new file mode 100644 index 0000000..a3c82f8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpFinish.java @@ -0,0 +1,50 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpFinish extends Explanation { + + private Font ebnffont; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpFinish(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setFont(ebnffont); + g2d.drawString("\u2022 "+Messages.getString("ebnf", "Trans.Finished"), 10, 30); + + } + + + + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.java new file mode 100644 index 0000000..fdf784a --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpOpt.java @@ -0,0 +1,114 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpOpt extends Explanation { + + private Font ebnffont; + + private Arc2D.Double arc_left_top; + + private Arc2D.Double arc_right_top; + + private Arc2D.Double arc_left_bottom; + + private Arc2D.Double arc_right_bottom; + + private Line2D.Double line_top; + + private Line2D.Double line_bottom; + + private Line2D.Double line_left; + + private Line2D.Double line_right; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpOpt(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + + + } + + public void paintComponent(Graphics g) { + + int radius = 15; + int x = 170; + int y = 40; + int width = 180; + int height = 50; + + arc_left_top = new Arc2D.Double(x, y, 2 * radius, 2 * radius, + 0, 90, Arc2D.OPEN); + arc_left_bottom = new Arc2D.Double(x + 2 * radius, y + height - 2 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + arc_right_top = new Arc2D.Double(x + width - 2 * radius, y, 2 * radius, + 2 * radius, 90, 90, Arc2D.OPEN); + arc_right_bottom = new Arc2D.Double(x + width - 4 * radius, y + height + - 2 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + + line_top = new Line2D.Double(x, y, x + width, y); + + line_bottom = new Line2D.Double(x + 3 * radius, y + height, x + width + - 3 * radius, y + height); + + line_left = new Line2D.Double(x + 2 * radius, y + radius, x + 2 * radius, y + + height - radius); + line_right = new Line2D.Double(x + width - 2 * radius, y + radius, x + + width - 2 * radius, y + height - radius); + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + //lines + g2d.setFont(ebnffont); + g2d.setColor(Color.BLACK); + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + + g2d.draw(line_top); + g2d.draw(line_bottom); + g2d.draw(line_left); + g2d.draw(line_right); + + g2d.setColor(Color.WHITE); + // trans element + + g2d.fillRoundRect(x + 3 * radius, y -radius, width - 6 * radius, 30, 30, 30); + g2d.setColor(Color.BLACK); + g2d.drawRoundRect(x + 3 * radius, y - radius, width - 6 * radius, 30, 30, 30); + + g2d.drawString("trans(\u03b1)", x + 3 * radius + 20, y + 5 ); + + + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" \u03b1 \u2208 T(\u2211,V)", 10, 30); + g2d.drawString("\u2022 trans(\u300c\u03b1\u300d) =", 50, 70); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.java new file mode 100644 index 0000000..3eca333 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpRep.java @@ -0,0 +1,115 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpRep extends Explanation { + + private Font ebnffont; + + private Arc2D.Double arc_left_top; + + private Arc2D.Double arc_right_top; + + private Arc2D.Double arc_left_bottom; + + private Arc2D.Double arc_right_bottom; + + private Line2D.Double line_top; + + private Line2D.Double line_bottom; + + private Line2D.Double line_left; + + private Line2D.Double line_right; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpRep(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + + + } + + public void paintComponent(Graphics g) { + + int radius = 15; + int x = 170; + int y = 40; + int width = 150; + int height = 50; + + arc_left_top = new Arc2D.Double(x + radius, y, 2 * radius, 2 * radius, + 90, 90, Arc2D.OPEN); + arc_left_bottom = new Arc2D.Double(x + radius, y + height - 2 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + arc_right_top = new Arc2D.Double(x + width - 3 * radius, y, 2 * radius, + 2 * radius, 0, 90, Arc2D.OPEN); + arc_right_bottom = new Arc2D.Double(x + width - 3 * radius, y + height + - 2 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + + line_top = new Line2D.Double(x, y, x + width, y); + + line_bottom = new Line2D.Double(x + 2 * radius, y + height, x + width + - 2 * radius, y + height); + + line_left = new Line2D.Double(x + radius, y + radius, x + radius, y + + height - radius); + line_right = new Line2D.Double(x + width - radius, y + radius, x + + width - radius, y + height - radius); + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + //lines + g2d.setFont(ebnffont); + g2d.setColor(Color.BLACK); + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + + g2d.draw(line_top); + g2d.draw(line_bottom); + g2d.draw(line_left); + g2d.draw(line_right); + + g2d.setColor(Color.WHITE); + // trans element + + g2d.fillRoundRect(x + 2 * radius, y + height - radius, width - 4 * radius, 30, 30, 30); + g2d.setColor(Color.BLACK); + + g2d.drawString("trans(\u03b1)", x + 2 * radius + 20, y + height + 5 ); + g2d.drawRoundRect(x + 2 * radius, y + height - radius, width - 4 * radius, 30, 30, 30); + + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" \u03b1 \u2208 T(\u2211,V)", 10, 30); + g2d.drawString("\u2022 trans(\u300F\u03b1\u3010) =", 50, 70); + g2d.drawString("\u2022 "+Messages.getString("ebnf", "Trans.Beachte_top"),350,70); + g2d.drawString(Messages.getString("ebnf", "Trans.Beachte_bottom"),360,90); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.java new file mode 100644 index 0000000..ac6d577 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTemp.java @@ -0,0 +1,48 @@ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpTemp extends Explanation { + + private Font ebnffont; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpTemp(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setFont(ebnffont); + g2d.drawString("\u2022 "+Messages.getString("ebnf", "Trans.FirstAd"), 10, 30); + g2d.drawString("\u2022 "+Messages.getString("ebnf", "Trans.SecondAd"), 10, 55); + + } + + + + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.java new file mode 100644 index 0000000..cbaeffd --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpTerminal.java @@ -0,0 +1,61 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpTerminal extends Explanation { + + private Font ebnffont; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpTerminal(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(Color.BLACK); + g2d.drawLine(140,65,210,65); + g2d.setColor(Color.WHITE); + g2d.fillRoundRect(160,50,30,30,30,30); + g2d.setColor(Color.BLACK); + g2d.setFont(new Font("Courier", Font.PLAIN, 16)); + g2d.drawString("w", 170, 70); + g2d.drawRoundRect(160,50,30,30,30,30); + + g2d.setFont(ebnffont); + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" w \u2208 \u2211", 10, 30); + g2d.drawString("\u2022 trans(w) =", 50, 70); + + + + } + + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.java new file mode 100644 index 0000000..21f23d4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/ExpVar.java @@ -0,0 +1,61 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import org.jalgo.main.util.Messages; + + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class ExpVar extends Explanation { + + private Font ebnffont; + + /** + * Inititalizes the element by getting the name of the symbol + * @param ebnfFont the EbnfFont + */ + public ExpVar(Font ebnfFont) { + + this.ebnffont = ebnfFont; + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(Color.BLACK); + g2d.drawLine(140,65,210,65); + g2d.setColor(Color.WHITE); + g2d.fillRect(160,50,30,30); + g2d.setColor(Color.BLACK); + g2d.setFont(new Font("Courier", Font.PLAIN, 16)); + g2d.drawString("v", 170, 70); + g2d.drawRect(160,50,30,30); + + g2d.setFont(ebnffont); + g2d.drawString(Messages.getString("ebnf", "Trans.Sei")+" v \u2208 V", 10, 30); + g2d.drawString("\u2022 trans(v) =", 50, 70); + + + + } + + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.java b/src/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.java new file mode 100644 index 0000000..5beeff1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/trans/explanations/Explanation.java @@ -0,0 +1,24 @@ +/** + * + */ +package org.jalgo.module.ebnf.gui.trans.explanations; + +import javax.swing.JPanel; + +/** + * @author Andre + * + */ +@SuppressWarnings("serial") +public class Explanation extends JPanel { + + /** + * empty element + */ + public Explanation() { + + + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.java new file mode 100644 index 0000000..d9103ec --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/AlgoCtrlPanel.java @@ -0,0 +1,420 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JTextField; +import javax.swing.JTextPane; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.WordGenerator; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.GenerateWordException; +import org.jalgo.module.ebnf.gui.syndia.display.DiagramSize; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This Panel contains the Textfield to enter a word which should be generated, + * a Button to start the Algorithm and buttons to undo and redo steps in the + * algorithm. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class AlgoCtrlPanel extends JPanel implements Observer { + + private static int counter = 0; + + private final Color bgcolor = Color.WHITE; + + private GuiController myGuiController; + + // Control to zoom or fit the DrawPanel + private JSlider zoomer = new JSlider(JSlider.HORIZONTAL); + + private JToggleButton fitToSize = new JToggleButton(new ImageIcon(Messages + .getResourceURL("ebnf", "Icon.FitToSize"))); + + // Start and Stop Button + private JButton startButton; + + private JButton stopButton; + + private JButton wordButton; + + // Textpane fpr Info, that algorithm has ended + private JTextPane finishPane; + + // Button to return to SynDiaView + private JButton returnButton; + + // WordInput + private JTextField inputWord; + + private JTextPane inputPane; + + private JTextPane outputPane; + + private JTextPane inputDescPane; + + private JTextPane outputDescPane; + + private Font outputFont; + + private static final int FONT_SIZE = 15; + + private MouseListener myStatusUpdater; + + /** + * Constructor to create a new AlgoCtrlPanel. + * + */ + public AlgoCtrlPanel(GuiController myGuiController, Font ebnfFont) { + + this.myGuiController = myGuiController; + this.outputFont = new Font("Tahoma", Font.PLAIN, FONT_SIZE); + + this.setLayout(null); + this.setBackground(Color.WHITE); + this.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " " + + Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_Description") + " ", + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + this.myStatusUpdater = StatusLineUpdater.getInstance(); + + init(); + + } + + /** + * Method initializes the Panel. Creates Buttons and Textfield. + * + */ + private void init() { + + // init ************************************************************* + startButton = new JButton(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_StartLabel")); + stopButton = new JButton(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_StopLabel")); + wordButton = new JButton(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_RandomWordLabel")); + returnButton = new JButton(Messages.getString("ebnf", + "SynDia.Control_ToSynDiaDisplay")); + inputPane = new JTextPane(); + inputWord = new JTextField(); + outputPane = new JTextPane(); + inputDescPane = new JTextPane(); + outputDescPane = new JTextPane(); + finishPane = new JTextPane(); + finishPane.addMouseListener(myStatusUpdater); + + // set ************************************************************* + startButton.setToolTipText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_StartTooltip")); + startButton.addMouseListener(myStatusUpdater); + stopButton.setToolTipText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_StopTooltip")); + stopButton.addMouseListener(myStatusUpdater); + returnButton.addMouseListener(myStatusUpdater); + wordButton.setToolTipText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_RandomWordTooltip")); + wordButton.addMouseListener(myStatusUpdater); + stopButton.setVisible(false); + + inputWord.setMinimumSize(new Dimension(200, 25)); + inputWord.setPreferredSize(new Dimension(600, 25)); + + fitToSize.setMnemonic(KeyEvent.VK_Z); + fitToSize.setBorder(new EmptyBorder(3, 3, 3, 3)); + fitToSize.setFocusPainted(false); + fitToSize.setToolTipText(Messages.getString("ebnf", + "SynDia.Control_FitToSize")); + fitToSize.addMouseListener(myStatusUpdater); + + zoomer.setMinimum(10); + zoomer.setMaximum(50); + zoomer.setValue(DiagramSize.getFontSize()); + zoomer.setPreferredSize(new Dimension(70, 20)); + zoomer.setBackground(Color.WHITE); + + // TextPane must be disabled, so they cant be edited by the user + inputPane.setFont(outputFont); + outputPane.setFont(outputFont); + finishPane.setFont(outputFont); + inputPane.setDisabledTextColor(Color.BLACK); + outputPane.setDisabledTextColor(Color.BLACK); + finishPane.setDisabledTextColor(Color.RED); + inputPane.setEnabled(false); + outputPane.setEnabled(false); + finishPane.setEnabled(false); + + inputDescPane.setText("Zu erzeugendes Wort: "); + inputDescPane.setFont(outputFont); + outputDescPane.setText("Erzeugtes Wort: "); + outputDescPane.setFont(outputFont); + inputDescPane.setDisabledTextColor(Color.BLACK); + outputDescPane.setDisabledTextColor(Color.BLACK); + inputDescPane.setEnabled(false); + outputDescPane.setEnabled(false); + + // layout ************************************************************* + // Panels needed to order the elements + JPanel lineOneLeft = new JPanel(); + JPanel lineOneRight = new JPanel(); + JPanel lineOne = new JPanel(); + JPanel lineTwoLeft = new JPanel(); + JPanel lineTwoRight = new JPanel(); + JPanel lineTwo = new JPanel(); + JPanel lineTwoBorder = new JPanel(); + lineOneLeft.setBackground(bgcolor); + lineOneRight.setBackground(bgcolor); + lineOne.setBackground(bgcolor); + lineTwoLeft.setBackground(bgcolor); + lineTwoRight.setBackground(bgcolor); + lineTwo.setBackground(bgcolor); + lineTwoBorder.setBackground(bgcolor); + + lineOneLeft.add(zoomer); + lineOneLeft.add(fitToSize); + lineOneLeft.add(startButton); + lineOneLeft.add(stopButton); + lineOneLeft.add(wordButton); + lineOneLeft.add(finishPane); + lineOneRight.add(returnButton); + lineOne.setLayout(new BorderLayout(0, 0)); + lineOne.add(lineOneLeft, BorderLayout.WEST); + lineOne.add(lineOneRight, BorderLayout.EAST); + lineTwoLeft.setLayout(new BoxLayout(lineTwoLeft, BoxLayout.Y_AXIS)); + lineTwoLeft.add(inputDescPane); + lineTwoLeft.add(outputDescPane); + lineTwoRight.setLayout(new BoxLayout(lineTwoRight, BoxLayout.Y_AXIS)); + lineTwoRight.add(inputWord); + lineTwoRight.add(inputPane); + lineTwoRight.add(outputPane); + lineTwo.setLayout(new BoxLayout(lineTwo, BoxLayout.X_AXIS)); + lineTwo.add(lineTwoLeft); + lineTwo.add(lineTwoRight); + lineTwoBorder.setLayout(new BorderLayout(0, 0)); + lineTwoBorder.add(lineTwo, BorderLayout.WEST); + this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + this.add(lineOne); + this.add(lineTwoBorder); + + initListener(); + + wordButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + generateWord(); + } + }); + + } + + /** + * Initializes Listeners + * + */ + private void initListener() { + + // Fit the Size + fitToSize.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + + if (e.getStateChange() == ItemEvent.SELECTED) { + + // An change zoomer value, if Font size changes. + int newFontSize = myGuiController.setAutoSize(true); + zoomer.setValue(newFontSize); + + } else { + + myGuiController.setAutoSize(false); + + } + } + }); + + // Zoomer + zoomer.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + fitToSize.setSelected(false); + } + }); + zoomer.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + myGuiController.setAutoSize(false); + myGuiController.updateDrawPanel(zoomer.getValue()); + } + }); + + // Switch to SynDiaView + returnButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + DiagramSize.setFontSize(myGuiController.getFontSize()); + myGuiController.switchToSynDiaView(); + } + }); + + // StartButton + startButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + startAlgorithm(); + } + }); + + // StopButton + stopButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + while (myGuiController.getWordAlgoController().isUndoPossible()) { + myGuiController.getWordAlgoController().undo(); + } + } + }); + + // wordInput.enter + inputWord.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + startAlgorithm(); + } + }); + } + + /** + * Called by listeners which peform a beginn of the algorithm. + * + */ + private void startAlgorithm() { + // Checkout if input from Textfield is valid. + if (myGuiController.getWordAlgoController().isWordValid( + inputWord.getText())) { + finishPane.setText(""); + myGuiController.getWordAlgoController() + .setWord(inputWord.getText()); + myGuiController.getWordAlgoController().startAlgorithm(); + } + // Inform the user that the entered String is incorrect. + else { + finishPane.setText(Messages.getString("ebnf", + "WordAlgo.Warning_WordNotValid")); + finishPane.setToolTipText(Messages.getString("ebnf", + "WordAlgo.Warning_WordNotValidToolTip")); + } + } + + /** + * Method called, if the Model of the WordAlgorithm has been changed. + * + */ + public void update(Observable anObservable, Object arg) { + // Cast the Observable to WordAlgoModel and + // update the parameters neede to paint the Panel. + if (anObservable instanceof WordAlgoModel) { + + WordAlgoModel myModel = (WordAlgoModel) anObservable; + + // Check if algorithm is running and enable and + // disable the Buttons, TextPanes and the TextField. + if (myModel.isAlgorithmRunning()) { + startButton.setEnabled(false); + stopButton.setEnabled(true); + startButton.setVisible(false); + stopButton.setVisible(true); + wordButton.setVisible(false); + inputWord.setEnabled(false); + inputWord.setVisible(false); + inputPane.setVisible(true); + finishPane.setText(""); + finishPane.setToolTipText(""); + this.inputPane.setText(myModel.getWord()); + this.outputPane.setText(myModel.getOutput()); + } else if (myModel.isAlgorithmFinished()) { + startButton.setEnabled(false); + stopButton.setEnabled(true); + startButton.setVisible(false); + stopButton.setVisible(true); + wordButton.setVisible(false); + inputWord.setEnabled(false); + inputWord.setVisible(false); + inputPane.setVisible(true); + if (myModel.isFinishedWithSuccess()) { + finishPane.setText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_FinishSuccess")); + finishPane.setToolTipText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_FinishSuccess")); + + } else { + finishPane.setText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_FinishUnsuccess")); + finishPane.setToolTipText(Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_FinishUnsuccess")); + } + this.inputPane.setText(myModel.getWord()); + this.outputPane.setText(myModel.getOutput()); + } else { + startButton.setEnabled(true); + stopButton.setEnabled(false); + startButton.setVisible(true); + stopButton.setVisible(false); + wordButton.setVisible(true); + inputWord.setEnabled(true); + inputWord.setVisible(true); + inputPane.setVisible(false); + finishPane.setText(""); + finishPane.setToolTipText(""); + this.inputPane.setText(""); + this.outputPane.setText(""); + } + + this.validate(); + } + } + + /** + * Generates a word which is possible in the SyntaxDiagram and puts it into + * the Textfield. + * + */ + private void generateWord() { + counter = 0; + WordGenerator wordGenerator = new WordGenerator(myGuiController + .getWordAlgoController().getSynDiaSystem()); + String word; + try { + while ((word = wordGenerator.start()).equals(inputWord.getText()) + && counter++ < 10) + ; + inputWord.setText(word); + + } catch (GenerateWordException e) { + word = Messages.getString("ebnf", + "WordAlgo.GuiControlPanel_RandomWordError"); + finishPane.setText(word); + } + } +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Entries b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..d2e7013 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Entries @@ -0,0 +1,9 @@ +/AlgoCtrlPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/DrawPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/ExplanationPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/GuiController.java/1.1/Fri Aug 11 16:40:31 2006// +/StackDrawPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/StackPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/SynDiaPanel.java/1.1/Fri Aug 11 16:40:31 2006// +/SynDiaSystemPanel.java/1.1/Fri Aug 11 16:40:31 2006// +D/events//// diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Repository b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..9038dbb --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/wordalgorithm diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Root b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.java new file mode 100644 index 0000000..104cdea --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/DrawPanel.java @@ -0,0 +1,695 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Dimension; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.syndia.display.IDrawPanel; +import org.jalgo.module.ebnf.gui.wordalgorithm.events.WordExitListener; +import org.jalgo.module.ebnf.gui.wordalgorithm.events.WordSplitListener; +import org.jalgo.module.ebnf.gui.wordalgorithm.events.WordSynDiaListener; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; +import org.jalgo.module.ebnf.renderer.ReturnDiagram; +import org.jalgo.module.ebnf.renderer.WordAlgoRenderer; +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderRepetition; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; +import org.jalgo.module.ebnf.renderer.wordalgorithm.Position; +import org.jalgo.module.ebnf.renderer.wordalgorithm.RenderEnd; +import org.jalgo.module.ebnf.renderer.wordalgorithm.ReturnAdress; + +/** + * This Panel contains a graphical representation of all SyntaxDiagrams. It + * contains a JScrollPanel, so that the SyntaxDiagrams are + * scrollable. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class DrawPanel extends JPanel implements Observer, IDrawPanel, + MouseWheelListener { + + // The Space between Border and the Diagrams. + private final int BORDER_SPACE = 20; + + // The Y-Position of the last diagram drawn. + // It's also the minimum height of mySynDiaPanel + private int posY; + + // The Width of the widest diagram drawn. + // It's also the minimum width of mySynDiaPanel + private int posX; + + // The Size of the Font during rendering + // (Default -1) + private int fontSize = -1; + + // The SynDiaRenderer renders SyntaxDiagram. Needed to Update the + // synDiaPanel. + private WordAlgoRenderer wordAlgoRenderer; + + // The GuiController is needed from the Listeners + private GuiController myGuiController; + + // Specifies, which SyntaxDiagrams uses which SynDiaPanel. + private Map synDiaPanelMap; + + // Specifies, which SyntaxDiagrams contain which RenderElements. + private Map> synDiaElemMap; + + // Contains all ReturnAdresses drawn. + private Map retAdressMap; + + // Contains all BorderPanels to the SynDiaPanels. Needed during + // JumpToDiagram. + private List borderPanelList; + + // needed to Update the graphical view + // (Just a copy of the WordAlgoModel). + private WordAlgoModel myModel = null; + + private SynDiaSystem mySynDiaSystem; + + // Needed to print the actual Position in a diagram + // during the algorithm. Must be Object because + // position can be a SynDiaElem and also a SyntaxDiagram. + private Object actualPosition; + + private Position actualRenderPosition = null; + + private SynDiaPanel actualPositionPanel = null; + + // Needed to get the Diagrams scrollable + private JScrollPane scrollPane; + + // Contains all SyntaxDiagrams. + private SynDiaSystemPanel mySynDiaPanel; + + // Specifies if returnAdresses can be removed + private boolean returnAdressesDrawn = false; + + // Specifies if autoSize should be on + private boolean autoSize = false; + + /** + * Construct a new DrawPanel. + * + * @param aSynDiaSystem + * The SynDiaSystem which should be drwan onto the + * DrawPanel during initilization. + * @param myGuiController + * The GuiController which should be used to + * perform clicks on + * SynDiaElem/code>s and Syntaxdiagrams. + */ + public DrawPanel(SynDiaSystem aSynDiaSystem, GuiController myGuiController) { + + this.setLayout(null); + this.setBackground(BACKGROUND_COLOR); + + // Draw Framborder + this.setMinimumSize(new Dimension(Short.MAX_VALUE, 150)); + this.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " " + + Messages.getString("ebnf", "Border_Draw") + " ", + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + this.myGuiController = myGuiController; + + mySynDiaSystem = aSynDiaSystem; + + setActualPosition(); + + // paint the gui + this.mySynDiaPanel = new SynDiaSystemPanel(); + scrollPane = new JScrollPane(); + init(aSynDiaSystem); + } + + /** + * Initializes the Gui of the DrawPanel + * + * @param aSynDiaSystem + * The SynDiaSystem given to the Constructor. + */ + private void init(SynDiaSystem aSynDiaSystem) { + + // INIT ************************************************************** + initDiagrams(aSynDiaSystem); + + // SET ************************************************************** + + // mySynDiaPanel must be at least as big as the Diagrams. + this.mySynDiaPanel.setPreferredSize(new Dimension(posX, posY)); + // this.mySynDiaPanel.setSize(posX, posY); + this.mySynDiaPanel.addMouseWheelListener(this); + + scrollPane.setViewportView(mySynDiaPanel); + scrollPane.setBackground(this.getBackground()); + scrollPane.setVisible(true); + // scrollPane.setPreferredSize(new Dimension(this.getVisibleRect().width + // - DIFFERENCE, this.getVisibleRect().height - DIFFERENCE)); + // scrollPane.setPreferredSize(new Dimension(mySynDiaPanel.getWidth(), + // mySynDiaPanel.getHeight())); + + // LAYOUT ************************************************************** + this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); + + this.add(scrollPane); + + this.addComponentListener(new ComponentListener() { + public void componentResized(ComponentEvent e) { + wasResized(); + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + } + }); + } + + /** + * Creates and Initializes the graphical representation of the + * SyntaxDiagrams. + * + * @param aSynDiaSystem + * The SynDiaSystem which should be drawn. + */ + private void initDiagrams(SynDiaSystem aSynDiaSystem) { + + // Maps needed to repaint the Diagrams. + synDiaPanelMap = new HashMap(); + + synDiaElemMap = new HashMap>(); + + retAdressMap = new HashMap(); + + borderPanelList = new ArrayList(); + + // Position of the first Diagram which is drawn should be the border + // space + posX = BORDER_SPACE; + posY = BORDER_SPACE; + + // Get the names of all Diagrams + List diagramNameList = aSynDiaSystem.getLabelsOfVariables(); + // Print all Diagrams + for (String aDiagramName : diagramNameList) { + // Try to get the Diagram to each name and paint it + try { + // Each diagram gets it's own SynDiaPanel. + SynDiaPanel aSynDiaPanel = new SynDiaPanel(this.getBackground()); + SyntaxDiagram aDiagram = aSynDiaSystem + .getSyntaxDiagram(aDiagramName); + paintDiagram(aSynDiaPanel, aDiagram); + mySynDiaPanel.add(aSynDiaPanel); + + // The synDiaPanel is putted to the map to be found + // again if the GUI has to be updated. + synDiaPanelMap.put(aDiagramName, aSynDiaPanel); + + // each Diagram gets a BorderPanel which is a bit bigger than + // the SynDiaPanel + // The border Panel is used for MouseOver events during a jump + // to a Diagram. + int difference = 3; + SynDiaPanel aBorderPanel = new SynDiaPanel(this.getBackground()); + aBorderPanel.setLocation(aSynDiaPanel.getX() - difference, + aSynDiaPanel.getY() - difference); + aBorderPanel.setSize(aSynDiaPanel.getWidth() + difference * 2, + aSynDiaPanel.getHeight() + difference * 2); + aBorderPanel.setVisible(true); + // BorderPanel gets a Listener for JumpToDiagrams + aBorderPanel.addMouseListener(new WordSynDiaListener( + myGuiController, aDiagram)); + mySynDiaPanel.add(aBorderPanel); + mySynDiaPanel.setComponentZOrder(aBorderPanel, mySynDiaPanel + .getComponentCount() - 1); + // Must be in List to be updated in Z-Order if jumpToDiagramm + borderPanelList.add(aBorderPanel); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + } + } + + } + + /** + * Gets a Panel an draws a SyntaxDiagram onto it. + * + * @param aSynDiaPanel + * The SynDiaPanel the SyntaxDiagram + *aDiagram + * should be drawn on. + * @param aDiagram + * The SyntaxDiagram which should be drawn. + */ + private void paintDiagram(SynDiaPanel aSynDiaPanel, SyntaxDiagram aDiagram) { + + wordAlgoRenderer = new WordAlgoRenderer(); + + // Set fontSite if not default. + if (fontSize > -1) { + wordAlgoRenderer.getRenderValues().setFontSize(fontSize); + } + + // Try to get a RenderMap to the Diagram which should be drawn. + ReturnDiagram renderMap = null; + renderMap = wordAlgoRenderer.getRenderedDiagram(aDiagram); + synDiaElemMap.put(aDiagram.getName(), renderMap.renderMap); + + // empty scrollPane + aSynDiaPanel.removeAll(); + + // Draw the Diagram Elements. + List lineBuffer = new ArrayList(); + for (RenderElement re : renderMap.renderMap.keySet()) { + if (!(re instanceof RenderTerminal) + && !(re instanceof RenderVariable)) { + lineBuffer.add(re); + } else { + aSynDiaPanel.add(re); + re.addMouseListener(new WordSynDiaListener(myGuiController, + renderMap.renderMap.get(re))); + re.setVisible(true); + re.repaint(); + } + } + for (RenderElement re : lineBuffer) { + aSynDiaPanel.add(re); + re.setVisible(true); + re.repaint(); + if (re instanceof RenderBranch || re instanceof RenderRepetition) { + WordSplitListener aListener = new WordSplitListener( + myGuiController, wordAlgoRenderer.getRenderValues(), + renderMap.renderMap.get(re)); + re.addMouseListener(aListener); + re.addMouseMotionListener(aListener); + } + if (re instanceof RenderBase) { + RenderBase aRenderBase = (RenderBase) re; + // draw End of Diagram + int exitWidth = (int) Math.round(wordAlgoRenderer + .getRenderValues().radius); + RenderEnd diagramExit = new RenderEnd(exitWidth); + diagramExit.setSize(exitWidth, renderMap.height); + diagramExit.setLocation(aRenderBase.getWidth() - exitWidth, 0); + diagramExit.setVisible(true); + diagramExit.update(); + diagramExit.repaint(); + WordExitListener anExitListener = new WordExitListener( + myGuiController, wordAlgoRenderer.getRenderValues(), + aDiagram); + diagramExit.addMouseListener(anExitListener); + diagramExit.addMouseMotionListener(anExitListener); + aSynDiaPanel.add(diagramExit); + } + } + // Set Size and Position + aSynDiaPanel.setLocation(BORDER_SPACE, posY); + posY = posY + 2 * wordAlgoRenderer.getRenderValues().space + + renderMap.height; + if (renderMap.width > posX) { + posX = renderMap.width + BORDER_SPACE * 2; + } + + aSynDiaPanel.setSize(renderMap.width + 40, renderMap.height); + aSynDiaPanel.setVisible(true); + + } + + /** + * Used to repaint Diagrams which were allready drawn. + */ + private void repaintDiagrams(WordAlgoModel myModel) { + + // Remove old Position + if (actualRenderPosition != null) { + actualPositionPanel.remove(actualRenderPosition); + actualPositionPanel.repaint(); + actualPositionPanel = null; + actualRenderPosition = null; + } + + // specifies, if position was allready drawn + boolean positionDrawn = false; + + // Get all Diagrams + SynDiaSystem aSynDiaSystem = myModel.getSynDiaSystem(); + + // Get the names of all Diagrams + List diagramNameList = aSynDiaSystem.getLabelsOfVariables(); + + // Interate over all Diagrams + for (String aDiagramName : diagramNameList) { + + try { + SyntaxDiagram aDiagram = aSynDiaSystem + .getSyntaxDiagram(aDiagramName); + // Get the name of each Diagram and paint the components + // which schould be drawn. + SynDiaPanel aSynDiaPanel = synDiaPanelMap.get(aDiagramName); + + Map aRenderMap = synDiaElemMap + .get(aDiagramName); + + // checkout if an Element like return adresses or a position + // should be drawn (Should be if algrotithm is running or + // finished). + if (myModel.isAlgorithmRunning() + || myModel.isAlgorithmFinished()) { + + // Iterate over all Elements of each diagram. + for (RenderElement re : aRenderMap.keySet()) { + + // If a return adress should be drawn, draw it + if (!returnAdressesDrawn) { + if (re instanceof RenderVariable) { + Variable aVar = (Variable) aRenderMap.get(re); + ReturnAdress anAdress = new ReturnAdress( + myModel.getAdressNumber(aVar) + .toString(), + (RenderVariable) re, fontSize); + aSynDiaPanel.add(anAdress); + anAdress.update(); + anAdress.setVisible(true); + aSynDiaPanel.setComponentZOrder(anAdress, 0); + anAdress.repaint(); + anAdress + .addMouseListener(new WordSynDiaListener( + myGuiController, aRenderMap + .get(re))); + // Put the drawn adress in the AdressMap. + retAdressMap.put(anAdress, aSynDiaPanel); + } + } + + // If a position should be drawn, draw it + if (!positionDrawn) { + // Checkout if the actualPosition is the Diagram + // himself + if (re instanceof RenderBase) { + this.setActualPosition(); + if (actualPosition == aDiagram + || actualPosition == aDiagram.getRoot() + || actualPosition == null) { + // Remove old Position + if (actualRenderPosition != null) { + actualPositionPanel + .remove(actualRenderPosition); + } + actualRenderPosition = new Position( + re, + false, + myModel.isPositionBehindElem(), + wordAlgoRenderer.getRenderValues().font, + false); + actualPositionPanel = aSynDiaPanel; + aSynDiaPanel.add(actualRenderPosition); + actualRenderPosition.update(); + actualRenderPosition.setVisible(true); + aSynDiaPanel.setComponentZOrder( + actualRenderPosition, 0); + actualRenderPosition.repaint(); + aSynDiaPanel.repaint(); + positionDrawn = true; + } + } + // Is the actual Element also the actual Position in + // the + // Diagram? + SynDiaElem actualElem = aRenderMap.get(re); + if (actualElem != null + && actualElem == actualPosition) { + // Needed to inform the Position, if the + // Position + // should be + // behind the return Adress of the Variable + boolean jumpOrNot = myModel.isJumpToDiagram(); + // Remove old Position + if (actualRenderPosition != null) { + actualPositionPanel + .remove(actualRenderPosition); + } + boolean changeDirection = false; + // Checkout if actual Position is a Repetition + // or in a Repetition + if (myModel.isPositionInRepetition()) { + // If true get the Repetition and check its + // order. + changeDirection = !myModel + .getFirstParentRepetition() + .rightOrder(); + } + actualRenderPosition = new Position( + re, + jumpOrNot, + myModel.isPositionBehindElem(), + wordAlgoRenderer.getRenderValues().font, + changeDirection); + actualPositionPanel = aSynDiaPanel; + // Paint PositionElement + aSynDiaPanel.add(actualRenderPosition); + actualRenderPosition.update(); + actualRenderPosition.setVisible(true); + aSynDiaPanel.setComponentZOrder( + actualRenderPosition, 0); + aSynDiaPanel.repaint(); + actualRenderPosition.repaint(); + } + } + } + } + } + // If SyntaxDiagramm cannot be found, finish the word algorithm + catch (ElementNotFoundException e) { + System.out.println(e.getMessage()); + System.out + .println("Error during paint of diagrams. Reswitch to SynDiaView"); + myGuiController.switchToSynDiaView(); + } + } + + // If returnAdresses should'nt be drawn. Remove old Adresses + if (!myModel.isAlgorithmRunning() && !myModel.isAlgorithmFinished()) { + // Remove Adresses + for (ReturnAdress aReturnAdress : retAdressMap.keySet()) { + SynDiaPanel aSynDiaPanel = retAdressMap.get(aReturnAdress); + aSynDiaPanel.remove(aReturnAdress); + aSynDiaPanel.repaint(); + } + retAdressMap.clear(); + returnAdressesDrawn = false; + } else { + returnAdressesDrawn = true; + } + } + + /** + * Method called by Observable if the DrawPanel should update its Gui. + */ + public void update(Observable anObservable, Object arg) { + // Cast the Observable to WordAlgoModel and + // update the parameters neede to paint the Panel. + if (anObservable instanceof WordAlgoModel) { + + this.myModel = (WordAlgoModel) anObservable; + setActualPosition(); + + repaintDiagrams(myModel); + + // BorderPanels must be arranged in Z-Order if is jumpOrNot + this.setDiagramZOrder(myModel, myModel.isJumpToDiagram()); + } + } + + /** + * Sets actualPosition to the actual Position Needed to paint positions + */ + private void setActualPosition() { + actualPosition = null; + if (myModel != null) { + // Addresses should be drawn if algorithm is already running. + if (myModel.isAlgorithmRunning() || myModel.isAlgorithmFinished()) { + actualPosition = myModel.getPosition(); + // If it is a Concatenation + if (actualPosition instanceof Concatenation) { + Concatenation actualConcat = (Concatenation) actualPosition; + // Checkout if parent is SyntaxDiagram or not + if (actualConcat.getParent() == null) { + actualPosition = actualConcat.getMySyntaxDiagram(); + } else { + actualPosition = actualConcat.getParent(); + } + } + } + } + } + + /** + * A function called by an Observer to rearrange the system by size. In + * reality it only widen the system. To get a systen smaller, start with + * size = 10. + * + * @param size + * the size of the Font associated to the syntax diaram + */ + public int resizeSystem(int size, int smaller) { + + if (size > 9) { + // Set FontSize + this.fontSize = size; + } + + // Reset SynDiaSystem and paint again + mySynDiaPanel.removeAll(); + mySynDiaPanel.repaint(); + + synDiaPanelMap = new HashMap(); + + synDiaElemMap = new HashMap>(); + + retAdressMap = new HashMap(); + + this.init(mySynDiaSystem); + + if (myModel != null) { + returnAdressesDrawn = false; + this.repaintDiagrams(myModel); + } + + // If autoSize is enabled, check if Diagrams should be drawn again. + if (autoSize) { + // if font size ist not set yet, set it + if (size <= 0) { + size = wordAlgoRenderer.getRenderValues().font.getSize(); + } + + // Calculate procentual Height and widht of the viewable part of the + // Panel which is used by the diagrams. + int procentualWidth = (int) Math + .round(posX * 100 / this.getWidth()); + int procentualHeight = (int) Math.round(posY * 100 + / this.getHeight()); + + // Checkout if Frame is not filled at least to 80 per cent + if ((procentualWidth < 80 && procentualHeight < 80) && smaller >= 0) { + // Else draw again + // save old fontSize + int oldFontSize = size; + // Checkout which direction uses more space + if (procentualWidth > procentualHeight) { + size = (int) Math.round(size * 100 / procentualWidth) - 1; + } else { + size = (int) Math.round(size * 100 / procentualHeight) - 1; + } + // If new size is the same as the old one, the algorithm stops. + if (oldFontSize != size) { + if (size <= 50) { + resizeSystem(size, 1); + } + } + } + } + + return size; + } + + /** + * This method sets the paramater autoSize deciding, whether the diagram + * size shall automatically fit to the screen size + * + * @param autosize + * true if AutoSize should be on + */ + public void setAutoSize(boolean autosize) { + + this.autoSize = autosize; + } + + /** + * This method returns the actual size of the set font for rendering syntax + * diagrams + * + * @return an int representing the font size + */ + public int getFontSize() { + + return wordAlgoRenderer.getRenderValues().font.getSize(); + + } + + /** + * This method arranges the Z-Order of the BorderPanels. If onTop is true, + * the BorderPanels are on Top else they are in the background + * + * @param myModel + * The WordAlgoModel used during update + * @param onTop + * If true, the BorderPanels are on Top else they are in the + * background + */ + private void setDiagramZOrder(WordAlgoModel myModel, boolean onTop) { + for (SynDiaPanel aBorderPanel : borderPanelList) { + if (onTop) { + mySynDiaPanel.setComponentZOrder(aBorderPanel, 0); + } else { + mySynDiaPanel.setComponentZOrder(aBorderPanel, mySynDiaPanel + .getComponentCount() - 1); + } + } + + } + + /** + * Resizes the panel after resizing of jAlgo + * + */ + private void wasResized() { + JPanel contentPane = (JPanel) this.getParent().getParent(); + this.setPreferredSize(new Dimension(contentPane.getVisibleRect().width + - myGuiController.STACK_WIDTH, + contentPane.getVisibleRect().height)); + } + + /** + * Faster scrolling realised via this method + */ + public void mouseWheelMoved(MouseWheelEvent e) { + javax.swing.JScrollBar scrollbar = scrollPane.getVerticalScrollBar(); + + if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { + int totalScrollAmount = e.getUnitsToScroll() * 4; + scrollbar.setValue(scrollbar.getValue() + totalScrollAmount); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.java new file mode 100644 index 0000000..475da52 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/ExplanationPanel.java @@ -0,0 +1,199 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This Panel contains the Explanation during the WordAlgorithm, its warnings an + * the word generated during algorithm. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class ExplanationPanel extends JPanel implements Observer { + + // Font of Explanation + // private Font explFont; + + // The Strings and TextPanes which contain the Explanation + private String explanation; + + private String warning; + + private JTextPane explPane; + + private JTextPane warningPane; + + private JPanel motherPanel; + + private JScrollPane scrollPane; + + private static final int FONT_SIZE = 15; + + /** + * Constructor to create a new ExplanationPanel. + * + * @param explanation + * The initilization value of the explanation. + * @param warning + * The initilization value of the warning. + * @param output + * The initilization value of the output. + */ + public ExplanationPanel(String explanation, String warning, Font ebnfFont) { + + this.setLayout(null); + this.setBackground(Color.WHITE); + + // this.explFont = ebnfFont.deriveFont(Font.PLAIN, 15f); + + // Frame Border + this.setMinimumSize(new Dimension(Short.MAX_VALUE, 150)); + this.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " " + + Messages.getString("ebnf", + "WordAlgo.GuiExplanationPanel_Description") + " ", + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + this.explanation = explanation; + this.warning = warning; + + init(); + + } + + /** + * Initializes the Gui of the Panel and sets its layout. + * + */ + private void init() { + + // init + explPane = new JTextPane(); + warningPane = new JTextPane(); + + // set + explPane.setText(explanation); + explPane.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE)); + + warningPane.setText(""); + warningPane.setForeground(Color.RED); + warningPane.setFont(new Font("Tahoma", Font.PLAIN, FONT_SIZE)); + + // TextPanes must be disabled, so the user cant change there + // content + explPane.setEnabled(false); + explPane.setDisabledTextColor(Color.BLACK); + warningPane.setEnabled(false); + warningPane.setDisabledTextColor(Color.RED); + + // layout + BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS); + this.setLayout(layout); + + scrollPane = new JScrollPane(); + + motherPanel = new JPanel(); + motherPanel.setBackground(this.getBackground()); + motherPanel.setLayout(new BoxLayout(motherPanel, BoxLayout.Y_AXIS)); + motherPanel.add(explPane); + motherPanel.add(warningPane); + motherPanel.setPreferredSize(getMinDimension()); + + scrollPane.setViewportView(motherPanel); + scrollPane.setBackground(this.getBackground()); + scrollPane + .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + + this.add(scrollPane); + + } + + /** + * Method called, if the Model of the WordAlgorithm has been changed. + * + */ + public void update(Observable anObservable, Object arg) { + // Cast the Observable to WordAlgoModel and + // update the parameters neede to paint the Panel. + if (anObservable instanceof WordAlgoModel) { + + WordAlgoModel myModel = (WordAlgoModel) anObservable; + + // Change explanation, output and Warning + this.explanation = myModel.getExplanation(); + this.warning = myModel.getWarning(); + + motherPanel.setPreferredSize(getMinDimension()); + + explPane.setText(explanation); + warningPane.setText(warning); + + // If the explanation is empty, it is not shown. + if (explanation.equals("")) { + explPane.setVisible(false); + } + // Else it is shown. + else { + explPane.setVisible(true); + } + // If the warning is empty, it is not shown. + if (warning.equals("")) { + warningPane.setVisible(false); + } + // Else it is shown. + else { + warningPane.setVisible(true); + } + + // scrollPane.set + } + } + + /** + * Calculates the width and height of explanation an returns the Dimension + * + * @return The dimension needed to show explPane and warninPane. + */ + private Dimension getMinDimension() { + + FontMetrics fontmetrics = this.getFontMetrics(new Font("Tahoma", + Font.PLAIN, FONT_SIZE)); + int windowWidth = scrollPane.getVisibleRect().width - 15; + if (windowWidth == 0) + windowWidth = 700; + int explLength = fontmetrics.stringWidth(explanation); + int warningLength = fontmetrics.stringWidth(warning); + int textHeight = fontmetrics.getHeight(); + + int linesOfText = (int) Math.round((explLength / windowWidth) + .5) + + (int) Math.round((warningLength / windowWidth) + .5); + + return new Dimension(windowWidth, (int) Math.round(linesOfText + * textHeight * 1.2)); + } + + /** + * Needed beacause the width of Explanation and Warning should be updated. + */ + public void repaint() { + if (scrollPane != null) { + motherPanel.setPreferredSize(getMinDimension()); + } + super.repaint(); + } +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.java new file mode 100644 index 0000000..f681bf5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/GuiController.java @@ -0,0 +1,445 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.Action; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JToolBar; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.WordAlgorithmController; +import org.jalgo.module.ebnf.gui.wordalgorithm.events.ToolbarButtonAction; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.util.ActionStack; + +/** + * This method represents the GuiController during the WordAlgorithm. This + * GuiController could be called by the MainController. This + * GuiController knows its WordAlgorithmController and its GUI. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class GuiController implements Observer { + + // Constants which define minimum and maximum values + private final int MINIMUM_WIDTH = 800; + + private final int MINIMUM_HEIGHT = 200; + + private final int ALGOCTRL_HEIGHT = 130; + + public final int STACK_WIDTH = 100; + + private final int EXPLANATION_HEIGHT = 100; + + // MyWordAlgorithmController. Needed to perform Clicks and Actions + // from the GUI. + private WordAlgorithmController myAlgoController; + + // This Panel represents the whole space which could be used by the + // GuiController. + private JPanel contentPane; + + // This Panel represents the space on which the SyntaxDiagrams should be + // drawn. + private DrawPanel drawPanel; + + // This Panel represents the space on which the Buttons and the Textfield + // are placed. + private AlgoCtrlPanel algoCtrlPanel; + + // This Panel represents the space on which the Explanations and Warnings + // should be drawn. + private ExplanationPanel explanationPanel; + + // This Panel represents the space on which the stack should be drawn. + private StackPanel stackPanel; + + // The Toolbar which can be used for undo and redo events + private JToolBar myToolBar; + + ToolbarButtonAction undoAction; + + ToolbarButtonAction performAction; + + // The Algorithm-Menu + private JMenu editMenu; + + private JMenuItem menuUndo; + + private JMenuItem menuUndoAll; + + private JMenuItem menuRedo; + + private JMenuItem menuRedoAll; + + private JMenuItem menuStartAlgo; + + private JMenuItem menuStopAlgo; + + /** + * Constructs a new GuiController. + * + * @param contentPane + * The JPane generated by the + * MainController which should be used by this + * GuiController as its contentPane. + * @param mySynDiaSystem + * The SynDiaSystem which should used during the algorithm. + * @param myAlgoController + * The WordAlgorithmController which controlles + * the Model which the GUI should present. + */ + public GuiController(JPanel contentPane, SynDiaSystem aSynDiaSystem, + WordAlgorithmController myAlgoController) { + + this.contentPane = contentPane; + + // Whatever is on the contentPane + this.contentPane.removeAll(); + + this.myAlgoController = myAlgoController; + + this.installToolbar(); + + // Initialize all graphical Components + init(aSynDiaSystem); + + // neded to observe the ActionStack to update the Toolbar Buttons undo + // and redo + this.myAlgoController.addActionStackObserver(this); + + this.installMenu(); + + // Need an update to draw especially the Stack correctly + this.myAlgoController.notifyModelObservers(); + } + + /** + * This method is called from the constructor to layout the GUI + * + * @param aSynDiaSystem + * The SynDiaSystem which schould be drawn. + * (Needed to intialize the DrawPanel). + */ + private void init(SynDiaSystem aSynDiaSystem) { + // INIT ************************************************************* + // The DrawPanel must be Observer of the AlgorithmModel. + this.drawPanel = new DrawPanel(aSynDiaSystem, this); + this.myAlgoController.addModelObserver(drawPanel); + + // The AlgoCtrlPanel must be Observer of the AlgorithmModel. + this.algoCtrlPanel = new AlgoCtrlPanel(this, myAlgoController + .getEbnfFont()); + this.myAlgoController.addModelObserver(algoCtrlPanel); + + // The ExplanationPanel must be Observer of the AlgorithmModel. + explanationPanel = new ExplanationPanel(myAlgoController + .getExplanation(), myAlgoController.getWarning(), + myAlgoController.getEbnfFont()); + this.myAlgoController.addModelObserver(explanationPanel); + + // The StackPanel must be Observer of the AlgorithmModel. + stackPanel = new StackPanel(myAlgoController + .getAdressNumbersFromStack()); + this.myAlgoController.addModelObserver(stackPanel); + + // SET ************************************************************* + // Size of some Panels +// drawPanel.setMinimumSize(new Dimension(MINIMUM_WIDTH - STACK_WIDTH, +// MINIMUM_HEIGHT - ALGOCTRL_HEIGHT - EXPLANATION_HEIGHT)); +// drawPanel.setPreferredSize(new Dimension(contentPane.getVisibleRect().width - STACK_WIDTH, +// contentPane.getVisibleRect().height - ALGOCTRL_HEIGHT - EXPLANATION_HEIGHT)); + + algoCtrlPanel.setMinimumSize(new Dimension(MINIMUM_WIDTH, + ALGOCTRL_HEIGHT)); + algoCtrlPanel.setPreferredSize(new Dimension(MINIMUM_WIDTH, + ALGOCTRL_HEIGHT)); + algoCtrlPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, + ALGOCTRL_HEIGHT)); + + stackPanel.setMinimumSize(new Dimension(STACK_WIDTH, MINIMUM_HEIGHT + - EXPLANATION_HEIGHT - ALGOCTRL_HEIGHT)); + stackPanel.setMaximumSize(new Dimension(STACK_WIDTH, Short.MAX_VALUE)); + stackPanel.setPreferredSize(new Dimension(STACK_WIDTH, contentPane + .getHeight() + - EXPLANATION_HEIGHT - ALGOCTRL_HEIGHT)); + + explanationPanel.setMinimumSize(new Dimension(MINIMUM_WIDTH, + EXPLANATION_HEIGHT)); + explanationPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, + EXPLANATION_HEIGHT)); + explanationPanel.setPreferredSize(new Dimension(MINIMUM_WIDTH, + EXPLANATION_HEIGHT)); + + // LAYOUT ************************************************************* + JPanel centerPanel = new JPanel(); + + // The center is divided into drawPanel and stackPanel +// centerPanel.setLayout(new BorderLayout(0,0)); +// centerPanel.add(drawPanel, BorderLayout.WEST); +// centerPanel.add(stackPanel, BorderLayout.EAST); + BoxLayout centerLayout = new BoxLayout(centerPanel, BoxLayout.X_AXIS); + centerPanel.setLayout(centerLayout); + centerPanel.add(drawPanel); + centerPanel.add(stackPanel); + + // The contenPane is divided into three parts: + BoxLayout contentLayout = new BoxLayout(contentPane, BoxLayout.Y_AXIS); + contentPane.setLayout(contentLayout); + contentPane.add(algoCtrlPanel); + contentPane.add(centerPanel); + contentPane.add(explanationPanel); + contentPane.validate(); + } + + /** + * This method sets up the toolbar. + */ + private void installToolbar() { + // Get the Toolbar + myToolBar = JAlgoGUIConnector.getInstance().getModuleToolbar( + myAlgoController.getModuleConnector()); + + myToolBar.addSeparator(); + + // Add undo and redo Button + undoAction = new ToolbarButtonAction(this, 2); + undoAction.setEnabled(false); + myToolBar.add(createToolbarButton(undoAction)); + + performAction = new ToolbarButtonAction(this, 3); + performAction.setEnabled(false); + myToolBar.add(createToolbarButton(performAction)); + + myToolBar.validate(); + myToolBar.repaint(); + } + + /** + * Installs the Algorithms own Menu in the j-Algo MenuBar + * + */ + private void installMenu() { + myAlgoController.getMainController().removeCustomMenu(); + editMenu = new JMenu(Messages.getString("ebnf", "WordAlgo.Menu_Title")); + myAlgoController.getMainController().addMenu(editMenu); + + menuStartAlgo = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_Start")); + menuStartAlgo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + myAlgoController.startAlgorithm(); + } + }); + editMenu.add(menuStartAlgo); + + menuStopAlgo = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_Reset")); + menuStopAlgo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + while (myAlgoController.isUndoPossible()) { + myAlgoController.undo(); + } + } + }); + menuStopAlgo.setEnabled(false); + editMenu.add(menuStopAlgo); + + editMenu.addSeparator(); + + menuUndo = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_Undo")); + menuUndo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + myAlgoController.undo(); + } + }); + menuUndo.setEnabled(false); + editMenu.add(menuUndo); + + menuRedo = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_Redo")); + menuRedo.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + myAlgoController.redo(); + } + }); + menuRedo.setEnabled(false); + editMenu.add(menuRedo); + + editMenu.addSeparator(); + + menuUndoAll = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_UndoAll")); + menuUndoAll.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + while (myAlgoController.isUndoPossible()) { + myAlgoController.undo(); + } + } + }); + menuUndoAll.setEnabled(false); + editMenu.add(menuUndoAll); + + menuRedoAll = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_RedoAll")); + menuRedoAll.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + while (myAlgoController.isRedoPossible()) { + myAlgoController.redo(); + } + } + }); + menuRedoAll.setEnabled(false); + editMenu.add(menuRedoAll); + + editMenu.addSeparator(); + + JMenuItem menuExit = new JMenuItem(Messages.getString("ebnf", + "WordAlgo.Menu_Exit")); + menuExit.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent anAction) { + switchToSynDiaView(); + } + }); + editMenu.add(menuExit); + } + + /** + * Creates a JButton object without border and text, which + * can be used in JToolBars + * + * @return a JButton instance with the given + * Action + */ + private JButton createToolbarButton(Action a) { + JToolbarButton button = new JToolbarButton((Icon) a + .getValue(Action.SMALL_ICON), null, null); + button.setAction(a); + button.setText(""); + return button; + } + + /** + * This method switches to the SynDiaView and removes the gui before + * + */ + public void switchToSynDiaView() { + + // Rearrange Menu + myAlgoController.getMainController().removeCustomMenu(); + + // empty content pane + contentPane.removeAll(); + + myAlgoController.switchToSynDiaView(); + } + + /** + * Enables the function of autosize in the DrawPanel. + * + * @param autosize + * True if autosize should be on. + * @return The new Size of the font if size changed. Else -1. + */ + public int setAutoSize(boolean autosize) { + + drawPanel.setAutoSize(autosize); + if (autosize) { + return drawPanel.resizeSystem(10, 0); + } + return -1; + + } + + /** + * This Method returns the WordAlgorithmController which is + * graphically represented by this GUI. + * + * @return The WordAlgorithmController represented by this + * GUI. + */ + public WordAlgorithmController getWordAlgoController() { + return myAlgoController; + } + + + /** + * This method returns the actual size of the set font for rendering syntax + * diagrams + * + * @return an int representing the font size + */ + public int getFontSize() { + + return drawPanel.getFontSize(); + + } + + /** + * Updates the DrawPanel (where the SyntaxDiagrams are located). + * + * @param size + * The size of the Font associated to the SyntaxDiagram. Use size + * 0 if you don't want to change the size + */ + public void updateDrawPanel(int size) { + + drawPanel.resizeSystem(size, 0); + + } + + /** + * This method is called, if ActionStack has changed. To update the + * button-Status's in the Toolbar. + */ + public void update(Observable anObservable, Object arg) { + if (anObservable instanceof ActionStack) { + // Update Toolbar and Menu + ActionStack myStack = (ActionStack) anObservable; + if (myStack.isRedoPossible()) { + performAction.setEnabled(true); + menuRedo.setEnabled(true); + menuRedoAll.setEnabled(true); + } else { + performAction.setEnabled(false); + menuRedo.setEnabled(false); + menuRedoAll.setEnabled(false); + } + if (myStack.isUndoPossible()) { + undoAction.setEnabled(true); + menuUndo.setEnabled(true); + menuUndoAll.setEnabled(true); + } else { + undoAction.setEnabled(false); + menuUndo.setEnabled(false); + menuUndoAll.setEnabled(false); + } + if (myAlgoController.isAlgorithmRunning() + || myAlgoController.isAlgorithmFinished()) { + menuStopAlgo.setEnabled(true); + menuStartAlgo.setEnabled(false); + } else { + menuStopAlgo.setEnabled(false); + menuStartAlgo.setEnabled(true); + } + myToolBar.validate(); + myToolBar.repaint(); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.java new file mode 100644 index 0000000..f58e79e --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackDrawPanel.java @@ -0,0 +1,198 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Rectangle; +import java.util.Iterator; +import java.util.List; + +import javax.swing.JPanel; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.wordalgorithm.StackAdress; +import org.jalgo.module.ebnf.renderer.wordalgorithm.StackBase; +import org.jalgo.module.ebnf.gui.syndia.display.IDrawPanel; +import org.jalgo.module.ebnf.gui.wordalgorithm.SynDiaPanel; + +/** + * This Panel contains the Graphical part of the Stack during the WordAlgorithm. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class StackDrawPanel extends JPanel implements IDrawPanel { + + // Formats of Adresses on Stack + private static final int ADRESS_WIDTH = 40; + + private static final int ADRESS_HEIGHT = 30; + + private static final int BASE_HEIGHT = 3; + + // Space between bottom and lowest Adress + private static final int BOTTOM_HEIGHT = 10; + + // Vars on stack since last update + private List varsOnStack; + + // Used to paint the Stack really + private JPanel myAdressPanel; + + /** + * Constructor to create a new StackDrawPanel. + * + * @param varsOnStack + * The initilization values on the stack. + */ + public StackDrawPanel(List varsOnStack) { + + this.setLayout(null); + this.setBackground(BACKGROUND_COLOR); + + this.varsOnStack = varsOnStack; + + // Needed because Stack should be scrollable + this.myAdressPanel = new SynDiaPanel(BACKGROUND_COLOR); + this.myAdressPanel.setVisible(true); + this.add(myAdressPanel); + + // the Stack is painted with allAdresses in the List. + paintStack(varsOnStack, false); + + } + + /** + * Method called, if the StackDrawPanel should be painted. + * + * @param varsOnStack + * The new Adresses on the stack (first element lowest adress). + * @param highestAdressHighlighted + * If true, the highest Adress on the stack is be highlighted. + */ + public void paintStack(List varsOnStack, boolean highestAdressHighlighted) { + + this.varsOnStack = varsOnStack; + + paintStack(varsOnStack, highestAdressHighlighted, + RenderElement.HIGHLIGHT_BLUE); + + } + + /** + * Method called, if the StackDrawPanel should be painted. + * + * @param varsOnStack + * The new Adresses on the stack (first element lowest adress). + * @param highestAdressHighlighted + * If true, the highest Adress on the stack is be highlighted. + * @param hColor + * The Color, the hightes Adress should be highlighted in + */ + public void paintStack(List varsOnStack, boolean highestAdressHighlighted, + Color hColor) { + + this.varsOnStack = varsOnStack; + + // The panel is resetted + this.myAdressPanel.removeAll(); + + // The minimum Size of the AdressPannel is updated because + // every Adress on the Stack schould be viewable. + updateSize(); + + // StartPositions + // Coordinates to draw the adresses + int posXCenter = (int) Math.round((this.myAdressPanel.getWidth() / 2)); + int posX = (int) Math.round(posXCenter - (ADRESS_WIDTH / 2)); + int posY = (int) Math.round(this.myAdressPanel.getHeight()); + + // Base Line is drawn. + int baseWidth = this.myAdressPanel.getWidth(); + if (baseWidth == 0) + baseWidth = ADRESS_WIDTH; + StackBase myBase = new StackBase(baseWidth); + + posY = posY - myBase.getHeight() - BOTTOM_HEIGHT; + myBase.setLocation((int) Math.round(posXCenter + - (myBase.getWidth() / 2)), posY); + myBase.update(); + myBase.setVisible(true); + myBase.repaint(); + this.myAdressPanel.add(myBase); + + // Eachs adress is drawn + Iterator adrListIterator = varsOnStack.iterator(); + int i = 0; + + while (adrListIterator.hasNext()) { + i++; + Integer anAdress = (Integer) adrListIterator.next(); + + // The Y-position is decremented before print the adress. + posY = posY - ADRESS_HEIGHT - BOTTOM_HEIGHT; + + StackAdress aRenderAdress = new StackAdress(anAdress.toString()); + // If its the last Adress and this should be highlighted + if (!adrListIterator.hasNext() && highestAdressHighlighted) { + aRenderAdress.setColor(hColor); + } + aRenderAdress.setSize(ADRESS_WIDTH, ADRESS_HEIGHT); + aRenderAdress.setLocation(posX, posY); + aRenderAdress.update(); + this.myAdressPanel.add(aRenderAdress); + aRenderAdress.setVisible(true); + aRenderAdress.repaint(); + } + + // The graphical view is updated: + this.myAdressPanel.repaint(); + } + + // Size must be updated because the visible size could have been changed + // (if the size of the jAlgo Window has changed). + public void repaint() { + + updateSize(); + + super.repaint(); + } + + /** + * Sets the adressPanel to its minimum size. Could be the visible part or if + * the number of Adresses on the Stack is bigger, it could be higher. + * + */ + public void updateSize() { + if (varsOnStack != null) { + // New panel Size if StackList can be higher or lower than the + // Panel's + // height. + int minHeight = (int) (varsOnStack.size() + * (ADRESS_HEIGHT + BOTTOM_HEIGHT) + BASE_HEIGHT + BOTTOM_HEIGHT * 3); + + // So it's updated. + Rectangle myVisiblePart = this.getVisibleRect(); + int minWidth = myVisiblePart.width; + if (ADRESS_WIDTH > myVisiblePart.width) + minWidth = ADRESS_WIDTH; + + myAdressPanel.setSize(new Dimension(minWidth, minHeight)); + myAdressPanel.setPreferredSize(new Dimension(minWidth, minHeight)); + + int difference = myVisiblePart.height - minHeight; + if (difference < 0) + difference = 0; + + myAdressPanel.setLocation(0, difference); + myAdressPanel.repaint(); + + if (minHeight < myVisiblePart.height) + minHeight = myVisiblePart.height; + + this.setSize(new Dimension(minWidth, minHeight)); + this.setPreferredSize(new Dimension(minWidth, minHeight)); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.java new file mode 100644 index 0000000..a42b33f --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/StackPanel.java @@ -0,0 +1,106 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Dimension; +import java.util.Observer; +import java.util.Observable; +import java.util.List; +import javax.swing.BoxLayout; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.syndia.display.IDrawPanel; +import org.jalgo.module.ebnf.model.wordalgorithm.WordAlgoModel; + +/** + * This Panel contains the Stack and its description during the WordAlgorithm. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class StackPanel extends JPanel implements Observer, IDrawPanel { + + // Represents the actual Status of the Stack. + // (Just a copy of a part of the Model!!!) + private List varsOnStack; + + // The part of the Stack which should be scrollable + private JScrollPane scrollPane; + + // Used to paint the Vars on the Stack + private StackDrawPanel stackDrawPanel; + + /** + * Constructor to create a new StackPanel. + * + * @param varsOnStack + * The initilization values on the stack. + */ + public StackPanel(List varsOnStack) { + + super(); + + this.varsOnStack = varsOnStack; + + this.setBackground(BACKGROUND_COLOR); + // this.setMinimumSize(new Dimension(Short.MAX_VALUE, 150)); + this.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " " + + Messages.getString("ebnf", + "WordAlgo.GuiStackPanel_Description") + " ", + javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, + javax.swing.border.TitledBorder.DEFAULT_POSITION, + new java.awt.Font("Tahoma", 0, 12))); + + init(); + + } + + /** + * Initializes the Stack's graphical Components + * + */ + private void init() { + + // init + scrollPane = new JScrollPane(); + stackDrawPanel = new StackDrawPanel(varsOnStack); + + // set + stackDrawPanel.setVisible(true); + + scrollPane.setViewportView(stackDrawPanel); + scrollPane.setPreferredSize(new Dimension((int) this.getPreferredSize() + .getWidth(), (int) this.getMaximumSize().getHeight())); + scrollPane + .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + scrollPane + .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scrollPane.setBackground(this.getBackground()); + + // layout + this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); + this.add(scrollPane); + + } + + /** + * Method called, if the Model of the WordAlgorithm has been changed. + * + */ + public void update(Observable anObservable, Object arg) { + // Try to cast the Observable to WordAlgoModel and + // update the parameters needed to paint the Panel. + if (anObservable instanceof WordAlgoModel) { + + // The AdressList is going to be updated + WordAlgoModel myModel = (WordAlgoModel) anObservable; + varsOnStack = myModel.getAdressNumbersFromStack(); + + // The Graphical Stack is updated. + stackDrawPanel.paintStack(varsOnStack, + myModel.isStackHighlighted(), myModel.getStackColor()); + } + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.java new file mode 100644 index 0000000..c31eb8b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaPanel.java @@ -0,0 +1,32 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Color; +import javax.swing.JPanel; + +/** + * This Panel represents the area in which ONE + * SyntaxDiagrams should be drawn on. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class SynDiaPanel extends JPanel { + + /** + * Constructor to create a new SynDiaPanel. + * + * @param bgcolor + * The Backgroundcolor of this Panel + */ + public SynDiaPanel(Color bgcolor) { + + this.setLayout(null); + this.setBackground(bgcolor); + + // Must be transparent because of the background + this.setOpaque(false); + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.java new file mode 100644 index 0000000..8028a00 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/SynDiaSystemPanel.java @@ -0,0 +1,78 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm; + +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; + +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.syndia.display.IDrawPanel; + +/** + * This Panel represents the area in which ALL + * SyntaxDiagrams should be drawn on. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class SynDiaSystemPanel extends JPanel implements IDrawPanel { + + // needed to print the Background + private String displayName = Messages.getString("ebnf", "WordAlgo.BgName"); + + private double factor = .2; + + /** + * Constructor to create a new SynDiaSystemPanel. + * + */ + public SynDiaSystemPanel() { + + this.setLayout(null); + this.setBackground(BACKGROUND_COLOR); + + } + + /** + * Calculates the width of a given String object in pixel + * + * @param s + * The String object to calculate + * @param f + * The Font which size is to calculate + * @return the width of the String object in pixel + */ + public int getWidthFromString(String s, Font f) { + + FontMetrics fontmetrics = this.getFontMetrics(f); + + return fontmetrics.stringWidth(s); + + } + + /** + * Paint the SynDiaSystemPanel and its background. + */ + public void paintComponent(Graphics g) { + + super.paintComponent(g); + + Graphics2D g2d = (Graphics2D) g; + int fontSize = (int) Math.round(factor * this.getParent().getWidth()); + Font f = new Font("Courier", Font.BOLD, fontSize); + + g2d.setFont(f); + g2d.setColor(FONT_COLOR); + int y = this.getParent().getHeight() + (int) Math.round(0.2 * fontSize); + g2d.rotate(-Math.PI * 7 / 180); + g2d.drawString(displayName, (int) (this.getParent().getWidth() + - getWidthFromString(displayName, f) - factor * 0.2 + * this.getParent().getWidth()), y); + + g2d.rotate(Math.PI * 7 / 180); + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Entries b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Entries new file mode 100644 index 0000000..2d4da1d --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Entries @@ -0,0 +1,4 @@ +/ToolbarButtonAction.java/1.1/Fri Aug 11 16:40:31 2006// +/WordExitListener.java/1.1/Fri Aug 11 16:40:31 2006// +/WordSplitListener.java/1.1/Fri Aug 11 16:40:31 2006// +/WordSynDiaListener.java/1.1/Fri Aug 11 16:40:31 2006// diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Repository b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Repository new file mode 100644 index 0000000..0ea7517 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/gui/wordalgorithm/events diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Root b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.java new file mode 100644 index 0000000..16ac40b --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/ToolbarButtonAction.java @@ -0,0 +1,92 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.gui.wordalgorithm.GuiController; + +/** + * ToolbarButtonAction represents a Button in the Toolbar. Could be an Undo, a + * Redo, an UndoAll or a RedoAsMuchAsPossible. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class ToolbarButtonAction extends AbstractAction { + + private GuiController myGuiController; + + // Specifies the Button Type + // 2 is Undo + // 3 is Redo + // (default is 2) + private int myType = 2; + + /** + * Constructs a ToolbarButtonAction object with the given + * references. + * + * @param myGuiController + * the GuiController instance usted to undo or + * redo Actions. + */ + public ToolbarButtonAction(GuiController myGuiController, int type) { + super(); + this.myGuiController = myGuiController; + + initType(type); + } + + /** + * Initiliazes the Type of Button + * + * @param type + * The type the Button should be. 2 is Undo 3 is Redo. + */ + private void initType(int type) { + this.myType = type; + switch (type) { + case 3: { + putValue(NAME, Messages.getString("ebnf", "Trans.Perform")); + putValue(SHORT_DESCRIPTION, Messages.getString("ebnf", + "WordAlgo.ToolBar_Redo")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("main", + "Icon.Redo"))); + break; + } + default: { + putValue(NAME, Messages.getString("ebnf", "Trans.Undo")); + putValue(SHORT_DESCRIPTION, Messages + .getString("ebnf", "WordAlgo.ToolBar_Undo")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("main", + "Icon.Undo"))); + } + } + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + switch (myType) { + case 3: { + // Redo + try { + myGuiController.getWordAlgoController().redo(); + } catch (Exception anException) { + anException.printStackTrace(); + } + break; + } + default: { + // Undo + try { + myGuiController.getWordAlgoController().undo(); + } catch (Exception anException) { + anException.printStackTrace(); + } + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.java new file mode 100644 index 0000000..e74a347 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordExitListener.java @@ -0,0 +1,133 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm.events; + +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import org.jalgo.module.ebnf.gui.wordalgorithm.GuiController; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.renderer.RenderValues; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.wordalgorithm.RenderEnd; + +/** + * Listens a RenderEnd and performs Actions if end is clicked or + * MouseOvered. + * + * @author Claas Wilke + * + */ +public class WordExitListener implements MouseListener, MouseMotionListener { + + private RenderValues rv; + + private boolean in = false; + + private Color highlightColor = RenderElement.HIGHLIGHT_BLUE; + + private GuiController myGuiController; + + private SyntaxDiagram myDiagram; + + /** + * Initializes the controller + * + * @param controller + * the GuiController which Model should used to perform Clicks. + * @param rv + * RenderValues needed to Highlight the RenderElem + * @param myDiagram + * The SyntaxDiagram, the Exit belongs to. + */ + public WordExitListener(GuiController controller, RenderValues rv, + SyntaxDiagram myDiagram) { + + this.myGuiController = controller; + + this.rv = rv; + + this.myDiagram = myDiagram; + + } + + public void mouseMoved(MouseEvent e) { + + if (myGuiController.getWordAlgoController().isAlgorithmRunning()) { + RenderEnd rb = (RenderEnd) e.getComponent(); + + // Check if curser is over the exit line + if (e.getY() > 2.8 * rv.radius && e.getY() < 3.2 * rv.radius) { + + if (!in) { + // Checkout if end could be reached, an is not reached + // allready. + in = myGuiController.getWordAlgoController() + .overSynDiaExitEntry(myDiagram); + + if (in) { + rb.setHighlighted(true, highlightColor); + } + } + } + // else check if exit from exit line + else { + if (in) { + myGuiController.getWordAlgoController() + .overSynDiaExitExit(); + in = false; + + rb.setHighlighted(false, RenderElement.STANDARD_COLOR); + } + } + } + } + + public void mouseDragged(MouseEvent e) { + + } + + public void mouseEntered(MouseEvent e) { + + } + + public void mouseExited(MouseEvent e) { + + // If position was over exit line, rechange Explanation + // and highlight color + if (in) { + myGuiController.getWordAlgoController().overSynDiaExitExit(); + in = false; + + RenderEnd rb = (RenderEnd) e.getComponent(); + rb.setHighlighted(false, RenderElement.STANDARD_COLOR); + } + + } + + public void mousePressed(MouseEvent e) { + + } + + public void mouseReleased(MouseEvent e) { + + // Perform click, if position is over exit line + if (e.getY() > 2.8 * rv.radius && e.getY() < 3.2 * rv.radius) { + + if (in) { + myGuiController.getWordAlgoController().leaveDiagram(); + in = false; + RenderEnd rb = (RenderEnd) e.getComponent(); + // rehighlight + rb.setHighlighted(false, RenderElement.STANDARD_COLOR); + } + + } + + } + + public void mouseClicked(MouseEvent e) { + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.java new file mode 100644 index 0000000..cbc6a78 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSplitListener.java @@ -0,0 +1,269 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm.events; + +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import org.jalgo.module.ebnf.gui.wordalgorithm.GuiController; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.renderer.elements.RenderSplit; +import org.jalgo.module.ebnf.renderer.RenderValues; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * Listens a Branch or Repetition and performs + * Actions if Left or Right Concatenation is empty. Can be added as a + * MouseListener or MouseMotionListener. + * + * @author Claas Wilke + * + */ +public class WordSplitListener implements MouseListener, MouseMotionListener { + + private RenderValues rv; + + private SynDiaElem myElement; + + private boolean top = false; + + private boolean in = false; + + boolean over = false; + + private Color highlightColor = RenderElement.HIGHLIGHT_BLUE; + + private GuiController myGuiController; + + /** + * Initializes the controller + * + * @param controller + * the GuiController which Model should used to perform Clicks. + * @param rv + * RenderValues needed to Highlight the RenderElem + * @param myElement + * The SynDiaElem which should be listened. + */ + public WordSplitListener(GuiController controller, RenderValues rv, + SynDiaElem myElement) { + + this.myGuiController = controller; + + this.rv = rv; + + this.myElement = myElement; + + } + + public void mouseMoved(MouseEvent e) { + + // Checkout if curser is in Element + if (in) { + RenderSplit rb = (RenderSplit) e.getComponent(); + + // Checkout if Repetition or Branch + Repetition aRepetition = null; + Branch aBranch = null; + Concatenation myConcat = null; + + boolean parentRepPos = false; + + if (myElement instanceof Repetition) { + aRepetition = (Repetition) myElement; + if (myGuiController.getWordAlgoController().getPosition() == aRepetition + && !myGuiController.getWordAlgoController() + .isPositionBehindElem()) { + parentRepPos = true; + } + } else if (myElement instanceof Branch) { + aBranch = (Branch) myElement; + } + + // Left Concatenation + if (e.getY() < 2 * rv.radius) { + + // Concat is just highlighted, if Concat is empty + if (aRepetition != null) { + myConcat = aRepetition.getLeft(); + } else if (aBranch != null) { + myConcat = aBranch.getLeft(); + } + if (myConcat != null + && !over + && (myGuiController.getWordAlgoController() + .getPosition() != myConcat) && !parentRepPos) { + + if ((!top || in) + && myConcat.getNumberOfElems() == 0 + && myGuiController.getWordAlgoController() + .isElementReachable(myConcat)) { + myGuiController.getWordAlgoController() + .overElementEntry(myConcat, false); + rb.setTopHighlight(true, highlightColor); + rb.setBottomHighlight(false, + RenderElement.STANDARD_COLOR); + top = true; + over = true; + } else + over = false; + + } + + } + // Right Concatenation + else { + + // Concat is just highlighted, if Concat is empty + if (aRepetition != null) { + myConcat = aRepetition.getRight(); + } else if (aBranch != null) { + myConcat = aBranch.getRight(); + } + if (myConcat != null + && !over + && (myGuiController.getWordAlgoController() + .getPosition() != myConcat) && !parentRepPos) { + + if ((top || in) + && myConcat.getNumberOfElems() == 0 + && myGuiController.getWordAlgoController() + .isElementReachable(myConcat)) { + myGuiController.getWordAlgoController() + .overElementEntry(myConcat, false); + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(true, highlightColor); + top = false; + over = true; + } else + over = false; + + } + } + // in = false; + } + + } + + public void mouseDragged(MouseEvent e) { + + } + + public void mouseEntered(MouseEvent e) { + + if (myGuiController.getWordAlgoController().isAlgorithmRunning()) { + in = true; + } else { + in = false; + } + + } + + public void mouseExited(MouseEvent e) { + + if (in) { + + in = false; + over = false; + myGuiController.getWordAlgoController().overElementExit(); + + RenderSplit rb = (RenderSplit) e.getComponent(); + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(false, RenderElement.STANDARD_COLOR); + } + + } + + public void mousePressed(MouseEvent e) { + + } + + public void mouseReleased(MouseEvent e) { + + if (in) { + Repetition aRepetition = null; + Branch aBranch = null; + Concatenation myConcat = null; + + boolean parentRepPos = false; + + if (myElement instanceof Repetition) { + aRepetition = (Repetition) myElement; + if (myGuiController.getWordAlgoController().getPosition() == aRepetition + && !myGuiController.getWordAlgoController() + .isPositionBehindElem()) { + parentRepPos = true; + } + } else if (myElement instanceof Branch) { + aBranch = (Branch) myElement; + } + + // Left Concatenation + if (e.getY() < 2 * rv.radius) { + + // Concat is just highlighted, if Concat is empty + if (aRepetition != null) { + myConcat = aRepetition.getLeft(); + } else if (aBranch != null) { + myConcat = aBranch.getLeft(); + } + if (myConcat != null + && (myGuiController.getWordAlgoController() + .getPosition() != myConcat) && !parentRepPos) { + + if ((!top || in) + && myConcat.getNumberOfElems() == 0 + && myGuiController.getWordAlgoController() + .isElementReachable(myConcat)) { + myGuiController.getWordAlgoController().gotoSplit( + myConcat); + in = false; + over = false; + + RenderSplit rb = (RenderSplit) e.getComponent(); + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(false, + RenderElement.STANDARD_COLOR); + } + + } + + } + // Right Concatenation + else { + + // Concat is just highlighted, if Concat is empty + if (aRepetition != null) { + myConcat = aRepetition.getRight(); + } else if (aBranch != null) { + myConcat = aBranch.getRight(); + } + if (myConcat != null + && (myGuiController.getWordAlgoController() + .getPosition() != myConcat) && !parentRepPos) { + + if ((top || in) && myConcat.getNumberOfElems() == 0) { + myGuiController.getWordAlgoController().gotoSplit( + myConcat); + in = false; + over = false; + + RenderSplit rb = (RenderSplit) e.getComponent(); + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(false, + RenderElement.STANDARD_COLOR); + } + + } + } + } + } + + public void mouseClicked(MouseEvent e) { + + } + +} diff --git a/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.java b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.java new file mode 100644 index 0000000..3610147 --- /dev/null +++ b/src/org/jalgo/module/ebnf/gui/wordalgorithm/events/WordSynDiaListener.java @@ -0,0 +1,247 @@ +package org.jalgo.module.ebnf.gui.wordalgorithm.events; + +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import org.jalgo.module.ebnf.gui.wordalgorithm.GuiController; +import org.jalgo.module.ebnf.gui.wordalgorithm.SynDiaPanel; +import org.jalgo.module.ebnf.renderer.wordalgorithm.ReturnAdress; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +/** + * This Listener performs the Click onto a Variable or a TerminalSymbol. + * + * @author Claas Wilke + * + */ +public class WordSynDiaListener implements MouseListener { + + // Neede to Highlight Element during MouseOver + private Color highlightColor = RenderElement.HIGHLIGHT_BLUE; + private static final Color DEHIGHLIGHTED_COLOR = Color.WHITE; + private static final Color RETURNADRESS_DEHIGHLIGHTED_COLOR = Color.BLACK; + + private GuiController myGuiController; + + private Object myCaller; + + private boolean over = false; + + /** + * Initializes the controller + * + * @param controller + * the GuiController which Model should used to perform Clicks. + * @param aSynDiaElem + * The SynDiaElem which clicks should be performed + * by this Controller. + */ + public WordSynDiaListener(GuiController controller, SynDiaElem aSynDiaElem) { + + this.myGuiController = controller; + + this.myCaller = aSynDiaElem; + + } + + /** + * Initializes the controller + * + * @param controller + * the GuiController which Model should used to perform Clicks. + * @param aSyntaxDiagram The + * SyntaxDiagram which clicks should be performed + * by this Controller. + */ + public WordSynDiaListener(GuiController controller, SyntaxDiagram aSyntaxDiagram) { + + this.myGuiController = controller; + + this.myCaller = aSyntaxDiagram; + + } + + public void mouseClicked(MouseEvent e) { + } + + /** + * Handles a MousOver event. + * + * Changes the Explanation. + * + */ + public void mouseEntered(MouseEvent e) { + // If Element was not entered before, enter. + if (!this.over) { + // Checkout which type of SynDiaElem was clicked + Object caller = e.getSource(); + if ((caller instanceof RenderVariable + || caller instanceof RenderTerminal) && myGuiController.getWordAlgoController().isAlgorithmRunning()) { + + this.over = true; + + SynDiaElem aSynDiaElem = (SynDiaElem) myCaller; + boolean isReacheable = myGuiController.getWordAlgoController().overElementEntry( + aSynDiaElem, false); + + // Color of Element is highlighted + RenderElement aRenderElem = (RenderElement) caller; + if (isReacheable) { + aRenderElem.setColor(this.highlightColor); + } + } + + if (caller instanceof ReturnAdress && myGuiController.getWordAlgoController().isAlgorithmRunning() && myGuiController.getWordAlgoController().isOnlyEndReachable()) { + + this.over = true; + + SynDiaElem aSynDiaElem = (SynDiaElem) myCaller; + boolean isReacheable = myGuiController.getWordAlgoController().overElementEntry( + aSynDiaElem, true); + + + // Color of Element is highlighted + RenderElement aRenderElem = (RenderElement) caller; + if (isReacheable) { + aRenderElem.setColor(this.highlightColor); + } + } + + // If the algorithm is during a Jump to a Diagram + if (caller instanceof SynDiaPanel) { + if (myGuiController.getWordAlgoController().isJumpToDiagram()) { + + SynDiaPanel myCallerPanel = (SynDiaPanel) caller; + myCallerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(highlightColor, 3)); + + this.over = true; + } + } + + } + } + + /** + * Handles a MousOver event. + * + * Changes the Explanation. + * + */ + public void mouseExited(MouseEvent e) { + // If Element was enteredbefore, leave. + if (this.over) { + // Checkout which type of SynDiaElem was clicked + Object caller = e.getSource(); + if (caller instanceof RenderVariable + || caller instanceof RenderTerminal + || caller instanceof ReturnAdress) { + this.over = false; + + // Color of Element is dehighlighted + RenderElement aRenderElem = (RenderElement) caller; + if (aRenderElem instanceof ReturnAdress) { + aRenderElem.setColor(RETURNADRESS_DEHIGHLIGHTED_COLOR); + } + else { + aRenderElem.setColor(DEHIGHLIGHTED_COLOR); + } + + // Change Explanation + myGuiController.getWordAlgoController().overElementExit(); + } + + if (caller instanceof SynDiaPanel) { + + // Change Explanation + myGuiController.getWordAlgoController().overElementExit(); + + SynDiaPanel myCallerPanel = (SynDiaPanel) caller; + myCallerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder()); + this.over = false; + } + + } + } + + /** + * Performs a Click on a SynDiaElem or + * SyntaxDiagram. + * + */ + public void mouseReleased(MouseEvent e) { + if (myGuiController.getWordAlgoController().isAlgorithmRunning()) { + // Checkout which type of SynDiaElem was clicked + Object caller = e.getSource(); + // If it was a Variable, perform a Click onto a Variable. + if (caller instanceof RenderVariable) { + Variable callerVar = (Variable) myCaller; + myGuiController.getWordAlgoController().gotoVariable(callerVar); + RenderElement aRenderElem = (RenderElement) caller; + if (!(myGuiController.getWordAlgoController().isElementReachable(callerVar) && myGuiController.getWordAlgoController().isAlgorithmRunning())) { + aRenderElem.setColor(DEHIGHLIGHTED_COLOR); + this.over = false; + } + } + // If it was a ReturnAdress of a Variable, perform a return to a + // Variable. + if (caller instanceof ReturnAdress && myGuiController.getWordAlgoController().isOnlyEndReachable()) { + Variable callerVar = (Variable) myCaller; + boolean wasSuccessfull = myGuiController.getWordAlgoController().returnToDiagram(callerVar); + RenderElement aRenderElem = (RenderElement) caller; + if (!(myGuiController.getWordAlgoController().isEndReached() && myGuiController.getWordAlgoController().isAlgorithmRunning())) { + aRenderElem.setColor(RETURNADRESS_DEHIGHLIGHTED_COLOR); + this.over = false; + } + if (!wasSuccessfull) { + animationReturn(aRenderElem); + } + } + // If it was a Termnial, perform a Click onto a Terminal. + if (caller instanceof RenderTerminal) { + TerminalSymbol callerTerminal = (TerminalSymbol) myCaller; + myGuiController.getWordAlgoController() + .gotoTerminal(callerTerminal); + RenderElement aRenderElem = (RenderElement) caller; + if (!(myGuiController.getWordAlgoController().isElementReachable(callerTerminal) && myGuiController.getWordAlgoController().isAlgorithmRunning())) { + aRenderElem.setColor(DEHIGHLIGHTED_COLOR); + this.over = false; + } + } + // If it was a SyntaxDiagram, perform a Click onto a SyntaxDiagram. + if (caller instanceof SynDiaPanel) { + SyntaxDiagram callerDiagram = (SyntaxDiagram) myCaller; + if (myGuiController.getWordAlgoController().isJumpToDiagram()) { + boolean wasSuccessfull = myGuiController.getWordAlgoController() + .jumpToDiagram(callerDiagram); + SynDiaPanel myCallerPanel = (SynDiaPanel) caller; + if (wasSuccessfull) { + myCallerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder()); + this.over = false; + } + else { + animationJump(myCallerPanel); + } + } + } + } + + } + + public void mousePressed(MouseEvent e) { + } + + private void animationJump(SynDiaPanel aCallerPanel) { + aCallerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED, 3)); + } + + private void animationReturn(RenderElement aRenderElem) { + aRenderElem.setColor(Color.RED); + } + +} diff --git a/src/org/jalgo/module/ebnf/jAlgoTabContrainerListener.java b/src/org/jalgo/module/ebnf/jAlgoTabContrainerListener.java new file mode 100644 index 0000000..841830c --- /dev/null +++ b/src/org/jalgo/module/ebnf/jAlgoTabContrainerListener.java @@ -0,0 +1,48 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf; + +import java.awt.event.ContainerEvent; +import java.awt.event.ContainerListener; + +public class jAlgoTabContrainerListener implements ContainerListener { + + private MainController mainController; + + public jAlgoTabContrainerListener(MainController mainController) { + this.mainController = mainController; + } + + /* (non-Javadoc) + * @see java.awt.event.ContainerListener#componentAdded(java.awt.event.ContainerEvent) + */ + public void componentAdded(ContainerEvent e) { + } + + /* (non-Javadoc) + * @see java.awt.event.ContainerListener#componentRemoved(java.awt.event.ContainerEvent) + */ + public void componentRemoved(ContainerEvent e) { + mainController.removeCustomMenu(); + } + +} diff --git a/src/org/jalgo/module/ebnf/model/CVS/Entries b/src/org/jalgo/module/ebnf/model/CVS/Entries new file mode 100644 index 0000000..fa2bbbf --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/CVS/Entries @@ -0,0 +1,4 @@ +D/ebnf//// +D/syndia//// +D/trans//// +D/wordalgorithm//// diff --git a/src/org/jalgo/module/ebnf/model/CVS/Repository b/src/org/jalgo/module/ebnf/model/CVS/Repository new file mode 100644 index 0000000..08e5128 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/model diff --git a/src/org/jalgo/module/ebnf/model/CVS/Root b/src/org/jalgo/module/ebnf/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/model/ebnf/CVS/Entries b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Entries new file mode 100644 index 0000000..14b65a5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Entries @@ -0,0 +1,13 @@ +/Definition.java/1.2/Thu Jan 31 20:15:07 2008// +/DefinitionFormatException.java/1.1/Fri Aug 11 16:40:30 2006// +/EAlternative.java/1.2/Thu Jan 31 20:15:08 2008// +/ECompoundTerm.java/1.2/Thu Jan 31 20:15:08 2008// +/EConcatenation.java/1.2/Thu Jan 31 20:15:07 2008// +/EOption.java/1.2/Thu Jan 31 20:15:08 2008// +/ERepetition.java/1.2/Thu Jan 31 20:15:07 2008// +/ESymbol.java/1.2/Thu Jan 31 20:15:08 2008// +/ETermContainer.java/1.2/Thu Jan 31 20:15:08 2008// +/ETerminalSymbol.java/1.2/Thu Jan 31 20:15:07 2008// +/EVariable.java/1.2/Thu Jan 31 20:15:07 2008// +/Rule.java/1.2/Thu Jan 31 20:15:07 2008// +/Term.java/1.2/Thu Jan 31 20:15:07 2008// diff --git a/src/org/jalgo/module/ebnf/model/ebnf/CVS/Repository b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Repository new file mode 100644 index 0000000..119a175 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/model/ebnf diff --git a/src/org/jalgo/module/ebnf/model/ebnf/CVS/Root b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/model/ebnf/Definition.java b/src/org/jalgo/module/ebnf/model/ebnf/Definition.java new file mode 100644 index 0000000..94d1ab7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/Definition.java @@ -0,0 +1,540 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +import java.io.Serializable; + +import org.jalgo.main.util.Messages; + +/** + * This is the interface to the EBNF definnition. + * @author johannes mey + */ +public class Definition extends java.util.Observable implements Serializable{ + + // ------------------------------------------------------------------------- + // private attributes ------------------------------------------------------ + // ------------------------------------------------------------------------- + + /** + * This is needed for restoring a saved definition + */ + private static final long serialVersionUID = 1L; + + /** + * the list of terminal symbols in the definition. it must not contain null + * elements and no two elements must have the same name. + */ + private java.util.List terminals + = new java.util.ArrayList(); + + /** + * the list of variable symbols. it must not contain null elements and no + * two elements must have the same name. + */ + private java.util.List variables + = new java.util.ArrayList(); + + /** + * the list of rules. it must not contain null elements and there is only + * one rule per variable symbol allowed. + * + */ + private java.util.List rules = new java.util.ArrayList(); + + /** + * the startVariable must be an element of the variables list. It can be be + * null only when there are no variables in the definition. + */ + private EVariable startVariable; + + // ------------------------------------------------------------------------- + // public methods ---------------------------------------------------------- + // ------------------------------------------------------------------------- + // 1. definition property methods ------------------------------------------ + // ------------------------------------------------------------------------- + + /** + * tests if all rules of the definition are strict according to the + * definition of ebnf terms, i.e. if all alternatives are binary + * + * @return true if all alternatives are binary, otherwise false + */ + public boolean isStrict() { + + // if a rule is not strict, the definition is not strict and false is + // returned + for (Rule rule : rules) + if(!rule.isStrict()) return false; + + // otherwise true is returned + return true; + } + + /** + * Checks if the symbol is valid, i.e. its name is not the beginning of + * another name and it is not an element of a symbols list yet. + * + * @param symbol + * the symbol to test + * @return if the symbol is valid + */ + private boolean isValidSymbolName(String symbol) { + + // return false if any name of a symbol starts with the name of the + // new symbol + for (ESymbol listSymbol : terminals) + if ((listSymbol.getName().startsWith(symbol)) || (symbol.startsWith(listSymbol.getName()))) + return false; + + + + for (ESymbol listSymbol : variables) + if ((listSymbol.getName().startsWith(symbol)) || (symbol.startsWith(listSymbol.getName()))) + return false; + + // otherwise return true + return true; + + } + + /** + * Checks if every variable has a corresponding rule + * + * @return true if the definition is complete + */ + public boolean isComplete() { + for(EVariable var:variables) { + if (!rules.contains(getRule(var))) return false; + } + return true; + } + + // ------------------------------------------------------------------------- + // public methods ---------------------------------------------------------- + // ------------------------------------------------------------------------- + // 2. getters -------------------------------------------------------------- + // ------------------------------------------------------------------------- + + /** + * Returns a strict Definition according to the definition of EBNF terms + * which fulfills the following conventions: + *
            + *
          • all Alternatives are binary
          • + *
          + * + * @return a strict Definition equivalent to the given Definition + * @throws DefinitionFormatException + */ + public Definition getStrict() throws DefinitionFormatException { + + // this should NEVER throw an Exception, so we should consider to ignore the fact that it can! + // but that is not too important... + + Definition strictDefinition = new Definition(); + + // add the existing terminal symbols. + for(ETerminalSymbol terminal:terminals) + strictDefinition.addTerminal(terminal); + + // add the existing variable symbols + for(EVariable variable:variables) + strictDefinition.addVariable(variable); + + // add the new, strict rules + for(Rule rule:rules) { + strictDefinition.addRule(rule.getStrict()); + } + + // Set the new start variable + strictDefinition.setStartVariable(this.startVariable); + + return strictDefinition; + } + + /** + * @param name is the name of the Symbol as a String + * @return the Symbol if it exists, otherwise null + */ + public ETerminalSymbol getTerminalSymbol(String name) { + for(ETerminalSymbol symbol:terminals) + if(symbol.getName().equals(name)) return symbol; + return null; + } + + /** + * @param name is the name of the Symbol as a String + * @return the Symbol if it exists, otherwise null + */ + public EVariable getVariable(String name) { + for(EVariable symbol:variables) + if(symbol.getName().equals(name)) return symbol; + return null; + } + + @Override + public String toString() { + String returnString = "E = (V,\u03a3,"; + if (startVariable == null) + returnString += ",R)\nV = {"; + else + returnString += startVariable.toString() + ",R)\nV = {"; + + for (int i = 0; i < variables.size(); i++) { + returnString += variables.get(i).toString(); + if (i != variables.size()-1) + returnString += ","; + } + + returnString += "}\n\u03a3 = {"; + + for (int i = 0; i < terminals.size(); i++) { + returnString += terminals.get(i).toString(); + if (i != terminals.size()-1) + returnString += ","; + } + + returnString += "}\n\nR:\n"; + + for (Rule rule : rules) { + returnString += rule.toString() + "\n"; + } + + return returnString; + } + + /** + * @return a list containing all Terminals + */ + public java.util.List getTerminals() { + return new java.util.ArrayList(terminals); + } + + /** + * @return a list containing all Variables + */ + public java.util.List getVariables() { + return new java.util.ArrayList(variables); + } + + /** + * @return Returns the startVariable. + */ + public EVariable getStartVariable() { + return startVariable; + } + + /** + * @return returns the rules. + */ + public java.util.List getRules() { + return new java.util.ArrayList(rules); + } + + /** + * Returns the rule with the given name + * @param name the name of the rule, i.e. the left side variable + * @return the rule, if it exists, otherwise null + */ + public Rule getRule(EVariable name) { + for(Rule rule:rules) + if(rule.getName().equals(name)) return rule; + return null; + } + + // ------------------------------------------------------------------------- + // public methods ---------------------------------------------------------- + // ------------------------------------------------------------------------- + // 3. setters -------------------------------------------------------------- + // ------------------------------------------------------------------------- + // there should be a call of setChanged() and notifyOberserves() + // in every method + // ------------------------------------------------------------------------- + + + /** + * Sets the start variable of the definition to var if the set of variables + * contains var. + * + * @param var + * the new start variable + * @throws DefinitionFormatException if the variable is not contained in the definition + */ + public void setStartVariable(EVariable var) throws DefinitionFormatException { + + if (var == null) { + startVariable = null; + } + else if (!variables.contains(var)) { + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.StartVarNotInDef")); + } + else { + startVariable = var; + + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + + } + + + // add/remove functions + + /** + * Adds a new terminal symbol. if any symbol with the given name already + * exists false is returned and the element is not added. + * + * @param symbol + * is the symbol to be added + * @throws DefinitionFormatException + */ + public void addTerminal(ETerminalSymbol symbol) throws DefinitionFormatException { + + if (isValidSymbolName(symbol.getName())) { + if(terminals.add(symbol)) { + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Undefined")); + } else + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidNameInDef")); + } + + /** + * Adds a new variable symbol. if any symbol with the given name already + * exists false is returned and the element is not added. + * @param symbol is the symbol to be added + * @throws DefinitionFormatException + */ + public void addVariable(EVariable symbol) throws DefinitionFormatException { + + if (isValidSymbolName(symbol.getName())) { + if(variables.add(symbol)){ + // // Auto-Set-StartVar + // if(getStartVariable()==null) setStartVariable(symbol); + // else { + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + // } + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Undefined")); + } else + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidNameInDef")); + } + + /** + * a terminal can only be removed if there are no rules containing it. + * @param symbol + * the symbol to be removed + * @throws DefinitionFormatException + */ + public void removeTerminal(ETerminalSymbol symbol) throws DefinitionFormatException { + + if (terminals.contains(symbol)) { + for (Rule rule:rules) { + if (rule.contains(symbol)) throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.SymbolOccoursInRule")); + } + if(terminals.remove(symbol)){ + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Undefined")); + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.NotATerminalSymbol")); + } + + /** + * a variable can only be removed if there are no rules containing it. + * + * @param symbol + * the symbol to be removed + * @throws DefinitionFormatException + */ + public void removeVariable(EVariable symbol) throws DefinitionFormatException { + + if (variables.contains(symbol)) { + for (Rule rule:rules) { + if (rule.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.SymbolOccoursInRule")); + } + if (this.getStartVariable()!=null && this.getStartVariable().equals(symbol)) { + this.startVariable = null; + // Auto-Set-StartVar + // if (!variables.isEmpty()) setStartVariable(variables.get(0)); + + } + if(variables.remove(symbol)) { + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Undefined")); + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.NotAVariable")); +} + + /** + * Adds a new rule to the end of the list of rules. The rule must not be + * and the name of the rule must be a variable that is an element of the + * variables list + * + * @param rule + * @throws DefinitionFormatException + */ + public void addRule(Rule rule) throws DefinitionFormatException { + if(rule == null) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.RuleIsNull")); + else if (!variables.contains(rule.getName())) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + rule.getName().getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.NotAVariable")); + else { + // check if there is no rule for the name of the new rule yet + for(Rule oldrule:rules) { + if (oldrule.getName().equals(rule.getName())) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " " + Messages.getString("ebnf", "Ebnf.Error.RuleAlreadyExists") + " '" + rule.getName().getName() + "'!"); + } + + // check if all symbols in the rule are part of the definition + for(ESymbol symbol:rule.getTerm().getSymbols()) { + if(symbol.getClass().equals(EVariable.class)) { + if (!variables.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + " '" + rule.getName().getName() + Messages.getString("ebnf", "Ebnf.Error.NotASymbol")); + } + else if(symbol.getClass().equals(ETerminalSymbol.class)) { + if (!terminals.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + symbol.getName() + " '" + rule.getName().getName() + Messages.getString("ebnf", "Ebnf.Error.NotASymbol")); + } + } + + rules.add(rule); + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + + } + + /** + * removes the rule rule if it is part of the defintion. + * @param rule the rule to be removed + * @throws DefinitionFormatException + */ + public void removeRule(Rule rule) throws DefinitionFormatException { + if(rules.remove(rule)) { + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + } + else throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Undefined")); + } + + + // replace/rename functions + + /** + * Renames the symbol symbol to newName if this is + * possible. + * @param symbol the symbol to be renamed + * @param newName the new name + * @throws DefinitionFormatException + */ + public void renameSymbol(ESymbol symbol, String newName) throws DefinitionFormatException { + + + if( !(isValidSymbolName(newName) || symbol.getName().startsWith(newName)|| newName.startsWith(symbol.getName()))) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + newName + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidSymbolName")); + else if(symbol instanceof EVariable) { + if(!variables.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + newName + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidSymbolName")); + } else if(symbol instanceof ETerminalSymbol) { + if(!terminals.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + newName + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidSymbolName")); + } + + symbol.setName(newName); + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + + } + + /** + * Replaces the Rule oldRule by newRule if oldRule is a valid rule of the + * definition + * + * @param oldRule the rule to be replaced + * @param newRule the replacement rule + * @return true if a rule could be replaced + * @throws DefinitionFormatException + */ + public void replaceRule(Rule oldRule, Rule newRule) throws DefinitionFormatException { + + // first of all check if there is a rule 'oldRule' + if (!rules.contains(oldRule)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.NotARuleReplace")); + + // then check if the new rule is not null + else if(newRule == null) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.ReplacementRuleIsNull")); + + // then check if the name of the rule is a variable from the definition + else if (!variables.contains(newRule.getName())) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " " + Messages.getString("ebnf", "Ebnf.Error.Replacement") + " '" + newRule.getName().getName() + "' " + Messages.getString("ebnf", "Ebnf.Error.NotAVariable")); + else { + // check if all symbols in the rule are part of the definition + for(ESymbol symbol:newRule.getTerm().getSymbols()) { + if(symbol.getClass().equals(EVariable.class)) { + if (!variables.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " " + Messages.getString("ebnf", "Ebnf.Error.Replacement") + " '" + symbol.getName() + " '" + newRule.getName().getName() + Messages.getString("ebnf", "Ebnf.Error.NotASymbol")); + } + else if(symbol.getClass().equals(ETerminalSymbol.class)) { + if (!terminals.contains(symbol)) + throw new DefinitionFormatException(Messages.getString("ebnf", "Ebnf.Error.Error") + " " + Messages.getString("ebnf", "Ebnf.Error.Replacement") + " '" + symbol.getName() + " '" + newRule.getName().getName() + Messages.getString("ebnf", "Ebnf.Error.NotASymbol")); + } + } + + rules.set(rules.indexOf(oldRule),newRule); + + // OBSERVER-PATTERN begin + this.setChanged(); + this.notifyObservers(); + // OBSERVER-PATTERN end + + } + } + + + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.java b/src/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.java new file mode 100644 index 0000000..e003183 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/DefinitionFormatException.java @@ -0,0 +1,26 @@ +package org.jalgo.module.ebnf.model.ebnf; + +public class DefinitionFormatException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public DefinitionFormatException() { + super(); + } + + public DefinitionFormatException(String message) { + super(message); + } + + public DefinitionFormatException(String message, Throwable cause) { + super(message, cause); + } + + public DefinitionFormatException(Throwable cause) { + super(cause); + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/EAlternative.java b/src/org/jalgo/module/ebnf/model/ebnf/EAlternative.java new file mode 100644 index 0000000..4761549 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/EAlternative.java @@ -0,0 +1,250 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + *

          + * Represents the alternative in an EBNF term (a|b). According to the definition + * an alternative is binary. Since the alternative is commonly used in a not + * binary way, the model also allows the alternative of more than two terms. + *

          + * + */ +public class EAlternative extends org.jalgo.module.ebnf.model.ebnf.Term { + + /** + * + */ + private static final long serialVersionUID = 1L; + /** + *

          + * Stores the terms of the alternative. It has to be ensured that this list + * always contains at least two elements. + *

          + * + */ + private java.util.List terms; + + /** + *

          + * Creates an Aternative with at least two terms. It only adds elements that + * are not null. + *

          + * + * @param terms + * is the list of terms to be in the alternative + * @throws DefinitionFormatException + * if there are less than two terms in the given list that are + * not null. + */ + public EAlternative(java.util.List terms) + throws DefinitionFormatException { + + if (terms == null) throw new DefinitionFormatException(); + this.terms = new java.util.ArrayList(); + + if(terms == null) + throw new DefinitionFormatException("List of terms is null"); + + // add all terms that are not null + for (Term term : terms) { + if (term != null) + this.terms.add(term); + } + + // check if alternative has alt least two terms, otherwise throw + // exception + if (this.terms.size() < 2) { + this.terms = null; + throw new DefinitionFormatException(); + } + + } + + /** + *

          + * Adds the term to the end of the list of alternatives if it is not null + * or is not the EAlternative itself. + *

          + * + * + * @param term + * is the term to be added + * @throws DefinitionFormatException + */ + public void addTerm(Term term) throws DefinitionFormatException { + if (term == null || term.contains(this)) + throw new DefinitionFormatException(); + else { + terms.add(term); + } + } + + /** + * @return a copy of the list of alternatives + */ + @Override + public java.util.List getTerms() { + return new java.util.ArrayList(terms); + } + + /** + *

          + * Creates a binary Alternative. If at least one of the arguments is null an + * Exception is thrown. + *

          + * + * + * @param term1 + * is the first alternative + * @param term2 + * is the second alternative + * @throws DefinitionFormatException + * @throws DefinitionFormatException + */ + public EAlternative(Term term1, Term term2) + throws DefinitionFormatException { + if (term1 == null || term2 == null) + throw new DefinitionFormatException("could not add null term"); + + terms = new java.util.ArrayList(); + terms.add(term1); + terms.add(term2); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#contains(org.jalgo.module.ebnf.model.ebnf.ESymbol) + */ + @Override + public boolean contains(Term term) { + // if the term is the requested term return true + if (this.equals(term)) return true; + + // otherwise check all the contained terms + for (Term subterm : terms) { + if(subterm.contains(term)) return true; + } + + return false; + } + + + /** + * Tests if the alternative and all alternatives in the contained term + * contain exactly two terms + * + * @return true if all alternatives contain two terms, otherwise false + */ + public boolean isStrict() { + if (terms.size() != 2) + return false; + + boolean isStrict = true; + for (Term term : terms) + isStrict = isStrict && term.isStrict(); + + return isStrict; + } + + /** + * This is the only implementation of getStrict that actually does something + * useful: it transforms the list of alternative terms into binary + * alternatives. + * @throws DefinitionFormatException if something goes worng with the + * creation of the strict term + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#getStrict() + */ + @Override + public Term getStrict() throws DefinitionFormatException { + // this is the alternative that will be returned + Term newAlternative = null; + + // this is the list of the new alternative + java.util.List newTerms = new java.util.ArrayList(); + + + // if the alternative already is binary, only modify the contained terms + if (terms.size() == 2) { + + // add the two terms to the new list of the concatenation + newTerms.add(terms.get(0).getStrict()); + newTerms.add(terms.get(1).getStrict()); + + } + // if the list contains more than two alternatives... + else { + // add the fist term of the list to the alternative + newTerms.add(terms.get(0).getStrict()); + + // create a new alternative for the rest of the terms. + Term restAlternative = null; + + // the list for the new rest-alternative + java.util.List restTerms = new java.util.ArrayList(); + + // fill the list + for (int i=1; i + * Represents a parenthesized term in EBNF + *

          + * + */ +public class ECompoundTerm extends ETermContainer { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * @param term + * @throws DefinitionFormatException + * if the term is null + */ + public ECompoundTerm(Term term) throws DefinitionFormatException { + setTerm(term); + + } + + /** + * The Compound term is a part of the ebnf definition but has no semantic + * purpose. Therefore it is removed in the 'strict' version of the term. + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#getStrict() + */ + @Override + public Term getStrict() throws DefinitionFormatException { + + return term.getStrict(); + + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + return "(" + term.toString() + ")"; + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/EConcatenation.java b/src/org/jalgo/module/ebnf/model/ebnf/EConcatenation.java new file mode 100644 index 0000000..3213327 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/EConcatenation.java @@ -0,0 +1,248 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + *

          + * Represents the concatenation in EBNF. The concatenation is not + * binary, but contains at least two terms + *

          + * + */ +public class EConcatenation extends org.jalgo.module.ebnf.model.ebnf.Term { + /** + * + */ + private static final long serialVersionUID = 1L; + /** + *

          + * the terms inside the concatenation + *

          + */ + private java.util.List terms = new java.util.ArrayList(); + + /** + *

          + * Creates a Concatenation with at least two terms. It only adds elements + * that are not null. + *

          + * + * @param terms + * is the list of terms to be in the alternative + * @throws DefinitionFormatException + * if there are less than two terms in the given list that are + * not null, if the list contains terms that are null am + * exception will be thrown + */ + public EConcatenation(java.util.List terms) + throws DefinitionFormatException { + this.terms = new java.util.ArrayList(); + + // add all terms that are not null and do not contain the concatenation + // itself + for (Term term : terms) { + if (term == null) + throw new DefinitionFormatException("could not add null term"); + else if(term.contains(this)) + throw new DefinitionFormatException + ("could not add term containing the parent term"); + else + this.terms.add(term); + } + + // check if the concatenation has at least two terms, otherwise + // throw exception + if (this.terms.size() < 2) { + this.terms = null; + throw new DefinitionFormatException + ("not enough terms in concatenation!"); + } + + } + + /** + *

          + * Creates a binary Concatenation. If at least one of the arguments is null an + * Exception is thrown. + *

          + * + * + * @param term1 + * is the first term + * @param term2 + * is the second term + * @throws DefinitionFormatException + */ + public EConcatenation(Term term1, Term term2) + throws DefinitionFormatException { + if (term1 == null || term2 == null) + throw new DefinitionFormatException("could not add null term"); + + terms = new java.util.ArrayList(); + terms.add(term1); + terms.add(term2); + } + + + /** + * @return a copy of the list of the terms + */ + @Override + public java.util.List getTerms() { + return new java.util.ArrayList(terms); + } + + /** + *

          + * Adds the term to the end of the list if it is not null + * or is not the EConcatenation itself. + *

          + * + * + * @param term + * is the term to be added + * @throws DefinitionFormatException + */ + public void addTerm(Term term) throws DefinitionFormatException { + if (term == null || term.contains(this)) + throw new DefinitionFormatException(); + else { + terms.add(term); + } + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#isStrict() + */ + @Override + public boolean isStrict() { + boolean isStrict = true; + for (Term term : terms) + isStrict = isStrict && term.isStrict(); + return isStrict; + } + + + /** + * This method returns the strict version of the EBNF term. Since the trans + * algorithm cannot process concatenations inside concatenations, all + * concatenations inside a concatenation are merged with the the first + * concatenation. If a concat includes a compound term this term will be + * removed and its inner term added to the concatenation. + * + * @return the strict version of the term + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#getStrict() + */ + @Override + public Term getStrict() throws DefinitionFormatException { + // the new concatenation + Term newConcatenation; + + // the list of the new concatenation + java.util.List newTerms = new java.util.ArrayList(); + + // remove nested concatenations + newTerms = getStrictRec(this.terms); + + // make terms in newTerms strict + for(int i = 0; i < newTerms.size();i++) { + newTerms.set(i,newTerms.get(i).getStrict()); + } + + // create the new concatenation with the new list + newConcatenation = new EConcatenation(newTerms); + + return newConcatenation; + } + + /** + * This private method is called by the getStrict method. It traverses the + * concatenations in the list and replaces every concatenation in the list + * with the included elements. + * + * @param subTerms the list of terms of the original concatenation + * @return the new list of elements of the concatenation. + */ + private java.util.List getStrictRec(java.util.List subTerms){ + + // create a new list for the subterms + java.util.List retTerms = new java.util.ArrayList(); + + // for every subTerm in the old list ... + for (Term subTerm : subTerms) { + // ... if it is a concatenation add all terms of this concatenation + // to the new list + if (subTerm instanceof EConcatenation) { + retTerms.addAll(getStrictRec(subTerm.getTerms())); + } + + // ...if it is a compound term add all subterms of the first (and + // only) subterm of the compound term to the list. + else if (subTerm instanceof ECompoundTerm) { + retTerms.addAll(getStrictRec(subTerm.getTerms().get(0).getTerms())); + } + + // ... if it is neither a compund term nor a concatenation, simply + // add the term to the list. + else { + retTerms.add(subTerm); + } + } + return retTerms; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#contains(org.jalgo.module.ebnf.model.ebnf.ESymbol) + */ + @Override + public boolean contains(Term term) { + // if the term is the requested term return true + if (this.equals(term)) return true; + + // otherwise check all the contained terms + for (Term subterm : terms) { + if(subterm.contains(term)) return true; + } + + return false; + } + + /** + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + String returnString = ""; + for (Term term : terms) { + returnString += term.toString(); + } + return returnString; + } +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/EOption.java b/src/org/jalgo/module/ebnf/model/ebnf/EOption.java new file mode 100644 index 0000000..db07716 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/EOption.java @@ -0,0 +1,73 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + *

          + * Represents a parenthesized term in EBNF + *

          + * + */ +public class EOption extends ETermContainer { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * @param term + * @throws DefinitionFormatException + * if the term is null + */ + public EOption(Term term) throws DefinitionFormatException { + setTerm(term); + + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#getStrict() + */ + @Override + public Term getStrict() throws DefinitionFormatException { + Term newOption; + + newOption = new EOption(term.getStrict()); + return newOption; + + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + return "[" + term.toString() + "]"; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/model/ebnf/ERepetition.java b/src/org/jalgo/module/ebnf/model/ebnf/ERepetition.java new file mode 100644 index 0000000..b2376ae --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/ERepetition.java @@ -0,0 +1,71 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + *

          + * Represents a parenthesized term in EBNF + *

          + * + */ +public class ERepetition extends ETermContainer { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * @param term + * @throws DefinitionFormatException + * if the term is null + */ + public ERepetition(Term term) throws DefinitionFormatException { + setTerm(term); + + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#getStrict() + */ + @Override + public Term getStrict() throws DefinitionFormatException { + Term newRepetition; + newRepetition = new ERepetition(term.getStrict()); + return newRepetition; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + return "{" + term.toString() + "}"; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/model/ebnf/ESymbol.java b/src/org/jalgo/module/ebnf/model/ebnf/ESymbol.java new file mode 100644 index 0000000..587f251 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/ESymbol.java @@ -0,0 +1,136 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +import java.util.List; + +import org.jalgo.main.util.Messages; + +/** + * Represents an EBNF symbol. The name must not be an empty String, null or a + * String consisting of blanks only + * + * @author Johannes Mey + */ +abstract public class ESymbol extends Term { + + /** + * This is the name of the symbol. + */ + private String name; + +// ----------------------------------------------------------------------------- +// ESymbol methods & constructors +// ----------------------------------------------------------------------------- + + + /** + * Creates a new symbol with the given name. + * + * @param name + * the name of the new Symbol + * @throws DefinitionFormatException + * if the name is invalid + */ + public ESymbol(String name) throws DefinitionFormatException { + this.setName(name); + } + + /** + * Renames the symbol. + * + * @param name + * the new name + * @throws DefinitionFormatException + * if the new name is invalid + */ + public void setName(String name) throws DefinitionFormatException { + + if (name == null) { + throw new DefinitionFormatException("No name for ESymbol given!"); + } + else if (name.equals("") || name.trim().equals("")) { + throw new DefinitionFormatException + (Messages.getString("ebnf", "Ebnf.Error.Error") + " '" + name + "' " + Messages.getString("ebnf", "Ebnf.Error.InvalidSymbolName")); + } + + this.name = name; + } + + /** + * @return the name of the symbol + */ + public String getName() { + return name; + } + +// ----------------------------------------------------------------------------- +// methods inherited from Term +// ----------------------------------------------------------------------------- + + /** + * Checks if the symbol is strict according to the definition of a strict + * term. this is always true! + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#isStrict() + * @return this method always returns true + */ + @Override + public boolean isStrict() { + return true; + } + + /* + * @see Term#getTerms() + */ + @Override + public List getTerms() { + return new java.util.ArrayList(); + } + + /* + * @see Term#toString() + */ + @Override + public String toString() { + return name; + } + + /* + * @see Term#getStrict() + */ + @Override + public Term getStrict() { + return this; + } + + /* + * @see Term#contains(ESymbol) + */ + @Override + public boolean contains(Term term) { + return this.equals(term); + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/ETermContainer.java b/src/org/jalgo/module/ebnf/model/ebnf/ETermContainer.java new file mode 100644 index 0000000..fe9c293 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/ETermContainer.java @@ -0,0 +1,108 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + * This abstract class holds the functionality for EOption, ECompoundTerm, and + * ERepetition. + * + */ +public abstract class ETermContainer extends Term { + + /** + *

          + * The term inside the brackets + *

          + * + */ + protected Term term; + + /** + * @return Returns the term. + */ + public Term getTerm() { + return term; + } + + /** + * Sets the sub-term to term. + * @param term + * The term to set. + * @throws DefinitionFormatException if the term is null or contains the + * container term itself + */ + public void setTerm(Term term) throws DefinitionFormatException { + + if (term == null || term.contains(this)) + throw new DefinitionFormatException(); + else + this.term = term; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#isStrict() + */ + @Override + public boolean isStrict() { + return term.isStrict(); + } + + /** + * @return a list including the sub-term as the only element + */ + @Override + public java.util.List getTerms() { + java.util.List returnList = new java.util.ArrayList(); + returnList.add(term); + return returnList; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#contains(org.jalgo.module.ebnf.model.ebnf.ESymbol) + */ + @Override + public boolean contains(Term term) { + // if this is the term or the sub-term is the term return true + if (this.equals(term) || this.term.equals(term)) + return true; + // otherwise test if the sub-term contains the term + return this.term.contains(term); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + return "[" + term.toString() + "]"; + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.java b/src/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.java new file mode 100644 index 0000000..727a4d1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/ETerminalSymbol.java @@ -0,0 +1,50 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + * Represents an EBNF terminal symbol. + * + */ +public class ETerminalSymbol extends ESymbol { + + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Creates a new terminal symbol with the given name. + * + * @param name + * the name of the terminal symbol + * @throws DefinitionFormatException + * if the name is not a valid name for an ESymbol + */ + public ETerminalSymbol(String name) throws DefinitionFormatException { + super(name); + } + + } diff --git a/src/org/jalgo/module/ebnf/model/ebnf/EVariable.java b/src/org/jalgo/module/ebnf/model/ebnf/EVariable.java new file mode 100644 index 0000000..8c49bab --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/EVariable.java @@ -0,0 +1,51 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +/** + * This class represents a syntactic variable of an EBNF definition. + * + * @author Johannes Mey + */ +public class EVariable extends ESymbol { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Creates a new variable with the given name. + * + * @param name + * the name of the variable + * @throws DefinitionFormatException + * if the name is not a valid name for an ESymbol + */ + + public EVariable(String name) throws DefinitionFormatException { + super(name); + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/Rule.java b/src/org/jalgo/module/ebnf/model/ebnf/Rule.java new file mode 100644 index 0000000..80d1e66 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/Rule.java @@ -0,0 +1,142 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +import java.io.Serializable; + +/** + * Represents a rule of an EBNF definition, a rule always contains a valid name + * (the variable on the left side) and a valid term (right side) + */ +public class Rule implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * The name of a rule is the name of the variable of the left side + */ + private EVariable name; + + /** + * The term is the right side of a rule + */ + private Term term; + + public Rule(EVariable name, Term term) throws DefinitionFormatException { + if (name == null || term == null) + throw new DefinitionFormatException( + "could not add variable or term because it was null"); + this.name = name; + this.term = term; + } + + /** + * Checks, if every Alternative in the Term has exactly two sub-terms + * + * @return true if every alternative has two sub-terms + */ + public boolean isStrict() { + return term.isStrict(); + } + + /** + * + * @return a version of the rule where the term contains binary alternatives + * only + * @throws DefinitionFormatException + * if for some reason the strict version could not be created + */ + public Rule getStrict() throws DefinitionFormatException { + Rule strictRule = new Rule(name, term.getStrict()); + + return strictRule; + } + + /** + * @see org.jalgo.module.ebnf.model.ebnf.Term#toString() + */ + @Override + public String toString() { + + return name.toString() + " ::= " + term.toString(); + } + + /** + * Returns the name of the Rule, i.e. the name of the Variable on the left + * side + * + * @return + */ + public EVariable getName() { + return name; + } + + /** + * Sets the name of the rule. + * + * @param name + * must not be null + * @throws DefinitionFormatException if the name is a null object + */ + public void setName(EVariable name) throws DefinitionFormatException { + if (name == null) + throw new DefinitionFormatException(); + this.name = name; + } + + /** + * @return the left side of the rule + */ + public Term getTerm() { + return term; + } + + /** + * Sets the term of the rule to term + * @param term + * The term to set. + * @throws DefinitionFormatException + */ + public void setTerm(Term term) throws DefinitionFormatException { + + if (term != null) + this.term = term; + else + throw new DefinitionFormatException(); + } + + /** + * Checks if the rule contains a certain term + * @param term to be searched for + * @return true if the rule contains the term + */ + public boolean contains (Term term) { + if (term.equals(name)) return true; + else return this.term.contains(term); + } + +} diff --git a/src/org/jalgo/module/ebnf/model/ebnf/Term.java b/src/org/jalgo/module/ebnf/model/ebnf/Term.java new file mode 100644 index 0000000..06abfd5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/ebnf/Term.java @@ -0,0 +1,96 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.ebnf; + +import java.io.Serializable; + +/** + *

          An abstract class representing an EBNF term.

          + * + * @author Johannes Mey + */ + +public abstract class Term implements Serializable{ + + /** + * Checks if, when the term is an alternative, it contains exactly two + * terms. + * + * @return true + */ + public abstract boolean isStrict(); + + + /** + * This method is used to create a copy of the current ebnf definition with + * only binary alternatives. + * + * @return a term with only binary alternatives. + * @throws DefinitionFormatException + */ + public abstract Term getStrict() throws DefinitionFormatException; + + /** + * Checks if the term term is contained in the term + * + * @param term the term to be searched for + * @return true if the term contains the term as a sub-term or is the term, + * false if it does not contain the term. + */ + public abstract boolean contains(Term term); + + + /** + * Returns the contained subterms. + * + * @return the contained subterms + */ + public abstract java.util.List getTerms(); + + + /** + * This is used in the addRule function of the Definition to + * insure that all symbols in a rule are included in the definition + * @return a list of all symbols in the rule. + */ + java.util.List getSymbols () { + java.util.List variablesList + = new java.util.ArrayList(); + for(Term subterm:getTerms()) + variablesList.addAll(subterm.getSymbols()); + + return variablesList; + + } + +/** + *

          This method is for testing purposes only. + * It should output the term, but there is no distinction + * between meta symbols and other symbols (i.e. no ^).

          + * + * + * @return a String representation of the EBNF-term + */ + public abstract String toString(); + } diff --git a/src/org/jalgo/module/ebnf/model/syndia/Branch.java b/src/org/jalgo/module/ebnf/model/syndia/Branch.java new file mode 100644 index 0000000..bd7276a --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/Branch.java @@ -0,0 +1,97 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +/** + * This class is the model of a branch. It consists of two concatenations: left + * and right. + * + * @author Michael Thiele + */ +public class Branch extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private Concatenation left; + + private Concatenation right; + + /** + * + * @param parent + * parent of the element + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public Branch(SynDiaElem parent, SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + left = new Concatenation(this, mySyntaxDiagram); + right = new Concatenation(this, mySyntaxDiagram); + } + + /** + * @return The left concatenation, which is the upper one when rendered. + */ + public Concatenation getLeft() { + return left; + } + + /** + * @return The right concatenation, which is the lower one when rendered. + */ + public Concatenation getRight() { + return right; + } + + /** + * Removes all NullElems from the Branch. + * + * @return true if NullElems were removed, + * false if nothing had to be removed + */ + public boolean removeNullElems() { + boolean retVal = false; + retVal = left.removeNullElems(); + retVal |= right.removeNullElems(); + return retVal; + } + + /** + * Fills the Branch with NullElems. + * + * @return true if NullElems were added, + * false if nothing had to be added + */ + public boolean fillWithNullElems() { + boolean retVal = false; + retVal = left.fillWithNullElems(); + retVal |= right.fillWithNullElems(); + return retVal; + } + + public String toString() { + return "[ Branch: " + left.toString() + ": " + right.toString() + "]"; + } + +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/CVS/Entries b/src/org/jalgo/module/ebnf/model/syndia/CVS/Entries new file mode 100644 index 0000000..fc74490 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/CVS/Entries @@ -0,0 +1,13 @@ +/Branch.java/1.2/Thu Jan 31 20:15:01 2008// +/Concatenation.java/1.2/Thu Jan 31 20:15:01 2008// +/ElementNotFoundException.java/1.2/Thu Jan 31 20:15:01 2008// +/NoNullElemException.java/1.2/Thu Jan 31 20:15:01 2008// +/NullElem.java/1.2/Thu Jan 31 20:15:01 2008// +/Repetition.java/1.2/Thu Jan 31 20:15:01 2008// +/SynDiaElem.java/1.2/Thu Jan 31 20:15:01 2008// +/SynDiaSystem.java/1.2/Thu Jan 31 20:15:01 2008// +/SynDiaSystemLibrary.java/1.1/Fri Aug 11 16:40:26 2006// +/SyntaxDiagram.java/1.2/Thu Jan 31 20:15:01 2008// +/TerminalSymbol.java/1.2/Thu Jan 31 20:15:01 2008// +/Variable.java/1.2/Thu Jan 31 20:15:01 2008// +/WordWrap.java/1.2/Thu Jan 31 20:15:01 2008// diff --git a/src/org/jalgo/module/ebnf/model/syndia/CVS/Repository b/src/org/jalgo/module/ebnf/model/syndia/CVS/Repository new file mode 100644 index 0000000..bf77de4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/model/syndia diff --git a/src/org/jalgo/module/ebnf/model/syndia/CVS/Root b/src/org/jalgo/module/ebnf/model/syndia/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/model/syndia/Concatenation.java b/src/org/jalgo/module/ebnf/model/syndia/Concatenation.java new file mode 100644 index 0000000..be383c7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/Concatenation.java @@ -0,0 +1,1090 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Messages; + +/** + * The class Concatenation administrates a list of syntax diagram + * elements, it consists of. All syntax diagram elements except a concatenation + * can be added and removed. Concatenation has only 2 elements if + * the syntax diagram is in strict mode. + * + * @author Michael Thiele + */ +public class Concatenation extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private List synDiaElem; + + private int line; // number of the current concatenation + + private static int lines = 1; // to have unique line numbers + + private boolean filledWithNullElems; + + /** + * Constructs a Concatenation by saving its parent element + * and initializing the list of syntax diagram elements. + * + * @param parent + * parent of the element + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public Concatenation(SynDiaElem parent, SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + synDiaElem = new LinkedList(); + line = lines++; // line is a unique number + // automatically insert a NullElem, so that other SynDiaElems can be + // inserted + synDiaElem.add(0, new NullElem(this, line, 0, mySyntaxDiagram)); + filledWithNullElems = true; + } + + /** + * @return number of elements in the concatenation + */ + public int getNumberOfElems() { + return synDiaElem.size(); + } + + /** + * Returns an element the concatenation consists of. + * + * @param index + * index of the syntax diagram element + * @return the syntax diagram element at position index + * @throws IndexOutOfBoundsException + */ + public SynDiaElem getSynDiaElem(int index) throws IndexOutOfBoundsException { + return synDiaElem.get(index); + } + + /** + * Inserts a syntax diagram element at the end of the concatenation. No new + * element is created! + * + * @param s + * the SynDiaElem to add + */ + private void insert(SynDiaElem s) { + synDiaElem.add(s); + } + + /** + * @param index + * index in the synDiaElem list + * @param s + * the SynDiaElem to include + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + private void addSynDiaElem(int index, SynDiaElem s) + throws NoNullElemException { + if (!(synDiaElem.get(index) instanceof NullElem)) { + throw new NoNullElemException(Messages.getString("ebnf", + "SynDiaModel.NoNullElemException") + + ". index= " + index); + } + // the old NullElem is NOT shifted to the right + synDiaElem.add(index + 1, s); + // all NullElems to the right have to get new index numbers + for (int i = index + 3; i < synDiaElem.size(); i = i + 2) { + // setIndex(i + 1) because at the end a new NullElem will be + // added left of this NullElem + ((NullElem) synDiaElem.get(i)).setIndex(i + 1); + } + // a new NullElem right of the SynDiaElem + synDiaElem.add(index + 2, new NullElem(this, line, index + 2, + getMySyntaxDiagram())); + getMySyntaxDiagram().getMySynDiaSystem().changed(); + } + + /** + * Adds a terminal symbol from the undoElemStack to the + * concatenation. + * + * @param index + * index in the synDiaElem list + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public void redoAddTerminal(int index) throws NoNullElemException { + TerminalSymbol t = (TerminalSymbol) getMySyntaxDiagram() + .getMySynDiaSystem().getUndoElemStack().pop(); + addSynDiaElem(index, t); + t.getMySyntaxDiagram().getMySynDiaSystem().addTerminal(t.getLabel()); + } + + /** + * Adds a terminal symbol from the deleteElemStack to the + * concatenation. + * + * @param index + * index in the synDiaElem list + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public void undoDeleteTerminal(int index) throws NoNullElemException { + TerminalSymbol t = (TerminalSymbol) getMySyntaxDiagram() + .getMySynDiaSystem().getDeleteElemStack().pop(); + addSynDiaElem(index, t); + t.getMySyntaxDiagram().getMySynDiaSystem().addTerminal(t.getLabel()); + } + + /** + * Adds a terminal symbol to the concatenation. + * + * @param index + * index in the synDiaElem list + * @param label + * label of the terminal symbol + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public void addTerminalSymbol(int index, String label) + throws NoNullElemException { + TerminalSymbol t = new TerminalSymbol(this, label, getMySyntaxDiagram()); + addSynDiaElem(index, t); + t.getMySyntaxDiagram().getMySynDiaSystem().addTerminal(t.getLabel()); + } + + /** + * Adds a variable from the undoElemStack to the + * concatenation.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.addVariable(retValueOfThisFunction) + * after calling this function! + * + * @param index + * index in the synDiaElem list + * @return the variable + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public Variable redoAddVariable(int index) throws NoNullElemException { + Variable v = (Variable) getMySyntaxDiagram().getMySynDiaSystem() + .getUndoElemStack().pop(); + addSynDiaElem(index, v); + return v; + } + + /** + * Adds a variable from the deleteElemStack to the + * concatenation.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.addVariable(retValueOfThisFunction) + * after calling this function! + * + * @param index + * index in the synDiaElem list + * @return the variable + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public Variable undoDeleteVariable(int index) throws NoNullElemException { + Variable v = (Variable) getMySyntaxDiagram().getMySynDiaSystem() + .getDeleteElemStack().pop(); + addSynDiaElem(index, v); + return v; + } + + /** + * Adds a variable to the concatenation.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.addVariable(retValueOfThisFunction) + * after calling this function! + * + * @param index + * index in the synDiaElem list + * @param label + * label of the variable + * @return the new variable + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public Variable addVariable(int index, String label) + throws NoNullElemException { + Variable v = new Variable(this, label, getMySyntaxDiagram()); + addSynDiaElem(index, v); + return v; + } + + private List addBranch(Branch b, int begin, int end) + throws NoNullElemException { + // end = begin + 2*n + if (begin > end || (begin != end && (end - begin) % 2 != 0)) { + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.BeginEndException: " + begin + ", " + end)); + } + if (!(synDiaElem.get(begin) instanceof NullElem) + || !(synDiaElem.get(end) instanceof NullElem)) { + throw new NoNullElemException(Messages.getString("ebnf", + "SynDiaModel.NoNullElemException")); + } + List retList = new ArrayList(); + // if there is something to copy + if (begin != end) { + // start with begin+1, because Branch already has NullElem + int _begin = begin + 1; + for (int i = _begin; i <= end; i++) { + // set new line and index for NullElems + if (synDiaElem.get(_begin) instanceof NullElem) { + ((NullElem) synDiaElem.get(_begin)) + .setLine(b.getLeft().line); + // i - begin, because there is already a NullElem in + // this concatenation + ((NullElem) synDiaElem.get(_begin)).setIndex(i - begin); + } + // the left side of the branch has to be new parent + synDiaElem.get(_begin).setParent(b.getLeft()); + b.getLeft().insert(synDiaElem.get(_begin)); + retList.add(synDiaElem.get(_begin)); + // delete copied elements + synDiaElem.remove(_begin); + } + } + // now add branch + addSynDiaElem(begin, b); + return retList; + } + + /** + * Adds a branch from the undoElemStack to the concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @return list with all contained syntax diagram elements + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + */ + public List redoAddBranch(int begin, int end) + throws NoNullElemException { + Branch b = (Branch) getMySyntaxDiagram().getMySynDiaSystem() + .getUndoElemStack().pop(); + return addBranch(b, begin, end); + } + + /** + * Adds a branch from the undoElemStack to the concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + */ + public void undoDeleteBranch(int begin, int end) throws NoNullElemException { + Branch b = (Branch) getMySyntaxDiagram().getMySynDiaSystem() + .getDeleteElemStack().pop(); + addBranch(b, begin, end); + // search for elements on the right side, that have wrong line and index + // numbers + Concatenation rightPath = b.getRight(); + for (int i = 0; i < rightPath.getNumberOfElems(); i++) { + rightPath.getSynDiaElem(i).setParent(rightPath); + if (rightPath.getSynDiaElem(i) instanceof NullElem) { + ((NullElem) rightPath.getSynDiaElem(i)) + .setLine(b.getRight().line); + ((NullElem) rightPath.getSynDiaElem(i)).setIndex(i); + } + } + } + + /** + * Adds a branch to the concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @return list with all contained syntax diagram elements + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + * @throws IllegalArgumentException + * Is thrown if begin > end. + */ + public List addBranch(int begin, int end) + throws NoNullElemException, IllegalArgumentException { + Branch b = new Branch(this, getMySyntaxDiagram()); + return addBranch(b, begin, end); + } + + private List addRepetition(Repetition r, int begin, int end) + throws NoNullElemException, IllegalArgumentException { + // end = begin + 2*n + if (begin > end || (begin != end && (end - begin) % 2 != 0)) { + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.BeginEndException: " + begin + ", " + end)); + } + if (!(synDiaElem.get(begin) instanceof NullElem) + || !(synDiaElem.get(end) instanceof NullElem)) { + throw new NoNullElemException(Messages.getString("ebnf", + "SynDiaModel.NoNullElemException")); + } + List retList = new ArrayList(); + // if there is something to copy + if (begin != end) { + // start with begin+1, because repetition already has NullElem + int _begin = begin + 1; + for (int i = _begin; i <= end; i++) { + // the left side of the repetition has to be new parent + synDiaElem.get(_begin).setParent(r.getLeft()); + r.getLeft().synDiaElem.add(0, (synDiaElem.get(_begin))); + retList.add(synDiaElem.get(_begin)); + // delete copied elements + synDiaElem.remove(_begin); + } + // set new line and index for NullElems + Concatenation leftPath = r.getLeft(); + for (int i = 0; i < leftPath.getNumberOfElems(); i++) { + if (leftPath.getSynDiaElem(i) instanceof NullElem) { + ((NullElem) leftPath.getSynDiaElem(i)) + .setLine(leftPath.line); + ((NullElem) leftPath.getSynDiaElem(i)).setIndex(i); + } + } + } + addSynDiaElem(begin, r); + return retList; + } + + /** + * Adds a new repetition to the concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @return list with all contained syntax diagram elements + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + * @throws IllegalArgumentException + * Is thrown if begin > end. + */ + public List addRepetition(int begin, int end) + throws IllegalArgumentException, NoNullElemException { + Repetition r = new Repetition(this, getMySyntaxDiagram()); + return addRepetition(r, begin, end); + } + + /** + * Adds a repetition from the undoElemStack to the + * concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @return list with all contained syntax diagram elements + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + * @throws IllegalArgumentException + * Is thrown if begin > end. + */ + public List redoAddRepetition(int begin, int end) + throws IllegalArgumentException, NoNullElemException { + Repetition r = (Repetition) getMySyntaxDiagram().getMySynDiaSystem() + .getUndoElemStack().pop(); + return addRepetition(r, begin, end); + } + + /** + * Adds a repetition from the deleteElemStack to the + * concatenation. + * + * @param begin + * begin index in the synDiaElem list + * @param end + * end index in the synDiaElem list + * @throws NoNullElemException + * Is thrown if begin does not point at a NullElem. + * @throws IllegalArgumentException + * Is thrown if begin > end. + */ + public void undoDeleteRepetition(int begin, int end) + throws NoNullElemException { + Repetition r = (Repetition) getMySyntaxDiagram().getMySynDiaSystem() + .getDeleteElemStack().pop(); + addRepetition(r, begin, end); + // search for elements on the right side, that have wrong line and index + // numbers + Concatenation rightPath = r.getRight(); + for (int i = 0; i < rightPath.getNumberOfElems(); i++) { + rightPath.getSynDiaElem(i).setParent(rightPath); + if (rightPath.getSynDiaElem(i) instanceof NullElem) { + ((NullElem) rightPath.getSynDiaElem(i)) + .setLine(r.getRight().line); + ((NullElem) rightPath.getSynDiaElem(i)).setIndex(i); + } + } + } + + /** + * Adds a manual word wrap to the concatenation. + * + * @param index + * index in the synDiaElem list + * @throws NoNullElemException + * Is thrown if index does not point at a NullElem. + */ + public void addWordWrap(int index) throws NoNullElemException { + WordWrap w = new WordWrap(this, getMySyntaxDiagram()); + addSynDiaElem(index, w); + } + + /** + * Fills the Concatenation with NullElems.
          + * The function is assumed that either there are no NullElems or all + * NullElems in the concatenation. + * + * @return true if NullElems were added, + * false if nothing had to be added + */ + public boolean fillWithNullElems() { + if (filledWithNullElems == true) { + return false; + } + // test, if there are already NullElems in the concatenation + if (synDiaElem.size() == 0) { + synDiaElem + .add(0, new NullElem(this, line, 0, getMySyntaxDiagram())); + filledWithNullElems = true; + return true; + } + boolean retVal = false; + // list with positions, where a NullElem has to be added + List fillList = new LinkedList(); + SynDiaElem currentElem; + for (int i = 0; i < synDiaElem.size(); i++) { + currentElem = synDiaElem.get(i); + // Branches and Repetitions have own concatenations --> fill them! + if (currentElem instanceof Branch) { + retVal = ((Branch) currentElem).fillWithNullElems(); + } else if (currentElem instanceof Repetition) { + retVal = ((Repetition) currentElem).fillWithNullElems(); + } + // all elements that are no NullElem will get a NullElem in front + if (!(currentElem instanceof NullElem)) { + retVal = true; + fillList.add(i * 2); // fill every 2nd gap + } + } + // now fill with NullElems ... + for (int i = 0; i < fillList.size(); i++) { + synDiaElem.add(fillList.get(i), new NullElem(this, line, fillList + .get(i), getMySyntaxDiagram())); + } + // ... don't forget the last element + synDiaElem.add(new NullElem(this, line, synDiaElem.size(), + getMySyntaxDiagram())); + filledWithNullElems = true; + // update the view + getMySyntaxDiagram().getMySynDiaSystem().changed(); + return retVal; + } + + /** + * Removes all NullElems in the concatenation. + * + * @return true if NullElems were removed, + * false if nothing had to be removed + */ + public boolean removeNullElems() { + if (filledWithNullElems == false) { + return false; + } + boolean retVal = false; + List removeList = new LinkedList(); + for (SynDiaElem e : synDiaElem) { + if (e instanceof Branch) { + retVal = ((Branch) e).removeNullElems(); + } else { + if (e instanceof Repetition) { + retVal = ((Repetition) e).removeNullElems(); + } else { + // if it is a NullElem add the element to the removeList + if (e instanceof NullElem) { + retVal = true; + removeList.add(e); + } + } + } + } + // remove all elements, that are in removeList + synDiaElem.removeAll(removeList); + filledWithNullElems = false; + // update the view + getMySyntaxDiagram().getMySynDiaSystem().changed(); + return retVal; + } + + /** + * Removes all elements except the first NullElem of the + * concatenation. + * + */ + public void removeAllElements() { + synDiaElem.subList(1, synDiaElem.size()).clear(); + } + + /** + * Removes a syntax diagram element from the concatenation. + * + * @param index + * index of the element to remove + * @param undoElemStack + * true if the element has to be put on the + * undoElemStack + * @param deleteStack + * true if the element has to be put on the + * deleteStack + * @return the NullElem before + */ + private NullElem removeSynDiaElem(int index, boolean undoElemStack, + boolean deleteStack) { + if (undoElemStack) { + getMySyntaxDiagram().getMySynDiaSystem().getUndoElemStack().push( + synDiaElem.get(index)); + } + if (deleteStack) { + getMySyntaxDiagram().getMySynDiaSystem().getDeleteElemStack().push( + synDiaElem.get(index)); + } + // save the NullElem BEFORE the deleted elem (for re-inserts) + NullElem retNullElem = (NullElem) synDiaElem.get(index - 1); + // push deleted element on the synDiaElemStack + synDiaElem.remove(index); + // the next element is a NullElem - delete it too + synDiaElem.remove(index); + // now update all indices of the next NullElems in the concatenation + // index + 1 --> next element surely is no NullElem + for (int i = index + 1; i < synDiaElem.size(); i++) { + if (synDiaElem.get(i) instanceof NullElem) { + ((NullElem) synDiaElem.get(i)).setIndex(i); + } + } + getMySyntaxDiagram().getMySynDiaSystem().changed(); + return retNullElem; + } + + /** + * Removes a SynDiaElem of the concatenation by an given + * SynDiaElem + * + * @param s + * the SynDiaElem to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the element is not part of the concatenation + */ + private NullElem removeSynDiaElem(SynDiaElem s, boolean undoElemStack, + boolean deleteStack) throws ElementNotFoundException { + for (int i = 0; i < synDiaElem.size(); i++) { + if (synDiaElem.get(i) == s) { + return removeSynDiaElem(i, undoElemStack, deleteStack); + } + } + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + + /** + * Removes a syntax diagram element that is neither pushed on the + * undoElemStack + * nor deleteElemStack. + * + * @param sde + * the sde to delete + * @throws ElementNotFoundException + * is thrown if the given element is no part of the + * concatenation. + */ + public void removeSynDiaElemCompletely(SynDiaElem sde) + throws ElementNotFoundException { + removeSynDiaElem(sde, false, false); + } + + /** + * Removes a terminal symbol from the concatenation and pushes it on the + * deleteElemStack. + * + * @param t + * a reference to the terminal symbol to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the terminal symbol is not part of the + * concatenation + */ + public NullElem deleteTerminal(TerminalSymbol t) + throws ElementNotFoundException { + t.getMySyntaxDiagram().getMySynDiaSystem().removeTerminal(t.getLabel()); + return removeSynDiaElem(t, false, true); + + } + + /** + * Removes a terminal symbol from the concatenation. + * + * @param t + * a reference to the terminal symbol to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the terminal symbol is not part of the + * concatenation + */ + public NullElem removeTerminalSymbol(TerminalSymbol t) + throws ElementNotFoundException { + t.getMySyntaxDiagram().getMySynDiaSystem().removeTerminal(t.getLabel()); + return removeSynDiaElem(t, true, false); + } + + /** + * Removes a terminal symbol from the concatenation. + * + * @param index + * index of the terminal symbol to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if element at index is not of type + * TerminalSymbol + */ + public NullElem removeTerminalSymbol(int index) + throws ElementNotFoundException { + if (!(synDiaElem.get(index) instanceof TerminalSymbol)) { + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + TerminalSymbol t = (TerminalSymbol) (synDiaElem.get(index)); + t.getMySyntaxDiagram().getMySynDiaSystem().removeTerminal(t.getLabel()); + return removeSynDiaElem(index, true, false); + } + + /** + * Removes a variable from the concatenation and pushes it on the + * deleteElemStack.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.removeVariable(removedVariable) + * after calling this function! + * + * @param v + * reference to the variable to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the variable is not part of the concatenation + */ + public NullElem deleteVariable(Variable v) throws ElementNotFoundException { + return removeSynDiaElem(v, false, true); + } + + /** + * Removes a variable from the concatenation.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.removeVariable(removedVariable) + * after calling this function! + * + * @param v + * reference to the variable to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the variable is not part of the concatenation + */ + public NullElem removeVariable(Variable v) throws ElementNotFoundException { + return removeSynDiaElem(v, true, false); + } + + /** + * Removes a variable from the concatenation.
          + * IMPORTANT: If this concatenation is part of a syntax diagram + * system, you have to call SynDiaSystem.removeVariable(removedVariable) + * after calling this function! + * + * @param index + * index of the variable to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if element at index is not of type + * Variable + */ + public NullElem removeVariable(int index) throws ElementNotFoundException { + if (!(synDiaElem.get(index) instanceof Variable)) { + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + return removeSynDiaElem(index, true, false); + } + + private void copyPath(Concatenation path, int index) { + for (int i = 1; i < path.getNumberOfElems(); i++) { + SynDiaElem leftPathSde = path.getSynDiaElem(i); + path.getSynDiaElem(i).setParent(this); + // set new line and index for NullElems + if (leftPathSde instanceof NullElem) { + ((NullElem) leftPathSde).setLine(line); + } + synDiaElem.add(index + i - 1, leftPathSde); + } + // if it is the left path, update all NullElems of the concatenation + for (int i = 0; i < synDiaElem.size(); i++) { + if (synDiaElem.get(i) instanceof NullElem) { + ((NullElem) synDiaElem.get(i)).setIndex(i); + } + } + } + + /** + * Removes a repetition from the concatenation and pushes it on the + * deleteElemStack. + * + * @param r + * reference to the repetition to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the repetition is not part of the concatenation + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem deleteRepetition(Repetition r, boolean left, boolean right) + throws IllegalArgumentException, ElementNotFoundException { + NullElem retNullElem = removeRepetition(r, left, right, true); + return retNullElem; + } + + /** + * Removes a repetition from the concatenation. + * + * @param r + * reference to the repetition to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @param delete + * true if the element will be put on delete stack + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the repetition is not part of the concatenation + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem removeRepetition(Repetition r, boolean left, boolean right, + boolean delete) throws ElementNotFoundException, + IllegalArgumentException { + for (int i = 0; i < synDiaElem.size(); i++) { + if (synDiaElem.get(i) == r) { + return removeRepetition(i, left, right, delete); + } + } + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + + /** + * Removes a repetition from the concatenation. + * + * @param index + * index of the repetition to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @param delete + * true if the element will be put on delete stack + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if element at index is not of type + * Repetition + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem removeRepetition(int index, boolean left, boolean right, + boolean delete) throws ElementNotFoundException, + IllegalArgumentException { + if (!(synDiaElem.get(index) instanceof Repetition)) { + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + if (left && right) { + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.LeftAndRightPathException")); + } + // preserve upper path + Repetition currentRep = (Repetition) synDiaElem.get(index); + if (left) { + // save old left path + Concatenation leftPath = currentRep.getLeft(); + // remove repetition + NullElem retNullElem = removeSynDiaElem(index, !delete, delete); + copyPath(leftPath, index); + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + currentRep.getLeft().removeAllElements(); + return retNullElem; + } else { + // preserve lower path --> switch elements + if (right) { + // save old right path + Concatenation rightPath = currentRep.getRight(); + // remove repetition + NullElem retNullElem = removeSynDiaElem(index, !delete, delete); + // insert old right path in reverse order in the current + // concatenation + copyPath(rightPath, index); + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + return retNullElem; + } else { + // if nothing has to be saved, simply remove repetition + currentRep.getLeft().removeAllElements(); + currentRep.getRight().removeAllElements(); + return removeSynDiaElem(index, !delete, delete); + } + } + } + + /** + * Removes a branch from the concatenation and pushes it on the + * deleteElemStack. + * + * @param b + * reference to the branch to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the branch is not part of the concatenation + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem deleteBranch(Branch b, boolean left, boolean right) + throws IllegalArgumentException, ElementNotFoundException { + NullElem retNullElem = removeBranch(b, left, right, true); + return retNullElem; + } + + /** + * Removes a branch from the concatenation. + * + * @param b + * reference to the branch to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @param delete + * true if the element will be put on delete stack + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the branch is not part of the concatenation + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem removeBranch(Branch b, boolean left, boolean right, + boolean delete) throws ElementNotFoundException, + IllegalArgumentException { + for (int i = 0; i < synDiaElem.size(); i++) { + if (synDiaElem.get(i) == b) { + return removeBranch(i, left, right, delete); + } + } + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + + /** + * Removes a branch from the concatenation. + * + * @param index + * index of the branch to remove + * @param left + * true if you want to preserve left path + * @param right + * false if you want to preserve right path + * @param delete + * true if the element will be put on delete stack + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if element at index is not of type + * Branch + * @throws IllegalArgumentException + * Is thrown if right and left are + * both true + */ + public NullElem removeBranch(int index, boolean left, boolean right, + boolean delete) throws ElementNotFoundException, + IllegalArgumentException { + if (!(synDiaElem.get(index) instanceof Branch)) { + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + if (left && right) { + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.LeftAndRightPathException")); + } + // see @removeRepetition() + Branch currentBranch = (Branch) synDiaElem.get(index); + if (left) { + Concatenation leftPath = currentBranch.getLeft(); + NullElem retNullElem = removeSynDiaElem(index, !delete, delete); + copyPath(leftPath, index); + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + currentBranch.getLeft().removeAllElements(); + return retNullElem; + } else { + if (right) { + Concatenation rightPath = currentBranch.getRight(); + NullElem retNullElem = removeSynDiaElem(index, !delete, delete); + copyPath(rightPath, index); + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + return retNullElem; + } else { + // if nothing has to be saved, simply remove branch + currentBranch.getRight().removeAllElements(); + currentBranch.getLeft().removeAllElements(); + return removeSynDiaElem(index, !delete, delete); + } + } + } + + /** + * Removes a word wrap from the concatenation. + * + * @param w + * reference to the word wrap to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if the word wrap is not part of the concatenation + */ + public NullElem removeWordWrap(WordWrap w) throws ElementNotFoundException { + return removeSynDiaElem(w, true, false); + } + + /** + * Removes a manual word wrap from the concatenation. + * + * @param index + * index of the word wrap to remove + * @return the NullElem before + * @throws ElementNotFoundException + * Is thrown if element at index is not of type + * WordWrap + */ + public NullElem removeWordWrap(int index) throws ElementNotFoundException { + if (!(synDiaElem.get(index) instanceof WordWrap)) { + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + return removeSynDiaElem(index, true, false); + } + + /** + * This function deletes all elements in the concatenation! + * + */ + public void deleteAllElements() { + synDiaElem.clear(); + } + + /** + * Returns true if concatenation is empty (NullElems do not + * count!). + * + * @return true if concatenation is empty (NullElems do not + * count!) + */ + public boolean isEmpty() { + if (filledWithNullElems) { + if (synDiaElem.size() == 1) + return true; + return false; + } else { + return synDiaElem.isEmpty(); + } + } + + public String toString() { + String retStr = "< "; + for (int i = 0; i < synDiaElem.size(); i++) { + retStr += synDiaElem.get(i).toString(); + // last String does not need a comma + if (i < synDiaElem.size() - 1) { + retStr += ", "; + } + } + return retStr + " > "; + } + + /** + * For test cases: returns a String with lines and indices of NullElems. + * + * @return String with NullElems + */ + public String printNullElems() { + String retStr = "< "; + for (int i = 0; i < synDiaElem.size(); i++) { + if (i % 2 == 0) { + retStr += ((NullElem) synDiaElem.get(i)).getLine(); + retStr += ", " + ((NullElem) synDiaElem.get(i)).getIndex(); + } else if (synDiaElem.get(i) instanceof Branch) { + retStr += "[ " + + ((Branch) synDiaElem.get(i)).getLeft() + .printNullElems(); + retStr += " : " + + ((Branch) synDiaElem.get(i)).getRight() + .printNullElems() + " ] "; + } else if (synDiaElem.get(i) instanceof Repetition) { + retStr += "{ " + + ((Repetition) synDiaElem.get(i)).getLeft() + .printNullElems(); + retStr += " : " + + ((Repetition) synDiaElem.get(i)).getRight() + .printNullElems() + " } "; + } + // last String does not need a comma + if (i < synDiaElem.size() - 1) { + retStr += "; "; + } + } + return retStr + " > "; + } + +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.java b/src/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.java new file mode 100644 index 0000000..2929fa6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/ElementNotFoundException.java @@ -0,0 +1,51 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +/** + * Exception is thrown if a syntax diagram element is not found in a + * concatenation. + * + * @author Michael Thiele + */ +public class ElementNotFoundException extends Exception { + + private static final long serialVersionUID = 3856852545129151653L; + + /** + * + * + */ + public ElementNotFoundException() { + super(); + } + + /** + * + * @param message + */ + public ElementNotFoundException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/NoNullElemException.java b/src/org/jalgo/module/ebnf/model/syndia/NoNullElemException.java new file mode 100644 index 0000000..3a8ad5f --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/NoNullElemException.java @@ -0,0 +1,58 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/** + * Exception is thrown if you want to add a new syntax diagram element at a + * position of a concatenation, where no NullElem is located. + * + * @author Michael Thiele + */ +package org.jalgo.module.ebnf.model.syndia; + +/** + * Exception that is thrown if you try to insert an element at a position that + * has no NullElement. + * + * @author Michael Thiele + * + */ +public class NoNullElemException extends Exception { + + private static final long serialVersionUID = -6819655720873059669L; + + /** + * + * + */ + public NoNullElemException() { + super(); + } + + /** + * + * @param message + */ + public NoNullElemException(String message) { + super(message); + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/NullElem.java b/src/org/jalgo/module/ebnf/model/syndia/NullElem.java new file mode 100644 index 0000000..64a3a0d --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/NullElem.java @@ -0,0 +1,95 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +/** + * The class NullElem represents a location in the syntax + * diagram, where new elements can be added. Use the getIndex() function to + * determine where to add new elements in a Concatenation. + * + * @author Michael Thiele + */ +public class NullElem extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private int line; + + private int index; + + /** + * Constructs a NullElem. + * + * @param parent + * parent of the element + * @param line + * the number of the concatenation + * @param index + * the position inside the concatenation + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public NullElem(SynDiaElem parent, int line, int index, + SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + this.line = line; + this.index = index; + + } + + /** + * @return Returns the number of the Concatenation the + * NullElem is in. + */ + public int getLine() { + return line; + } + + /** + * @return Returns the index inside of a Concatenation. + */ + public int getIndex() { + return index; + } + + /** + * @param index + * the new index + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * @param line + * the new line + */ + public void setLine(int line) { + this.line = line; + } + + public String toString() { + return "NullElem"; + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/Repetition.java b/src/org/jalgo/module/ebnf/model/syndia/Repetition.java new file mode 100644 index 0000000..221468a --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/Repetition.java @@ -0,0 +1,120 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +/** + * This class is the model of a repetition. It consists of two concatenations: + * left and right. + * + * @author Michael Thiele + */ +public class Repetition extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private Concatenation left; + + private Concatenation right; + + /** + * Constructs a Repetition. + * + * @param parent + * parent of the element + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public Repetition(SynDiaElem parent, SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + left = new Concatenation(this, mySyntaxDiagram); + right = new Concatenation(this, mySyntaxDiagram); + } + + /** + * @return The left concatenation, which is the upper one when rendered. + */ + public Concatenation getLeft() { + return left; + } + + /** + * @return The right concatenation, which is the lower one when rendered. + */ + public Concatenation getRight() { + return right; + } + + /** + * Removes all NullElems from the Repetition. + * + * @return true if NullElems were removed, + * false if nothing had to be removed + */ + public boolean removeNullElems() { + boolean retVal = false; + retVal = left.removeNullElems(); + retVal |= right.removeNullElems(); + return retVal; + } + + /** + * Fills the Repetition with NullElems. + * + * @return true if NullElems were added, + * false if nothing had to be added + */ + public boolean fillWithNullElems() { + boolean retVal = false; + retVal = left.fillWithNullElems(); + retVal |= right.fillWithNullElems(); + return retVal; + } + + /** + * Tests if Repetiton has to save elements in right or + * reverse order + * + * @return true if elements are in right order
          + * false if elements are in reverse order + */ + public boolean rightOrder() { + boolean retVal = false; + SynDiaElem s = this; + // get all parents + while (s != null) { + s = s.getParent(); + // each repetition changes the order + if (s instanceof Repetition) { + retVal = !retVal; + } + } + return retVal; + } + + public String toString() { + return "{ Repetition: " + left.toString() + ": " + right.toString() + + "}"; + } + +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/SynDiaElem.java b/src/org/jalgo/module/ebnf/model/syndia/SynDiaElem.java new file mode 100644 index 0000000..de9c80d --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/SynDiaElem.java @@ -0,0 +1,81 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import java.io.Serializable; + +/** + * SynDiaElem is the super class of all syntax diagram model + * classes. It provides the knowledge of its parent. + * + * @author Michael Thiele + */ +public abstract class SynDiaElem implements Serializable { + + private static final long serialVersionUID = 1L; + + private SynDiaElem parent; + + private SyntaxDiagram mySyntaxDiagram; + + /** + * Constructs an abstract SynDiaElem. + * + * @param parent + * parent of the element + * @param mySyntaxDiagram + * the syntax diagram the element belongs to + */ + public SynDiaElem(SynDiaElem parent, SyntaxDiagram mySyntaxDiagram) { + this.parent = parent; + this.mySyntaxDiagram = mySyntaxDiagram; + } + + /** + * @return Returns the parent of the element. + */ + public SynDiaElem getParent() { + return parent; + } + + /** + * Sets the new parent for the syntax diagram element + * + * @param parent + * new parent + */ + public void setParent(SynDiaElem parent) { + this.parent = parent; + } + + /** + * + * @return the syntax diagram the element belongs to + */ + public SyntaxDiagram getMySyntaxDiagram() { + return mySyntaxDiagram; + } + + public abstract String toString(); +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.java b/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.java new file mode 100644 index 0000000..cb1f3fe --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystem.java @@ -0,0 +1,419 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Stack; + +import org.jalgo.main.util.Messages; + +/** + * A SynDiaSystem consists of many SyntaxDiagrams. + * It administrates all Variables and + * TerminalSymbols to know, if the system is consistent.
          + * The startDiagram is the label of the first element in the list of variables. + * + * @author Michael Thiele + */ +public class SynDiaSystem extends Observable implements Serializable { + + private static final long serialVersionUID = 1L; + + private String startDiagram; + + private List variables; + + private List terminals; + + /** + * List with all syntax diagrams. + */ + private List syntaxDiagrams; + + /** + * The deleteStack is used to keep track, what elements were + * deleted through the "rubber". If an element is removed of the + * concatenation, it is pushed on this stack to possibly re-insert it again + * at the same position with the same attributes (e.g. line number and left + * and right side for branches and repetitions). + */ + private Stack deleteElemStack = new Stack(); + + /** + * Elements are pushed on the undoElemStack if they were + * removed by clicking "undo". + */ + private Stack undoElemStack = new Stack(); + + /** + * Syntax diagrams that were deleted come to this stack. + */ + private Stack deleteSynDiaStack; + + /** + * Syntax diagrams that were removed (through "undo") are put on this stack. + */ + private Stack undoSynDiaStack; + + /** + * Constructs a syntax diagram system without a start diagram. + */ + public SynDiaSystem() { + variables = new LinkedList(); + terminals = new LinkedList(); + syntaxDiagrams = new LinkedList(); + deleteSynDiaStack = new Stack(); + undoSynDiaStack = new Stack(); + } + + /** + * Constructs a syntax diagram system with a start diagram. + * + * @param startDiagram + * the start diagram + */ + public SynDiaSystem(String startDiagram) { + this(); + this.addSyntaxDiagram(startDiagram); + this.startDiagram = startDiagram; + } + + /** + * @param startDiagram + * the new start diagram + */ + public void setStartDiagram(String startDiagram) { + this.startDiagram = startDiagram; + } + + /** + * @return Returns the name of the start diagram. + */ + public String getStartDiagram() { + return startDiagram; + } + + /** + * Checks, if the syntax diagram is complete. That means, all variables are + * the start variable of a syntax diagram. + * + * @return true if system is complete
          + */ + public boolean isComplete() { + boolean retVal; + for (String var : variables) { + retVal = false; + for (int i = 0; i < syntaxDiagrams.size(); i++) { + if (syntaxDiagrams.get(i).getName().equals(var)) { + retVal = true; + break; + } + } + if (retVal == false) { + return false; + } + } + return true; + } + + /** + * Returns the deleteElemStack that is used to re-insert + * syntax diagram elements that were deleted by the "rubber". + * + * @return the deletedElemStack + */ + public Stack getDeleteElemStack() { + return deleteElemStack; + } + + /** + * Returns the undoElemStack that is used to re-insert syntax + * diagram elements that were removed by "undo". + * + * @return the undoElemStack + */ + public Stack getUndoElemStack() { + return undoElemStack; + } + + /** + * @return Returns the size of the syntax diagram list. + */ + public int getNumberOfDiagrams() { + return syntaxDiagrams.size(); + } + + /** + * Returns a list with all labels of variables in the syntax diagram system. + * + * @return a list with all labels of variables in the syntax diagram system. + */ + public List getLabelsOfVariables() { + List retList = new LinkedList(); + for (SyntaxDiagram sd : syntaxDiagrams) { + retList.add(sd.getName()); + } + return retList; + } + + /** + * Returns a list with all labels of terminal symbols in the syntax diagram + * system. + * + * @return a list with all labels of terminal symbols in the syntax diagram + * system. + */ + public List getLabelsOfTerminals() { + List retList = new LinkedList(); + for (String label : terminals) { + if (!retList.contains(label)) { + retList.add(label); + } + } + return retList; + } + + /** + * @param name + * name of the syntax diagram + * @return the syntax diagram + * @throws ElementNotFoundException + * Is thrown if no syntax diagram with the given name exists in + * the syntax diagram system. + */ + public SyntaxDiagram getSyntaxDiagram(String name) + throws ElementNotFoundException { + for (SyntaxDiagram s : syntaxDiagrams) { + if (s.getName().equals(name)) { + return s; + } + } + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException") + + "; " + name); + } + + private void addSyntaxDiagram(SyntaxDiagram s) { + syntaxDiagrams.add(s); + if (syntaxDiagrams.size() == 1) { + startDiagram = s.getName(); + } + setChanged(); + } + + /** + * Adds a syntax diagram to the syntax diagram system. + * + * @param name + * name of the new syntax diagram + */ + public void addSyntaxDiagram(String name) { + SyntaxDiagram s = new SyntaxDiagram(name, this); + addSyntaxDiagram(s); + } + + /** + * Adds a syntax diagram that is popped from the undoSynDiaStack. + * + */ + public void undoRemoveSyntaxDiagram() { + SyntaxDiagram s = undoSynDiaStack.pop(); + addSyntaxDiagram(s); + } + + /** + * Adds a syntax diagram that is popped from the deleteSynDiaStack. + * + */ + public void undoDeleteSyntaxDiagram() { + SyntaxDiagram s = deleteSynDiaStack.pop(); + addSyntaxDiagram(s); + } + + /** + * Insert a complete syntax diagram in the syntax diagram system. + * + * @param s + * the syntax diagram to insert + */ + public void insertSyntaxDiagram(SyntaxDiagram s) { + syntaxDiagrams.add(s); + setChanged(); + } + + /** + * Removes a syntax diagram by a given name. + * + * @param name + * The name of the syntax diagram to remove. + * @param delete + * true if the diagram will be deleted + * @return true if the list contained the syntax diagram + * @throws ElementNotFoundException + * Is thrown if no syntax diagram with the given name exists in + * the syntax diagram system. + * @throws IllegalArgumentException + * Is thrown if you try to delete the start diagram. + */ + public boolean removeSyntaxDiagram(String name, boolean delete) + throws ElementNotFoundException, IllegalArgumentException { + if (name.equals(startDiagram)) { + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.DeleteStartDiagramException")); + } + for (SyntaxDiagram s : syntaxDiagrams) { + if (s.getName().equals(name)) { + if (delete) + deleteSynDiaStack.push(s); + else + undoSynDiaStack.push(s); + boolean retVal = syntaxDiagrams.remove(s); + setChanged(); + return retVal; + } + } + throw new ElementNotFoundException(Messages.getString("ebnf", + "SynDiaModel.ElementNotFoundException")); + } + + /** + * Removes an element of the variable list. + * + * @param variable + * the Variable to remove + * @return true if the list contained the variable + */ + public boolean removeVariable(String variable) { + return variables.remove(variable); + } + + /** + * Removes a terminal symbol of the terminal symbol list. + * + * @param terminal + * the terminal to remove + * @return true if the list contained the terminal symbol + */ + boolean removeTerminal(String terminal) { + return terminals.remove(terminal); + } + + /** + * Adds a variable. + * + * @param variable + * the variable to add + * @return true if the variable was added to the variable + * list + */ + public boolean addVariable(String variable) { + return variables.add(variable); + } + + /** + * Returns the list with all variables in the syntax diagram system. + * + * @return the list with all variables in the syntax diagram system + */ + public List getVariables() { + List retList = new LinkedList(); + for (String label : variables) { + if (!retList.contains(label)) { + retList.add(label); + } + } + return retList; + } + + /** + * Adds a terminal symbol. + * + * @param terminal + * the terminal symbol to add + * @return true if the terminal symbol was added to the + * terminal symbol list + */ + boolean addTerminal(String terminal) { + return terminals.add(terminal); + } + + /** + * Fills the whole syntax diagram system with NullElems. + * + * @return true if a new NullElem was added. + */ + public boolean fillWithNullElems() { + boolean retVal = false; + for (SyntaxDiagram s : syntaxDiagrams) { + retVal |= s.fillWithNullElems(); + } + changed(); + return retVal; + } + + /** + * Removes all NullElems in the whole syntax diagram system. + * + * @return true if a NullElem was removed. + */ + public boolean removeNullElems() { + boolean retVal = false; + for (SyntaxDiagram s : syntaxDiagrams) { + retVal |= s.removeNullElems(); + } + changed(); + return retVal; + } + + /** + * This function is used by elements of the syntax diagram system to signal + * that something has been changed. + * + */ + void changed() { + setChanged(); + } + + public String toString() { + String retString = ""; + for (SyntaxDiagram s : syntaxDiagrams) { + retString += s.toString() + "\n"; + } + return retString; + } + + /** + * @return String with all NullElems + */ + public String printNullElems() { + String retString = ""; + for (SyntaxDiagram s : syntaxDiagrams) { + retString += s.printNullElems() + "\n"; + } + return retString; + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.java b/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.java new file mode 100644 index 0000000..5327a9e --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/SynDiaSystemLibrary.java @@ -0,0 +1,139 @@ +package org.jalgo.module.ebnf.model.syndia; + +/** + * Creates syntax diagram systems + * + * @author MichA + * + */ +public class SynDiaSystemLibrary { + + static { + setUpSyntaxDiagrams(); + } + + private static SynDiaSystem sds1, sds2; + + private static void setUpSyntaxDiagrams() { + // sds1 aus Skript S.152 + sds1 = new SynDiaSystem("S"); + sds1.addSyntaxDiagram("A"); + // Wichtig: bis auf StartVariable müssen ALLE Variablen in das sds "per + // Hand" eingefügt werden!!! + sds1.addVariable("A"); + // sds2 frei erfunden... + sds2 = new SynDiaSystem("Start"); + sds2.addSyntaxDiagram("Diagram1"); + sds2.addVariable("Diagram1"); + sds2.addSyntaxDiagram("Diagram2"); + sds2.addVariable("Diagram2"); + sds2.addSyntaxDiagram("Diagram3"); + sds2.addVariable("Diagram3"); + // Füllen von Syntaxdiagrammsystem 1 + try { + sds1.getSyntaxDiagram("S").getRoot().addRepetition(0, 0); + ((Repetition) sds1.getSyntaxDiagram("S").getRoot().getSynDiaElem(1)) + .getRight().addTerminalSymbol(0, "c"); + sds1.getSyntaxDiagram("S").getRoot().addVariable(2, "A"); + sds1.addVariable("A"); + // ---- + sds1.getSyntaxDiagram("A").getRoot().addBranch(0, 0); + ((Branch) sds1.getSyntaxDiagram("A").getRoot().getSynDiaElem(1)) + .getLeft().addTerminalSymbol(0, "a"); + ((Branch) sds1.getSyntaxDiagram("A").getRoot().getSynDiaElem(1)) + .getLeft().addTerminalSymbol(2, "b"); + ((Branch) sds1.getSyntaxDiagram("A").getRoot().getSynDiaElem(1)) + .getLeft().addVariable(2, "A"); + sds1.addVariable("A"); + ((Branch) sds1.getSyntaxDiagram("A").getRoot().getSynDiaElem(1)) + .getRight().addTerminalSymbol(0, "a"); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (NoNullElemException e) { + e.printStackTrace(); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + } + // Füllen von Syntaxdiagrammsystem 2 + try { + sds2.getSyntaxDiagram("Start").getRoot().addTerminalSymbol(0, "a"); + sds2.getSyntaxDiagram("Start").getRoot().addVariable(2, "Diagram1"); + sds2.addVariable("Diagram1"); + sds2.getSyntaxDiagram("Start").getRoot().addRepetition(4, 4); + sds2.getSyntaxDiagram("Start").getRoot().addTerminalSymbol(6, "c"); + ((Repetition) sds2.getSyntaxDiagram("Start").getRoot() + .getSynDiaElem(5)).getLeft().addTerminalSymbol(0, "b"); + ((Repetition) sds2.getSyntaxDiagram("Start").getRoot() + .getSynDiaElem(5)).getRight().addVariable(0, "Diagram2"); + sds2.addVariable("Diagram2"); + // ---- 2 + sds2.getSyntaxDiagram("Diagram1").getRoot().addTerminalSymbol(0, + "a"); + sds2.getSyntaxDiagram("Diagram1").getRoot().addTerminalSymbol(2, + "b"); + sds2.getSyntaxDiagram("Diagram1").getRoot().addVariable(4, + "Diagram3"); + sds2.addVariable("Diagram3"); + sds2.getSyntaxDiagram("Diagram1").getRoot().addTerminalSymbol(6, + "b"); + sds2.getSyntaxDiagram("Diagram1").getRoot().addTerminalSymbol(8, + "c"); + sds2.getSyntaxDiagram("Diagram1").getRoot().addBranch(2, 8); + ((Branch) sds2.getSyntaxDiagram("Diagram1").getRoot() + .getSynDiaElem(3)).getRight().addTerminalSymbol(0, "a"); + // ---- 3 + sds2.getSyntaxDiagram("Diagram2").getRoot().addTerminalSymbol(0, + "e"); + sds2.getSyntaxDiagram("Diagram2").getRoot().addVariable(2, + "Diagram2"); + sds2.addVariable("Diagram2"); + sds2.getSyntaxDiagram("Diagram2").getRoot().addBranch(2, 4); + sds2.getSyntaxDiagram("Diagram2").getRoot().addRepetition(2, 4); + ((Repetition) sds2.getSyntaxDiagram("Diagram2").getRoot() + .getSynDiaElem(3)).getRight().addTerminalSymbol(0, "g"); + ((Repetition) sds2.getSyntaxDiagram("Diagram2").getRoot() + .getSynDiaElem(3)).getRight().addTerminalSymbol(2, "f"); + ((Repetition) sds2.getSyntaxDiagram("Diagram2").getRoot() + .getSynDiaElem(3)).getRight().addRepetition(2, 2); + ((Repetition) ((Repetition) sds2.getSyntaxDiagram("Diagram2") + .getRoot().getSynDiaElem(3)).getRight().getSynDiaElem(3)) + .getRight().addTerminalSymbol(0, "a"); + ((Repetition) ((Repetition) sds2.getSyntaxDiagram("Diagram2") + .getRoot().getSynDiaElem(3)).getRight().getSynDiaElem(3)) + .getRight().addTerminalSymbol(2, "b"); + // ---- 4 + sds2.getSyntaxDiagram("Diagram3").getRoot().addBranch(0, 0); + ((Branch) sds2.getSyntaxDiagram("Diagram3").getRoot() + .getSynDiaElem(1)).getRight().addBranch(0, 0); + ((Branch) sds2.getSyntaxDiagram("Diagram3").getRoot() + .getSynDiaElem(1)).getRight().addTerminalSymbol(2, "b"); + ((Branch) ((Branch) sds2.getSyntaxDiagram("Diagram3").getRoot() + .getSynDiaElem(1)).getRight().getSynDiaElem(1)).getRight() + .addTerminalSymbol(0, "c"); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (NoNullElemException e) { + e.printStackTrace(); + } catch (ElementNotFoundException e) { + e.printStackTrace(); + } + } + + /** + * + * @return syntax diagram system 1 + */ + public static SynDiaSystem getSynDiaSystem1() { + return sds1; + } + + /** + * + * @return syntax diagram system 2 + */ + public static SynDiaSystem getSynDiaSystem2() { + // System.out.println("sds2: " + sds2); + // System.out.println("sds2: " + sds2.printNullElems()); + return sds2; + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.java b/src/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.java new file mode 100644 index 0000000..96b80f0 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/SyntaxDiagram.java @@ -0,0 +1,137 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import java.io.Serializable; + +/** + * A SyntaxDiagram. It can be strict, so that all + * Concatenations have to be binary. + * + * @author Michael Thiele + */ +public class SyntaxDiagram implements Serializable { + + private static final long serialVersionUID = 1L; + + private boolean isStrict; + + private String name; + + private Concatenation root; + + private SynDiaSystem mySynDiaSystem; + + /** + * Constructs a syntax diagram that is non strict. + * + * @param name + * the name of this syntax diagram + * @param sds + * the syntax diagram system this syntax diagram belongs to + */ + public SyntaxDiagram(String name, SynDiaSystem sds) { + isStrict = false; + root = new Concatenation(null, this); + this.name = name; + mySynDiaSystem = sds; + } + + /** + * @return Returns the root element of the syntax diagram. + */ + public Concatenation getRoot() { + return root; + } + + /** + * @return Returns the start variable of the syntax diagram. + */ + public String getName() { + return name; + } + + /** + * Sets the new name of the syntax diagram. + * + * @param name + * the new name + */ + public void setName(String name) { + this.name = name; + mySynDiaSystem.changed(); + } + + /** + * @return Returns true, if the parentheses are correct + * (left-associative). If concatenations can have more than 2 items + * it returns false + */ + public boolean isStrict() { + return isStrict; + } + + /** + * Fills the syntax diagram with NullElems. Has to be called + * when a syntax diagram is loaded and then edited. + * + * @return true if NullElems were added, + * false if nothing had to be added + */ + public boolean fillWithNullElems() { + return root.fillWithNullElems(); + } + + /** + * Removes all NullElems from the syntax diagram. Has to be + * called when editor mode is over. + * + * @return true if NullElems were removed, + * false if nothing had to be removed + */ + public boolean removeNullElems() { + return root.removeNullElems(); + } + + /** + * + * @return the syntax diagram system this syntax diagram belongs to + */ + public SynDiaSystem getMySynDiaSystem() { + return mySynDiaSystem; + } + + public String toString() { + return root.toString(); + } + + /** + * Only for test purposes: prints NullElems. + * + * @return NullElems + */ + public String printNullElems() { + return root.printNullElems(); + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.java b/src/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.java new file mode 100644 index 0000000..c35ce36 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.java @@ -0,0 +1,84 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import org.jalgo.main.util.*; + +/** + * A TerminalSymbol has a label. + * + * @author Michael Thiele + */ +public class TerminalSymbol extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private String label; + + /** + * Constructs a terminal Symbol. + * + * @param parent + * parent of the element + * @param label + * label of the terminal symbol + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public TerminalSymbol(SynDiaElem parent, String label, + SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + if (label == null || label.trim().equals("")) + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.EmptyNameException")); + this.label = label; + } + + /** + * @return Returns the label of the terminal symbol. + */ + public String getLabel() { + return label; + } + + /** + * Sets the label name. + * + * @param label + * label of the terminal symbol + */ + public void setLabel(String label) { + if (label == null || label.trim().equals("")) + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.EmptyNameException")); + this.getMySyntaxDiagram().getMySynDiaSystem().removeTerminal(this.label); + this.label = label; + this.getMySyntaxDiagram().getMySynDiaSystem().addTerminal(this.label); + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + } + + public String toString() { + return "Terminal: " + label; + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/Variable.java b/src/org/jalgo/module/ebnf/model/syndia/Variable.java new file mode 100644 index 0000000..75a65dd --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/Variable.java @@ -0,0 +1,82 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +import org.jalgo.main.util.Messages; + +/** + * A Variable has a label. + * + * @author Michael Thiele + */ +public class Variable extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + private String label; + + /** + * Constructs a variable. + * + * @param parent + * parent of the element + * @param label + * label of the variable + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public Variable(SynDiaElem parent, String label, + SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + if (label == null || label.trim().equals("")) + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.EmptyNameException")); + this.label = label; + } + + /** + * @return Returns the label of the variable. + */ + public String getLabel() { + return label; + } + + /** + * Sets the label name. + * + * @param label + * label of the variable + */ + public void setLabel(String label) { + if (label == null || label.trim().equals("")) + throw new IllegalArgumentException(Messages.getString("ebnf", + "SynDiaModel.EmptyNameException")); + this.label = label; + this.getMySyntaxDiagram().getMySynDiaSystem().changed(); + } + + public String toString() { + return "Variable: " + label; + } +} diff --git a/src/org/jalgo/module/ebnf/model/syndia/WordWrap.java b/src/org/jalgo/module/ebnf/model/syndia/WordWrap.java new file mode 100644 index 0000000..0d37617 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/syndia/WordWrap.java @@ -0,0 +1,50 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.ebnf.model.syndia; + +/** + * Manually inserted WordWrap + * + * @author Michael Thiele + */ +public class WordWrap extends SynDiaElem { + + private static final long serialVersionUID = 1L; + + /** + * Constructs a word wrap. + * + * @param parent + * parent of the element + * @param mySyntaxDiagram + * the syntax diagram this element belongs to + */ + public WordWrap(SynDiaElem parent, SyntaxDiagram mySyntaxDiagram) { + super(parent, mySyntaxDiagram); + } + + public String toString() { + return "WordWrap"; + } +} diff --git a/src/org/jalgo/module/ebnf/model/trans/CVS/Entries b/src/org/jalgo/module/ebnf/model/trans/CVS/Entries new file mode 100644 index 0000000..636acf4 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/trans/CVS/Entries @@ -0,0 +1 @@ +/TransMap.java/1.1/Fri Aug 11 16:40:30 2006// diff --git a/src/org/jalgo/module/ebnf/model/trans/CVS/Repository b/src/org/jalgo/module/ebnf/model/trans/CVS/Repository new file mode 100644 index 0000000..c58ddf2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/trans/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/model/trans diff --git a/src/org/jalgo/module/ebnf/model/trans/CVS/Root b/src/org/jalgo/module/ebnf/model/trans/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/trans/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/model/trans/TransMap.java b/src/org/jalgo/module/ebnf/model/trans/TransMap.java new file mode 100644 index 0000000..aa22493 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/trans/TransMap.java @@ -0,0 +1,104 @@ +/** + * + */ +package org.jalgo.module.ebnf.model.trans; + +import java.util.Map; +import java.util.LinkedHashMap; +import java.util.Set; +import java.util.Observable; + +import org.jalgo.module.ebnf.model.ebnf.Term; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; + + +/** + * @author Andre + */ +public class TransMap extends Observable { + + /** + * Represents the transMap + */ + private Map observableLinkedHashMap; + + /** + * Initializes the LinkedHashMap + */ + public TransMap() { + + observableLinkedHashMap = new LinkedHashMap(); + + } + + /** + * This method calls the put()-method of the LinkedHashMap and informs all + * observers, that the Map has changed + * + * @param key a SynDiaElem + * @param value a Term + */ + public void put(SynDiaElem key, Term value) { + + observableLinkedHashMap.put(key, value); + this.setChanged(); + + + } + + /** + * This method calls the get()-method of the LinkeHashMap + * + * @param key a SyntaxDiagram element + * @return The Term associated to SyntaxDiagram element + */ + public Term get(SynDiaElem key) { + + return observableLinkedHashMap.get(key); + + } + + /** + * This method calls the keySet()-method of the LinkedHashMap + * + * @return A set containing all keys + */ + public Set keySet() { + + return observableLinkedHashMap.keySet(); + + } + + /** + * This method checks whether the Map is completely tranformed or not + * + * @return True, if the Map is completely transformed + */ + public boolean isTransformed() { + + for (Term t : observableLinkedHashMap.values()) { + + if (t != null) + return false; + + } + return true; + + } + + /** This method checks if NO step was performed + * @return True, if no element was transformed yet + */ + public boolean isEbnf() { + + for (Term t : observableLinkedHashMap.values()) { + + if (t == null) + return false; + + } + return true; + + } + +} diff --git a/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Entries b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..6c4507f --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Entries @@ -0,0 +1 @@ +/WordAlgoModel.java/1.1/Fri Aug 11 16:40:33 2006// diff --git a/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Repository b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..0894b3d --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/model/wordalgorithm diff --git a/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Root b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.java b/src/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.java new file mode 100644 index 0000000..4631bde --- /dev/null +++ b/src/org/jalgo/module/ebnf/model/wordalgorithm/WordAlgoModel.java @@ -0,0 +1,1100 @@ +package org.jalgo.module.ebnf.model.wordalgorithm; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Stack; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.InconsistentDiagramSystemException; +import org.jalgo.module.ebnf.controller.wordalgorithm.exceptions.InitializationFailedException; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.ElementNotFoundException; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SynDiaSystem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * This class represents the Model used by the WordAlgorithm The model has to be + * in a seperate class because it is observable. + * + * @author Claas Wilke + * + */ +public class WordAlgoModel extends Observable { + + // Specifies, if the algorithm is started yet. + private boolean algorithmRunning; + + // Specifies, if the algorithm is finished yet. + // (Successfully or not) + private boolean algorithmFinished; + + // Specifies, if the algorithm should show warnings. + private boolean withWarnings; + + // Specifies, if the algorithm performs a jumpt to a Diagram via a + // Variable. Needed to decide wether or not a return to a Diagram + // is possible when a Variable is the (actual) position. + private boolean duringJumpToDiagram; + + // The word which should be generated during the algorithm + private String word; + + // The word which will be generated during the algorithm + private String output; + + // This String represents the explanations printed during the algorithm + private String explanation; + + // This String contains the last warning thrown by the algorithm. + // (Warnings are just generated if the Boolean withWarnings is true) + private String warning; + + // The SynDiaSystem used during the algorithm + private SynDiaSystem mySynDiaSystem; + + // The actual position in a SyntaxDiagram during the algorithm + private SynDiaElem position; + + // Specifies, if the actaulPosition is behind or in front of the Element. + private boolean positionBehindElem; + + // The Stack to push and pop Adresses during the algorithm // + private Stack myStack; + + private boolean stackHighlighted; + + // A Map of all the rsAdresses used during the algorithm Each Variable in + // the SynDiaSystem has it's own adress (int). + private Map adrNumbers; + + // This int is used in the recursive method generatedAdresses and therefore + // it must be global. + private int numberOfVariableInstances; + + // Specifies, if the end of a Diagram was reached. + private boolean endReached; + + // Contains all Elements in the SynDiaSystem that can be reached + // (Could be SynDiaElems or SyntaxDiagrams). + private List allElemsReachable; + + // The Color, the Stack should be highlighte with + private Color stackColor = RenderElement.HIGHLIGHT_BLUE; + + // Sepecifies, if the algorithm was finished successfully or not + private boolean finishedWithSuccess; + + /** + * Constructor constructs a new WordAlgoModel. Throws + * InitializationFailedException if initialization fails. + * + * @param aSynDiaSystem + * The SynDiaSystem, the algorithm should work + * with. + */ + public WordAlgoModel(SynDiaSystem aSynDiaSystem) + throws InitializationFailedException { + try { + initialize(aSynDiaSystem); + } catch (InitializationFailedException e) { + throw e; + } + } + + /** + * Initializes the WordAlgorithmModel. Used by the Constructor. + * + * @param mySynDiaSystem + * The SynDiaSystem which should used during the algorithm. + */ + private void initialize(SynDiaSystem aSynDiaSystem) + throws InitializationFailedException { + + algorithmRunning = false; + + algorithmFinished = false; + + withWarnings = true; + + duringJumpToDiagram = false; + + word = ""; + + output = ""; + + explanation = Messages.getString("ebnf", + "WordAlgo.Explanation_BeforeStart"); + + warning = ""; + + positionBehindElem = false; + + stackHighlighted = false; + + finishedWithSuccess = false; + + mySynDiaSystem = aSynDiaSystem; + + // Gets the first Concatenation of the StartDiagram. + // If getting Concatenation fails, an Exception is thrown. + try { + String startDiagramName = mySynDiaSystem.getStartDiagram(); + SyntaxDiagram myStartDiagram = mySynDiaSystem + .getSyntaxDiagram(startDiagramName); + Concatenation startRootConcat = myStartDiagram.getRoot(); + position = startRootConcat; + // Update Set with all Elements which are reachable + allElemsReachable = new ArrayList(); + addAllElemsReachable(startRootConcat); + } catch (ElementNotFoundException exception) { + throw new InitializationFailedException( + "Error during initialization of WordAlgoModel: " + + "DiagramSystem: StartDiagram not found."); + } + + myStack = new Stack(); + + // Now an adress mark for each Variable in the Diagrams is generated. + // Using the private Method generateAdresses. + // If generating adresses fails, an Exception is thrown. + adrNumbers = new HashMap(); + numberOfVariableInstances = 0; + try { + generateAdresses(); + } catch (InconsistentDiagramSystemException e) { + throw new InitializationFailedException(e.getMessage()); + } + } + + /** + * This method generates an adress for each Variable in the SynDiaSystem and + * enters the adress into the Map myAdresses. + */ + /* + * It uses the private method addAdressOfAnElement, wich parses the + * SynDiaSystem recursive. + */ + public void generateAdresses() throws InconsistentDiagramSystemException { + List diagramList = mySynDiaSystem.getLabelsOfVariables(); + for (String aVariable : diagramList) { + try { + Concatenation aConcat = mySynDiaSystem.getSyntaxDiagram( + aVariable).getRoot(); + addAdressOfAnElement(aConcat); + } catch (Exception e) { + throw new InconsistentDiagramSystemException( + "Error during generation of " + + "return adresses. SynDiaSystem inconsistent."); + } + + } + } + + /** + * This mehtod generates a new Adress for a SynDiaElem and puts the adress + * into the Map adrNumbers. + * + * @param anElement + */ + private void addAdressOfAnElement(SynDiaElem anElement) { + // If the element is a Concatenation, the mehtod is used recursive for + // all the elements inside the Concatenation. + if (anElement instanceof Concatenation) { + int n = ((Concatenation) anElement).getNumberOfElems(); + for (int i = 0; i < n; i++) { + addAdressOfAnElement(((Concatenation) anElement) + .getSynDiaElem(i)); + } + } + // If the element is a Branch, the method is used recursive for the left + // and the right path of the Branch. + else if (anElement instanceof Branch) { + addAdressOfAnElement(((Branch) anElement).getLeft()); + addAdressOfAnElement(((Branch) anElement).getRight()); + } + // If the element is a Repetition, the method is used recursive for the + // first and the second part of the Repetition. + else if (anElement instanceof Repetition) { + addAdressOfAnElement(((Repetition) anElement).getLeft()); + addAdressOfAnElement(((Repetition) anElement).getRight()); + } + // If the Element is a Variable, a new ReturnAdress is genereated + else if (anElement instanceof Variable) { + // Increment to avoid that the number was used before. + numberOfVariableInstances++; + adrNumbers.put((Variable) anElement, numberOfVariableInstances); + } + + } + + /** + * This method returns the running status of the algorithm. + * + * @return True if Algorithm is already started. + */ + public boolean isAlgorithmRunning() { + return algorithmRunning; + } + + /** + * This method returns the finished status of the algorithm. + * + * @return True if Algorithm is already finished. (Successfully or not) + */ + public boolean isAlgorithmFinished() { + return algorithmFinished; + } + + /** + * This method returns the warnings status of the algorithm. + * + * @return True if warnings are enabled. + */ + public boolean isWarningsOn() { + return withWarnings; + } + + /** + * This method returns true, if the algorithm is during a jump to another + * SyntaxDiagram. Needed to decide wether or not a return to + * a Diagram is possible when a Variable is the (actual) position. + */ + public boolean isJumpToDiagram() { + return duringJumpToDiagram; + } + + /** + * This mehtod returns true if the Stack is empty. + * + * @return True if the Stack is empty. + */ + public boolean isStackEmpty() { + return myStack.empty(); + } + + /** + * This mehtod returns true if the actual position should be behind the + * actual SynDiaElem which represents the actual position. + * + * @return True if the position is behind. + */ + public boolean isPositionBehindElem() { + return this.positionBehindElem; + } + + /** + * This mehtod returns true if the highest adress on the Stack should be + * highlighted. + * + * @return true if the highest adress on the Stack should be highlighted. + */ + public boolean isStackHighlighted() { + return this.stackHighlighted; + } + + /** + * This mehtod returns true if the actual position is inside a Repetition + * + * @return true if the actual position is inside a Repetition. + */ + public boolean isPositionInRepetition() { + SynDiaElem tempPosition = position; + SynDiaElem oldPosition = null; + while (tempPosition != null) { + oldPosition = tempPosition; + tempPosition = tempPosition.getParent(); + // If a position is found checkout, if the actual position + // is in the right concatenation + if (tempPosition instanceof Repetition) { + Repetition tempRepetition = (Repetition) tempPosition; + if (oldPosition == tempRepetition.getRight()) { + return true; + } + } + } + return false; + } + + /** + * This mehtod returns true if the end of a Diagram was reached. + * + * @return true if the end of a Diagram was reached. + */ + public boolean isEndReached() { + return this.endReached; + } + + /** + * This mehtod returns true if the algorithm was finished successfully. + * + * @return true if the algorithm was finished successfully. + */ + public boolean isFinishedWithSuccess() { + return this.finishedWithSuccess; + } + + /** + * This method returns the word which should be generated by the algorithm. + * + * @return The world which should be generated + */ + public String getWord() { + return word; + } + + /** + * This method returns the word which was already generated by the algoritm. + * + * @return The word which was already generated. + */ + public String getOutput() { + return output; + } + + /** + * This method returns the explanation of the actual algorithm step. + * + * @return The explanation of the actual step. + */ + public String getExplanation() { + return explanation; + } + + /** + * This method returns the last warning generated by the algorithm. (Only if + * warnings are enabled). + * + * @return Last warning generated during algorithm. + */ + public String getWarning() { + if (isWarningsOn()) + return warning; + return ""; + } + + /** + * This method returns the actual position in a SyntaxDiagram during + * algorithm. + * + * @return Actual algorithm position in a SyntaxDiagram. + */ + public SynDiaElem getPosition() { + return position; + } + + /** + * This method returns the SynDiaSystem used by the algorithm. + * + * @return The SynDiaSystem used by the algorithm + * + */ + public SynDiaSystem getSynDiaSystem() { + return mySynDiaSystem; + } + + /** + * This method returns the return marks of all Variables pushed on the Stack + * starting with the oldest. + * + * @return List containing return marks (int). + */ + public List getAdressNumbersFromStack() { + // varList contains the Variables pushed onto the Stack. + LinkedList varList = new LinkedList(); + for (int i = 0; i < myStack.size(); i++) { + Variable aVar = myStack.get(i); + varList.add(aVar); + } + // adrList should contain the return marks of the Variables pushed onto + // the Stack. + LinkedList adrList = new LinkedList(); + for (Variable aVariable : varList) { + adrList.add((Integer) getAdressNumber(aVariable)); + } + return adrList; + } + + /** + * This method returns the adress number for a specific Variable used as + * return adress during the algorithm. + * + * @param var + * The Variable which return adress should be returned. + */ + public Number getAdressNumber(Variable var) { + return adrNumbers.get(var); + } + + /** + * This mehtod returns the first Repetition which is around the actual + * position. If there is now parent repetition, null is returned. + * + * @return the first Repetition which is around the actual position. + */ + public Repetition getFirstParentRepetition() { + SynDiaElem tempPosition = position; + SynDiaElem oldPosition = null; + while (tempPosition != null) { + oldPosition = tempPosition; + tempPosition = tempPosition.getParent(); + // If a position is found checkout, if the actual position + // is in the right concatenation + if (tempPosition instanceof Repetition) { + Repetition tempRepetition = (Repetition) tempPosition; + if (oldPosition == tempRepetition.getRight()) { + return tempRepetition; + } + } + } + return null; + } + + /** + * This mehtod returns the color, the stack should be highlighted with + */ + public Color getStackColor() { + return this.stackColor; + } + + /** + * This method sets the algorihm status running. + * + */ + public void enableAlgorithmRunning() { + if (!algorithmRunning) { + setChanged(); + algorithmRunning = true; + } + } + + /** + * This method stops the algorithm. Attention: Algorithm Status is + * lost if algorithm is disabled. + * + */ + public void disableAlgorithmRunning() { + if (algorithmRunning) { + setChanged(); + algorithmRunning = false; + } + } + + /** + * This method sets the algorihm status finished. + * + */ + public void enableAlgorithmFinished() { + if (!algorithmFinished) { + setChanged(); + algorithmFinished = true; + } + } + + /** + * This method resets the algorithm status to not finished. + * + */ + public void disableAlgorithmFinished() { + if (algorithmFinished) { + setChanged(); + algorithmFinished = false; + } + } + + /** + * This method enables warnings during algorithm. + */ + public void enableWarnings() { + if (!withWarnings) { + setChanged(); + withWarnings = true; + } + } + + /** + * This method disables warnings during algorithm. + * + */ + public void disableWarnings() { + if (withWarnings) { + setChanged(); + withWarnings = false; + } + } + + /** + * This method enables that the algorithm is during a jump to a Diagram. + * Needed to decide wether or not a return to a Diagram is possible when a + * Variable is the (actual) position. + */ + public void enableJumpToDiagram() { + if (!duringJumpToDiagram) { + duringJumpToDiagram = true; + setChanged(); + } + } + + /** + * This method disables that the algorithm is during a jump to a Diagram. + * Needed to decide wether or not a return to a Diagram is possible when a + * Variable is the (actual) position. + * + */ + public void disableJumpToDiagram() { + if (duringJumpToDiagram) { + duringJumpToDiagram = false; + setChanged(); + } + } + + /** + * Sets the value that the actual Position is behind the + * SynDiaElem which represents the actualPosition true. + * + */ + public void enablePositionBehind() { + if (!positionBehindElem) { + this.positionBehindElem = true; + setChanged(); + } + } + + /** + * Sets the value that the actual Position is behind the + * SynDiaElem which represents the actualPosition false. + * + */ + public void disablePositionBehind() { + if (positionBehindElem) { + this.positionBehindElem = false; + setChanged(); + } + } + + /** + * This mehtod returns sets the highest adress on the Stack highlighted. + * Stack is highlighted with its default color. + */ + public void enableStackHighlighted() { + if (!stackHighlighted) { + this.stackHighlighted = true; + this.stackColor = RenderElement.HIGHLIGHT_BLUE; + setChanged(); + } + } + + /** + * This mehtod returns sets the highest adress on the Stack highlighted. + * Stack is highlighte with the color aColor. + * + * @param aColor + * The Color the Stack should be highlighted in. + */ + public void enableStackHighlighted(Color aColor) { + this.stackHighlighted = true; + this.stackColor = aColor; + setChanged(); + } + + /** + * This mehtod returns sets the highest adress on the Stack dehighlighted. + */ + public void disableStackHighlighted() { + if (stackHighlighted) { + this.stackHighlighted = false; + setChanged(); + } + } + + /** + * Sets the value that the Algorithm was finished correctly true. + * + */ + public void enableFinishedWithSuccess() { + if (!finishedWithSuccess) { + this.finishedWithSuccess = true; + setChanged(); + } + } + + /** + * Sets the value that the Algorithm was finished correctly false. + * + */ + public void disableFinishedWithSuccess() { + if (finishedWithSuccess) { + this.finishedWithSuccess = false; + setChanged(); + } + } + + /** + * This method sets the word which should be generated by the algorithm. + * + * @param word + * The word which should be generated. + */ + public void setWord(String word) { + this.word = word; + setChanged(); + } + + /** + * This method sets the output which is generated by the algorithm. + * + * @param output + * The output generated. + */ + public void setOutput(String output) { + this.output = output; + setChanged(); + } + + /** + * This method sets the explanation which is generated by the algorithm. + * + * @param explanation + * The explanation generated. + */ + public void setExplanation(String explanation) { + this.explanation = explanation; + setChanged(); + } + + /** + * This method sets the warning which is generated by the algorithm. + * (Warning is just thrown if warnings are enabled). + * + * @param warning + * The warning generated. + */ + public void setWarning(String warning) { + this.warning = warning; + setChanged(); + } + + /** + * This method changes the position in a SyntaxDiagram. + * + * @param anElem + * New position in the SyntaxDiagram. + */ + public void setPosition(SynDiaElem anElem) { + position = anElem; + // Update the list of all Elems reachable + setAllElemsReachable(); + setChanged(); + } + + /** + * This method pushes a Variable on the stack. + * + * @param aVar + * The Variable which should be pushed onto the + * stack. + */ + public void pushToStack(Variable aVar) { + myStack.push(aVar); + setChanged(); + } + + /** + * This method pops a Variable from the Stack. + * + * @return The Variable popped from the Stack. Is + * null if Stack is empty. + */ + public Variable popFromStack() { + if (!myStack.isEmpty()) { + return myStack.pop(); + } + return null; + } + + /** + * This method empties the Stack. + * + */ + public void emptyStack() { + myStack.clear(); + } + + /** + * This model reinitializes the model. + */ + public void reset() throws InitializationFailedException { + try { + initialize(mySynDiaSystem); + setChanged(); + } catch (InitializationFailedException e) { + throw e; + } + } + + /** + * This method checks, if an SynDiaElem is in a + * SyntaxDiagram. + * + * @param anElem + * The Element which should be in the Diagram. + * @param aDiagram + * The Diagram the Element should be in. + * @return True if anElem is in aDiagram. + */ + public boolean isElementInDiagram(SynDiaElem anElem, SyntaxDiagram aDiagram) { + return (anElem.getMySyntaxDiagram().getRoot() == aDiagram.getRoot()); + } + + /** + * Searches for the next position in the Diagram and returns it. + * + * @param anElem + * The SynDiaElem which is before the new position + * @return The new position (a SynDiaElem). + */ + public SynDiaElem getPositionBehind(SynDiaElem anElem) { + if (anElem instanceof TerminalSymbol) { + return getPositionBehindInConcatenation(anElem); + } + if (anElem instanceof Variable) { + if (this.isJumpToDiagram()) { + this.disablePositionBehind(); + return anElem; + } else { + return getPositionBehindInConcatenation(anElem); + } + } + if (anElem instanceof Concatenation) { + Concatenation aConcat = (Concatenation) anElem; + return getPositionBehindConcatenation(aConcat, anElem); + } + this.disablePositionBehind(); + return anElem; + } + + /** + * Searches for a Position behind an SynDiaElem in a + * Concatenation + * + * @param anElem + * The SynDiaElem where behind this method should + * use. + * + * @return The new position (a SynDiaElem). + */ + private SynDiaElem getPositionBehindInConcatenation(SynDiaElem anElem) { + // Get the parentConcat + if (anElem.getParent() instanceof Concatenation) { + Concatenation parentConcat = (Concatenation) anElem.getParent(); + int parentConcatSize = parentConcat.getNumberOfElems(); + if (parentConcatSize > 1) { + for (int i = 0; i < parentConcatSize - 1; i++) { + // Test if Element i is actual element + if (parentConcat.getSynDiaElem(i) == anElem) { + // return the following element + this.disablePositionBehind(); + return getPositionToElem(parentConcat + .getSynDiaElem(i + 1)); + } + } + } + // Else Element must be behind Concatenation + return getPositionBehindConcatenation(parentConcat, anElem); + } else + return null; + } + + /** + * Searches for a Position behind a Concatenation. + * + * @param aConcat + * The Concatenation the new position should be + * behind. + * + * @param anElem + * The SynDiaElem the new position should be + * behind. + * + * @return The new position (a SynDiaElem). + */ + private SynDiaElem getPositionBehindConcatenation(Concatenation aConcat, + SynDiaElem anElem) { + // get the Concatenations Parent + SynDiaElem concatsParent = aConcat.getParent(); + // Check the Type of the Concat's parent. + // 1. A Branch + // *************************************************************** + if (concatsParent instanceof Branch) { + // The next decision must be behind the Branch. + return getPositionBehindInConcatenation(concatsParent); + } + // 2. A Repetition + // *********************************************************** + if (concatsParent instanceof Repetition) { + Repetition aRepetition = (Repetition) concatsParent; + // Checkout if Concat is left or right concatenation + if (aConcat == aRepetition.getLeft()) { + // If left Concat contains Elements, position is Behind last + // Element in Concat. + if (aConcat.getNumberOfElems() != 0) { + this.enablePositionBehind(); + return aConcat + .getSynDiaElem(aConcat.getNumberOfElems() - 1); + } else { + return anElem; + } + } else { + // if its the right branch, the decision is in front of the + // first + // Element in the left Concatenation. + this.disablePositionBehind(); + return aRepetition.getLeft(); + } + } + // 3. NULL + // ******************************************************************* + // There is no Element behind the actual Element. + // So the decision is behind the actual Element + this.enablePositionBehind(); + this.endReached = true; + return anElem; + } + + /** + * Gets the position to a specific SynDiaElem, if the elem + * should be the new position. + * + * @param anElem + * The Element, which should be the new position. + * @return The new position. + */ + private SynDiaElem getPositionToElem(SynDiaElem anElem) { + if (anElem instanceof Repetition) { + Repetition aRepetition = (Repetition) anElem; + this.disablePositionBehind(); + return aRepetition.getLeft(); + } + this.disablePositionBehind(); + return anElem; + } + + /** + * Adds all the elements which could be reached from aSynDiaElem to the List + * allElemsReachable. Attention: this method does not clear the List + * allElemsReachable before. + * + * @param aSynDiaElem + * the SynDiaElem from where Elems should be reached. + */ + private void addAllElemsReachable(SynDiaElem aSynDiaElem) { + // Checkout which type of SynDiaElem aSynDiaElem is. + // If its a TerminalSymbol + if (aSynDiaElem instanceof TerminalSymbol) { + allElemsReachable.add(aSynDiaElem); + } + // If its a Variable + if (aSynDiaElem instanceof Variable) { + if (this.isJumpToDiagram()) { + addAllDiagramsReachable(); + } else + allElemsReachable.add(aSynDiaElem); + } + // If its a Repetition + else if (aSynDiaElem instanceof Repetition) { + // The Elements of the left Concatenation are reachable: + Repetition aRepetition = (Repetition) aSynDiaElem; + addAllElemsReachable(aRepetition.getLeft()); + } + // If its a Branch + else if (aSynDiaElem instanceof Branch) { + // Tehe Elements of the left and the Right Concatenation are + // reachable: + Branch aBranch = (Branch) aSynDiaElem; + addAllElemsReachable(aBranch.getLeft()); + addAllElemsReachable(aBranch.getRight()); + } + // If its a Concatenation + else if (aSynDiaElem instanceof Concatenation) { + Concatenation aConcat = (Concatenation) aSynDiaElem; + // If Concat contains Elements, add the first + if (aConcat.getNumberOfElems() > 0) { + addAllElemsReachable(aConcat.getSynDiaElem(0)); + } + // Else add the elements Reachable behind + else { + // If the Element is not the root Element, it is reachable + // itself + if (aConcat.getParent() != null) { + allElemsReachable.add(aConcat); + } + addAllElemsReachableBehind(aConcat); + } + } + } + + /** + * Adds all Elems reachable behind a SynDiaElem to the Reachable Element + * Set. + * + * Attention: this method does not clear the List allElemsReachable + * before. + * + * @param aSynDiaElem + * the SynDiaElem from where Elems should be reached. + */ + private void addAllElemsReachableBehind(SynDiaElem aSynDiaElem) { + // Checkout which type of SynDiaElem aSynDiaElem is + if (aSynDiaElem instanceof Variable + || aSynDiaElem instanceof TerminalSymbol + || aSynDiaElem instanceof Repetition + || aSynDiaElem instanceof Branch) { + Concatenation parentConcat = (Concatenation) aSynDiaElem + .getParent(); + boolean elemFound = false; + for (int i = 0; i < (parentConcat.getNumberOfElems() - 1); i++) { + // If the Element is at position i in the Concatenation, + // the Element the method has to look for must be behind that + // Element. + if (parentConcat.getSynDiaElem(i) == aSynDiaElem) { + addAllElemsReachable(parentConcat.getSynDiaElem(i + 1)); + elemFound = true; + break; + } + } + if (!elemFound) { + addAllElemsReachableBehind(parentConcat); + } + } + // If its a Concatenation + if (aSynDiaElem instanceof Concatenation) { + // Checkout if Concat has a parent + Concatenation aConcat = (Concatenation) aSynDiaElem; + SynDiaElem parentElem = aConcat.getParent(); + if (parentElem != null) { + // Checkout which type of parent parentElem is + if (parentElem instanceof Branch) { + // Add Elems Behind + addAllElemsReachableBehind(parentElem); + } else if (parentElem instanceof Repetition) { + // Checkout if Concat is left or right Concat + Repetition parentRep = (Repetition) parentElem; + if (aConcat == parentRep.getLeft()) { + // Add Elems in RightConcat and Behind Repetition + addAllElemsReachableBehind(parentRep); + // Checkout if RightConcat is empty + if (parentRep.getRight().getNumberOfElems() > 0) { + // If not, add its Elements. + addAllElemsReachable(parentRep.getRight()); + } + // Else if left Concat is not empty, add its Elements + else if (parentRep.getLeft().getNumberOfElems() > 0) { + addAllElemsReachable(parentRep.getLeft()); + } + } + } + } + // Else the end of the diagram was reached + else { + this.endReached = true; + } + } + } + + /** + * Adds all SyntaxDiagrams to the Set of all reachable + * Elements. + * + */ + private void addAllDiagramsReachable() { + List diagramList = mySynDiaSystem.getLabelsOfVariables(); + for (String aDiagramName : diagramList) { + try { + allElemsReachable.add(mySynDiaSystem + .getSyntaxDiagram(aDiagramName)); + } catch (Exception e) { + System.out.println(e.getMessage()); + System.out + .println("Error in WordAlgoModel: Incosistent SynDiaSystem. Exit"); + System.exit(-1); + } + } + } + + /** + * Sets all the Elements which are reachable from the actual position in the + * SynDiaSystem + */ + public void setAllElemsReachable() { + this.endReached = false; + this.allElemsReachable.clear(); + if (this.positionBehindElem) { + addAllElemsReachableBehind(position); + } else { + addAllElemsReachable(position); + } + } + + /** + * Return true if the Element could be reached from the actual Position + * + * @param aSynDiaElem + * The Element which should be reached. + */ + public boolean isElementReachable(SynDiaElem aSynDiaElem) { + Iterator it = allElemsReachable.iterator(); + while (it.hasNext()) { + Object anObject = it.next(); + if (anObject == aSynDiaElem) { + return true; + } + } + return false; + } + + /** + * Return true if the Diagram could be reached from the actual Position + * + * @param aSyntaxDiagram + * The SyntaxDiagram which should be reached. + */ + public boolean isElementReachable(SyntaxDiagram aSyntaxDiagram) { + Iterator it = allElemsReachable.iterator(); + while (it.hasNext()) { + Object anObject = it.next(); + if (anObject == aSyntaxDiagram) { + return true; + } + } + return false; + } + + /** + * Returns true if List of all Elements which are reachable from actual + * position is empty + */ + public boolean isNoElementReachable() { + return allElemsReachable.isEmpty(); + } + + /** + * Sets this Model changed, so that a notifyObservers() will notify the + * Observers. + * + */ + public void setModelChanged() { + this.setChanged(); + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/CVS/Entries b/src/org/jalgo/module/ebnf/renderer/CVS/Entries new file mode 100644 index 0000000..98df9fd --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/CVS/Entries @@ -0,0 +1,11 @@ +/EditorRenderer.java/1.1/Fri Aug 11 16:40:26 2006// +/RenderElementFactory.java/1.1/Fri Aug 11 16:40:26 2006// +/RenderValues.java/1.1/Fri Aug 11 16:40:26 2006// +/ReturnDiagram.java/1.1/Fri Aug 11 16:40:26 2006// +/SynDiaRenderer.java/1.2/Fri Oct 31 16:12:36 2008// +/TransRenderer.java/1.2/Fri Oct 31 16:12:36 2008// +/VirtualDim.java/1.1/Fri Aug 11 16:40:26 2006// +/WordAlgoRenderer.java/1.2/Fri Oct 31 16:12:36 2008// +D/elements//// +D/event//// +D/wordalgorithm//// diff --git a/src/org/jalgo/module/ebnf/renderer/CVS/Repository b/src/org/jalgo/module/ebnf/renderer/CVS/Repository new file mode 100644 index 0000000..3672f0c --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/renderer diff --git a/src/org/jalgo/module/ebnf/renderer/CVS/Root b/src/org/jalgo/module/ebnf/renderer/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/renderer/EditorRenderer.java b/src/org/jalgo/module/ebnf/renderer/EditorRenderer.java new file mode 100644 index 0000000..0c38999 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/EditorRenderer.java @@ -0,0 +1,227 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; + +/** + * This class gets a syntax diagram, a drawing area (JComponent) and some + * other optional params. As result you will get a drawn syntax diagram (system) on the + * given area. + * + * @author Andre Viergutz + */ +public class EditorRenderer extends SynDiaRenderer{ + + + + /** + * Decreases the size of the SPACE between render elements + */ + public EditorRenderer() { + + super(); + this.rv.space = super.rv.space / 2; + } + + protected VirtualDim getMyDim(SyntaxDiagram sd) { + + return getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, true, true); + + } + + /** + * Caclulates the Dimension of a given element by collecting informations + * from its children [and puts all elements (besides Concatenation) on the + * way into the renderList] + * + * @param e A SyntaxDiagram element + * @param x x-position of the element + * @param y y-position of the element + * @param direction true: read left to right, false: read right to left + * @param render A paramter, telling the method, whether creating + * RenderElements or just calculate the Dimension + * @return Width of e + */ + protected VirtualDim getDimFromElement(SynDiaElem e, int x, int y, boolean direction, + boolean render) { + + /* + * TERMINAL + */ + if (e.getClass() == TerminalSymbol.class) { + TerminalSymbol t = (TerminalSymbol) e; + + int width = rv.getWidthFromString(t.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + if (render) + addElemToRenderList(RenderValues.TERMINAL, t, x, y, width, + height, t.getLabel()); + + return dim; + /* + * VARIABLE + */ + }else if (e.getClass() == Variable.class) { + + Variable v = (Variable) e; + + int width = rv.getWidthFromString(v.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + + if (render) + addElemToRenderList(RenderValues.VARIABLE, v, x, y, width, + height, v.getLabel()); + + return dim; + /* + * BRANCH + */ + } else if (e.getClass() == Branch.class) { + + // width + Branch b = (Branch) e; + VirtualDim dim_left = getDimFromElement(b.getLeft(), x + 3 + * rv.radius, y, direction, render); + + VirtualDim dim_right = getDimFromElement(b.getRight(), x + 3 + * rv.radius, y + dim_left.height + rv.space, direction, + render); + + VirtualDim dim = dim_left; + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + dim.width += 6 * rv.radius; + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) + addElemToRenderList(RenderValues.BRANCH, b, x, y, dim.width, + dim.height, ""); + + return dim; + /* + * CONCATENATION + */ + } else if (e.getClass() == Concatenation.class) { + + Concatenation c = (Concatenation) e; + + // width & height + VirtualDim dim = new VirtualDim(); + VirtualDim dim_tmp = new VirtualDim(); + + int i = 0; + SynDiaElem sde; + for (i = 0; i < c.getNumberOfElems(); i++) { + + if (direction) + sde = c.getSynDiaElem(i); + else + sde = c.getSynDiaElem(c.getNumberOfElems() - i - 1); + + dim_tmp = getDimFromElement(sde, x, y, direction, render); + dim.width += dim_tmp.width; + + if (dim_tmp.virtualHeight > dim.virtualHeight) + dim.virtualHeight = dim_tmp.virtualHeight; + + x += dim_tmp.width + rv.space; + + } + + if (i > 0) + dim.width += (i - 1) * rv.space; + + if (dim.virtualHeight < 2 * rv.radius) { + + dim.virtualHeight = 2 * rv.radius; + + } + dim.height = dim.virtualHeight; + return dim; + /* + * REPETITION + */ + } else if (e.getClass() == Repetition.class) { + + // width + Repetition r = (Repetition) e; + VirtualDim dim_left = getDimFromElement(r.getLeft(), x + 2 + * rv.radius, y, direction, render); + + VirtualDim dim_right = getDimFromElement(r.getRight(), x + 2 + * rv.radius, y + dim_left.height + rv.space, !direction, + render); + VirtualDim dim = dim_left; + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + dim.width += 4 * rv.radius; + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) + addElemToRenderList(RenderValues.REPETITION, r, x, y, + dim.width, dim.height, ""); + + return dim; + /* + * NULL ELEM + */ + } else if (e.getClass() == NullElem.class) { + + NullElem ne = (NullElem) e; + + int width = 2 * rv.radius; + int height = 2 * rv.radius; + + VirtualDim dim = new VirtualDim(width, height, height); + + if (render) + addElemToRenderList(RenderValues.NULLELEM, ne, x, y, width, + height, ""); + + return dim; + + } + /* + * OTHERS + */ + return new VirtualDim(0, 0, 0); + } + + +} diff --git a/src/org/jalgo/module/ebnf/renderer/RenderElementFactory.java b/src/org/jalgo/module/ebnf/renderer/RenderElementFactory.java new file mode 100644 index 0000000..7da1601 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/RenderElementFactory.java @@ -0,0 +1,73 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import java.util.List; + +import org.jalgo.module.ebnf.renderer.elements.RenderBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderNoStairBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderNullElem; +import org.jalgo.module.ebnf.renderer.elements.RenderRepetition; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderTrans; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +/** + * This factory creates a RenderElement by type + * + * @author Andre Viergutz + */ +public class RenderElementFactory { + + /** + * represents a render element + */ + private static RenderElement element; + + /** + * This method gets the type of the RenderElement to create, to be found in + * the RenderValues and the name of the element in case of a Variable or + * TerminalSymbol and returns a RenderElement RenderElement + * + * @param type the type identified by an int to be found in the RenderValues + * @param label the name of a Variable or a TerminalSymbol + * @param stringList A list of first children Strings (from EBNF Definition) + * @return a RenderElement + */ + public static RenderElement createElement(int type, String label, List stringList) { + + if (type == RenderValues.TERMINAL) + element = new RenderTerminal(label); + else if (type == RenderValues.VARIABLE) + element = new RenderVariable(label); + else if (type == RenderValues.BRANCH) + element = new RenderBranch(); + else if (type == RenderValues.BRANCHNOSTAIRS) + element = new RenderNoStairBranch(); + else if (type == RenderValues.REPETITION) + element = new RenderRepetition(); + else if (type == RenderValues.NULLELEM) + element = new RenderNullElem(); + else if (type == RenderValues.TRANSTERM) + element = new RenderTrans(label, stringList); + return element; + + } + + /** + * This method gets the type of the RenderElement to create, to be found in + * the RenderValues and returns a + * RenderElement + * + * @param type the type identified by an int to be found in the RenderValues + * @return a RenderElement + */ + public static RenderElement createElement(int type) { + + return createElement(type, "leer", null); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/RenderValues.java b/src/org/jalgo/module/ebnf/renderer/RenderValues.java new file mode 100644 index 0000000..3697cc0 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/RenderValues.java @@ -0,0 +1,148 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import java.awt.Font; +import java.awt.FontMetrics; +import javax.swing.JPanel; + +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.syndia.display.DiagramSize; + +/** + * This class holds all preferences for rendering. + * + * @author Andre Viergutz + */ +public class RenderValues { + + /** + * Represents a terminal symbol + */ + public static int TERMINAL = 0; + + /** + * Represents a variable + */ + public static int VARIABLE = 1; + + /** + * Represents a concatenation + */ + public static int CONCATENATION = 2; + + /** + * Represents a branch + */ + public static int BRANCH = 3; + + /** + * Represents a branch + */ + public static int BRANCHNOSTAIRS = 4; + + + /** + * Represents a repetition + */ + public static int REPETITION = 5; + + /** + * Represents a null element + */ + public static int NULLELEM = 6; + + /** + * Represents a null element + */ + public static int TRANSTERM = 7; + + /** + * Represents a ghost object for creating the FontMetrics obect + */ + private static JPanel PANEL = new JPanel(); + + /** + * Represents the radius of the rounded rectangle and the arc angle of the + * branch and repetition + */ + public int radius = 15; + + /** + * Represents the space between two syntax diagram elements + */ + public int space = 15; + + /** + * Represents whether to render with or without stairs at multiple branches + */ + public boolean withStairs = true; + + + /** + * Represents the font of the symbols + */ + public Font font; + /** + * Represent the font metrics for calculating the string width in pixel + */ + public FontMetrics fm; + + /** + * Sets the size of the font saved in DiagramSize + */ + public RenderValues() { + + this.setFontSize(DiagramSize.getFontSize()); + + } + + + /** + * Sets the size of the actual Font + * + * @param size The size + */ + public void setFontSize(int size) { + + try { + this.font = EbnfFont.getFont().deriveFont(Font.PLAIN, size); + } catch (FontNotInitializedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + fm = PANEL.getFontMetrics(font); + radius = (int) Math.round(0.6 * fm.getHeight()); + space = radius; + } + + /** + * Calculates the width of the given String object in pixel + * + * @param s The String object to calculate + * @return the width of the String object in pixel + */ + public int getWidthFromString(String s) { + + return fm.stringWidth(s); + + } + + /** + * Calculates the width of the given String object in pixel + * + * @param s The String object to calculate + * @param f The Font which size is to calculate + * @return the width of the String object in pixel + */ + public int getWidthFromString(String s, Font f) { + + FontMetrics fontmetrics = PANEL.getFontMetrics(f); + + return fontmetrics.stringWidth(s); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/ReturnDiagram.java b/src/org/jalgo/module/ebnf/renderer/ReturnDiagram.java new file mode 100644 index 0000000..b34a5f7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/ReturnDiagram.java @@ -0,0 +1,35 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import java.util.Map; +import java.util.LinkedHashMap; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * This class is a data container and holds a renderMap, the width and height of + * a syntax diagram and is used by render method + * + * @author Andre + */ +public class ReturnDiagram { + + /** + * A Map where each rendered element is associated to a syntax diagram + * element in the model + */ + public Map renderMap = new LinkedHashMap(); + + /** + * the width of the syntax diagram + */ + public int width = 0; + + /** + * the height of a syntax diagram + */ + public int height = 0; + +} diff --git a/src/org/jalgo/module/ebnf/renderer/SynDiaRenderer.java b/src/org/jalgo/module/ebnf/renderer/SynDiaRenderer.java new file mode 100644 index 0000000..6f4e978 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/SynDiaRenderer.java @@ -0,0 +1,165 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import java.awt.Dimension; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderName; + +/** + * This class gets a syntax diagram, a drawing area (JComponent) and some + * other optional params. As result you will get a drawn syntax diagram (system) on the + * given area. + * + * @author Andre Viergutz + */ +public abstract class SynDiaRenderer { + + protected Map renderMap = new LinkedHashMap(); + + /** + * All needed parameters to render a SyntaxDiagram + */ + protected RenderValues rv = new RenderValues(); + + + + /** Creates a Map containing all RenderElements to be rendered including RenderTrans + * @param sd A SyntaxDiagram + * @return A map with all elements to be rendered + */ + public ReturnDiagram getRenderedDiagram(SyntaxDiagram sd) { + + renderMap.clear(); + + VirtualDim vdim = getMyDim(sd); + + //NAME OF DIAGRAM + RenderName rn; + if (sd.getName().equals(sd.getMySynDiaSystem().getStartDiagram())) + rn = new RenderName(sd.getName(), true); + else + rn = new RenderName(sd.getName(), false); + rn.setRenderValues(rv); + rn.setSize((int) (1.3*rv.getWidthFromString(sd.getName())) + 20, 2 * rv.radius); + rn.setLocation(0, 0); + rn.setVisible(true); + + renderMap.put(rn, null); + + + //BASE LINE + SIZE OF DIAGRAM + RenderBase rb; + rb = new RenderBase(); + rb.setRenderValues(rv); + rb.setSize(vdim.width + 2 * rv.radius, 4 * rv.radius); + rb.setLocation(0, 0); + rb.setVisible(true); + + renderMap.put(rb, null); + + + ReturnDiagram rd = new ReturnDiagram(); + rd.renderMap = renderMap; + rd.width = vdim.width + 2*rv.radius; + if (rv.getWidthFromString(sd.getName()) > rd.width) + rd.width = rv.getWidthFromString( + sd.getName()); + rd.height = vdim.virtualHeight + 2*rv.radius; + + return rd; + } + + /** This method is specific for the class is used as a template for getting the dimension of an element + * @param sd the SyntaxDiagram to render + * @return the VirtualDim object containing width, height as well as the virtualHeight + */ + protected abstract VirtualDim getMyDim(SyntaxDiagram sd); + + /** + * Calculates the size of the given diagram + * + * @param sd A SyntaxDiagram + * @return A map with all elements to be rendered + */ + public Dimension getDiagramSize(SyntaxDiagram sd) { + + VirtualDim vdim = getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, true, false); + + Dimension dimension = new Dimension(); + + dimension.width = vdim.width + 2 * rv.radius; + dimension.height = vdim.virtualHeight + 2 * rv.radius; + + return dimension; + } + + + /** + * Caclulates the Dimension of a given element by collecting informations + * from its children [and puts all elements (besides Concatenation) on the + * way into the renderList] + * + * @param e A SyntaxDiagram element + * @param x x-position of the element + * @param y y-position of the element + * @param direction true: read left to right, false: read right to left + * @param render A paramter, telling the method, whether creating + * RenderElements or just calculate the Dimension + * @return Width of e + */ + protected abstract VirtualDim getDimFromElement(SynDiaElem e, int x, int y, boolean direction, + boolean render); + + /** + * @param type One of the types to be found in the RenderValues + * @param s the SynDiaElem to be added + * @param x the x-position of the element + * @param y the y-position of the element + * @param width the width of the element + * @param height the height of the element + * @param label if terminal or variable, the name, otherwise null + */ + protected void addElemToRenderList(int type, SynDiaElem s, int x, int y, int width, + int height, String label) { + + RenderElement renderElem = RenderElementFactory.createElement(type, + label, null); + + renderElem.setRenderValues(rv); + + //Shadow for TerminalSymbol and Variable +// The if-branch will never be executed... (michael p, 31/10/08) +// if (renderElem.getClass() == TerminalSymbol.class || renderElem.getClass() == Variable.class) { +// renderElem.setSize(width+3, height+3); +// renderElem.setLocation(x-1, y-1); +// } else { + renderElem.setSize(width, height); + renderElem.setLocation(x, y); +// } + //new position for the element + renderElem.update(); + + //hinzufügen zur renderMap + renderMap.put(renderElem, s); + + } + + /** This method returns the RenderValues object containing all render informations + * @return The RenderValues object containing all render informations + */ + public RenderValues getRenderValues() { + + return rv; + } +} diff --git a/src/org/jalgo/module/ebnf/renderer/TransRenderer.java b/src/org/jalgo/module/ebnf/renderer/TransRenderer.java new file mode 100644 index 0000000..a9c26f8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/TransRenderer.java @@ -0,0 +1,469 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +import java.awt.Dimension; +import java.awt.Font; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.ebnf.EbnfRenderer; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderName; + +/** + * This class gets a syntax diagram, a drawing area (JComponent) and some other + * optional params. As result you will get a drawn syntax diagram (system) on + * the given area. + * + * @author Andre Viergutz + */ +public class TransRenderer extends SynDiaRenderer { + + + private TransMap transMap = new TransMap(); + + /** + * Creates a Map containing all RenderElements to be rendered including + * RenderTrans + * + * @param sd + * A SyntaxDiagram + * @param transMap + * A map where each syntax diagram element is associated to a + * Term, showing if the element is already transformed or no + * @return A map with all elements to be rendered + */ + public ReturnDiagram getRenderedDiagram(SyntaxDiagram sd, TransMap transMap) { + + renderMap.clear(); + this.transMap = transMap; + + VirtualDim vdim = getMyDim(sd); + + // BASE LINE + SIZE OF DIAGRAM + RenderBase rb; + rb = new RenderBase(); + rb.setRenderValues(rv); + rb.setSize(vdim.width + 2 * rv.radius, 4 * rv.radius); + rb.setLocation(0, 0); + rb.setVisible(true); + + renderMap.put(rb, null); + + // NAME OF DIAGRAM + RenderName rn; + if (sd.getName().equals(sd.getMySynDiaSystem().getStartDiagram())) + rn = new RenderName(sd.getName(), true); + else + rn = new RenderName(sd.getName(), false); + rn.setRenderValues(rv); + rn.setSize(rv.getWidthFromString(sd.getName()), 2 * rv.radius); + rn.setLocation(0, 0); + rn.setVisible(true); + + renderMap.put(rn, null); + + ReturnDiagram rd = new ReturnDiagram(); + rd.renderMap = renderMap; + rd.width = vdim.width + 2 * rv.radius; + rd.height = vdim.virtualHeight + 2 * rv.radius; + + return rd; + } + + protected VirtualDim getMyDim(SyntaxDiagram sd) { + return getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, 0, true, true, true); + } + + /** + * Calculates the size of the given diagram + * + * @param sd + * A SyntaxDiagram + * @return A map with all elements to be rendered + */ + public Dimension getDiagramSize(SyntaxDiagram sd) { + + VirtualDim vdim = getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, 0, true, true, false); + + Dimension dimension = new Dimension(); + + dimension.width = vdim.width + 2 * rv.radius; + dimension.height = vdim.virtualHeight + 2 * rv.radius; + + return dimension; + } + + /** + * This method checks whether the given element is already transformed or + * not. In case of an element is to transform a RenderTrans is created, + * otherwise the other fitting element + * + * @param e + * a SynDiaElem> to be calculated + * @param x + * the start position + * @param y + * the start position + * @param min_width + * if the width of a parental element is greater than the element + * itself, the min_width is used + * @param direction + * changes its value on each repetition + * @param stairs + * boolean, telling wether to render or without stairs + * @param render + * indicates whether RenderElements should be created or not. + * @return a virtual dimension, containing the real coordinates of a + * Component and the virtual dimension of the syntax diagram element + */ + private VirtualDim getDimFromElement(SynDiaElem e, int x, int y, + int min_width, boolean direction, boolean stairs, boolean render) { + + VirtualDim dim = new VirtualDim(); + + // Vergleich ob trans(...) oder Element + if (transMap.get(e) != null) { + + // + // TRANSELEMENT + // + + Font ebnfFont = null; + try { + ebnfFont = EbnfFont.getFont().deriveFont(Font.ITALIC, + rv.font.getSize()); + } catch (FontNotInitializedException ex) { + + ex.printStackTrace(); + } + + int width = rv.getWidthFromString("trans(" + + EbnfRenderer.toRenderString(transMap.get(e), true, "") + + ")", ebnfFont) + + (int) Math.round(1.3 * rv.radius); + + int height = 2 * rv.radius; + + if (width < height) + width = height; + + dim = new VirtualDim(width, height, height); + if (render) + addElemToRenderList(RenderValues.TRANSTERM, e, x, y, width, + height, "trans(" + + EbnfRenderer.toRenderString(transMap.get(e), + true, "") + ")", EbnfRenderer + .toRenderStringList(transMap.get(e), true)); + + return dim; + + } else { + + dim = this.getDimFromElem(e, x, y, min_width, direction, stairs, + render); + + } + + return dim; + + } + + /** + * Never used!!! + */ + protected VirtualDim getDimFromElement(SynDiaElem e, int x, int y, + boolean direction, boolean render) { + + return null; + + } + + /** + * Caclulates the Dimension of a given element by collecting informations + * from its children [and puts all elements (besides Concatenation) on the + * way into the renderList] + * + * @param e + * A SyntaxDiagram element + * @param x + * x-position of the element + * @param y + * y-position of the element + * @param min_width + * if the width of a parental element is greater than the element + * itself, the min_width is used + * @param direction + * true: read left to right, false: read right to left + * @param stairs + * boolean, telling wether to render or without stairs + * @param render + * A paramter, telling the method, whether creating + * RenderElements or just calculate the Dimension + * @return Width of e + */ + private VirtualDim getDimFromElem(SynDiaElem e, int x, int y, + int min_width, boolean direction, boolean stairs, boolean render) { + + /* + * TERMINAL + */ + if (e instanceof TerminalSymbol) { + TerminalSymbol t = (TerminalSymbol) e; + + int width = rv.getWidthFromString(t.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + if (render) + addElemToRenderList(RenderValues.TERMINAL, t, x, y, width, + height, t.getLabel(), null); + + return dim; + /* + * VARIABLE + */ + } else if (e instanceof Variable) { + + Variable v = (Variable) e; + + int width = rv.getWidthFromString(v.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + + if (render) + addElemToRenderList(RenderValues.VARIABLE, v, x, y, width, + height, v.getLabel(), null); + + return dim; + /* + * BRANCH + */ + } else if (e instanceof Branch) { + + // width + Branch b = (Branch) e; + VirtualDim dim_left = getDimFromElement(b.getLeft(), x + 2 + * rv.radius, y, min_width, direction, true, render); + VirtualDim dim = dim_left; + VirtualDim dim_right = null; + + Concatenation right = b.getRight(); + if (dim_left.width > min_width) + min_width = dim_left.width; + + if (right.getNumberOfElems() == 1 + && right.getSynDiaElem(0) instanceof Branch + && !rv.withStairs) { + if (transMap.get(right.getSynDiaElem(0)) != null) { + dim_right = getDimFromElement(right, x + 2 * rv.radius, y + + dim_left.height + rv.space, min_width, direction, + false, render); + } else { + dim_right = getDimFromElement(right, x, y + dim_left.height + + rv.space, min_width, direction, false, render); + } + + } else { + dim_right = getDimFromElement(right, x + 2 * rv.radius, y + + dim_left.height + rv.space, 0, direction, + true, render); + } + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + if (dim.width < min_width && !rv.withStairs) + dim.width = min_width; + + if (b.getRight().getNumberOfElems() == 1 + && b.getRight().getSynDiaElem(0) instanceof Branch + && !rv.withStairs) { + if (transMap.get(b.getRight().getSynDiaElem(0)) != null) + dim.width += 4 * rv.radius; + + } else { + + dim.width += 4 * rv.radius; + } + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) { + + if (stairs || rv.withStairs) + addElemToRenderList(RenderValues.BRANCH, b, x, y, + dim.width, dim.height, "", null); + else + addElemToRenderList(RenderValues.BRANCHNOSTAIRS, b, x, y, + dim.width, dim.height, "", null); + } + + return dim; + /* + * CONCATENATION + */ + } else if (e instanceof Concatenation) { + + Concatenation c = (Concatenation) e; + + // width & height + VirtualDim dim = new VirtualDim(); + VirtualDim dim_tmp = new VirtualDim(); + + int i = 0; + SynDiaElem sde; + for (i = 0; i < c.getNumberOfElems(); i++) { + + if (direction) + sde = c.getSynDiaElem(i); + else + sde = c.getSynDiaElem(c.getNumberOfElems() - i - 1); + + dim_tmp = getDimFromElement(sde, x, y, min_width, direction, + (stairs || rv.withStairs), render); + + dim.width += dim_tmp.width; + + if (dim_tmp.virtualHeight > dim.virtualHeight) + dim.virtualHeight = dim_tmp.virtualHeight; + + x += dim_tmp.width + rv.space; + + } + + if (i > 0) + dim.width += (i - 1) * rv.space; + + if (dim.virtualHeight < 2 * rv.radius) { + + dim.virtualHeight = 2 * rv.radius; + + } + dim.height = dim.virtualHeight; + + return dim; + /* + * REPETITION + */ + } else if (e instanceof Repetition) { + + // width + Repetition r = (Repetition) e; + VirtualDim dim_left = getDimFromElement(r.getLeft(), x + 2 + * rv.radius, y, min_width, direction, true, render); + + VirtualDim dim_right = getDimFromElement(r.getRight(), x + 2 + * rv.radius, y + dim_left.height + rv.space, min_width, + !direction, true, render); + VirtualDim dim = dim_left; + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + dim.width += 4 * rv.radius; + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) + addElemToRenderList(RenderValues.REPETITION, r, x, y, + dim.width, dim.height, "", null); + + return dim; + + } + /* + * OTHERS + */ + return new VirtualDim(0, 0, 0); + } + + /** + * Adds an element to the render List + * + * @param type + * to be found in the RenderValues + * @param s + * the syntax diagram element itself + * @param x + * the position of the element + * @param y + * the position of the element + * @param width + * the width of that element + * @param height + * the height of that element + * @param label + * optionally the name (or null) of the element + * @param stringList + * the List of all substrings the label consists of + */ + private void addElemToRenderList(int type, SynDiaElem s, int x, int y, + int width, int height, String label, List stringList) { + + RenderElement renderElem = RenderElementFactory.createElement(type, + label, stringList); + + renderElem.setRenderValues(rv); + + // Shadow for TerminalSymbol and Variable +// The if-branch will never be executed... (michael p, 31/10/08) +// if (renderElem.getClass() == TerminalSymbol.class +// || renderElem.getClass() == Variable.class) { +// +// renderElem.setSize(width + 3, height + 3); +// renderElem.setLocation(x - 1, y - 1); +// } else { + + renderElem.setSize(width, height); + renderElem.setLocation(x, y); +// } + // new position for the element + renderElem.update(); + + // hinzufügen zur renderMap + renderMap.put(renderElem, s); + + } + + /** + * @return the associated RenderValues + */ + public RenderValues getRenderValues() { + + return rv; + } +} diff --git a/src/org/jalgo/module/ebnf/renderer/VirtualDim.java b/src/org/jalgo/module/ebnf/renderer/VirtualDim.java new file mode 100644 index 0000000..014f44d --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/VirtualDim.java @@ -0,0 +1,53 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer; + +/** + * Is a class, which contains the real dimension used to define an element to + * render and a virtualHeight needed to get the rekursive full height of a + * branch + * + * @author Andre + */ +public class VirtualDim { + + /** + * Represents the real width of a drawn element + */ + public int width; + + /** + * Represents the real height of a drawn element + */ + public int height; + + /** + * Reperesents the height including all children + */ + public int virtualHeight; + + /** + * Initializes the elements and sets them to 0 + */ + public VirtualDim() { + + this.width = 0; + this.height = 0; + this.virtualHeight = 0; + + } + + /** Initializes the elements by getting the values + * @param width the width + * @param height the height + * @param virtualHeight the virtualHeight. + */ + public VirtualDim(int width, int height, int virtualHeight) { + + this.width = width; + this.height = height; + this.virtualHeight = virtualHeight; + + } +} diff --git a/src/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.java b/src/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.java new file mode 100644 index 0000000..aa79336 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/WordAlgoRenderer.java @@ -0,0 +1,323 @@ +package org.jalgo.module.ebnf.renderer; + +import java.awt.Dimension; +import java.awt.Font; +import java.util.List; + +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; +import org.jalgo.module.ebnf.gui.ebnf.EbnfRenderer; +import org.jalgo.module.ebnf.model.syndia.Branch; +import org.jalgo.module.ebnf.model.syndia.Concatenation; +import org.jalgo.module.ebnf.model.syndia.NullElem; +import org.jalgo.module.ebnf.model.syndia.Repetition; +import org.jalgo.module.ebnf.model.syndia.SynDiaElem; +import org.jalgo.module.ebnf.model.syndia.SyntaxDiagram; +import org.jalgo.module.ebnf.model.syndia.TerminalSymbol; +import org.jalgo.module.ebnf.model.syndia.Variable; +import org.jalgo.module.ebnf.model.trans.TransMap; +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderName; + +/** + * This class gets a syntax diagram, a drawing area (JComponent) and some + * other optional params. As result you will get a drawn syntax diagram (system) on the + * given area. + * + * @author Andre Viergutz + */ +public class WordAlgoRenderer extends SynDiaRenderer{ + + protected VirtualDim getMyDim(SyntaxDiagram sd) { + + return getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, 0, true, true, true); + + } + + @Override + protected VirtualDim getDimFromElement(SynDiaElem e, int x, int y, boolean direction, boolean render) { + return null; + } + + /** + * This method checks whether the given element is already transformed or + * not. In case of an element is to transform a RenderTrans is created, + * otherwise the other fitting element + * + * @param e + * a SynDiaElem> to be calculated + * @param x + * the start position + * @param y + * the start position + * @param min_width + * if the width of a parental element is greater than the element + * itself, the min_width is used + * @param direction + * changes its value on each repetition + * @param stairs + * boolean, telling wether to render or without stairs + * @param render + * indicates whether RenderElements should be created or not. + * @return a virtual dimension, containing the real coordinates of a + * Component and the virtual dimension of the syntax diagram element + */ + protected VirtualDim getDimFromElement(SynDiaElem e, int x, int y, + int min_width, boolean direction, boolean stairs, boolean render) { + + /* + * TERMINAL + */ + if (e instanceof TerminalSymbol) { + TerminalSymbol t = (TerminalSymbol) e; + + int width = rv.getWidthFromString(t.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + if (render) + addElemToRenderList(RenderValues.TERMINAL, t, x, y, width, + height, t.getLabel(), null); + + return dim; + /* + * VARIABLE + */ + } else if (e instanceof Variable) { + + Variable v = (Variable) e; + + int width = rv.getWidthFromString(v.getLabel()) + + (int) Math.round(1.3 * rv.radius); + int height = 2 * rv.radius; + + if (width < height) + width = height; + + VirtualDim dim = new VirtualDim(width, height, height); + + if (render) + addElemToRenderList(RenderValues.VARIABLE, v, x, y, width, + height, v.getLabel(), null); + + return dim; + /* + * BRANCH + */ + } else if (e instanceof Branch) { + + // width + Branch b = (Branch) e; + VirtualDim dim_left = getDimFromElement(b.getLeft(), x + 2 + * rv.radius, y, min_width, direction, true, render); + VirtualDim dim = dim_left; + VirtualDim dim_right = null; + + Concatenation right = b.getRight(); + if (dim_left.width > min_width) + min_width = dim_left.width; + + if (right.getNumberOfElems() == 1 + && right.getSynDiaElem(0) instanceof Branch + && !rv.withStairs) { + + dim_right = getDimFromElement(right, x, y + dim_left.height + + rv.space, min_width, direction, false, render); + + } else { + dim_right = getDimFromElement(right, x + 2 * rv.radius, y + + dim_left.height + rv.space, 0, direction, + true, render); + } + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + if (dim.width < min_width && !rv.withStairs) + dim.width = min_width; + + if (b.getRight().getNumberOfElems() == 1 + && b.getRight().getSynDiaElem(0) instanceof Branch + && !rv.withStairs) { + + } else { + + dim.width += 4 * rv.radius; + } + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) { + + if (stairs || rv.withStairs) + addElemToRenderList(RenderValues.BRANCH, b, x, y, + dim.width, dim.height, "", null); + else + addElemToRenderList(RenderValues.BRANCHNOSTAIRS, b, x, y, + dim.width, dim.height, "", null); + } + + return dim; + /* + * CONCATENATION + */ + } else if (e instanceof Concatenation) { + + Concatenation c = (Concatenation) e; + + // width & height + VirtualDim dim = new VirtualDim(); + VirtualDim dim_tmp = new VirtualDim(); + + int i = 0; + SynDiaElem sde; + for (i = 0; i < c.getNumberOfElems(); i++) { + + if (direction) + sde = c.getSynDiaElem(i); + else + sde = c.getSynDiaElem(c.getNumberOfElems() - i - 1); + + dim_tmp = getDimFromElement(sde, x, y, min_width, direction, + (stairs || rv.withStairs), render); + + dim.width += dim_tmp.width; + + if (dim_tmp.virtualHeight > dim.virtualHeight) + dim.virtualHeight = dim_tmp.virtualHeight; + + x += dim_tmp.width + rv.space; + + } + + if (i > 0) + dim.width += (i - 1) * rv.space; + + if (dim.virtualHeight < 2 * rv.radius) { + + dim.virtualHeight = 2 * rv.radius; + + } + dim.height = dim.virtualHeight; + + return dim; + /* + * REPETITION + */ + } else if (e instanceof Repetition) { + + // width + Repetition r = (Repetition) e; + VirtualDim dim_left = getDimFromElement(r.getLeft(), x + 2 + * rv.radius, y, min_width, direction, true, render); + + VirtualDim dim_right = getDimFromElement(r.getRight(), x + 2 + * rv.radius, y + dim_left.height + rv.space, min_width, + !direction, true, render); + VirtualDim dim = dim_left; + + if (dim_right.width > dim.width) + dim.width = dim_right.width; + + dim.width += 4 * rv.radius; + + // height + dim.height = dim_left.height + rv.space + 2 * rv.radius; + + dim.virtualHeight = dim_left.virtualHeight + rv.space + + dim_right.virtualHeight; + + if (render) + addElemToRenderList(RenderValues.REPETITION, r, x, y, + dim.width, dim.height, "", null); + + return dim; + + } + /* + * OTHERS + */ + return new VirtualDim(0, 0, 0); + } + + /** + * Adds an element to the render List + * + * @param type + * to be found in the RenderValues + * @param s + * the syntax diagram element itself + * @param x + * the position of the element + * @param y + * the position of the element + * @param width + * the width of that element + * @param height + * the height of that element + * @param label + * optionally the name (or null) of the element + * @param stringList + * the List of all substrings the label consists of + */ + private void addElemToRenderList(int type, SynDiaElem s, int x, int y, + int width, int height, String label, List stringList) { + + RenderElement renderElem = RenderElementFactory.createElement(type, + label, stringList); + + renderElem.setRenderValues(rv); + + // Shadow for TerminalSymbol and Variable +// The if-branch will never be executed... (michael p, 31/10/08) +// if (renderElem.getClass() == TerminalSymbol.class +// || renderElem.getClass() == Variable.class) { +// +// renderElem.setSize(width + 3, height + 3); +// renderElem.setLocation(x - 1, y - 1); +// } else { + + renderElem.setSize(width, height); + renderElem.setLocation(x, y); +// } + // new position for the element + renderElem.update(); + + // hinzufügen zur renderMap + renderMap.put(renderElem, s); + + } + + /** + * Calculates the size of the given diagram + * + * @param sd + * A SyntaxDiagram + * @return A map with all elements to be rendered + */ + public Dimension getDiagramSize(SyntaxDiagram sd) { + + VirtualDim vdim = getDimFromElement(sd.getRoot(), rv.radius, + 2 * rv.radius, 0, true, true, false); + + Dimension dimension = new Dimension(); + + dimension.width = vdim.width + 2 * rv.radius; + dimension.height = vdim.virtualHeight + 2 * rv.radius; + + return dimension; + } + + + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/CVS/Entries b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Entries new file mode 100644 index 0000000..7bb42e6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Entries @@ -0,0 +1,13 @@ +/RenderBase.java/1.1/Fri Aug 11 16:40:29 2006// +/RenderBranch.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderElement.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderName.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderNoStairBranch.java/1.1/Fri Aug 11 16:40:29 2006// +/RenderNullElem.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderRepetition.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderSplit.java/1.1/Fri Aug 11 16:40:29 2006// +/RenderTerminal.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderTiledBranch.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderTiledRepetition.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderTrans.java/1.1/Fri Aug 11 16:40:29 2006// +/RenderVariable.java/1.1/Fri Aug 11 16:40:29 2006// diff --git a/src/org/jalgo/module/ebnf/renderer/elements/CVS/Repository b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Repository new file mode 100644 index 0000000..89aa3cc --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/renderer/elements diff --git a/src/org/jalgo/module/ebnf/renderer/elements/CVS/Root b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderBase.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderBase.java new file mode 100644 index 0000000..b606fc9 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderBase.java @@ -0,0 +1,43 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * This class reperesents the base elements of a syntax diagram, like the base + * line and the name + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderBase extends RenderElement { + + /** + * Initializes the render base and sets the name of the syntax diagram + */ + public RenderBase() { + + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(STANDARD_COLOR); + g2d.drawLine(0, 3 * rv.radius, this.getWidth(), 3 * rv.radius); + + } + + public void update() { + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderBranch.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderBranch.java new file mode 100644 index 0000000..c873bd9 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderBranch.java @@ -0,0 +1,43 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.geom.Arc2D; + +/** + * This class represents a drawn branch of a syntax diagram + * + * @author Andre + */ +@SuppressWarnings("serial") +public class RenderBranch extends RenderSplit { + + + public void update() { + + int radius = rv.radius; + + arc_left_top.setArc(-radius, radius, 2 * radius, 2 * radius, 0, 90, + Arc2D.OPEN); + + arc_left_bottom.setArc(radius, this.getHeight() - 3 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_top.setArc(this.getWidth() - radius, radius, 2 * radius, + 2 * radius, 92, 90, Arc2D.OPEN); + arc_right_bottom.setArc(this.getWidth() - 3 * radius, this.getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_top.setLine(2, radius, this.getWidth()-2, radius); + line_bottom.setLine(2 * radius, this.getHeight() - radius, this + .getWidth() + - 2 * radius, this.getHeight() - radius); + line_left.setLine(radius, 2 * radius, radius, this.getHeight() - 2 + * radius); + line_right.setLine(this.getWidth() - radius, 2 * radius, this + .getWidth() + - radius, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderElement.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderElement.java new file mode 100644 index 0000000..06a2e1e --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderElement.java @@ -0,0 +1,116 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Stroke; + +import javax.swing.JComponent; + +import org.jalgo.module.ebnf.renderer.RenderValues; + +/** + * @author Andre Viergutz + */ +public abstract class RenderElement extends JComponent { + + /** + * a fat stroke, used on mouse over in the syntax diagram editor + */ + public static final Stroke HIGHLIGHT_STROKE = new BasicStroke(4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); + /** + * a warning red, used to show elements to delete + */ + public static final Color HIGHLIGHT_COLOR = new Color(255, 50, 50); + /** + * the standard stroke + */ + public static final Stroke STANDARD_STROKE = new BasicStroke(); + /** + * the standard color of basic strokes in diagram + */ + public static final Color STANDARD_COLOR = new Color(0, 0, 0); + /** + * the standard fill color of elements + */ + public static final Color STANDARD_FILL_COLOR = new Color(255, 255, 255); + /** + * a light green + */ + public static final Color HIGHLIGHT_COLOR_2 = new Color(220, 255, 220); + /** + * a light yellow + */ + public static final Color HIGHLIGHT_YELLOW = new Color(240, 240, 200); + /** + * a light blue + */ + public static final Color HIGHLIGHT_BLUE = new Color(200, 200, 240); + + protected Color color = STANDARD_FILL_COLOR; + + protected RenderValues rv = new RenderValues(); + + protected AlphaComposite makeComposite(float alpha) { + int type = AlphaComposite.SRC_OVER; + return (AlphaComposite.getInstance(type, alpha)); + } + + /** + * Must be implemented, nothing happens (paintComponent is called anyway) + */ + public abstract void update(); + + /** Sets the given Color + * @param c a Color object + */ + public void setColor(Color c) { + this.color = c; + this.repaint(); + } + /** Changes each coloor channel by 20 values. + * @param brighter true, if it should be brighter or false, if darker + */ + public void changeColor(boolean brighter) { + + if (brighter) { + int r = color.getRed() + 20; + int g = color.getGreen() + 20; + int b = color.getBlue() + 20; + + if (r > 255) r = 255; + if (g > 255) g = 255; + if (b > 255) b = 255; + + color = new Color(r, g, b); + } else { + + int r = color.getRed() - 20; + int g = color.getGreen() - 20; + int b = color.getBlue() - 20; + + if (r > 255) r = 255; + if (g > 255) g = 255; + if (b > 255) b = 255; + + color = new Color(r, g, b); + + } + update(); + this.getParent().repaint(); + + } + + /** Sets the given RenderValues + * @param rv + */ + public void setRenderValues(RenderValues rv) { + + this.rv = rv; + } + + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderName.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderName.java new file mode 100644 index 0000000..00ba4b2 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderName.java @@ -0,0 +1,74 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * This class reperesents the base elements of a syntax diagram, like the base + * line and the name + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderName extends RenderElement { + + /** + * Reperesents the name of the syntax diagram + */ + private String name; + private boolean startDiagram; + private int fontStyle; + + /** + * Initializes the render base and sets the name of the syntax diagram + * + * @param name + * the name of the syntax diagram + * @param startDiagram + * indicates whether this RenderBase belongs to a startDiagram + */ + public RenderName(String name, boolean startDiagram) { + + this.name = name; + this.startDiagram = startDiagram; + this.setBackground(new Color(150, 150, 50)); + fontStyle = Font.ITALIC; + + } + + /** + * Sets the style of the font. + * + * @param fontStyle + * the style of the font + */ + public void setFontStyle(int fontStyle) { + this.fontStyle = fontStyle; + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setFont(new Font(rv.font.getName(), fontStyle, rv.font.getSize())); + if (startDiagram) + g2d.setColor(HIGHLIGHT_COLOR); + + g2d.drawString(name, 0, (int) Math.round(0.9 * rv.radius)); + + } + + public void update() { + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.java new file mode 100644 index 0000000..abf5972 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderNoStairBranch.java @@ -0,0 +1,82 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +/** + * This class represents a drawn branch of a syntax diagram + * + * @author Andre + */ +@SuppressWarnings("serial") +public class RenderNoStairBranch extends RenderSplit { + + + + /** + * Initializes the elements + */ + public RenderNoStairBranch() { + + this.setEnabled(true); + + arc_left_bottom = new Arc2D.Double(); + arc_right_bottom = new Arc2D.Double(); + + line_top = new Line2D.Double(); + line_bottom = new Line2D.Double(); + line_left = new Line2D.Double(); + line_right = new Line2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(STANDARD_COLOR); + g2d.setStroke(STANDARD_STROKE); + g2d.draw(line_top); + + g2d.setColor(bottomColor); + g2d.setStroke(bottomStroke); + g2d.draw(arc_left_bottom); + g2d.draw(arc_right_bottom); + + g2d.draw(line_bottom); + g2d.draw(line_left); + g2d.draw(line_right); + + } + + public void update() { + + int radius = rv.radius; + + arc_left_bottom.setArc(radius, this.getHeight() - 3 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_bottom.setArc(this.getWidth() - 3 * radius, this.getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_top.setLine(2 * radius, radius, this.getWidth() - 2 * radius, radius); + line_bottom.setLine(2 * radius, this.getHeight() - radius, this + .getWidth() + - 2 * radius, this.getHeight() - radius); + line_left.setLine(radius, 0, radius, this.getHeight() - 2 + * radius); + line_right.setLine(this.getWidth() - radius, 0, this + .getWidth() + - radius, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.java new file mode 100644 index 0000000..0b92fec --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderNullElem.java @@ -0,0 +1,95 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.AffineTransform; +import java.awt.geom.RoundRectangle2D; + +/** + * This class reperesents the element in the syntax diagram editor showing if + * the user is possible add a new element + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderNullElem extends RenderElement { + + /** + * Some shape to represent this element + */ + private RoundRectangle2D.Double kreis; + + private float composite; + + /** + * grey, used when mouse outside null element + */ + public final static Color STANDARD_COLOR_GREY = new Color(130, 130, 110); + + /** + * green, used when mouse over null element + */ + public final static Color HIGHLIGHT_GREEN = new Color(0, 150, 0); + + /** + * Inititalizes the element + */ + public RenderNullElem() { + + this.setEnabled(true); + + composite = 0.2f; + + this.setColor(STANDARD_COLOR_GREY); + kreis = new RoundRectangle2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + + g2d.setComposite(makeComposite(composite)); + g2d.setColor(color); + + AffineTransform at = new AffineTransform(); + at.rotate(0.25 * Math.PI, 0.5 * getWidth(), 0.5 * getHeight()); + g2d.transform(at); + g2d.fill(kreis); + + } + + public void update() { + + int width = (int) Math.round(getWidth()/2*Math.sqrt(2)); + int height = (int) Math.round(getHeight()/2*Math.sqrt(2)); + kreis.setRoundRect( + (getWidth()-width)/2, + (getHeight()-height)/2, + width, + height, + 0.1 * getHeight(), + 0.1 * getHeight()); + + } + + public void setColor(Color color) { + this.color = color; + if (color.equals(STANDARD_COLOR_GREY)) { + composite = 0.2f; + } else { + composite = 0.4f; + } + this.repaint(); + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.java new file mode 100644 index 0000000..e6c8ed1 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderRepetition.java @@ -0,0 +1,41 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.geom.Arc2D; + +/** + * This class represents a drawn repetition of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderRepetition extends RenderSplit { + + + public void update() { + + int radius = rv.radius; + + arc_left_top.setArc(2, radius, 2 * radius, 2 * radius, 90, 90, + Arc2D.OPEN); + + arc_left_bottom.setArc(2, this.getHeight() - 3 * radius, 2 * radius, + 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_top.setArc(this.getWidth() - 2 * radius - 2, radius, 2 * radius, + 2 * radius, 0, 90, Arc2D.OPEN); + arc_right_bottom.setArc(this.getWidth() - 2 * radius - 2, this + .getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_top.setLine(radius, radius, this.getWidth()-radius, radius); + line_bottom.setLine(radius, this.getHeight() - radius, this.getWidth() + - radius, this.getHeight() - radius); + line_left.setLine(2, 2 * radius, 2, this.getHeight() - 2 * radius); + line_right.setLine(this.getWidth() - 2, 2 * radius, + this.getWidth() - 2, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderSplit.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderSplit.java new file mode 100644 index 0000000..7d27868 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderSplit.java @@ -0,0 +1,158 @@ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Stroke; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +/** + * This class represents a drawn branch of a syntax diagram + * + * @author Andre + */ +@SuppressWarnings("serial") +public class RenderSplit extends RenderElement { + + // TODO [Andre] Man kann auch über affine Transformationen mit nur einem + // Arc2D aukommen + + protected Arc2D.Double arc_left_top; + + protected Arc2D.Double arc_right_top; + + protected Arc2D.Double arc_left_bottom; + + protected Arc2D.Double arc_right_bottom; + + protected Line2D.Double line_top; + + protected Line2D.Double line_bottom; + + protected Line2D.Double line_left; + + protected Line2D.Double line_right; + + protected Color topColor = new Color(0, 0, 0); + + protected Color bottomColor = new Color(0, 0, 0); + + protected Stroke topStroke = new BasicStroke(); + + protected Stroke bottomStroke = new BasicStroke(); + + /** + * Initializes the elements + */ + public RenderSplit() { + + this.setEnabled(true); + arc_left_top = new Arc2D.Double(); + arc_right_top = new Arc2D.Double(); + arc_left_bottom = new Arc2D.Double(); + arc_right_bottom = new Arc2D.Double(); + + line_top = new Line2D.Double(); + line_bottom = new Line2D.Double(); + line_left = new Line2D.Double(); + line_right = new Line2D.Double(); + + } + + /** + * Sets the given color to the top area of a branch or repetition and + * changes the stroke to thin or fat + * + * @param highlight true, if you want to highlight this part + * @param hColor the highlight color + */ + public void setTopHighlight(boolean highlight, Color hColor) { + + if (highlight) { + topColor = hColor; + topStroke = HIGHLIGHT_STROKE; + } else { + topColor = hColor; + topStroke = STANDARD_STROKE; + } + this.repaint(); + + } + + /** + * Sets the given color to the bottom area of a branch or repetition and + * changes the stroke to thin or fat + * + * @param highlight true, if you want to highlight this part + * @param hColor the highlight color + */ + public void setBottomHighlight(boolean highlight, Color hColor) { + + if (highlight) { + bottomColor = hColor; + bottomStroke = HIGHLIGHT_STROKE; + } else { + bottomColor = hColor; + bottomStroke = STANDARD_STROKE; + } + this.repaint(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // top + g2d.setColor(topColor); + g2d.setStroke(topStroke); + g2d.draw(line_top); + + // bottom + g2d.setColor(bottomColor); + g2d.setStroke(bottomStroke); + + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + + g2d.draw(line_bottom); + g2d.draw(line_left); + g2d.draw(line_right); + + } + + public void update() { + + int radius = rv.radius; + + arc_left_top.setArc(-radius, radius, 2 * radius, 2 * radius, 0, 90, + Arc2D.OPEN); + + arc_left_bottom.setArc(radius, this.getHeight() - 3 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_top.setArc(this.getWidth() - radius, radius, 2 * radius, + 2 * radius, 92, 90, Arc2D.OPEN); + arc_right_bottom.setArc(this.getWidth() - 3 * radius, this.getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_top.setLine(2, radius, this.getWidth() - 2, radius); + line_bottom.setLine(2 * radius, this.getHeight() - radius, this + .getWidth() + - 2 * radius, this.getHeight() - radius); + line_left.setLine(radius, 2 * radius, radius, this.getHeight() - 2 + * radius); + line_right.setLine(this.getWidth() - radius, 2 * radius, this + .getWidth() + - radius, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.java new file mode 100644 index 0000000..26876e9 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderTerminal.java @@ -0,0 +1,88 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.RoundRectangle2D; + +/** + * This class represents a drawn terminal symbol of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderTerminal extends RenderElement { + + /** + * Represents the name of the terminal symbol + */ + public String label; + + /** + * Represents the border of the symbol + */ + private RoundRectangle2D.Double kreis; + + /** + * Inititalizes the element by getting the name of the symbol + * + * @param label the name of the terminal symbol + */ + public RenderTerminal(String label) { + + this.label = label; + // this.setEnabled(true); + + kreis = new RoundRectangle2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(Color.BLACK); + kreis.x += 3; + kreis.y += 3; + + g2d.setComposite(makeComposite(0.4F)); + g2d.fill(kreis); + + kreis.x -= 3; + kreis.y -= 3; + + g2d.setComposite(makeComposite(1F)); + + g2d.setColor(color); + g2d.fill(kreis); + + g2d.setColor(STANDARD_COLOR); + g2d.setFont(rv.font); + + int x; + if (label.length() > 1) + x = (int) Math.round(0.6 * rv.radius); + else + x = (int) Math.round(0.66 * rv.radius); + g2d.drawString(label, x, (int) Math + .floor(1.27 * rv.radius)); + + g2d.draw(kreis); + + } + + public void update() { + + kreis.setRoundRect(1, 1, getWidth() - 5, getHeight() - 5, + getHeight() - 5, getHeight() - 5); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.java new file mode 100644 index 0000000..045a9e7 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledBranch.java @@ -0,0 +1,106 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +/** + * This class represents a drawn branch of a syntax diagram + * + * @author Andre + */ +@SuppressWarnings("serial") +public class RenderTiledBranch extends RenderElement { + + // TODO [Andre] Man kann auch über affine Transformationen mit nur einem + // Arc2D aukommen + + private Arc2D.Double arc_left_top; + + private Arc2D.Double arc_right_top; + + private Arc2D.Double arc_left_bottom; + + private Arc2D.Double arc_right_bottom; + + private Line2D.Double line_bottom; + + private Line2D.Double line_left; + + private Line2D.Double line_right; + + /** + * Initializes the elements + */ + public RenderTiledBranch() { + + this.setEnabled(true); + arc_left_top = new Arc2D.Double(); + arc_right_top = new Arc2D.Double(); + arc_left_bottom = new Arc2D.Double(); + arc_right_bottom = new Arc2D.Double(); + + line_bottom = new Line2D.Double(); + line_left = new Line2D.Double(); + line_right = new Line2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + + float dash[] = { 2.0f, 5.0f }; + g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, + BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f)); + g2d.setColor(Color.GRAY); + + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(line_left); + + + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + g2d.draw(line_bottom); + g2d.draw(line_right); + + } + + public void update() { + + int radius = rv.radius; + + arc_left_top.setArc(-radius, radius, 2 * radius, 2 * radius, 0, 90, + Arc2D.OPEN); + + arc_left_bottom.setArc(radius, this.getHeight() - 3 * radius, + 2 * radius, 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_top.setArc(this.getWidth() - radius, radius, 2 * radius, + 2 * radius, 90, 90, Arc2D.OPEN); + arc_right_bottom.setArc(this.getWidth() - 3 * radius, this.getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_bottom.setLine(2 * radius, this.getHeight() - radius, this + .getWidth() + - 2 * radius, this.getHeight() - radius); + line_left.setLine(radius, 2 * radius, radius, this.getHeight() - 2 + * radius); + line_right.setLine(this.getWidth() - radius, 2 * radius, this + .getWidth() + - radius, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.java new file mode 100644 index 0000000..05e3e66 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderTiledRepetition.java @@ -0,0 +1,103 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; + +/** + * This class represents a drawn repetition of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderTiledRepetition extends RenderElement { + + // TODO [Andre] Man kann auch über affine Transformationen mit nur einem + // Arc2D aukommen + + + private Arc2D.Double arc_left_top; + private Arc2D.Double arc_right_top; + private Arc2D.Double arc_left_bottom; + private Arc2D.Double arc_right_bottom; + private Line2D.Double line_bottom; + private Line2D.Double line_left; + private Line2D.Double line_right; + + /** + * Initializes the elements + */ + public RenderTiledRepetition() { + + this.setEnabled(true); + arc_left_top = new Arc2D.Double(); + arc_right_top = new Arc2D.Double(); + arc_left_bottom = new Arc2D.Double(); + arc_right_bottom = new Arc2D.Double(); + + line_bottom = new Line2D.Double(); + line_left = new Line2D.Double(); + line_right = new Line2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + /* + * g2d.setColor(Color.BLACK); kreis.x += 3; kreis.y += 3; + * g2d.setComposite(makeComposite(0.4F)); g2d.fill(kreis); kreis.x -= 3; + * kreis.y -= 3; g2d.setComposite(makeComposite(1F)); + */ + + float dash[] = { 2.0f, 5.0f }; + g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, + BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f)); + g2d.setColor(Color.GRAY); + + g2d.draw(arc_left_top); + g2d.draw(arc_left_bottom); + g2d.draw(line_left); + + g2d.draw(arc_right_top); + g2d.draw(arc_right_bottom); + g2d.draw(line_bottom); + g2d.draw(line_right); + + } + + public void update() { + + int radius = rv.radius; + + arc_left_top.setArc(0, radius, 2 * radius, 2 * radius, 90, 90, + Arc2D.OPEN); + + arc_left_bottom.setArc(0, this.getHeight() - 3 * radius, 2 * radius, + 2 * radius, 180, 90, Arc2D.OPEN); + + arc_right_top.setArc(this.getWidth() - 2 * radius, radius, 2 * radius, + 2 * radius, -1, 90, Arc2D.OPEN); + arc_right_bottom.setArc(this.getWidth() - 2 * radius - 1, this + .getHeight() + - 3 * radius, 2 * radius, 2 * radius, 270, 90, Arc2D.OPEN); + line_bottom.setLine(radius, this.getHeight() - radius, this.getWidth() + - radius, this.getHeight() - radius); + line_left.setLine(0, 2 * radius, 0, this.getHeight() - 2 * radius); + line_right.setLine(this.getWidth() - 1, 2 * radius, + this.getWidth() - 1, this.getHeight() - 2 * radius); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderTrans.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderTrans.java new file mode 100644 index 0000000..8f81221 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderTrans.java @@ -0,0 +1,145 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.RoundRectangle2D; +import java.util.List; + +import org.jalgo.module.ebnf.gui.EbnfFont; +import org.jalgo.module.ebnf.gui.FontNotInitializedException; + +/** + * This class represents a transformable element of a syntax diagram used in the + * trans() algorithm + * + * @author Andre + */ +@SuppressWarnings("serial") +public class RenderTrans extends RenderElement { + + private static Color TRANS_HIGHLIGHT_STD = new Color(90, 110, 80); + + /** + * Represents some shape + */ + private RoundRectangle2D.Double kreis; + + /** + * Represents the "trans(..)"-String + */ + private String label; + + private List stringList; + + private boolean showSeperated = false; + + /** + * Initializes the elements + * + * @param label + * the trans(..)-String + * @param stringList + * all trans(..)-Strings separated by first layer + */ + public RenderTrans(String label, List stringList) { + + this.setEnabled(true); + this.label = label; + this.stringList = stringList; + kreis = new RoundRectangle2D.Double(); + + color = new Color(170, 190, 160); + } + + public void paintComponent(Graphics g) { + + // font + Font ebnfFont = null; + try { + ebnfFont = EbnfFont.getFont().deriveFont(Font.ITALIC, + rv.font.getSize()); + } catch (FontNotInitializedException e) { + + e.printStackTrace(); + } + + FontMetrics fm = getFontMetrics(ebnfFont); + + // rendering hints + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // rounded rectangle + g2d.setColor(color); + g2d.fill(kreis); + + // String + g2d.setFont(ebnfFont); // (new Font(rv.font.getName(), Font.ITALIC, + // rv.font.getSize())); + g2d.setColor(new Color(0, 0, 0)); + + if (showSeperated) { + int x = (int) Math.round(0.6 * rv.radius); + + // "trans(" begin String + g2d.setColor(TRANS_HIGHLIGHT_STD); + g2d.drawString("trans(", x, (int) Math.floor(1.3 * rv.radius)); + x += fm.stringWidth("trans("); + + // Term in different colors + for (int i = 0; i < stringList.size(); i++) { + + String s = stringList.get(i); + + if (i % 2 == 0) + g2d.setColor(new Color(250, 250, 250)); + else + g2d.setColor(new Color(0, 0, 0)); + + g2d.drawString(s, x, (int) Math.floor(1.3 * rv.radius)); + + x += fm.stringWidth(s); + + } + // ")" closing bracket + g2d.setColor(TRANS_HIGHLIGHT_STD); + g2d.drawString(")", x, (int) Math.floor(1.3 * rv.radius)); + } else { + + g2d.drawString(label, (int) Math.round(0.6 * rv.radius), (int) Math + .floor(1.3 * rv.radius)); + } + g2d.setColor(Color.BLACK); + g2d.draw(kreis); + + } + + /** + * Tells the element if it should display the trans(..)-String in separated + * colors or not + * + * @param showSep true, if should be separated (alterning black - white) + */ + public void showSeperated(boolean showSep) { + + this.showSeperated = showSep; + this.repaint(); + } + + public void update() { + + kreis.setRoundRect(1, 1, getWidth() - 2, getHeight() - 2, + getHeight() - 2, getHeight() - 2); + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/elements/RenderVariable.java b/src/org/jalgo/module/ebnf/renderer/elements/RenderVariable.java new file mode 100644 index 0000000..53acc25 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/elements/RenderVariable.java @@ -0,0 +1,82 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.elements; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Rectangle2D; + +/** + * This class represents a drawn variable of a syntax diagram + * + * @author Andre Viergutz + */ +@SuppressWarnings("serial") +public class RenderVariable extends RenderElement { + + /** + * Represents the name of the variable + */ + public String label; + + /** + * Represents some shape + */ + protected Rectangle2D.Double rect; + + /** + * Initializes the element + * + * @param label + * the name of the variable + */ + public RenderVariable(String label) { + + this.label = label; + // this.setEnabled(true); + + rect = new Rectangle2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(Color.BLACK); + rect.x += 3; + rect.y += 3; + g2d.setComposite(makeComposite(0.4F)); + g2d.fill(rect); + + rect.x -= 3; + rect.y -= 3; + g2d.setComposite(makeComposite(1F)); + g2d.setColor(color); + g2d.fill(rect); + + g2d.setColor(Color.BLACK); + g2d.setFont(rv.font); + int x; + if (label.length() > 1) + x = (int) Math.round(0.6 * rv.radius); + else + x = (int) Math.round(0.56 * rv.radius); + g2d.drawString(label, x, (int) Math.floor(1.275 * rv.radius)); + + g2d.draw(rect); + + } + + public void update() { + + rect.setRect(1, 1, this.getWidth() - 5, this.getHeight() - 5); + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/event/CVS/Entries b/src/org/jalgo/module/ebnf/renderer/event/CVS/Entries new file mode 100644 index 0000000..de540ce --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/CVS/Entries @@ -0,0 +1,3 @@ +/ColorChangeListener.java/1.1/Fri Aug 11 16:40:33 2006// +/HighlightColorListener.java/1.1/Fri Aug 11 16:40:33 2006// +/SplitListener.java/1.1/Fri Aug 11 16:40:33 2006// diff --git a/src/org/jalgo/module/ebnf/renderer/event/CVS/Repository b/src/org/jalgo/module/ebnf/renderer/event/CVS/Repository new file mode 100644 index 0000000..49003bd --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/renderer/event diff --git a/src/org/jalgo/module/ebnf/renderer/event/CVS/Root b/src/org/jalgo/module/ebnf/renderer/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.java b/src/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.java new file mode 100644 index 0000000..b84e8f6 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/ColorChangeListener.java @@ -0,0 +1,34 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.event; + + +import java.awt.Color; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * @author Andre Viergutz + * + */ +public class ColorChangeListener extends MouseAdapter { + + + public void mouseEntered(MouseEvent e) { + + ((RenderElement) e.getComponent()).setColor(new Color(240,240,200)); + + } + + public void mouseExited(MouseEvent e) { + + ((RenderElement) e.getComponent()).setColor(RenderElement.STANDARD_FILL_COLOR); + + } + + + +} diff --git a/src/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.java b/src/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.java new file mode 100644 index 0000000..a74afe0 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/HighlightColorListener.java @@ -0,0 +1,37 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.event; + + +import java.awt.event.MouseListener; +import java.awt.event.MouseEvent; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * @author Andre Viergutz + * + */ +public class HighlightColorListener implements MouseListener { + + public void mouseClicked(MouseEvent e) {} + + public void mouseEntered(MouseEvent e) { + + ((RenderElement) e.getComponent()).changeColor(true); + + } + + public void mouseExited(MouseEvent e) { + + ((RenderElement) e.getComponent()).changeColor(false); + + } + + public void mousePressed(MouseEvent e) {} + + public void mouseReleased(MouseEvent e) {} + + +} diff --git a/src/org/jalgo/module/ebnf/renderer/event/SplitListener.java b/src/org/jalgo/module/ebnf/renderer/event/SplitListener.java new file mode 100644 index 0000000..a8d060b --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/event/SplitListener.java @@ -0,0 +1,93 @@ +/** + * + */ +package org.jalgo.module.ebnf.renderer.event; + +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import org.jalgo.module.ebnf.renderer.RenderValues; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderSplit; + +/** + * @author Andre + * + */ +public class SplitListener implements MouseListener, MouseMotionListener { + + private RenderValues rv; + + private boolean top = false; + + private boolean in = true; + + /** + * Initializes the controller + * + * @param rv + * The RenderValues to calculate the border + * between top and bottom + */ + public SplitListener(RenderValues rv) { + + this.rv = rv; + + } + + public void mouseMoved(MouseEvent e) { + + RenderSplit rb = (RenderSplit) e.getComponent(); + + if (e.getY() < 2 * rv.radius) { + + if (!top || in) { + rb.setTopHighlight(true, RenderElement.HIGHLIGHT_COLOR); + rb.setBottomHighlight(false, RenderElement.STANDARD_COLOR); + top = true; + } + + } else { + + if (top || in) { + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(true, RenderElement.HIGHLIGHT_COLOR); + top = false; + } + } + in = false; + + } + + public void mouseDragged(MouseEvent e) { + + } + + public void mouseEntered(MouseEvent e) { + + in = true; + + } + + public void mouseExited(MouseEvent e) { + + RenderSplit rb = (RenderSplit) e.getComponent(); + rb.setTopHighlight(false, RenderElement.STANDARD_COLOR); + rb.setBottomHighlight(false, RenderElement.STANDARD_COLOR); + + } + + public void mousePressed(MouseEvent e) { + + } + + public void mouseReleased(MouseEvent e) { + + } + + public void mouseClicked(MouseEvent e) { + + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Entries b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Entries new file mode 100644 index 0000000..55a76b3 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Entries @@ -0,0 +1,5 @@ +/Position.java/1.1/Fri Aug 11 16:40:30 2006// +/RenderEnd.java/1.1/Fri Aug 11 16:40:30 2006// +/ReturnAdress.java/1.1/Fri Aug 11 16:40:30 2006// +/StackAdress.java/1.1/Fri Aug 11 16:40:30 2006// +/StackBase.java/1.1/Fri Aug 11 16:40:30 2006// diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Repository b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Repository new file mode 100644 index 0000000..50c34ff --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/renderer/wordalgorithm diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Root b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.java b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.java new file mode 100644 index 0000000..62ab409 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/Position.java @@ -0,0 +1,397 @@ +package org.jalgo.module.ebnf.renderer.wordalgorithm; + +import org.jalgo.module.ebnf.renderer.elements.RenderBase; +import org.jalgo.module.ebnf.renderer.elements.RenderBranch; +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderRepetition; +import org.jalgo.module.ebnf.renderer.elements.RenderTerminal; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Point; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Rectangle2D; + +import javax.swing.JPanel; + +/** + * This Element is the graphical representation of the actual Position in a + * SyntaxDiagram during the WordAlgorithm + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class Position extends RenderElement { + + // Size of the positionPoint + private int positionSize; + + // Needed to correct positions + private int corr; + + private int radius; + + // Represents some shape + protected Rectangle2D.Double rect; + + /** + * Initializes the element + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @param renderFont + * The font which is used, to draw Terminals or Variables. + * @param changeDirection + * specifies wether or not, the direction should be changed (used + * in repetitions) + */ + public Position(RenderElement aRenderElem, boolean alternativeMode, + boolean behindElement, Font renderFont, boolean changeDirection) { + + int fontSize = renderFont.getSize(); + + FontMetrics fm = new JPanel().getFontMetrics(new Font("Courier", + Font.PLAIN, fontSize)); + radius = (int) Math.round(0.7 * fm.getHeight()); + corr = (int) Math.round(radius / 1.5); + + // Height of the positionPoint is 60% of the Height of a Variable. + this.positionSize = (int) Math.round(0.6 * fm.getHeight()); + + // The ADRESS_SIZE part size of its Variable + this.setSize(positionSize, positionSize); + + // Checkout, which Location is needed for the Position + // It depends on the type of aRenderElem + + // If aRenderElem is a Terminal, the Position can be + // behind or in front of the RenderElem. It depends on the depth + // of repetitions. + if (aRenderElem instanceof RenderTerminal) { + this.setLocation(initTerminal(aRenderElem, alternativeMode, + behindElement, changeDirection)); + } + + // If aRenderElem is a Variable, the Position can be behind the Variable + // or at the jump to a Diagram + if (aRenderElem instanceof RenderVariable) { + this.setLocation(initVariable(aRenderElem, alternativeMode, + behindElement, changeDirection)); + } + + // If aRenderElem is a RenderBase the position must be the begin of the + // SyntaxDiagram. + else if (aRenderElem instanceof RenderBase) { + this.setLocation(initRenderBase(aRenderElem, alternativeMode, + behindElement)); + } + + // If aRenderElem is a RenderRepetition the position must be the begin + // of the + // SyntaxDiagram. + else if (aRenderElem instanceof RenderRepetition) { + this.setLocation(initRepetition(aRenderElem, alternativeMode, + behindElement, changeDirection)); + } + + // If aRenderElem is a RenderBranch the position must be the begin of + // the + // SyntaxDiagram. + else if (aRenderElem instanceof RenderBranch) { + this.setLocation(initBranch(aRenderElem, alternativeMode, + behindElement, changeDirection)); + } + + int correctureX; + + if (this.getX() < 0) + correctureX = 0; + else + correctureX = this.getX(); + this.setLocation(correctureX, this.getY()); + + rect = new Rectangle2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // Shadow + g2d.setColor(Color.BLACK); + rect.x += 3; + rect.y += 3; + g2d.setComposite(makeComposite(0.4F)); + g2d.fill(rect); + + // Point itself + rect.x -= 3; + rect.y -= 3; + g2d.setComposite(makeComposite(1F)); + g2d.setColor(Color.RED); + g2d.fill(rect); + + g2d.draw(rect); + + } + + public void update() { + rect.setRect(0, 0, this.getWidth() - 4, this.getHeight() - 4); + } + + /** + * Init method if aRenderElem is a Terminal + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @return a Point which represents the Location where the Position should + * be drawn. + * @param changeDirection + * specifies wether or not, the direction should be changed + */ + private Point initTerminal(RenderElement aRenderElem, + boolean alternativeMode, boolean behindElement, + boolean changeDirection) { + + int posX, posY; + + // The location realative to the Element + // Ceckout if position should be drawn in front of or behind + if (behindElement ^ changeDirection) { + posX = (int) Math.round(aRenderElem.getX() + aRenderElem.getWidth() + + corr * 0.2); + posY = (int) Math.round(aRenderElem.getY() + radius + - (positionSize / 2) + 1); + } else { + posX = (int) Math.round(aRenderElem.getX() - corr * 1.2); + posY = (int) Math.round(aRenderElem.getY() + radius + - (positionSize / 2) + 1); + } + + return new Point(posX, posY); + } + + /** + * Init method if aRenderElem is a Variable + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @return a Point which represents the Location where the Position should + * be drawn. + * @param changeDirection + * specifies wether or not, the direction should be changed + */ + private Point initVariable(RenderElement aRenderElem, + boolean alternativeMode, boolean behindElement, + boolean changeDirection) { + + int posX, posY; + + // Checkout, if jump to Diagram or not + // The location realative to the Element + if (alternativeMode) { + posX = (int) Math.round(aRenderElem.getX() + aRenderElem.getWidth() + + (aRenderElem.getHeight() * ReturnAdress.ADRESS_SIZE / 2) + - this.getWidth()); + posY = (int) Math.round(aRenderElem.getY() + - (aRenderElem.getHeight() * ReturnAdress.ADRESS_SIZE / 2)); + } + // Ceckout if position should be drawn in front of or behind + else if (behindElement ^ changeDirection) { + posX = (int) Math.round(aRenderElem.getX() + aRenderElem.getWidth() + + corr * 0.2); + posY = Math.round(aRenderElem.getY() + radius - (positionSize / 2) + + 1); + } else { + posX = (int) Math.round(aRenderElem.getX() - corr * 1.2); + posY = Math.round(aRenderElem.getY() + radius - (positionSize / 2) + + 1); + } + + return new Point(posX, posY); + } + + /** + * Init method if aRenderElem is a Branch + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @param changeDirection + * specifies wether or not, the direction should be changed + * @return a Point which represents the Location where the Position should + * be drawn. + */ + private Point initBranch(RenderElement aRenderElem, + boolean alternativeMode, boolean behindElement, + boolean changeDirection) { + + int posX, posY; + + // The location realative to the Element + if (!changeDirection) { + if (behindElement) { + posX = (int) Math.round(aRenderElem.getX() + + aRenderElem.getWidth() + (corr * .4)); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } else { + posX = (int) Math.round(aRenderElem.getX() - (corr * 1.4)); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } + } else { + if (behindElement) { + posX = (int) Math.round(aRenderElem.getX() + - (corr * 1.4)); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } else { + posX = (int) Math.round(aRenderElem.getX() + + aRenderElem.getWidth() + (corr * .4)); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } + } + + return new Point(posX, posY); + } + + /** + * Init method if aRenderElem is a Repetition + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @param changeDirection + * specifies wether or not, the direction should be changed + * @return a Point which represents the Location where the Position should + * be drawn. + */ + private Point initRepetition(RenderElement aRenderElem, + boolean alternativeMode, boolean behindElement, + boolean changeDirection) { + + int posX, posY; + + // The location realative to the Element + if (!changeDirection) { + if (behindElement) { + posX = (int) Math.round(aRenderElem.getX() + + aRenderElem.getWidth()); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } else { + posX = (int) Math.round(aRenderElem.getX() + corr * 1.5); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } + } else { + if (behindElement) { + posX = (int) Math.round(aRenderElem.getX()); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } else { + posX = (int) Math.round(aRenderElem.getX() + + aRenderElem.getWidth() - positionSize * 2); + posY = Math.round(aRenderElem.getY() + radius - positionSize + / 2); + } + + } + + return new Point(posX, posY); + } + + /** + * Init method if aRenderElem is a RenderBase + * + * @param aRenderElem + * The RenderElement that is the actual Position + * in a SyntaxDiagram during the WordAlgorithm. + * @param alternativeMode + * makes a second position of the Position possible. For example + * the Position at the returnAdress of a Variable when the user + * should jump to a Diagram. + * @param behindElement + * if true, the position is drawn behind the Element which + * represents the actual position. + * @return a Point which represents the Location where the Position should + * be drawn. + */ + private Point initRenderBase(RenderElement aRenderElem, + boolean alternativeMode, boolean behindElement) { + + // The positionHeight must be correted. It depends on the position + // height + int correcture = 3; + if (positionSize > 30) + correcture = -1; + else if (positionSize > 24) + correcture = 0; + else if (positionSize > 16) + correcture = 1; + else if (positionSize > 8) + correcture = 2; + + int posX, posY; + + // The location realative to the Element + if (behindElement) { + posX = aRenderElem.getWidth() - rv.radius; + posY = Math.round(aRenderElem.getHeight() * 2 / 3) + correcture; + } else { + posX = aRenderElem.getX() + 3; + posY = Math.round(aRenderElem.getHeight() * 2 / 3) + correcture; + } + + return new Point(posX, posY); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.java b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.java new file mode 100644 index 0000000..88aedf5 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/RenderEnd.java @@ -0,0 +1,78 @@ +package org.jalgo.module.ebnf.renderer.wordalgorithm; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Stroke; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; + +/** + * This class reperesents the end of an SyntaxDiagram. + * + * Use to make the end clickable by an own MouseListener. + * + * @author Claas Wilke + */ +@SuppressWarnings("serial") +public class RenderEnd extends RenderElement { + + /** + * Represents the base line of the exit of syntax diagram + */ + + private int radius; + + protected Stroke stroke = new BasicStroke(); + + /** + * Initializes the render end. + */ + public RenderEnd(int radius) { + this.radius = radius; + + this.stroke = STANDARD_STROKE; + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + g2d.setColor(this.color); + g2d.setStroke(stroke); + g2d.drawLine(0, 3 * radius, this.getWidth(), 3 * radius); + + } + + public void update() { + + } + + /** + * Sets the Element highlighted + * + * @param highlight + * If true the elem should be highlighted, else the highlightinf + * should be resetted. + * @param hColor + * The Color the Element should be highlighted or + * dehighlighted with. + */ + public void setHighlighted(boolean highlight, Color hColor) { + + color = hColor; + if (highlight) { + stroke = HIGHLIGHT_STROKE; + } else { + stroke = STANDARD_STROKE; + } + + repaint(); + } + +} diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.java b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.java new file mode 100644 index 0000000..53c1beb --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/ReturnAdress.java @@ -0,0 +1,140 @@ +package org.jalgo.module.ebnf.renderer.wordalgorithm; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import org.jalgo.module.ebnf.renderer.elements.RenderVariable; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * This Element is the graphical representation of a ReturnAdress from a + * Variable. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class ReturnAdress extends RenderElement { + + // Specifies the size of the ReturnAdress relative + // to the size of its Variable + public static final double ADRESS_SIZE = 1; + + // Shadow is deacitivated + // // Space between Arrow and its shadow in half Pixels + // // For example: Shadow_Width of 4 means a 2px Space between arrow and its + // // shadow. + // private static final int SHADOW_WIDTH = 4; + + // The Name of the return Adress (an int). + public String label; + + // The Color of the Arrow (default is black). + public Color myColor = Color.BLACK; + + /** + * Initializes the element + * + * @param label + * The name of the ReturnAdress. + * @param aVar + * The Variable that belongs to this + * ReturnAdress. + * @param fontSize + * The size the font of the Number should have (default -1); + */ + public ReturnAdress(String label, RenderVariable aVar, int fontSize) { + + this.label = label; + if (fontSize > 0) { + this.rv.setFontSize(fontSize); + } + + // The position at right top edge of the Variable + this + .setLocation((aVar.getX() + aVar.getWidth()) - 3, + (aVar.getY() - (int) Math.round(aVar.getHeight() + * ADRESS_SIZE)) + 3); + + // The ADRESS_SIZE part size of its Variable + this.setSize((int) Math.round(aVar.getHeight() * ADRESS_SIZE * 2), + (int) Math.round(aVar.getHeight() * ADRESS_SIZE)); + + } + + /** + * Used when the Adress should be drawn + */ + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // Shadow is deacitivated + // // Draw Arrow + // // Shadow + // g2d.setColor(Color.GRAY); + // // Diagonal Line + // g2d.drawLine(0, this.getHeight(), + // (int) Math.round(this.getHeight() / 2), (int) Math.round(this + // .getWidth() / 2)); + // // Horizontal Line + // g2d.drawLine((int) Math.round(this.getHeight() / 4), (int) Math + // .round(this.getHeight() / 2), (int) Math + // .round(this.getHeight() / 2), (int) Math + // .round(this.getHeight() / 2)); + // // Vertical Line + // g2d.drawLine((int) Math.round(this.getHeight() / 2), (int) Math + // .round(this.getHeight() / 2), (int) Math + // .round(this.getHeight() / 2), (int) Math + // .round(this.getHeight() / 4 * 3)); + // // Draw Adress + // g2d.setFont(new Font(rv.font.getName(), Font.ITALIC, (int) Math + // .round(rv.font.getSize() * ADRESS_SIZE))); + // g2d.drawString(label, (int) Math.round(this.getHeight() * 4 / 7 + // + SHADOW_WIDTH / 2), (int) Math + // .floor((1.27 * rv.radius * ADRESS_SIZE) + SHADOW_WIDTH / 2)); + + // Arrow Himself + g2d.setColor(this.myColor); + // Diagonal Line + g2d.drawLine(0, this.getHeight(), (int) Math + .round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 2)); + // Horizontal Line + g2d.drawLine((int) Math.round(this.getHeight() / 4), (int) Math + .round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 2)); + // Vertical Line + g2d.drawLine((int) Math.round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 2), (int) Math + .round(this.getHeight() / 4 * 3)); + // Draw Adress + g2d.setFont(new Font(rv.font.getName(), Font.ITALIC, (int) Math + .round(rv.font.getSize() * ADRESS_SIZE))); + g2d.drawString(label, (int) Math.round(this.getHeight() * 4 / 7), + (int) Math.floor(1.5 * rv.radius * ADRESS_SIZE)); + } + + /** + * Called when the ReturnAdress is repainted. + */ + public void update() { + } + + /** + * Sets the Color, which should be used to draw the Arrow. + */ + public void setColor(Color myColor) { + + this.myColor = myColor; + repaint(); + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.java b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.java new file mode 100644 index 0000000..1d18d8d --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackAdress.java @@ -0,0 +1,80 @@ +package org.jalgo.module.ebnf.renderer.wordalgorithm; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.Rectangle2D; + +/** + * This Element is the graphical representation of a ReturnAdress from a + * Variable on the Stack during the Algorithm. + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class StackAdress extends RenderElement { + + // The Name of the return Adress (an int). + private String label; + + // Represents some shape + protected Rectangle2D.Double rect; + + /** + * Initializes the element + * + * @param label + * The name of the ReturnAdress. + * @param aVar + * The Variable that belongs to this + * ReturnAdress. + */ + public StackAdress(String label) { + + this.label = label; + + rect = new Rectangle2D.Double(); + + } + + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // Shadow + g2d.setColor(Color.BLACK); + rect.x += 3; + rect.y += 3; + g2d.setComposite(makeComposite(0.4F)); + g2d.fill(rect); + + // Rectangle + rect.x -= 3; + rect.y -= 3; + g2d.setComposite(makeComposite(1F)); + g2d.setColor(this.color); + g2d.fill(rect); + + // Adress itself + g2d.setColor(Color.BLACK); + g2d + .setFont(new Font(rv.font.getName(), Font.ITALIC, 17)); + g2d.drawString(label, (int) Math.round(0.6 * 15), (int) Math + .floor(1.27 * 15)); + + g2d.draw(rect); + + } + + public void update() { + rect.setRect(0, 0, this.getWidth() - 4, this.getHeight() - 4); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.java b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.java new file mode 100644 index 0000000..f5b4d23 --- /dev/null +++ b/src/org/jalgo/module/ebnf/renderer/wordalgorithm/StackBase.java @@ -0,0 +1,74 @@ +package org.jalgo.module.ebnf.renderer.wordalgorithm; + +import org.jalgo.module.ebnf.renderer.elements.RenderElement; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * This Element is the graphical representation of a Base Line at the bottom of the Stack + * + * @author Claas Wilke + * + */ +@SuppressWarnings("serial") +public class StackBase extends RenderElement { + + private int width; + + // Space between Line and shadow in pixels + private static final int SHADOW_WIDTH = 2; + + private Color myColor = Color.BLACK; + + /** + * Initializes the element + * + */ + public StackBase(int width) { + + this.width = width; + // The ADRESS_SIZE part size of its Variable + this.setSize(width, SHADOW_WIDTH + 1); + + } + + /** + * Used when the Adress should be drawn + */ + public void paintComponent(Graphics g) { + + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(new RenderingHints( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON)); + + // Draw Base + // Shadow + g2d.setColor(Color.GRAY); + // Horizontal Line + g2d.drawLine(SHADOW_WIDTH, SHADOW_WIDTH, width, SHADOW_WIDTH); + + // Base Himself + g2d.setColor(this.myColor); + // Horizontal Line + g2d.drawLine(0, 0, width - SHADOW_WIDTH, 0); + } + + /** + * Called when the ReturnAdress is repainted. + */ + public void update() { + } + + /** + * Sets the Color, which should be used to draw the stack baseline. + */ + public void setColor(Color myColor) { + + this.myColor = myColor; + repaint(); + + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/res.properties b/src/org/jalgo/module/ebnf/res.properties new file mode 100644 index 0000000..04552ed --- /dev/null +++ b/src/org/jalgo/module/ebnf/res.properties @@ -0,0 +1,55 @@ +Module_logo=/ebnf_pix/logo.gif +HelpSet_Name=/help/jhelp/ebnf_help.hs + +Start_load=/ebnf_pix/start_load.gif +Start_load_rollover=/ebnf_pix/start_load_rollover.gif +Start_load_description_de=/ebnf_pix/start_load_desc_de.gif +Start_load_description_en=/ebnf_pix/start_load_desc_en.gif +Start_ebnf=/ebnf_pix/start_ebnf.gif +Start_ebnf_rollover=/ebnf_pix/start_ebnf_rollover.gif +Start_ebnf_description_de=/ebnf_pix/start_ebnf_desc_de.gif +Start_ebnf_description_en=/ebnf_pix/start_ebnf_desc_en.gif +Start_syndia=/ebnf_pix/start_syndia.gif +Start_syndia_rollover=/ebnf_pix/start_syndia_rollover.gif +Start_syndia_description_de=/ebnf_pix/start_syndia_desc_de.gif +Start_syndia_description_en=/ebnf_pix/start_syndia_desc_en.gif +Ebnf_Font=/font/EbnfSans.ttf + +ModeEdit_Image=/ebnf_pix/edit.gif +ModeAddTerminal_Image=/ebnf_pix/addTerminal.gif +ModeAddVariable_Image=/ebnf_pix/addVariable.gif +ModeAddBranch_Image=/ebnf_pix/addBranch.gif +ModeAddRepetition_Image=/ebnf_pix/addRepetition.gif +ModeDelete_Image=/ebnf_pix/rubber.gif + +Cursor_Branch=/ebnf_pix/cursor/branch.gif +Cursor_Repetition=/ebnf_pix/cursor/repetition.gif +Cursor_Variable=/ebnf_pix/cursor/variable.gif +Cursor_Terminal=/ebnf_pix/cursor/terminal.gif +Cursor_Delete=/ebnf_pix/cursor/rubber.gif +Cursor_Edit=/ebnf_pix/cursor/edit.gif +Cursor_BranchRight=/ebnf_pix/cursor/branch_right.gif +Cursor_RepetitionRight=/ebnf_pix/cursor/repetition_right.gif + +Icon.Edit=/ebnf_pix/button/edit.gif +Icon.AddTerminal=/ebnf_pix/button/addTerminal.gif +Icon.AddVariable=/ebnf_pix/button/addVariable.gif +Icon.AddBranch=/ebnf_pix/button/addBranch.gif +Icon.AddRepetition=/ebnf_pix/button/addRepetition.gif +Icon.Delete=/ebnf_pix/button/rubber.gif +Icon.AddDiagram=/ebnf_pix/button/addDiagram.gif +Icon.SelectedEdit=/ebnf_pix/button/selected_edit.gif +Icon.SelectedAddTerminal=/ebnf_pix/button/selected_addTerminal.gif +Icon.SelectedAddVariable=/ebnf_pix/button/selected_addVariable.gif +Icon.SelectedAddBranch=/ebnf_pix/button/selected_addBranch.gif +Icon.SelectedAddRepetition=/ebnf_pix/button/selected_addRepetition.gif +Icon.SelectedDelete=/ebnf_pix/button/selected_rubber.gif + +Icon.FitToSize=/ebnf_pix/button/fittosize.gif +Icon.FitToWidth=/ebnf_pix/button/fittowidth.gif +Icon.FitSelf=/ebnf_pix/button/zoomer.gif +Icon.NoStairs=/ebnf_pix/button/nostairs.gif +Icon.Stairs=/ebnf_pix/button/stairs.gif + +Light_Red=/ebnf_pix/light_red.png +Light_Green=/ebnf_pix/light_green.png \ No newline at end of file diff --git a/src/org/jalgo/module/ebnf/rootPaneListener.java b/src/org/jalgo/module/ebnf/rootPaneListener.java new file mode 100644 index 0000000..717ab25 --- /dev/null +++ b/src/org/jalgo/module/ebnf/rootPaneListener.java @@ -0,0 +1,61 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and + * platform independent. j-Algo is developed with the help of Dresden + * University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.ebnf; + +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; + +import javax.swing.JMenu; +import javax.swing.JMenuBar; + +public class rootPaneListener implements ComponentListener { + + private MainController mainController; + + public rootPaneListener(MainController mainController) { + this.mainController = mainController; + } + + public void componentResized(ComponentEvent arg0) { + + } + + public void componentMoved(ComponentEvent arg0) { + + } + + public void componentShown(ComponentEvent arg0) { + if (mainController.getCustomMenuListBackup() != null) { + for (JMenu item: mainController.getCustomMenuListBackup()) { + mainController.addMenu(item); + } + } + } + + public void componentHidden(ComponentEvent arg0) { + mainController.removeCustomMenu(); + } + + + + +} diff --git a/src/org/jalgo/module/ebnf/util/ActionStack.java b/src/org/jalgo/module/ebnf/util/ActionStack.java new file mode 100644 index 0000000..564452d --- /dev/null +++ b/src/org/jalgo/module/ebnf/util/ActionStack.java @@ -0,0 +1,225 @@ +package org.jalgo.module.ebnf.util; + +import java.util.Stack; +import java.util.Observable; +import java.util.Observer; + +/** + * The ActionStack implements two Stacks. One Stack saves the + * operations performed, the other Stack saves the operations undone. Each + * operation must be an implemented IAction. + * + * The ActionStack is observable. He must have at least one + * observer, the MainController. Therefore you have to give the Adress of the + * MainController to the ActionStack if you create one. + * + * The ActionStack will inform the MainController if redo or undo + * is possible and if one of these statuses has changed. + * + * The ActionStack will throw Exceptions + * implemented by the Action performed, if perform(), + * undo() or redo() + * fails. + * + * @author Claas Wilke + * + */ +public class ActionStack extends Observable { + + /* + * Every IAction that was performed is going to be pushed onto the undoList. + */ + private Stack undoList; + + /* + * Each IAction the user has made undon is going to be pushed onto the + * redoList. + */ + private Stack redoList; + + /** + * The constructor constructs a new ActionStack with an empty undoList and + * an empty redoList. + * + * @param observer + * An Observer the ActionStack will notify if its undo or redo + * status will change. The observer will be a MainController in a + * future version. It is any class which implements + * java.Util.Observer by now. TODO change param type to + * MainController. + */ + public ActionStack(Observer observer) { + undoList = new Stack(); + redoList = new Stack(); + addObserver(observer); + } + + public ActionStack() { + undoList = new Stack(); + redoList = new Stack(); + + } + + /** + * Returns true if an undoOperation is possible. An undoOperation is + * possible, if the undoList is not empty. + * + * @return True if undo() is possible. + */ + public boolean isUndoPossible() { + return !undoList.empty(); + } + + /** + * Returns true if an redoOperation is possible. An redoOperation is + * possible, if the redoList is not empty. + * + * @return True if redo() is possible. + */ + public boolean isRedoPossible() { + return !redoList.empty(); + } + + /** + * Makes an IAction undone, if there is an IAction in the undoList. + * + * Throws Exceptions implemented by the IAction + * which should be redone. + * + * @return True if step was undone + */ + public boolean undo() throws Exception { + if (isUndoPossible()) { + /* + * If redoList is empty, the status will change to full. (Used at + * the end of the method to (optionaly) inform the Observers. + */ + try { + boolean statusWillChange = !isRedoPossible(); + + IAction anAction = undoList.pop(); + anAction.undo(); + /* The Action undone can now be redone. */ + redoList.push(anAction); + + if (statusWillChange || !isUndoPossible()) { + setChanged(); + notifyObservers(this); + } + + return true; + } catch (Exception e) { + throw e; + } + + } else { + // System.out.println("Undo was not possible."); + return false; + } + } + + /** + * Makes an IAction redone, if there is an IAction in the redoList. + * + * Throws Exceptions implemented by the IAction + * which should be redone. + * + * @return True if step was redone + */ + public boolean redo() throws Exception { + if (isRedoPossible()) { + try { + boolean statusWillChange = !isUndoPossible(); + + IAction anAction = redoList.pop(); + anAction.perform(); + /* The Action can now be undone again */ + undoList.push(anAction); + + if (statusWillChange || !isRedoPossible()) { + setChanged(); + notifyObservers(this); + } + + return true; + + } catch (Exception e) { + throw e; + } + + } else { + // System.out.println("Redo was not possible."); + return false; + } + } + + /** + * Performs an IAction an pushes the IAction onto the + * undoList. + * + * Throws Exceptions implemented by the IAction + * which should be performed. + * + * @param anAction + * IAction which should be performed. + */ + public void perform(IAction anAction) throws Exception { + /* + * If undoList is empty, the status will change to full. (Used at the + * end of the method to (optionaly) inform the Observers. + */ + try { + Boolean statusWillChange = !isUndoPossible(); + anAction.perform(); + undoList.push(anAction); + /* + * If redoList is not empty it has to be cleared. Every IAction + * undone before can not be redone any longer. + */ + if (isRedoPossible()) { + redoList.clear(); + /* + * Redo is not possible any longer. The Class has to notify its + * Observers. + */ + setChanged(); + notifyObservers(this); + } + /* + * If the undoList was empty before the IAction was performed, the + * undoList has changed its status. The Class has to notify its + * Observers (if not done before). + */ + else if (statusWillChange) { + setChanged(); + notifyObservers(this); + } + } catch (Exception e) { + throw e; + } + } + + /** + * This method empty the undo and the redo list and makes every undo or redo + * operation impossible. Be carefull! + * + */ + public void clear() { + undoList.clear(); + redoList.clear(); + setChanged(); + notifyObservers(this); + } + + public String toString() { + String s = "undoList:\n"; + for(IAction action:undoList) { + s += action.getClass() + "\n"; + } + s += "\nredoList:\n"; + for(IAction action:redoList) { + s += action.getClass() + "\n"; + } + return s; + } +} diff --git a/src/org/jalgo/module/ebnf/util/CVS/Entries b/src/org/jalgo/module/ebnf/util/CVS/Entries new file mode 100644 index 0000000..31cf26e --- /dev/null +++ b/src/org/jalgo/module/ebnf/util/CVS/Entries @@ -0,0 +1,2 @@ +/ActionStack.java/1.1/Fri Aug 11 16:40:33 2006// +/IAction.java/1.1/Fri Aug 11 16:40:33 2006// diff --git a/src/org/jalgo/module/ebnf/util/CVS/Repository b/src/org/jalgo/module/ebnf/util/CVS/Repository new file mode 100644 index 0000000..560a038 --- /dev/null +++ b/src/org/jalgo/module/ebnf/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/ebnf/util diff --git a/src/org/jalgo/module/ebnf/util/CVS/Root b/src/org/jalgo/module/ebnf/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/ebnf/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/ebnf/util/IAction.java b/src/org/jalgo/module/ebnf/util/IAction.java new file mode 100644 index 0000000..7e79a97 --- /dev/null +++ b/src/org/jalgo/module/ebnf/util/IAction.java @@ -0,0 +1,28 @@ +package org.jalgo.module.ebnf.util; + +/** + * IAction is single step during a algorithm or input. Every IAction can be made + * undone by the user. Ervery IAction has to implement the two methods perform() + * and undo(). + * + * Can throw any Exception during perform() or undo(). + * + * @author Claas Wilke + * + */ + +public interface IAction { + + /** + * Perform is the the method represented by the IAction. + * + * + */ + public abstract void perform() throws Exception; + + /** + * Undo is the method the user can use to have the represented Action + * undone. + */ + public abstract void undo() throws Exception; +} diff --git a/src/org/jalgo/module/em/CVS/Entries b/src/org/jalgo/module/em/CVS/Entries new file mode 100644 index 0000000..01e95c4 --- /dev/null +++ b/src/org/jalgo/module/em/CVS/Entries @@ -0,0 +1,9 @@ +/ModuleConnector.java/1.1/Mon Jan 30 18:56:52 2012// +/ModuleInfo.java/1.1/Mon Jan 30 18:56:52 2012// +D/control//// +D/data//// +/de.properties/1.1/Mon Jan 30 18:56:52 2012// +/en.properties/1.1/Mon Jan 30 18:56:52 2012// +D/gui//// +/res.properties/1.1/Mon Jan 30 18:56:52 2012// +D/test//// diff --git a/src/org/jalgo/module/em/CVS/Repository b/src/org/jalgo/module/em/CVS/Repository new file mode 100644 index 0000000..f1264a1 --- /dev/null +++ b/src/org/jalgo/module/em/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em diff --git a/src/org/jalgo/module/em/CVS/Root b/src/org/jalgo/module/em/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/ModuleConnector.java b/src/org/jalgo/module/em/ModuleConnector.java new file mode 100644 index 0000000..49d9ed4 --- /dev/null +++ b/src/org/jalgo/module/em/ModuleConnector.java @@ -0,0 +1,54 @@ +package org.jalgo.module.em; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.em.control.Controller; + +/** Connection between main program and the em module. + * + * @author Christian Hendel + */ +public class ModuleConnector extends AbstractModuleConnector { + //private Controller cont; + private JComponent content; + private JMenu menu; + private JToolBar toolbar; + + + + @Override + public void init() { + content = JAlgoGUIConnector.getInstance().getModuleComponent(this); + menu = JAlgoGUIConnector.getInstance().getModuleMenu(this); + toolbar =JAlgoGUIConnector.getInstance().getModuleToolbar(this); + //cont = new Controller(content,menu,toolbar); + new Controller(content, menu, toolbar); + } + + @Override + public void run() { + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + + } + + @Override + public ByteArrayOutputStream getDataForFile() { + return null; + } + + @Override + public void print() { + // here is no action performed in test module + } + +} diff --git a/src/org/jalgo/module/em/ModuleInfo.java b/src/org/jalgo/module/em/ModuleInfo.java new file mode 100644 index 0000000..95f1833 --- /dev/null +++ b/src/org/jalgo/module/em/ModuleInfo.java @@ -0,0 +1,71 @@ +package org.jalgo.module.em; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * The information class for the j-Algo module. + * + * @author tobias + * + */ +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + @Override + public String getName() { + return Messages.getString("em", "ModuleInfo.name"); + } + + @Override + public String getVersion() { + return "1.0"; + } + + @Override + public String getAuthor() { + return "Meinhardt Branig, Kilian Gebhardt, Christian Hendel, Tobias Nett, Tom Schumann."; + } + + @Override + public String getDescription() { + return Messages.getString("em", "ModuleInfo.info"); + } + + @Override + public URL getLogoURL() { + return Messages.getResourceURL("em","EM.ICON"); + } + + @Override + public String getLicense() { + return Messages.getString("em", "ModuleInfo.license"); + } + + @Override + public URL getHelpSetURL(){ + return Messages.getResourceURL("em","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/em/control/CVS/Entries b/src/org/jalgo/module/em/control/CVS/Entries new file mode 100644 index 0000000..26cd1f5 --- /dev/null +++ b/src/org/jalgo/module/em/control/CVS/Entries @@ -0,0 +1,9 @@ +/Controller.java/1.1/Mon Jan 30 18:56:51 2012// +/EMModule.java/1.1/Mon Jan 30 18:56:51 2012// +/IOController.java/1.1/Mon Jan 30 18:56:51 2012// +/InputController.java/1.1/Mon Jan 30 18:56:51 2012// +/LogState.java/1.1/Mon Jan 30 18:56:51 2012// +/MainController.java/1.1/Mon Jan 30 18:56:51 2012// +/OptionPane.java/1.1/Mon Jan 30 18:56:51 2012// +/TestCalculation.java/1.1/Mon Jan 30 18:56:51 2012// +/package-info.java/1.1/Mon Jan 30 18:56:51 2012// diff --git a/src/org/jalgo/module/em/control/CVS/Repository b/src/org/jalgo/module/em/control/CVS/Repository new file mode 100644 index 0000000..5e537a3 --- /dev/null +++ b/src/org/jalgo/module/em/control/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/control diff --git a/src/org/jalgo/module/em/control/CVS/Root b/src/org/jalgo/module/em/control/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/control/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/control/Controller.java b/src/org/jalgo/module/em/control/Controller.java new file mode 100644 index 0000000..6a9cd27 --- /dev/null +++ b/src/org/jalgo/module/em/control/Controller.java @@ -0,0 +1,385 @@ +package org.jalgo.module.em.control; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Box; +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JToolBar; + +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.StartScreen; + +/** + * Main controller for the JAlgo module for the EM-Algorithm. The controller + * handles the two view controllers and prepares menus and tool bars for user + * actions. + * + * @author Christian Hendel + */ +public class Controller { + + private OptionPane optionbox; + private MainController output; + private InputController input; + private LogState logstate; + private StartParameters params; + private JComponent content; + private JToolBar toolbar; + private JMenu menu; + private JToolbarButton wback, back, forw, wforw, save, load, presentation, + preferences,home; + private ActionListener lwback, lback, lforw, lwforw, lhyview, ldiaview, + ltabview, llogmode, lsave, lload, lbeamer, lprefs,lhome; + private JMenuItem HyView, DiaView, TabView, logmode; + private JCheckBoxMenuItem beamer; + private IOController IO = new IOController(); + private StartScreen startscreen; + private ImageIcon beamerOff = new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.beamerOff")); + private ImageIcon beamerOn = new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.beamerOn")); + private boolean presMode; + private double limit = -1; + + private JLabel stepLabel = new JLabel(); + + /** + * Creates a controller and sets action listener for all buttons. + * + * @param content + * the main panel which should hold the content + * @param menu + * the pull-down menu + * @param toolbar + * the JAlgo tool bar + */ + public Controller(JComponent content, JMenu menu, JToolBar toolbar) { + params = new StartParameters(); + presMode = false; + this.menu = menu; + this.content = content; + this.toolbar = toolbar; + lhome = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + home.setEnabled(true); + logmode.setEnabled(false); + HyView.setEnabled(false); + wback.setEnabled(false); + back.setEnabled(false); + forw.setEnabled(false); + wforw.setEnabled(false); + DiaView.setEnabled(false); + TabView.setEnabled(false); + save.setEnabled(false); + preferences.setEnabled(false); + stepLabel.setVisible(false); + input.backToInputView(); + } + }; + lprefs = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + options(); + } + }; + lwback = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.stepBack(); + stepLabel.setText(logstate.getStepCount()+"."+logstate.getSingleStepCount()); + } + }; + lback = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.singleStepBackward(); + stepLabel.setText(logstate.getStepCount()+"."+logstate.getSingleStepCount()); + } + }; + lforw = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.singleStepForward(); + stepLabel.setText(logstate.getStepCount()+"."+logstate.getSingleStepCount()); + } + }; + lwforw = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.stepForward(); + stepLabel.setText(logstate.getStepCount()+"."+logstate.getSingleStepCount()); + } + }; + lhyview = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.showHybrid(); + } + }; + ldiaview = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.showDiagram(); + } + }; + ltabview = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + output.showTable(); + } + }; + llogmode = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (logstate.isLogarithmicLikelihoodRepresentationEnabled()) { + logstate.setLogarithmicLikelihoodRepresentation(false); + } else { + logstate.setLogarithmicLikelihoodRepresentation(true); + } + output.updateViews(); + } + }; + lsave = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + IO.write(params); + + } + }; + lload = new ActionListener(){ + @Override + public void actionPerformed(ActionEvent e) { + params = IO.read(); + if (params != null) { + setStartParameters(params); + home.setEnabled(false); + logmode.setEnabled(false); + HyView.setEnabled(false); + wback.setEnabled(false); + back.setEnabled(false); + forw.setEnabled(false); + wforw.setEnabled(false); + DiaView.setEnabled(false); + TabView.setEnabled(false); + save.setEnabled(false); + load.setEnabled(true); + preferences.setEnabled(false); + input(); + } + } + }; + lbeamer = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + presMode = !presMode; + if (input != null) { + input.setBeamer(!input.isBeamer()); + } + if (output != null) { + output.changePresentationMode(); + } + if (presMode) { + presentation.setIcon(beamerOn); + } else { + presentation.setIcon(beamerOff); + } + beamer.setSelected(presMode); + getToolbar().updateUI(); + } + }; + + init(); + + optionbox = new OptionPane(this, stepLabel); + } + + /** + * initializes the menu bar and tool bar and assigns action listener to all + * items. + */ + public void init() { + clear(); + save = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", "ToolBarIcon.save")), + Messages.getString("em", "ToolBar.save"), ""); + toolbar.add(save); + load = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", "ToolBarIcon.load")), + Messages.getString("em", "ToolBar.load"), ""); + toolbar.add(load); + toolbar.addSeparator(); + + preferences = new JToolbarButton(new ImageIcon(Messages.getResourceURL( + "em", "ToolBarIcon.run")), Messages.getString("em", + "ToolBar.run"), ""); + toolbar.add(preferences); + + wback = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.wback")), + Messages.getString("em", "ToolBar.wback"), ""); + toolbar.add(wback); + + back = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.back")), Messages.getString("em", "ToolBar.back"), + ""); + toolbar.add(back); + + forw = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.forw")), Messages.getString("em", "ToolBar.forw"), + ""); + toolbar.add(forw); + + home = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.home")), Messages.getString("em", "ToolBar.home"), + ""); + + wforw = new JToolbarButton(new ImageIcon(Messages.getResourceURL("em", + "ToolBarIcon.wforw")), + Messages.getString("em", "ToolBar.wforw"), ""); + toolbar.add(wforw); + toolbar.addSeparator(); + toolbar.add(home); + toolbar.addSeparator(); + presentation = new JToolbarButton(beamerOff, Messages.getString("em", + "Controller.togglePMode"), null); + toolbar.add(presentation); + toolbar.addSeparator(); + toolbar.add(Box.createHorizontalGlue()); + toolbar.add(stepLabel); + toolbar.add(Box.createHorizontalStrut(10)); + + // add action listeners + wback.addActionListener(lwback); + wforw.addActionListener(lwforw); + save.addActionListener(lsave); + load.addActionListener(lload); + presentation.addActionListener(lbeamer); + forw.addActionListener(lforw); + back.addActionListener(lback); + preferences.addActionListener(lprefs); + home.addActionListener(lhome); + + // init menu entries + HyView = new JMenuItem(Messages.getString("em", "Menu.hybrid")); + HyView.addActionListener(lhyview); + DiaView = new JMenuItem(Messages.getString("em", "Menu.diagram")); + DiaView.addActionListener(ldiaview); + TabView = new JMenuItem(Messages.getString("em", "Menu.table")); + TabView.addActionListener(ltabview); + logmode = new JMenuItem(Messages.getString("em", "Menu.log")); + logmode.addActionListener(llogmode); + beamer = new JCheckBoxMenuItem(Messages.getString("em", "Menu.presentation")); + beamer.addActionListener(lbeamer); + // add menu items to the dropdown menu + menu.add(HyView); + menu.add(DiaView); + menu.add(TabView); + menu.add(logmode); + menu.add(beamer); + // init button states + home.setEnabled(false); + logmode.setEnabled(false); + HyView.setEnabled(false); + wback.setEnabled(false); + back.setEnabled(false); + forw.setEnabled(false); + wforw.setEnabled(false); + DiaView.setEnabled(false); + TabView.setEnabled(false); + save.setEnabled(false); + load.setEnabled(true); + preferences.setEnabled(false); + // init start screen and add it to the panel + startscreen = new StartScreen(this, IO, params); + content.add(startscreen); + }; + + /** + * Clears the content panel and updates the UI. + */ + public void clear() { + content.removeAll(); + content.updateUI(); + }; + + /** + * Starts the first input view to offer the user the ability to enter new + * data. + */ + public void input() { + // params = startscreen.getSparams();options + clear(); + stepLabel.setVisible(false); + input = new InputController(content, this, params, presMode); + }; + + /** + * Starts the output process of visualization the EM experiment. + */ + public void output() { + logstate = new LogState(params); + + + preferences.setEnabled(true); + save.setEnabled(true); + logmode.setEnabled(true); + HyView.setEnabled(true); + wback.setEnabled(true); + back.setEnabled(true); + forw.setEnabled(true); + wforw.setEnabled(true); + DiaView.setEnabled(true); + TabView.setEnabled(true); + home.setEnabled(true); + + + clear(); + + if (input != null) { + output = new MainController(logstate, content, input.isBeamer(),this); + } else { + output = new MainController(logstate, content, false,this); + } + stepLabel.setText(logstate.getStepCount()+"."+logstate.getSingleStepCount()); + stepLabel.setVisible(true); + }; + + public JToolBar getToolbar() { + return toolbar; + } + + /** + * Overwrites the current StartParameters Object. + * + * @param startParameters + * the new StartParameters Object + */ + public void setStartParameters(StartParameters startParameters) { + this.params = startParameters; + } + public void options(){ + + optionbox.setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE ); + optionbox.setSize( 450, 150 ); + optionbox.setVisible( true ); + } + public void setLimit(double d){ + this.limit=d; + } + + public double getLimit(){return limit;} + + public LogState getLogState(){return logstate;} + + public MainController getMC(){return output;} + + +} diff --git a/src/org/jalgo/module/em/control/EMModule.java b/src/org/jalgo/module/em/control/EMModule.java new file mode 100644 index 0000000..44fb4bb --- /dev/null +++ b/src/org/jalgo/module/em/control/EMModule.java @@ -0,0 +1,211 @@ +package org.jalgo.module.em.control; + +import java.awt.Point; +import java.util.HashMap; +import java.util.Map; + +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; +/** + * EMModule is responsible for calculating the EMSteps.
          + * This Module is the implementation of the EM Algorithm + * for the Data Structure of this Project. + * + * @author Kilian Gebhardt + * + */ +public class EMModule { + /** + * This function will calculate the next ProbabilityDistribution, + * Statistical Analyzer, the approximated Frequency for each Event, + * as well as the Probability Distribution for all SingleEvents and + * Partitions. At last it will calculation the Likelihood of this + * Distributions concerning the situation described in StartParameters. + * + * calcNextEMData takes one EMData and produces the next EMData, which means, that is has to be + * applied on all EMData of one EMState, and the new EMData have to be composed to the next EMState + * + * @param currentData the predecessor of the step, that is going to be calculated + * @param p0Index index of p0 + * @param startParameters the {@code StartParameters} object of this experiment + * @return the 'next' EM Step + */ + public static EMData calcNextEMData(final EMData currentData, final int p0Index, final StartParameters startParameters) { + //calculating the next Statistical Analyzer d_i(x) + Map nextStatisticalAnalyzer = new HashMap(); + for (Event event : startParameters.getEvents()) { + if (currentData.getPForPartition().get(event.getYield()) == 0.0) { + nextStatisticalAnalyzer.put(event, + startParameters.getP0EMState().getEMData() + .get(p0Index).getP().get(event) + / startParameters.getP0EMState().getEMData() + .get(p0Index).getPForPartition().get(event.getYield())); + } else { + nextStatisticalAnalyzer.put(event, + currentData.getP().get(event) + / currentData.getPForPartition().get(event.getYield())); + } + } + + //calculating the Frequency h(x) + Map nextEventFrequency = new HashMap(); + for (Event event : startParameters.getEvents()) { + nextEventFrequency.put(event, + event.getYield().getFrequency() + * nextStatisticalAnalyzer.get(event)); + } + + //calculating the singleEvent Probability (O(n * m)) + + Map nextSingleEventProbability = new HashMap(); + for (Point singleEvent : currentData.getPForSingleEvent().keySet()) { + Double probability = new Double(0); + + for (Event event : startParameters.getEvents()) { + if (event.getTuple().get(singleEvent.y) == singleEvent.x) { + probability += nextEventFrequency.get(event); + } + + nextSingleEventProbability.put(singleEvent, + probability + / startParameters.getFrequencySum()); + } + } + + //calculating the singleEventProbability (O(m + n)) + /* + int max = startParameters.getExperiment().get(0); + for (int i = 1; i < startParameters.getObjectCount(); i++) { + if (startParameters.getExperiment().get(i) > max) { + max = startParameters.getExperiment().get(i); + } + } + double[][] singleEventProbabilityArray = new double[max][startParameters.getObjectCount()]; + for (int x = 0; x < max; x++) { + for (int y = 0; y < startParameters.getObjectCount(); y++) { + singleEventProbabilityArray[x][y] = 0; + } + } + Map nextSingleEventProbability = new HashMap(); + + for (Event event : startParameters.getEvents()) { + for (int objectIndex = 0; objectIndex < startParameters.getObjectCount(); objectIndex++) { + singleEventProbabilityArray[event.getTuple().get(objectIndex) - 1][objectIndex] += nextEventFrequency.get(event); + } + } + + for (Point singleEvent : currentData.getPForSingleEvent().keySet()) { + nextSingleEventProbability.put(singleEvent, singleEventProbabilityArray[singleEvent.x - 1][singleEvent.y] + / startParameters.getFrequencySum()); + } + */ + //calculating the Probability p(x) + Map nextEventProbability = new HashMap(); + for (Event event : startParameters.getEvents()) { + Double probability = new Double(1); + + for (int objectIndex = 0; + objectIndex < event.getTuple().size(); + objectIndex++) { + probability *= + nextSingleEventProbability + .get(new Point(event.getTuple() + .get(objectIndex), objectIndex)); + } + + nextEventProbability.put(event, probability); + } + + //calculating the Probability for the Partitions p'(y) + Map nextPartitionProbability = new HashMap(); + for (Partition partition : startParameters.getObservations()) { + Double probability = new Double(0); + + for (Event event : partition.getElements()) { + probability += nextEventProbability.get(event); + } + + nextPartitionProbability.put(partition, probability); + } + + //calculating the Likelihood L + Double likelihood = new Double(0); + for (Partition partition : startParameters.getObservations()) { + if (partition.getFrequency() == 0) { + likelihood += 0; + } else { + likelihood += partition.getFrequency() + * Math.log10(nextPartitionProbability.get(partition)); + } + } + + return new EMData(nextStatisticalAnalyzer, + nextEventFrequency, + nextEventProbability, + nextPartitionProbability, + nextSingleEventProbability, + likelihood); + } + + /** + * Calculates the probability for each event and partition and + * the likelihood, based on the initial ProbabilityDistribution + * This function is used for creating the EMDatas for P0EMState + * and for calculating the 3DPlot. + * + * @param singleEventStartProbability the initial probability distribution + * @param startParameters the {@code StartParameters} object of this experiment + * @return EMData, where the Maps for 'd' and 'h' are null ! + */ + public static EMData calcFirstStep( + final Map singleEventStartProbability, + final StartParameters startParameters) { + + //calculating the Probability p(x) + Map eventStartProbability = new HashMap(); + for (Event event : startParameters.getEvents()) { + Double probability = new Double(1); + + for (int objectIndex = 0; + objectIndex < event.getTuple().size(); + objectIndex++) { + probability *= + singleEventStartProbability.get(new Point(event.getTuple().get(objectIndex), objectIndex)); + } + + eventStartProbability.put(event, probability); + } + + //calculating the Probability for the Partitions p'(y) + Map partitionStartProbability = new HashMap(); + for (Partition partition : startParameters.getObservations()) { + Double probability = new Double(0); + + for (Event event : partition.getElements()) { + probability += eventStartProbability.get(event); + } + + partitionStartProbability.put(partition, probability); + } + + //calculating the Likelihood L + Double likelihood = new Double(0); + for (Partition partition : startParameters.getObservations()) { + if (partition.getFrequency() == 0) { + likelihood += 0; + } else { + likelihood += partition.getFrequency() + * Math.log10(partitionStartProbability.get(partition)); + } + } + + return new EMData(null, + null, + eventStartProbability, + partitionStartProbability, + singleEventStartProbability, + likelihood); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/em/control/IOController.java b/src/org/jalgo/module/em/control/IOController.java new file mode 100644 index 0000000..36558f9 --- /dev/null +++ b/src/org/jalgo/module/em/control/IOController.java @@ -0,0 +1,211 @@ +package org.jalgo.module.em.control; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Reader; +import java.io.Writer; + +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.StartParameters; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.io.StreamException; +import com.thoughtworks.xstream.mapper.CannotResolveClassException; + +/** + * The {@code IOController} handles the input and output user actions. + * + * @author Tom Schumann, Tobias Nett + */ + +public class IOController { + + /** + * creates an {@code IOController} object. + */ + public IOController() { + + } + + /** + * Generates and opens a dialog for choosing a path to a directory or file. + * Returns the path, or null if the selection was canceled. + * + * @param String to identify the chooser + * + * @return the path of the selected file as {@code String}, {@code null} if + * selection was canceled + */ + private String open(String type) { + final JFileChooser chooser = new JFileChooser(Messages.getString("em", + "IOController.FileChooser")); + if(type.equals("SAVE")){ + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + } + else{ + chooser.setDialogType(JFileChooser.OPEN_DIALOG); + } + + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + // the folder that appears at file chooser startup + final File file = new File("examples/em/"); + chooser.setCurrentDirectory(file); + chooser.setVisible(true); + + if(type.equals("OPEN")){ + final int result = chooser.showOpenDialog(null); + if (result == JFileChooser.APPROVE_OPTION) { + File pathToFile = chooser.getSelectedFile(); + // only accepts *.em files + if (pathToFile.getName().toLowerCase().endsWith("em")) { + String inputVerzStr = pathToFile.getPath(); + return inputVerzStr; + } + } + } + if(type.equals("SAVE")){ + chooser.showSaveDialog(null); + File fileread = chooser.getSelectedFile(); + chooser.setVisible(false); + return fileread.getAbsolutePath(); + } + return null; + } + + /** + * Stores the specified {@code StartParameters} object into a file. + * + * @param params + * the {@code StartParameters} object to be stored + */ + public void write(StartParameters params) { + String pfad = this.open("SAVE")+".em"; + if (pfad != null) { + Writer out = null; + XStream xstream = new XStream(); + ObjectOutputStream outstream = null; + try { + out = new BufferedWriter(new FileWriter(pfad)); + } catch (IOException e) { + System.out.println("Error by creating" + e); + } + try { + outstream = xstream.createObjectOutputStream(out); + } catch (IOException e) { + System.out.println("Error by creating" + e); + } + try { + outstream.writeObject(params); + } catch (IOException e) { + System.out.println("Error by writing" + e); + } + try { + outstream.flush(); + out.flush(); + } catch (Exception e) { + System.out.println("Error while flushing" + e); + } + try { + outstream.close(); + System.out.println("XOutputStream has been closed"); + } catch (Exception e) { + System.out.println("Error while closing XOutputStream" + e); + } + + try { + + out.close(); + System.out.println("Writer has been closed"); + + } catch (Exception e) { + System.out.println("Error while closing Writer" + e); + } + } + + } + + /** + * Opens a dialog to choose a file and reads this file into a + * {@code StartParameters} object that can be visualized by the module. + * + * @return {@code StartParameters} object read out of the specified file + */ + public StartParameters read(){ + String path = this.open("OPEN"); + Reader read = null; + XStream xstream = new XStream(); + StartParameters obj = null; + ObjectInputStream input = null; + if (path != null) { + try { + read = new BufferedReader(new FileReader(path)); + } catch (FileNotFoundException e) { +// System.out.println("Error while opening the File" + e); + + JOptionPane.showMessageDialog(null, Messages.getString( + "em", "StartScreen.LoadErrorDescription"), Messages + .getString("em", "StartScreen.LoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); + } + try { + input = xstream.createObjectInputStream(read); + } catch (IOException e) { +// System.out.println("Error while creating the InputStream" + e); + + JOptionPane.showMessageDialog(null, Messages.getString( + "em", "StartScreen.LoadErrorDescription"), Messages + .getString("em", "StartScreen.LoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); + } catch (ArrayIndexOutOfBoundsException e) { + JOptionPane.showMessageDialog(null, Messages.getString( + "em", "StartScreen.LoadErrorDescription"), Messages + .getString("em", "StartScreen.LoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); + } catch (StreamException e) { +// System.out.println("Error while creating the InputStream" + e); + + JOptionPane.showMessageDialog(null, Messages.getString( + "em", "StartScreen.LoadErrorDescription"), Messages + .getString("em", "StartScreen.LoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); + } + if (input != null) { + try { + obj = (StartParameters) input.readObject(); + } catch (Exception e) { + JOptionPane.showMessageDialog(null, Messages.getString( + "em", "StartScreen.LoadErrorDescription"), Messages + .getString("em", "StartScreen.LoadErrorTitle"), + JOptionPane.ERROR_MESSAGE); + } + } + if (read != null) { + try { + read.close(); + } catch (IOException e) { +// System.out.println("Error while closing reader" + e); + } + } + if (input != null) { + try { + input.close(); + } catch (IOException e) { +// System.out.println("Error while closing XStream" + e); + } + } + return obj; + } + return null; + } + +} diff --git a/src/org/jalgo/module/em/control/InputController.java b/src/org/jalgo/module/em/control/InputController.java new file mode 100644 index 0000000..e7c9e72 --- /dev/null +++ b/src/org/jalgo/module/em/control/InputController.java @@ -0,0 +1,223 @@ +package org.jalgo.module.em.control; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JComponent; + +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.input.P0InputPanel; +import org.jalgo.module.em.gui.input.PartitionPanel; +import org.jalgo.module.em.gui.input.XInputPanel; +import org.jalgo.module.em.gui.input.YFrequencyPanel; + +/** + * Class InputController is a controller for input screens used to + * collect data to create StartParameters. It is able to load and + * save presets and finally initializes the main calculations. + * + * @author Christian Hendel, Tobias Nett + * + */ +public class InputController { + + private JComponent content; + private Controller control; + + private StartParameters params; + + // input views + private XInputPanel xInputView; + private PartitionPanel partitionView; + private YFrequencyPanel yView; + private P0InputPanel p0View; + private boolean beamer; + + /** + * Creates a new InputControlloer object that handles input + * views and user actions. + * + * @param content + * the main GUI component of JAlgo + * @param controller + * main controller of this j-Algo module + * @param params + * StartParameters object whose values are to be + * edited + * @param presMode + * the current state of presentation mode + */ + + public InputController(final JComponent content, + final Controller controller, StartParameters params, + boolean presMode) { + this.content = content; + this.control = controller; + this.params = params; + this.beamer = presMode; + createXInputView(); + } + + /** + * Creates a new YFrequencyPanel object and adds action + * listeners to the back/forward buttons. The created panel is directly + * shown in the content pane. + */ + public void createFrequencyView() { + yView = new YFrequencyPanel(params, beamer); + + yView.getForwardButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + createP0View(); + } + }); + yView.getBackButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + setView(partitionView); + } + }); + setView(yView); + } + + /** + * Creates a new P0InputPanel object and adds action listeners + * to the back/forward buttons. The created panel is directly shown in the + * content pane. + */ + public void createP0View() { + p0View = new P0InputPanel(params, beamer); + + p0View.getForwardButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent e) { + p0View.writeP0ToStartParameters(); + // Creates a new Window, in which a TestCalculation printed + /* + org.jalgo.module.testModule.ConsoleCalculation.outputCalcSteps( + params, org.jalgo.module.testModule.ConsoleCalculation + .createConsoe(), 20); + */ + control.output(); + } + }); + p0View.getBackButton().addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + p0View.writeTempP0ToStartParameters(); + setView(yView); + } + }); + setView(p0View); + } + + /** + * Creates a new PartitionPanel object and adds action + * listeners to the back/forward buttons. The created panel is directly + * shown in the content pane. + */ + public void createPartitionView() { + partitionView = new PartitionPanel(params, beamer); + + partitionView.getForwardButton().addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + partitionView.writeObservation(); + createFrequencyView(); + } + }); + partitionView.getBackButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + setView(xInputView); + } + }); + // content.add(partitionView, BorderLayout.CENTER); + setView(partitionView); + } + + /** + * Creates a new XInputPanel object and adds action listeners + * to the forward button. The created panel is directly shown in the content + * pane. + */ + public void createXInputView() { + xInputView = new XInputPanel(params, beamer); + xInputView.getForwardButton().addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + xInputView.writeExperiment(); + createPartitionView(); + } + }); + setView(xInputView); + } + + /** + * Returns the current StartParameters object. + * + * @return returns the current StartParameters object + */ + public StartParameters getParams() { + return params; + } + + /** + * Returns {@code true} if the module runs in presentation mode, + * {@code false} otherwise. + * + * @return {@code true} if the module is currently in presentation mode, + * {@code false} otherwise. + */ + public boolean isBeamer() { + return beamer; + } + + /** + * Starts presentation mode on {@code true} argument, ends presentation mode + * on {@code false} argument. The change takes effect on every view of this + * module. + * + * @param beamer + * {@code true} to start presentation mode, {@code false} to end + * presentation mode. + */ + public void setBeamer(boolean beamer) { + this.beamer = beamer; + + if (xInputView != null) + xInputView.setBeamerMode(this.beamer); + if (partitionView != null) + partitionView.setBeamerMode(this.beamer); + if (yView != null) + yView.setBeamerMode(this.beamer); + if (p0View != null) { + p0View.setBeamerMode(this.beamer); + } + + } + + /** + * Sets the view to the specified component. view should extend + * JPanel and implement InputPanel, but this is + * not necessary. + *

          + * At first, all other components are removed from the content pane, then + * view is added and the UI is updated. + * + * @param view + * the JComponent that should be displayed + */ + private void setView(final JComponent view) { + content.removeAll(); + content.add(view); + content.updateUI(); + } + + public void backToInputView() { + setView(p0View); + } +} diff --git a/src/org/jalgo/module/em/control/LogState.java b/src/org/jalgo/module/em/control/LogState.java new file mode 100644 index 0000000..3481eae --- /dev/null +++ b/src/org/jalgo/module/em/control/LogState.java @@ -0,0 +1,451 @@ +package org.jalgo.module.em.control; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; + +/** + * LogState is the Class, that controls the calculation of new EM Steps, has the + * DataStructure in which new EM steps are included and provides access to the + * calculated data to the Output-Classes.
          + * LogState stores as well, up to which step, the calculated data should be + * visualized by the Output-Classes
          + *
          + * A new instance LogState should be created, after all StartParameters were set + * correctly. Changing the StartParameters afterwards can cause Problems! + * + * @author kilian + * + */ +public class LogState { + private List emStates; + private StartParameters startParameters; + private int step; + private int singleStep; + private boolean logarithmicLikelihoodRepresentation; + + /** + * Creates a new Instance of LogState, sets StartParameters, the Step and + * the Default LikelihoodRepresentation to nonLogarithmic. + * + * @param startParameters + * Complete and valid startParameters, that should not be changed + * afterwards. + */ + public LogState(final StartParameters startParameters) { + this.startParameters = startParameters; + emStates = new ArrayList(); + emStates.add(startParameters.getP0EMState()); + step = 0; + logarithmicLikelihoodRepresentation = false; + } + + /** + * calculates the Next EMState and inserts it into the emState List. + */ + private void calcNextState() { + List nextEMDataBlocks = new ArrayList(); + for (EMData currentData : emStates.get(emStates.size() - 1).getEMData()) { + nextEMDataBlocks.add(EMModule.calcNextEMData(currentData, emStates + .get(emStates.size() - 1).getEMData().indexOf(currentData), + startParameters)); + } + emStates.add(new EMState(nextEMDataBlocks)); + } + + /** + * calcUntilLimit calculates new EMSteps until the difference of + * Likelihood[i] and Likelihood[i - 1]) falls below limit (percentage) + * + * @param limit + * > 0, where 100% = 1.0 and 1% = 0.01 + */ + public void calcUntilLimit(double limit) { + boolean status; + if (emStates.size() > 1) { + status = false; + for (int p0Index = 0; p0Index < getP0Count(); p0Index++) { + if ((this.getLogarithmicL(p0Index, + this.emStates.size() - 1) + - this.getLogarithmicL(p0Index, + this.emStates.size() - 2)) > Math.log10(1 + limit)) { + status = true; + } + } + } else { + status = true; + } + //System.out.println(limit); + while (status) { + calcNextState(); + status = false; + for (int p0Index = 0; p0Index < getP0Count(); p0Index++) { + if ((this.getLogarithmicL(p0Index, + this.emStates.size() - 1) + - this.getLogarithmicL(p0Index, + this.emStates.size() - 2)) > Math.log10(1 + limit)) { + status = true; + } + } + this.step = emStates.size() - 1; + this.singleStep = 0; + } + + int stepIndex = this.emStates.size() - 1; + status = true; + while ((stepIndex > 0) && status) { + status = true; + for (int p0Index = 0; p0Index < getP0Count(); p0Index++) { + if ((this.getLogarithmicL(p0Index, stepIndex) + - this.getLogarithmicL(p0Index, stepIndex - 1)) > Math.log10(1 + limit)) { + status = false; + } + } + stepIndex--; + } + if (stepIndex != 0 || status == false) { + this.step = stepIndex + 2; + } else { + this.step = stepIndex + 1; + } + //this.singleStep = 0; + } + + /** + * Gives direct access to the Likelihood in a certain step. + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 0 <= step <= getStepCount() + * @return Likelihood, in Logarithmic or 'normal' Representation, depending + * on setLogarithmicLikelihoodRepresentation(boolean) + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + */ + public final Double getL(final int p0Index, final int step) { + if (this.logarithmicLikelihoodRepresentation) { + return getLogarithmicL(p0Index, step); + } else { + return Math.pow(10, getLogarithmicL(p0Index, step)); + } + } + + /** + * Gives direct access to the Likelihood in a certain step. + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 0 <= step <= getStepCount() + * @return Likelihood in Logarithmic Representation + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + */ + private final Double getLogarithmicL(final int p0Index, final int step) { + return emStates.get(step).getEMData().get(p0Index).getLikelihood(); + } + + /** + * gives direct access to the Probability of a SingleEvent in a certain step + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 1 <= step <= getStepCount() + * @param singleEvent + * the SinlgeEvent in Point Representation + * @return the probability of the singleEvent + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + */ + public final Double getPSingleEvent(final int p0Index, final int step, + final Point singleEvent) { + return emStates.get(step).getEMData().get(p0Index).getPForSingleEvent() + .get(singleEvent); + } + + /** + * gives direct access to the Statistical Analyzer of an Event + * in a certain step. + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 1 <= step <= getStepCount() + * @param event + * the {@code Event} whose statistic analyzer is questioned + * @return the statistic analyzer of an event + * @throws NullPointerException + * if step = 0 + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + * + */ + public final Double getD(final int p0Index, final int step, + final Event event) throws NullPointerException, + IndexOutOfBoundsException { + return emStates.get(step).getEMData().get(p0Index).getD().get(event); + } + + /** + * gives direct access to the Frequency of an Event in a + * certain step. + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 1 <= step <= getStepCount() + * @param event the {@code Event} whose frequency is questioned + * @return the estimated frequency of an event + * @throws NullPointerException + * if step = 0 + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + */ + public final Double getH(final int p0Index, final int step, + final Event event) { + return emStates.get(step).getEMData().get(p0Index).getH().get(event); + } + + /** + * gives direct access to the Probability of an Event in a + * certain step + * + * @param p0Index + * for 0 <= p0 < getP0Count() + * @param step + * for 0 <= step <= getStepCount() + * @param event + * the {@code Event} whose probability is questioned + * @return the probability of an event + * @throws IndexOutOfBoundsException + * if step > the amount of calculated steps or p0 >= + * getP0Count() + */ + public Double getP(int p0Index, int step, Event event) { + return emStates.get(step).getEMData().get(p0Index).getP().get(event); + } + + /** + * Calculates the Likelihood for a 2-Coin Experiment from given + * probabilities for "K" - Side of each Coin. The probability of the "Z" - + * Side is implicated ( 1 - p1(K) ). + * + * @param p1K + * = p1(K) out of [0 .. 1] + * @param p2K + * = p2(K) out of [0 .. 1] + * @return Likelihood + */ + public final double getL3DGraph(final double p1K, final double p2K) { + HashMap singleEventProbability = new HashMap(); + singleEventProbability.put(new Point(2, 0), p1K); + singleEventProbability.put(new Point(1, 0), 1 - p1K); + singleEventProbability.put(new Point(2, 1), p2K); + singleEventProbability.put(new Point(1, 1), 1 - p2K); + if (! isLogarithmicLikelihoodRepresentationEnabled()) { + return Math.pow(10, + EMModule.calcFirstStep(singleEventProbability, startParameters) + .getLikelihood()); + } else { + return EMModule.calcFirstStep(singleEventProbability, startParameters) + .getLikelihood(); + } + + } + + /** + * Checks, whether the Experiment consists of 2 coins, and therefore a + * 3D-Graph can be plotted. => double getL3DGraph(..) + * + * @return true if a 3D Graph can be plotted, or false instead. + */ + public final boolean activate3D() { + if ((startParameters.getObjectCount() == 2) + && (startParameters.getExperiment().get(0) == 2) + && (startParameters.getExperiment().get(1) == 2)) { + return true; + } + return false; + } + + /** + * @return Number of StartProbability-Distributions + */ + public final int getP0Count() { + return startParameters.getP0EMState().getEMData().size(); + } + + /** + * Returns the yield of the specified event. + * + * @param event + * the {@code Event} whose yield is questioned + * @return Partition in which the Event is + * located. + */ + public final Partition getYield(final Event event) { + return event.getYield(); + } + + /** + * @return the Experiment Vector + */ + public final Vector getExperiment() { + return startParameters.getExperiment(); + } + + /** + * generates a Set with SingleExperiments. + * + * @return all SingleExperiments + */ + public final Set getSingleEvents() { + return startParameters.getSingleExperiments(); + } + + /** + * @return a Set with all Events + */ + public final Set getEvents() { + return startParameters.getEvents(); + } + + /** + * @return the step, up to which the Data shall be displayed (inclusive + * step) + */ + public final int getStepCount() { + return step; + } + + /** + * @return the amount singleSteps, that have to be added to the "full" step + * => range is [0 , 2] - where 3 SingleSteps are 1 "full Step" = + * "step" + */ + public final int getSingleStepCount() { + return singleStep; + } + + /** + * @return the step, up to which the Data shall be displayed after the + * increase + */ + public final int singleStepForward() { + singleStep++; + if (singleStep == 3) { + singleStep = 0; + step++; + } + if (emStates.size() < step + 5) { + calcNextState(); + } + return singleStep; + } + + /** + * @return the singleStep, up to which the Data shall be displayed after the + * decrease + */ + public final int singleStepBackward() { + singleStep--; + if (singleStep == -1) { + if (step > 0) { + singleStep = 2; + step--; + } else { + singleStep = 0; + } + } + return singleStep; + } + + /** + * @return the step, up to which the Data shall be displayed after the + * decrease + */ + public final int stepForward() { + step++; + if (emStates.size() < step + 5) { + calcNextState(); + } + return step; + } + + /** + * @return the step, up to which the Data shall be displayed after decrease + */ + public final int stepBackward() { + step--; + if (step < 0) { + step = 0; + singleStep = 0; + } + return step; + } + + /** + * The Likelihood is naturally in range of 0..1 and has the tendency to + * become very small. Therefore all operations are performed on the + * logarithm of the Likelihood.
          + * If this Option is set, getL(int p0, int step) will return + * the Logarithm of the Likelihood. + * + * @param enable + * true, if it the Option should be enabled, + * false otherwise + */ + public final void setLogarithmicLikelihoodRepresentation( + final boolean enable) { + logarithmicLikelihoodRepresentation = enable; + } + + /** + * The Likelihood is naturally in range of 0..1 and has the tendency to + * become very small Therefore all operations are performed on the logarithm + * of the Likelihood.
          + * If setLogarithmicLikelihoodRepresentation(boolean enable) + * was set, getL(int p0, int step) will return the Logarithm of + * the Likelihood. + * + * @return true, if LogarithmicLikelihoodRepresentation is + * enabled, false otherwise + */ + public final boolean isLogarithmicLikelihoodRepresentationEnabled() { + return logarithmicLikelihoodRepresentation; + } + + /** + * + * @return Vector with String representations of the objects' names (like + * "dice 1", "coin 1", "coin2",...) + */ + public final String[] getObjectNames() { + return startParameters.getObjectNames(); + } + + /** + * @param singleEvent + * the Single Event in Point Representation + * @return a String of the Form " Objekt y Side x" + */ + public final String singleEventToString(Point singleEvent){ + return startParameters.singleEventToString(singleEvent); + } +} diff --git a/src/org/jalgo/module/em/control/MainController.java b/src/org/jalgo/module/em/control/MainController.java new file mode 100644 index 0000000..a622115 --- /dev/null +++ b/src/org/jalgo/module/em/control/MainController.java @@ -0,0 +1,287 @@ +package org.jalgo.module.em.control; + +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.concurrent.Semaphore; + +import javax.swing.JComponent; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import org.jalgo.module.em.gui.output.diagram.DiagramPanel; +import org.jalgo.module.em.gui.output.table.TableViewPanel; + +/** + * Controls visual output and navigation through various em states. It can + * switch views and activate presentation mode. + * + * @Author Christian Hendel + * @Author Tobias Nett + * @Author Kilian Gebhardt + */ +public class MainController { + + private static final int HYBRID = 1; + private static final int TABLE = 2; + private static final int DIAGRAM = 0; + private DiagramPanel diagram; + private TableViewPanel table; + private LogState logstate; + private JComponent content; + private JSplitPane hypanel = new JSplitPane(); + private boolean beamer; + private JScrollPane tabframe; + private int view; + private PropertyChangeListener dividerSizeChangedListener; + + //Semaphore and protected Variable + private final Semaphore resizing = new Semaphore(1, false); + private int windowHeight; + + + /** + * Constructor for {@code MainController} class. Saves the values specified + * by {@code Controller} object. + * + * @param logstate + * reference to the {@code LogState} object + * @param content + * the component that should hold the visible content + * @param beamer + * specifies if presentation mode is active + */ + public MainController(LogState logstate, JComponent content, boolean beamer, Controller controller) { + this.logstate = logstate; + this.content = content; + this.beamer = beamer; + mainView(); + + }; + + /** + * Starts main output view for user to observe all dates. Prepares Diagram + * View and Table View. + */ + public void mainView() { + diagram = new DiagramPanel(logstate); + view = HYBRID; + //MouseListerner catches MouseEvents when clicking + //on LikelihoodTable-Headers and resizes the SplitView + table = new TableViewPanel(logstate, new MouseAdapter() { + + @Override + public void mouseClicked(MouseEvent e) { + hybridResize(); + super.mouseClicked(e); + } + + }); + + table.setBeamerMode(beamer); + + content.removeAll(); + table.update(); + diagram.upDate(); + tabframe = new JScrollPane(table); + + //Initialize View with Hybird View + setUpHybrid(); + showHybrid(); + + //ComponentListener, that Resizes Diagram and Table, + //if Size of JAlgo was Changed + hypanel.addComponentListener(new ComponentListener() { + @Override + public void componentResized(ComponentEvent e) { + if (resizing.tryAcquire()) { + hybridResize(); + windowHeight = hypanel.getHeight(); + resizing.release(); + } + } + + @Override + public void componentHidden(ComponentEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void componentMoved(ComponentEvent e) { + // TODO Auto-generated method stub + + } + + @Override + public void componentShown(ComponentEvent e) { + // TODO Auto-generated method stub + + } + }); + + }; + + /** + * one em step forward,updating all views + */ + public void stepForward() { + logstate.stepForward(); + diagram.upDate(); + table.update(); + content.updateUI(); + + }; + + /** + * steps one em step backwards, updating all views + */ + public void stepBack() { + logstate.stepBackward(); + diagram.upDate(); + table.update(); + }; + + /** + * Performs a single step forward. Calculates the needed data and updates + * all related views. + */ + public void singleStepForward() { + logstate.singleStepForward(); + diagram.upDate(); + table.update(); + table.update(); + } + + /** + * Performs a single step backward. Calculates the needed data and updates + * all related views. + */ + public void singleStepBackward() { + logstate.singleStepBackward(); + diagram.upDate(); + table.update(); + table.update(); + } + + /** + * shows Hybrid view(diagram and Table) + */ + public void showHybrid() { + view = HYBRID; + table.setViewLike(); + hybridResize(); + }; + + public void setUpHybrid(){ + hypanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, diagram, tabframe); + hybridResize(); + hypanel.setOneTouchExpandable(true); + + dividerSizeChangedListener = new PropertyChangeListener() { + + @Override + public void propertyChange(PropertyChangeEvent arg0) { + if (resizing.tryAcquire()){ + if (arg0.getPropertyName().equals("dividerLocation") && windowHeight == hypanel.getHeight()){ + if ((Integer) arg0.getNewValue() == 1) { + view = TABLE; + } else if ((Integer) arg0.getNewValue() > windowHeight - hypanel.getDividerSize() - 5) { + view = DIAGRAM; + } else if ((view == TABLE && ((Integer) arg0.getNewValue() > (Integer) arg0.getOldValue())) + || (view == DIAGRAM && ((Integer) arg0.getNewValue() < (Integer) arg0.getOldValue()))) { + view = HYBRID; + } + } + resizing.release(); + } + } + }; + hypanel.addPropertyChangeListener(dividerSizeChangedListener); + + content.add(hypanel); + content.updateUI(); + } + + /** + * shows diagram only + */ + public void showDiagram() { + view = DIAGRAM; + hypanel.setDividerLocation(1.0); + }; + + /** + * shows table only + */ + public void showTable() { + view = TABLE; + if (logstate.getEvents().size() > 10) { + table.setViewLikeSingle(); + } else { + table.setViewLikeSinglePart(); + } + hypanel.setDividerLocation(0.0); + }; + + /** + * Toggles the presentation mode. Updates all views that provide a + * presentation mode. + */ + public void changePresentationMode() { + beamer = !beamer; + table.setBeamerMode(beamer); + table.update(); + hybridResize(); + } + + public void updateViews(){ + table.update(); + diagram.upDate(); + } + + /** + * Sizes the TablePanel to min{50% of the heights; + * preferred size in which every L-Table can be displayed}. + * @author kilian + */ + private void hybridResize() { + //Set the number of TableColumns + if (view != DIAGRAM) { + if (content.getWidth() <= 900) { + table.setShownum(2); + table.update(); + } else if (content.getWidth() < 1043) { + table.setShownum(3); + table.update(); + } else { + table.setShownum(4); + table.update(); + } + } + if (view == HYBRID) { + if (tabframe.getPreferredSize().height - hypanel.getDividerSize() > content.getSize().height / 2) { + hypanel.setDividerLocation(0.5); + } else { + //If the Window is smaller than 1110, a horizontal Scrollbar + //is needed: this consumes extra space + int scroll_offset = 0; + if (hypanel.getSize().width < 1110) { + scroll_offset = 15; + } + hypanel.setDividerLocation(content.getSize().height + - tabframe.getPreferredSize().height + - hypanel.getDividerSize() + - scroll_offset + - 2); + } + } else if (view == TABLE) { + hypanel.setDividerLocation(0.0); + } else { + hypanel.setDividerLocation(1.0); + } + diagram.resetButtons(); + } +} diff --git a/src/org/jalgo/module/em/control/OptionPane.java b/src/org/jalgo/module/em/control/OptionPane.java new file mode 100644 index 0000000..7b2e3a4 --- /dev/null +++ b/src/org/jalgo/module/em/control/OptionPane.java @@ -0,0 +1,121 @@ +package org.jalgo.module.em.control; + +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JTextField; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.gui.input.InputStringParser; + +/** + * An option window to change the settings + * to limit precalculations. + * + * @author Christian Hendel + */ +public class OptionPane extends JFrame implements FocusListener { + + private static final String DEFAULT = "1,5"; + + private static final long serialVersionUID = 5698661714725081879L; + private double limit = -1; + private JLabel label1 = new JLabel(Messages.getString("em", "Options.limitlabel")); + private JTextField inpLimit = new JTextField(DEFAULT); + private GridBagLayout layout = new GridBagLayout(); + private GridBagConstraints c= new GridBagConstraints(); + private JButton ok = new JButton("OK"); + private JButton cancel = new JButton(Messages.getString("em", "Options.c")); + private ActionListener lok,lc; + private Controller cont; + private JLabel stepLabel; + + /** + * this Constructor just initilizes the BoxbagLayout and one actionlistener + * + * @param cont Controller for the module + */ + public OptionPane(Controller cont, JLabel stepLabel){ + this.cont=cont; + this.stepLabel = stepLabel; + lc = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + zu(); + } + }; + lok = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ok(); + } + }; + inpLimit.addFocusListener(this); + inpLimit.addActionListener(lok); + + ok.addActionListener(lok); + cancel.addActionListener(lc); + this.setLayout(layout); + c.gridx=0; + c.gridy=0; + c.weightx=0.75; + this.add(label1,c); + c.gridx=2; + c.gridy=0; + c.weightx=0.25; + this.add(inpLimit,c); + inpLimit.setPreferredSize(new Dimension(120, inpLimit.getPreferredSize().height)); + inpLimit.setMinimumSize(inpLimit.getPreferredSize()); + c.gridy=1; + c.gridx=2; + this.add(ok,c); + c.gridy=1; + c.gridx=0; + this.add(cancel,c); + + } + /** + * this method is used when the OK button is pressed. + * It converts inputed text to a usable float + * and catches errors that occur when + * input is not usable + */ + public void ok(){ + try{ + limit=(InputStringParser.parseInputString(inpLimit.getText(), 0, 100)) / 100; + cont.setLimit(limit); + cont.getLogState().calcUntilLimit(limit); + cont.getMC().updateViews(); + stepLabel.setText(cont.getLogState().getStepCount()+"."+cont.getLogState().getSingleStepCount()); + close(); + } + catch (IllegalArgumentException e){ + JOptionPane.showMessageDialog(null,Messages.getString("em", "Options.ex1"),"Error",JOptionPane.ERROR_MESSAGE); + } + } + + public void close(){ + if (!(limit < 0)){ + this.setVisible(false); + } + + } + + public void focusGained(FocusEvent foc){ + inpLimit.selectAll(); + } + + public void focusLost(FocusEvent foc) { + } + + public void zu(){this.setVisible(false);} +} diff --git a/src/org/jalgo/module/em/control/TestCalculation.java b/src/org/jalgo/module/em/control/TestCalculation.java new file mode 100644 index 0000000..bf0f4b4 --- /dev/null +++ b/src/org/jalgo/module/em/control/TestCalculation.java @@ -0,0 +1,268 @@ +package org.jalgo.module.em.control; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; + +/** + * Class for testing usage. You can use this to get a hard coded example. + */ +public class TestCalculation { + + /** + * You can use this for Testing the output-Views. You have to use the + * stepForward function, to calculate new Steps. For an example look at + * TestCalculation.main(). + * + * @return initialized LogState that has StartParameters for the Coin + * Example and 3 StartProbabilityDistributions + */ + public static LogState createCoinExample() { + StartParameters startParameters = createCoinExampleStartParams(); + + return new LogState(startParameters); + } + + /** + * Creates a test object of start parameters that can be used for testing + * the output views. + *

          + * The example is very similar to the example given in the lecture. + * + * @return a complete {@code StartParameters} object for test usage + */ + public static StartParameters createCoinExampleStartParams() { + StartParameters startParameters = new StartParameters(); + + // Creating Events + Set events = new HashSet(); + Vector kkEventVector = new Vector(3); + Vector kzEventVector = new Vector(3); + Vector zkEventVector = new Vector(3); + Vector zzEventVector = new Vector(3); + kkEventVector.setSize(2); + kzEventVector.setSize(2); + zkEventVector.setSize(2); + zzEventVector.setSize(2); + + kkEventVector.setElementAt(2, 0); + kkEventVector.setElementAt(2, 1); + kzEventVector.setElementAt(2, 0); + kzEventVector.setElementAt(1, 1); + zkEventVector.setElementAt(1, 0); + zkEventVector.setElementAt(2, 1); + zzEventVector.setElementAt(1, 0); + zzEventVector.setElementAt(1, 1); + + Event kkEvent = new Event(kkEventVector); + Event kzEvent = new Event(kzEventVector); + Event zkEvent = new Event(zkEventVector); + Event zzEvent = new Event(zzEventVector); + + events.add(zzEvent); + events.add(zkEvent); + events.add(kzEvent); + events.add(kkEvent); + + Vector experimentVector = new Vector(); + experimentVector.setSize(2); + experimentVector.set(0, 2); + experimentVector.set(1, 2); + startParameters.setExperiment(experimentVector); + + startParameters.setEvents(events); + Set elements1 = new HashSet(); + Set elements2 = new HashSet(); + Set elements3 = new HashSet(); + + elements1.add(kkEvent); + elements2.add(kzEvent); + elements3.add(zkEvent); + elements1.add(zzEvent); + + // Creating Partitions + Partition partition1 = new Partition(elements1, "0 mal Zahl"); // KK; h + // = 2 + Partition partition2 = new Partition(elements2, "1 mal Zahl"); // KZ , + // ZK; h + // = 9 + Partition partition3 = new Partition(elements3, "2 mal Zahl"); // ZZ; h + // = 4 + + partition1.setFrequency(9); + partition2.setFrequency(2); + partition3.setFrequency(4); + + Set observations = new HashSet(); + observations.add(partition1); + observations.add(partition2); + observations.add(partition3); + startParameters.setObservations(observations); + + // Set Yield + for (Partition partition : startParameters.getObservations()) { + for (Event event : partition.getElements()) { + event.setYield(partition); + } + } + + List p0DataList = new ArrayList(); + + // Creating p0 Distributions + // p0 No. 1 + Map singleEventStartProbability = new HashMap(); + singleEventStartProbability.put(new Point(2, 0), 0.5); + singleEventStartProbability.put(new Point(1, 0), 0.5); + singleEventStartProbability.put(new Point(2, 1), 0.5); + singleEventStartProbability.put(new Point(1, 1), 0.5); + EMData p0Data = EMModule.calcFirstStep(singleEventStartProbability, + startParameters); + + p0DataList.add(p0Data); + + // p0 No. 2 + Map singleEventStartProbability2 = new HashMap(); + singleEventStartProbability2.put(new Point(2, 0), 0.3); + singleEventStartProbability2.put(new Point(1, 0), 0.7); + singleEventStartProbability2.put(new Point(2, 1), 0.4); + singleEventStartProbability2.put(new Point(1, 1), 0.6); + EMData p0Data2 = EMModule.calcFirstStep(singleEventStartProbability2, + startParameters); + p0DataList.add(p0Data2); + + // p0 No. 3 + Map singleEventStartProbability3 = new HashMap(); + singleEventStartProbability3.put(new Point(2, 0), 0.1); + singleEventStartProbability3.put(new Point(1, 0), 0.9); + singleEventStartProbability3.put(new Point(2, 1), 0.2); + singleEventStartProbability3.put(new Point(1, 1), 0.8); + EMData p0Data3 = EMModule.calcFirstStep(singleEventStartProbability3, + startParameters); + p0DataList.add(p0Data3); + + EMState p0EMState = new EMState(p0DataList); + startParameters.setP0EMState(p0EMState); + + return startParameters; + } + + + + /** + * @param args + */ + + + public static void main(String[] args) { + System.out.println(Double.MIN_VALUE); + LogState myLogState = createCoinExample(); + //myLogState.setLogarithmicLikelihoodRepresentation(true); + //Calculating 20 EMStates and setting the StepCount to 19 + //for (int i = 0; i<20; i++) myLogState.stepForward(); + myLogState.calcUntilLimit(0.01); + System.out.println("P0 Count " + myLogState.getP0Count()); + System.out.println("step Count" + myLogState.getStepCount()); + for (int p0 = 0; p0 p; + private Map d; + private Map h; + private Map pForPartition; + private Map pForSingleEvent; + private Double likelihood; + + /** + * The Constructor sets all the Stored Values. + * @param d Statistical Analyzer of the Events d(x) + * @param h estimated Frequency of the Events h(x) + * @param p the Probability of the Events p(x) + * @param pForPartition the Probability for the Partitions p'(y) + * @param pForSingleEvent the Probability for + * the each singleEvent, given in Point representation + * @param likelihood the Likelihood of the + * ProbabilityDistribution, in Relation to the y-corpus + * given in global StartParameters + */ + public EMData(final Map d, + final Map h, + final Map p, + final Map pForPartition, + final Map pForSingleEvent, + final Double likelihood) { + this.d = d; + this.h = h; + this.p = p; + this.pForPartition = pForPartition; + this.pForSingleEvent = pForSingleEvent; + this.likelihood = likelihood; + } + + /** + * @return the Probability for each Event in the current Step + */ + public final Map getP() { + return p; + } + + /** + * @return the Statistical Analyzer for each Event in the current Step + */ + public final Map getD() { + return d; + } + + /** + * @return the Frequency for each Event in the current Step + */ + public final Map getH() { + return h; + } + + /** + * @return the Probability for each Partition in the current Step + */ + public final Map getPForPartition() { + return pForPartition; + } + + /** + * @return a map, where the Keys are + * singleEvents in Point Representation: + * Point.x = Side out of [1..] + * Point.y = number of the Object + * in the Experiment Vector out of [0..n-1] + */ + public final Map getPForSingleEvent() { + return pForSingleEvent; + } + /** + * @return Likelihood of the current Step + */ + public final Double getLikelihood() { + return likelihood; + } +} diff --git a/src/org/jalgo/module/em/data/EMState.java b/src/org/jalgo/module/em/data/EMState.java new file mode 100644 index 0000000..51d8d5d --- /dev/null +++ b/src/org/jalgo/module/em/data/EMState.java @@ -0,0 +1,36 @@ +package org.jalgo.module.em.data; + +import java.util.List; + +/** + * The EMState holds all the EMData for the different + * StartProbabilityDistributions that belong to one EMStep. + * + * @author kilian + */ +public class EMState { + /** + * The EMData that belong to the EMStep, ordered according to + * the Index of their StartProbabilityDistribution. + */ + private List data; + + /** + * Creates the EMState, by setting the EMData. The + * EMData have to be ordered in the List according to the index + * of the StartProbabilityDistribution they belong to. + * + * @param data the ordered list of {@code EMData} + */ + public EMState(final List data) { + this.data = data; + } + + /** + * @return a List with EMData that belong to this EMSTep, + * ordered by StartProbabilityIndex. + */ + public final List getEMData() { + return data; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/em/data/Event.java b/src/org/jalgo/module/em/data/Event.java new file mode 100644 index 0000000..ec257cd --- /dev/null +++ b/src/org/jalgo/module/em/data/Event.java @@ -0,0 +1,129 @@ +package org.jalgo.module.em.data; + +import java.util.Vector; + +import org.jalgo.main.util.Messages; + +/** + * Represents an event, that consists of multiple SingleEvents. + * @author Kilian Gebhardt + * @author Tobias Nett + */ +public class Event implements Comparable { + private Vector tuple, experimentVector; + private Partition yield; + + /** + * @param tuple + * The tuple with SingleEvents. + * @param experimentVector The experimentVector. + */ + public Event(final Vector tuple, final Vector experimentVector) { + this.tuple = tuple; + this.yield = null; + this.experimentVector = experimentVector; + } + + /** + * @param tuple + * The tuple with SingleEvents. + */ + public Event(final Vector tuple) { + this.tuple = tuple; + this.yield = null; + this.experimentVector = null; + } + + /** + * @param yield + * The Partition to which the event belongs. + */ + public final void setYield(final Partition yield) { + this.yield = yield; + } + + /** + * Clears this event's yield by setting it to null. + */ + public final void clearYield() { + this.yield = null; + } + + /** + * Generates a String "(x1,x2,x3,...)", + * where xi is either a number in case of a dice or "K" or "Z" + * (German) or "H" or "T" (English) in case of a coin. + * + * @return The String Representation of the Event. + */ + @Override + public final String toString() { + StringBuilder output = new StringBuilder(); + output.append("("); + for (int i = 0; i < tuple.size(); i++) { + if (experimentVector != null){ + output.append((experimentVector.get(i) == 2) + ? ((tuple.get(i) == 1) + ? Messages.getString("em", "StartParameters.Tail") + ", " + : Messages.getString("em", "StartParameters.Head") + ", ") + : tuple.get(i) + ", "); + } else { + output.append(tuple.get(i) + ", "); + } + } + output.delete(output.lastIndexOf(", "), output.length()); + output.append(")"); + return output.toString(); + } + + /** + * @return Partition of the Event. + */ + public final Partition getYield() { + return yield; + } + + /** + * @return Events tuple with SingleEvents + */ + public final Vector getTuple() { + return tuple; + } + + /** + * Compares this event with the specified event for order. The tuple entries + * have a descending priority and the vector elements will be compared until + * they are not equal. + * + * @param e + * the Event to compare + * @return a negative integer, zero, or a positive integer as this object is + * less than, equal to, or greater than the specified object. + */ + @Override + public final int compareTo(final Event e) { + // get the length of the shorter event + int size = Math.min(e.getTuple().size(), this.tuple.size()); + int cmp = 0; + for (int i = 0; i < size; i++) { + cmp = this.tuple.get(i).compareTo(e.getTuple().get(i)); + if (cmp != 0) { + break; + } + } + return cmp; + } + + @Override + public final boolean equals(final Object e) { + if (e instanceof Event) + return ((Event) e).getTuple().equals(tuple); + return false; + } + + @Override + public final int hashCode() { + return tuple.hashCode(); + } + +} diff --git a/src/org/jalgo/module/em/data/Partition.java b/src/org/jalgo/module/em/data/Partition.java new file mode 100644 index 0000000..aa788bf --- /dev/null +++ b/src/org/jalgo/module/em/data/Partition.java @@ -0,0 +1,190 @@ +package org.jalgo.module.em.data; + +import java.util.Set; +import java.util.TreeSet; + +/** + * Data object representing a partition of the experiment's event set (a class of a partition). + *

          A Partition consists of a set of Events and a frequency, which is + * a real number greater or equal 0. + * + * @author Tobias Nett + * + */ +public class Partition { + + private String name; + private double frequency = 0; + private Set elements; + + /** + * Creates a new, empty Partition object. + */ + public Partition(){ + elements = new TreeSet(); + name = ""; + } + + /** + * Creates a new Partition which consists of all Events in elements. + * All the Events are yielded to this partition. + * + * @param elements Set of Events which belong to this partition + */ + public Partition(Set elements) { + if (elements == null) + throw new NullPointerException("null argument(s)"); + this.elements = new TreeSet(elements); + + this.name = ""; + if (elements != null) + yieldEvents(); + } + + /** + * Creates a new Partition which consists of all Events in elements. + * The Partition's name is set to name (e.g. "two time head"). + * All the Events are yielded to this partition. + * + * @param elements Set of Events which belong to this partition + * @param name Name of the Partition + */ + public Partition(Set elements, String name) { + if (name == null || elements == null) + throw new NullPointerException("null argument(s)"); + this.elements = new TreeSet(elements); + this.name = name; + + if (elements != null) + yieldEvents(); + } + + /** + * Yields this partition to every Event. + */ + private void yieldEvents(){ + for (Event e : elements) { + e.setYield(this); + } + } + + /** + * Adds an Event to this partition and sets the yield of the Event. + * + * @param e Event to add + */ + public void addElement(Event e){ + if (elements == null) + elements = new TreeSet(); + elements.add(e); + e.setYield(this); + } + + /** + * Removes the Event from the partition + * + * @param e Event to remove + */ + public void removeElement(Event e){ + if (elements != null) + elements.remove(e); + } + + /** + * Clears the yield of every Event. Should be called before deleting the partition. + */ + public void remove(){ + for (Event e : elements) { + e.clearYield(); + } + } + + /** + * Returns a mathematical string representation of this partition in the form + * "{(1,1), (1,2), ... }". + * + * @return mathematical representation of this partition + */ + public String getMathSet(){ + StringBuilder out = new StringBuilder("{ "); + for (Event event : elements) { + out.append(event.toString()); + out.append(", "); + } + out.deleteCharAt(out.lastIndexOf(", ")); + out.append("}"); + return out.toString(); + } + + /** + * Returns the name of the Partition, which should be better human-readable than the mathematical + * representation of the element set, e.g. "3-times head" or "Sum: 4". + * + * + * @return the partition's name + */ + public String getName() { + return name; + } + + /** + * Sets the name of the partition to the given value. + * + * @param name the partition's name + */ + public void setName(String name) { + if (name == null) + throw new NullPointerException("no null arguments allowed"); + this.name = name; + } + + /** + * Get the partition's frequency, which often means a natural number at the beginning of an experiment. + * + * @return the frequency - a real number >= 0 + */ + public double getFrequency() { + return frequency; + } + + /** + * + * @param frequency the frequency to set + * + * @throws IllegalArgumentException is raised when the argument is < 0 + */ + public void setFrequency(double frequency) throws IllegalArgumentException { + if (frequency < 0) + throw new IllegalArgumentException("Negative frequency"); + this.frequency = frequency; + } + + /** + * Return a Set of all Events that belong to this Partition. null is returned + * if there are no elements in this partition. + * + * @return all elements of this partition + */ + public Set getElements(){ + return elements; + } + + /** + * Generates a String "{ (x1, x2,...),(x1, x2,...),..}", + * where (x1, x2,...) is a Event of the partition. + * + * @return The String Representation of the Partition. + */ + @Override + public String toString(){ + //if there are no elements in this partition + if (elements == null || elements.isEmpty()) + return "empty"; + // otherwise, generate a mathematical representation of its Event set. + //StringBuilder out = new StringBuilder("{ "); + StringBuilder out = new StringBuilder(""+name+"
          "); + out.append(getMathSet()); + out.append(""); + return out.toString(); + } +} diff --git a/src/org/jalgo/module/em/data/StartParameters.java b/src/org/jalgo/module/em/data/StartParameters.java new file mode 100644 index 0000000..e032a09 --- /dev/null +++ b/src/org/jalgo/module/em/data/StartParameters.java @@ -0,0 +1,252 @@ +package org.jalgo.module.em.data; + +import java.awt.Point; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.Vector; + +import org.jalgo.main.util.Messages; + +/** + * StartParameters will hold all Information, that is collected during the input + * phase. Only these values will be stored, if the StoreFunctionality is used. + * + * @author kilian + * @version Alpha + * + * + */ +public class StartParameters { + + private Set events; + private Set observations; + private EMState p0EMState; + private Vector experiment; + private Double frequencySum; + private int type; + private int par1; + private int par2; + + /** + * Creates a new {@code StartParameters} object without any initialized + * values. + */ + public StartParameters() { + type = 0; + par1 = -1; + par2 = -1; + + } + + /** + * The experiments {@code Event}s. + * + * @return set of all events of this experiment + */ + public Set getEvents() { + return events; + } + + /** + * Sets the possible {@code Event}s of this experiment to the specified + * value. + * + * @param events + * set of all possible {@code Event}s + */ + public void setEvents(Set events) { + this.events = events; + } + + /** + * Sets the {@link org.jalgo.module.em.data.EMState} in the start parameters + * to the specified value. + * + * @param p0EMState + * the new state value + */ + public void setP0EMState(EMState p0EMState) { + this.p0EMState = p0EMState; + } + + /** + * The current observation set. + * + * @return the current observation set as {@code Set} + */ + public Set getObservations() { + return this.observations; + } + + /** + * Sets the observation set to the specified value. + * + * @param observations + * the new observation set as a {@code Set} + */ + public void setObservations(Set observations) { + this.observations = observations; + } + + /** + * + * @return the Sum of the Frequency from all Partitions + */ + public Double getFrequencySum() { + frequencySum = .0; + for (Partition partition : observations) { + frequencySum += partition.getFrequency(); + } + return frequencySum; + } + + /** + * + * @return Number of Objects in the Experiment Vector. + */ + public int getObjectCount() { + return experiment.size(); + } + + /** + * + * @return the Experiment Vector - {@code null} if the vector is not + * initialized + */ + public Vector getExperiment() { + return this.experiment; + } + + /** + * + * @return the Initial EMState, with p0, p'0 and L0 for each + * p0-distribution. + */ + public EMState getP0EMState() { + return p0EMState; + } + + /** + * + * @return a set with all SingleExperiments + */ + public Set getSingleExperiments() { + Set singleExperiments = new HashSet(); + for (int object = 0; object < experiment.size(); object++) { + for (int count = 1; count <= experiment.get(object); count++) { + singleExperiments.add(new Point(count, object)); + } + } + return singleExperiments; + } + + /** + * Sets the experiment vector to the specified vector. + * + * @param experiment + * the new experiment vector as {@code Vector} + */ + public void setExperiment(Vector experiment) { + this.experiment = new Vector(experiment); + } + + /** + * + * @return Vector with String representations of the objects' names (like + * "dice 1", "coin 1", "coin2",...) + */ + public String[] getObjectNames() { + String[] objectNames = new String[experiment.size()]; + Map map = new TreeMap(); + for (int i = 0; i < experiment.size(); i++) { + int sides = experiment.get(i); + if (!(map.containsKey(sides))) { + map.put(sides, 1); + } + objectNames[i] = this.ObjectName(experiment.get(i)) + " " + + map.get(sides); + map.put(sides, map.get(sides) + 1); + } + return objectNames; + } + + /** + * Returns the name of the specified object. This name is the same as in the + * names array returned by {@link #getObjectNames()} at position + * {@code index}. + * + * @param index + * the index of the object whose name is inquired + * @return the name of the specified object, e.g. 'coin 2', 'dice 5', ... + */ + public String getObjectName(int index) { + if (index < experiment.size()) + return getObjectNames()[index]; + return null; + } + + /** + * Generates a 'human readable' representation of the object (e.g. coin, + * dice, ...) or a symbolic representation like 'W7". + * + * @param sides + * count of object's sides + * + * @return A 'human readable" representation of the object (e.g. coin, dice, + * ...) + */ + private String ObjectName(Integer sides) { + String key = "ObjectName." + sides; + String name = Messages.getString("em", key); + if (name.equals("!" + key + "!")) { + name = Messages.getString("em", "ObjectName") + sides; + } + return name; + } + + /** + * @param singleEvent + * the Single Event in Point Representation + * @return a String of the Form " Objekt y Side x" + */ + public final String singleEventToString(final Point singleEvent) { + StringBuilder eventString = new StringBuilder(); + eventString.append(getObjectName(singleEvent.y)); + eventString.append(": "); +// eventString.append(Messages.getString("em", "StartParameters.side")); +// eventString.append(" "); + if (experiment.get(singleEvent.y) != 2) { + eventString.append(String.format("%d", singleEvent.x)); + } else { + eventString.append((singleEvent.x == 1) + ? Messages.getString("em", "StartParameters.Tail") + : Messages.getString("em", "StartParameters.Head")); + } + return eventString.toString(); + } + + /** + * The type of the partitioning, so that it can be + * detected and restored. + * @return A length 3 Array, + * that encodes the type of the partitioning. + */ + public int[] getObservationType() { + int[] observationType = { type, par1, par2 }; + return observationType; + } + + /** + * Sets the type of the partitioning, so that it can be + * detected when it is loaded. + * @param observationType A length 3 Array, + * that encodes the type of the partitioning. + */ + public void setObservationType(int[] observationType) { + this.type = observationType[0]; + this.par1 = observationType[1]; + this.par2 = observationType[2]; + } +} diff --git a/src/org/jalgo/module/em/data/package-info.java b/src/org/jalgo/module/em/data/package-info.java new file mode 100644 index 0000000..6e6863d --- /dev/null +++ b/src/org/jalgo/module/em/data/package-info.java @@ -0,0 +1,5 @@ +/** + * The data package consists of the data classes needed for the em module. + */ +package org.jalgo.module.em.data; + diff --git a/src/org/jalgo/module/em/de.properties b/src/org/jalgo/module/em/de.properties new file mode 100644 index 0000000..59b460d --- /dev/null +++ b/src/org/jalgo/module/em/de.properties @@ -0,0 +1,111 @@ +ObjectName=W +ObjectName.2=Münze +ObjectName.4=Tetraeder +ObjectName.6=Würfel +ObjectName.8=Oktaeder +Controller.togglePMode=Präsentationsmodus wechseln +ToolBar.save=Experiment speichern +ToolBar.load=Experiment laden +ToolBar.preferences=Einstellungen +ToolBar.wback=EM-Schritt zurück +ToolBar.back=Einzelschritt zurück +ToolBar.forw=Einzelschritt vorwärts +ToolBar.wforw=EM-Schritt vorwärts +ToolBar.home=Zurück in den Inputmodus +ToolBar.run=EM-Algorithmus bis Konvergenz ausführen +Menu.hybrid=Hybridansicht +Menu.table=Tabellenansicht +Menu.diagram=Diagrammansicht +Menu.log=logarithmische Likelihood +Menu.presentation=Präsentationsmodus +IOController.FileChooser=Datei wählen +InputPanel.bForward=Weiter +InputPanel.bBack=Zurück +StartScreen.start.description=Ein neues Experiment mit der Eingabe der Parameter beginnen +StartScreen.load.description=Ein gespeichertes Experiment laden und direkt visualisieren lassen +StartScreen.LoadErrorDescription=Die ausgewählte Datei ist fehlerhaft oder keine gültige em-Datei! +StartScreen.LoadErrorTitle=Ladefehler +XInputPanel.bAddCoin=Münze hinzufügen +XInputPanel.bAddDice=Würfel hinzufügen +XInputPanel.bAdd=n-seitiges Objekt hinzufügen +XInputPanel.bRemoveLast=Rückgängig +XInputPanel.lXInput=

          Objekte hinzufügen

          +XInputPanel.description=Fügen Sie durch klicken auf die Buttons mindestens ein neues Objekt zum Experiment hinzu. +XInputPanel.ErrorMessageDescriptionNegative=Ein Objekt kann keine negative Anzahl an Seiten haben. Geben Sie eine ganze Zahl &ge 1 ein. +XInputPanel.ErrorMessageTitle=Eingabefehler +XInputPanel.ErrorMessageDescription=Geben Sie eine ganze Zahl &ge 1 ein. +Partition.Name.Sum=Summe der Seiten: +Partition.Name.SideCount=-mal Seite +Partition.Name.Doublet=Pasch (gleiche Seiten) +Partition.Name.NoDoublet=kein Pasch +Partition.Name.Property= zeigt Seite +Partition.Name.PropertyNot=zeigt nicht Seite +PartitionPanel.lSelection=Auswahl +PartitionPanel.bSameSide=Gleiche Seite +PartitionPanel.bSideCount=Anzahl Seite +PartitionPanel.bObjectProperty=Ein Objekt hat
          eine Eigenschaft +PartitionPanel.bSum=Summe der Seiten +PartitionPanel.bCustomize=Eigene Partitionierung +PartitionPanel.lList=Partitionen +PartitionPanel.bRemove=Partition löschen +PartitionPanel.lTable=Partitionierung anpassen +PartitionPanel.bNew=neue Partition erstellen +PartitionPanel.bFill=Partition aus Rest +PartitionPanel.coin.head=Kopf +PartitionPanel.coin.tail=Zahl +PartitionPanel.DefaultPartitionName=Partition +YFrequencyPanel.lHeading=Häufigkeit der Beobachtungen +YFrequencyPanel.lDescription=Tragen Sie in der Tabelle die Häufigkeit der jeweiligen Beobachtung (Partition) ein. +YFrequencyTableModel.PartitionName=Beobachtung (Partition) +YFrequencyTableModel.PartitionElements=Elemente +YFrequencyTableModel.Frequency=Häufigkeit +YFrequencyPanel.ErrorMessageDescription=Die Häufigkeit muss eine relle Zahl &ge 0 sein. Die Eingabe darf in der Form "1,5", "1.5" oder "3/2" sein. +YFrequencyPanel.ErrorMessageTitle=Eingabefehler +DiagramPanel.StandartZoom=zur\u00fcck zu Standardzoom +DiagramPanel.iterationToLiklihood=f(Iteration)=Likelihood +DiagramPanel.twoCoinsPlot=Likelihood 3D +DiagramPanel.iterationToD=f(Iteration)=Statistischer Analysator +DiagramPanel.iterationToH=f(Iteration)=X-Korpus +DiagramPanel.iterationToP=f(Iteration)=Wahrscheinlichkeit +DiagramPanel.iterationToPSingle=f(Iteration)=Wahrscheinlichkeit Einzelereignis +DiagramPanel.d=Statistischer Analysator +DiagramPanel.l=Likelihood +DiagramPanel.p=Wahrscheinlichkeit +DiagramPanel.psingle=Wahrscheinlichkeit Einzelereignis +DiagramPanel.h=X-Korpus +DiagramPanel.d.short=d +DiagramPanel.l.short=L +DiagramPanel.p.short=p +DiagramPanel.psingle.short=p +DiagramPanel.h.short=h +DiagramPanel.twoCoinsPlot.short=L 3D +DiagramPanel.3DAxisX=p1(K) +DiagramPanel.3DAxisY=p2(K) +P0InputPanel.bAddP0=p0 hinzufügen +P0InputPanel.bRemoveP0=p0 entfernen +P0InputPanel.bEquipartition=gleichverteilt auffüllen +P0InputPanel.bRandomFilling=zufällig auffüllen +P0InputPanel.lP0Input=

          Startwahrscheinlichkeitsverteilung eingeben

          +P0InputPanel.description=Geben Sie eine oder mehrere Startwahrscheinlichkeiten an. Dabei muss die Summe der Wahrscheinlichkeiten je Objekt 1 ergeben und jede Wahrscheinlichkeit > 0 sein. +StartParameters.side=Seite +StartParameters.Tail=Z +StartParameters.Head=K +P0InputPanel.ErrorMessageTitle=Eingabefehler +P0InputPanel.ErrorMessageDescriptionNoP0=Es wurde keine Startwahrscheinlichkeitsverteilung eingegeben. Geben Sie mindestens eine gültige Startwahrscheinlichkeitsverteilung ein! +P0InputPanel.ErrorMessageDescriptionNoDouble=Die Wahrscheinlichkeit muss eine reelle Zahl > 0 und &le 1 sein. Die Eingabe darf in der Form "0,5", "0.5" or "2/3" sein. +P0InputPanel.ErrorMessageDescriptionSumNot1=Die Summe der Startwahrscheinlichkeiten für ein Objekt ist ungleich 1! +P0InputPanel.ErrorMessageDescriptionNoSelection=Es wurde keine Spalte markiert! +P0InputPanel.bAddP0ToolTip=Eine neue Spalte für eine weitere Startwahrscheinlichkeitsverteilung hinzufügen. +P0InputPanel.bRemoveP0ToolTip=Die angewählte Spalte löschen. +P0InputPanel.bEquipartitionToolTip=Die unbelegten Zellen der angewählten Spalte gleichmäßig auffüllen, so dass die Summe in der Spalte 1 ergibt. +P0InputPanel.bRandomFillingToolTip=Die unbelegten Zellen der angewählten Spalte zufällig auffüllen, so dass die Summe in der Spalte 1 ergibt. +P0InputPanel.bForwardToolTip=Die Eingabe der Startwahrscheinlichkeitsverteilungen abschließen und zur Berechnung von EM-Schritten übergehen. +P0InputPanel.bBackToolTip=Zurück zur Eingabe für die Häufigkeiten der Beobachtungen. +Options.limitlabel=Bitte ein Berechnungslimit in Prozent eingeben. +Options.ex1=Bitte einen gültigen Prozentwert eingeben! +Options.ex2=Parserfehler. Bitte den Input prüfen +Options.c=Abbrechen +TableViewPanel.Event=Ereignis +ModuleInfo.info=Dieses Modul behandelt den EM-Algorithmus. +ModuleInfo.license=GPL. Grafiken von Onebit. +ModuleInfo.name=EM-Algorithmus \ No newline at end of file diff --git a/src/org/jalgo/module/em/en.properties b/src/org/jalgo/module/em/en.properties new file mode 100644 index 0000000..b3f8f9f --- /dev/null +++ b/src/org/jalgo/module/em/en.properties @@ -0,0 +1,111 @@ +ObjectName=D +ObjectName.2=Coin +ObjectName.4=Tetrahedron +ObjectName.6=Dice +ObjectName.8=Octahedron +Controller.togglePMode=toggle presentation mode +ToolBar.save=save experiment +ToolBar.load=load experiment +ToolBar.preferences=preferences +ToolBar.wback=EM-step back +ToolBar.back=single step back +ToolBar.forw=single step forward +ToolBar.wforw=EM-step forward +ToolBar.home=Back to inputscreens +ToolBar.run=run EM-algorithm until convergence +Menu.hybrid=hybrid view +Menu.table=table view +Menu.diagram=diagram view +Menu.log=logarithmic Likelihood +Menu.presentation=presentation mode +IOController.FileChooser=Choose File +InputPanel.bForward=Next +InputPanel.bBack=Back +StartScreen.start.description=Start a new experiment with entering all needed parameters +StartScreen.load.description=Load a saved experiment and start the visualization immediately +StartScreen.LoadErrorDescription=The chosen file is invalid. +StartScreen.LoadErrorTitle=Load Error +XInputPanel.bAddCoin=Add coin +XInputPanel.bAddDice=Add dice +XInputPanel.bAdd=Add n-sided object +XInputPanel.bRemoveLast=undo +XInputPanel.lXInput=Add objects +XInputPanel.description=Add at least one object to the experiment by clicking on the buttons. +XInputPanel.ErrorMessageDescriptionNegative=The number of sides of an object has to be &ge 1. +XInputPanel.ErrorMessageDescription=Please enter a valid integer &ge 1. +XInputPanel.ErrorMessageTitle=Input Error +Partition.Name.Sum=Sum: +Partition.Name.SideCount=-times side +Partition.Name.Doublet=Doublet (same sides) +Partition.Name.NoDoublet=No doublet +Partition.Name.Property= shows side +Partition.Name.PropertyNot=does not show side +PartitionPanel.lSelection=Selection +PartitionPanel.bSameSide=Same side +PartitionPanel.bSideCount=Side frequency +PartitionPanel.bObjectProperty=A Object has a
          specific property +PartitionPanel.bSum=Sum +PartitionPanel.bCustomize=Own partitioning +PartitionPanel.lList=Partitioning +PartitionPanel.bRemove=Delete partition +PartitionPanel.lTable=Customize Partitioning +PartitionPanel.bNew=Create new partition +PartitionPanel.bFill=Partition from rest +PartitionPanel.coin.head=Head +PartitionPanel.coin.tail=Tail +PartitionPanel.DefaultPartitionName=partition +YFrequencyPanel.lHeading=Observation's frequency +YFrequencyPanel.lDescription=Please enter the frequency of each observation into the table. +YFrequencyTableModel.PartitionName=Observation (partition) +YFrequencyTableModel.PartitionElements=Elements +YFrequencyTableModel.Frequency=Frequency +YFrequencyPanel.ErrorMessageDescription=The frequency must be a real number &ge 0. The entered value could be in the format "1,5", "1.5" or "3/2". +YFrequencyPanel.ErrorMessageTitle=Input Error +DiagramPanel.StandartZoom=restore standardzoom +DiagramPanel.iterationToLiklihood=f(Iteration)=Likelihood +DiagramPanel.twoCoinsPlot=Likelihood 3D +DiagramPanel.iterationToD=f(Iteration)=Statistical Analyzer +DiagramPanel.iterationToH=f(Iteration)=X-Corpus +DiagramPanel.iterationToP=f(Iteration)=Probability +DiagramPanel.iterationToP=f(Iteration)=Probability single events +DiagramPanel.d=Statistical Analyzer +DiagramPanel.l=Likelihood +DiagramPanel.p=Probability +DiagramPanel.psingle=Probability Single Event +DiagramPanel.h=X-Corpus +DiagramPanel.d.short=d +DiagramPanel.l.short=L +DiagramPanel.p.short=p +DiagramPanel.psingle.short=p +DiagramPanel.h.short=h +DiagramPanel.twoCoinsPlot.short=L 3D +DiagramPanel.3DAxisX=p1(H) +DiagramPanel.3DAxisY=p2(H) +P0InputPanel.bAddP0=add p0 +P0InputPanel.bRemoveP0=remove p0 +P0InputPanel.bEquipartition=fill uniform distributed +P0InputPanel.bRandomFilling=fill randomly +P0InputPanel.lP0Input=

          Enter StartProbabilityDistribution

          +StartParameters.side=Side +StartParameters.Tail=T +StartParameters.Head=H +P0InputPanel.description=Enter one or more start probability distributions. The sum of the start probabilities for each Object has to be 1. +P0InputPanel.ErrorMessageTitle=Input Error +P0InputPanel.ErrorMessageDescriptionNoP0=No Start Probability Distribution was entered. Enter at least one Start Probability Distribution! +P0InputPanel.ErrorMessageDescriptionNoDouble=The frequency must be a real number > 0 and &le 1. The entered value could be in the format "0,5", "0.5" or "2/3". +P0InputPanel.ErrorMessageDescriptionSumNot1=The Sum of the start probabilities for one object is not 1! +P0InputPanel.ErrorMessageDescriptionNoSelection=No Column has been selected! +P0InputPanel.bAddP0ToolTip=Adds a new column for a new start probability distribution. +P0InputPanel.bRemoveP0ToolTip=Deletes the selected column. +P0InputPanel.bEquipartitionToolTip=Fills the empty cells of the selected column equally, that the sum in the column is 1. +P0InputPanel.bRandomFillingToolTip=Fills the empty cells of the selected column randomly, that the sum in the column is 1. +P0InputPanel.bForwardToolTip=Completes the input of start probability distributions and starts the calculation of EM steps. +P0InputPanel.bBackToolTip=Steps back to the input for observation's frequency." +Options.limitlabel=Please enter a calculation limit in percentage. +Options.ex1=Please enter a valid percentage! +Options.ex2=Error while Parsing. Check input! +Options.c=Cancel +TableViewPanel.Event=Event +ModuleInfo.info=This module is about the EM-Algorithm. +ModuleInfo.license=GPL. Graphics from Onebit. +ModuleInfo.name=EM-Algorithm \ No newline at end of file diff --git a/src/org/jalgo/module/em/gui/CVS/Entries b/src/org/jalgo/module/em/gui/CVS/Entries new file mode 100644 index 0000000..1642b31 --- /dev/null +++ b/src/org/jalgo/module/em/gui/CVS/Entries @@ -0,0 +1,6 @@ +/StartButton.java/1.1/Mon Jan 30 18:56:51 2012// +/StartScreen.java/1.1/Mon Jan 30 18:56:51 2012// +/UIConstants.java/1.1/Mon Jan 30 18:56:51 2012// +D/input//// +D/output//// +/package-info.java/1.1/Mon Jan 30 18:56:51 2012// diff --git a/src/org/jalgo/module/em/gui/CVS/Repository b/src/org/jalgo/module/em/gui/CVS/Repository new file mode 100644 index 0000000..6f13ac1 --- /dev/null +++ b/src/org/jalgo/module/em/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/gui diff --git a/src/org/jalgo/module/em/gui/CVS/Root b/src/org/jalgo/module/em/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/gui/StartButton.java b/src/org/jalgo/module/em/gui/StartButton.java new file mode 100644 index 0000000..bc034b0 --- /dev/null +++ b/src/org/jalgo/module/em/gui/StartButton.java @@ -0,0 +1,68 @@ +package org.jalgo.module.em.gui; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +import org.jalgo.module.em.gui.StartScreen.StartScreenActionHandler; + +/** + * This class represents a button with a description and default/rollover icons, + * which can be displayed on mouse hovering. + * + * @author Tobias Nett + * + */ +public class StartButton extends JToggleButton { + + private static final long serialVersionUID = -1924541401853204950L; + private final String desc; + + /** + * Constructs a StartButton object with the given parameters. + * The description string is shown when the user moves the mouse over the + * icon. + * + * @param defaultIcon the icon, which is displayed, when button is not selected + * @param rolloverIcon the icon, which is displayed on mouse hovering + * @param description the action description string + * @param actionCommand the action command + * @param action an event handler implementing ActionListener + * and MouseListener + */ + public StartButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + String description, String actionCommand, + StartScreenActionHandler action) { + + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + desc = description; + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension( + getIcon().getIconWidth(), + getIcon().getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(action); + } + + /** + * Returns the description of this buttons action as a string. + * + * @return the description string + */ + public String getDescription() { + return desc; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/em/gui/StartScreen.java b/src/org/jalgo/module/em/gui/StartScreen.java new file mode 100644 index 0000000..3423030 --- /dev/null +++ b/src/org/jalgo/module/em/gui/StartScreen.java @@ -0,0 +1,213 @@ +package org.jalgo.module.em.gui; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.control.Controller; +import org.jalgo.module.em.control.IOController; +import org.jalgo.module.em.data.StartParameters; + +/** + * Class StartScreen represents a screen with two buttons, where + * the user can choose which action he/she wants to perform. The buttons have a + * roll-over effect and additionally a description of the selected action is + * displayed. + * + * @author Tobias Nett + */ +public class StartScreen extends JPanel { + + /** + * + */ + private static final long serialVersionUID = -9085830968372916356L; + + private static final Color START_SCREEN_BACKGROUND = new Color(0x00, 0x86, + 0x8b); + + private StartScreenActionHandler actionhandler; + private Controller controller; + private IOController ioController; + + // components + private StartButton loadButton; + private StartButton startButton; + private JLabel descriptionLabel; + private StartParameters startParameters; + + /** + * Creates a StartScreen object with the specified controllers. + * + * @param controller + * the module's main controller + * @param ioController + * the controller for load/save actions + * @param startParameters + * {@code StartParameters} object for the experiment + * + */ + public StartScreen(Controller controller, final IOController ioController, + StartParameters startParameters) { + this.startParameters = startParameters; + this.controller = controller; + this.ioController = ioController; + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + actionhandler = new StartScreenActionHandler(); + + loadButton = new StartButton(new ImageIcon(Messages.getResourceURL( + "em", "StartScreen.load")), new ImageIcon( + Messages.getResourceURL("em", "StartScreen.load.rollover")), + Messages.getString("em", "StartScreen.load.description"), + "load", actionhandler); + + startButton = new StartButton(new ImageIcon(Messages.getResourceURL( + "em", "StartScreen.start")), new ImageIcon( + Messages.getResourceURL("em", "StartScreen.start.rollover")), + Messages.getString("em", "StartScreen.start.description"), + "start", actionhandler); + + descriptionLabel = new JLabel(); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(START_SCREEN_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(startButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(loadButton); + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + } + + /** + * Sets the description label's text to the given string and updates the UI. + * + * @param desc + * the action's textual description + */ + public void setDescription(String desc) { + descriptionLabel.setText(desc); + descriptionLabel.updateUI(); + } + + /** + * Sets the enabled status of the buttons. If the given value is + * false, also the description string is removed from the + * screen. + * + * @param b + * true, if the buttons should be enabled, + * false otherwise + */ + public void setButtonsEnabled(boolean b) { + loadButton.setEnabled(b); + startButton.setEnabled(b); + if (!b) + setDescription(null); + } + + /** + * Draws the background of this panel. + *

          + * This method is a workaround for Linux (GTK), because + * setBackground(..) does not work correctly. + */ + @Override + protected void paintComponent(Graphics g) { + g.setColor(START_SCREEN_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + } + + /** + * The {@code StartScreenActionHandler} listens for mouse and action events + * caused by components of the {@code StartScreen} class. + * + * @author Tobias Nett + * + */ + class StartScreenActionHandler implements ActionListener, MouseListener { + + @Override + public void actionPerformed(ActionEvent e) { + String actionCommand = e.getActionCommand(); + + if (actionCommand.equals("load")) { + startParameters = ioController.read(); + if (startParameters != null) { + controller.setStartParameters(startParameters); + controller.input(); + } + } else if (actionCommand.equals("start")) { //$NON-NLS-1$ + controller.input(); + } + // deselect the button and remove the description + ((StartButton) e.getSource()).setSelected(false); + setDescription(null); + } + + /** + * Causes the event source button to highlight and to display its + * description string on screen. + */ + @Override + public void mouseEntered(MouseEvent e) { + StartButton source = (StartButton) e.getSource(); + if (!source.isEnabled()) + return; + source.setSelected(true); + setDescription(source.getDescription()); + } + + /** + * Causes the event source button to be displayed normally and to remove + * the description string from the screen. + */ + @Override + public void mouseExited(MouseEvent e) { + ((StartButton) e.getSource()).setSelected(false); + setDescription(null); + } + + /** + * This method has no effect. + */ + @Override + public void mouseClicked(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + @Override + public void mousePressed(MouseEvent e) { + // This method has no effect + } + + /** + * This method has no effect. + */ + @Override + public void mouseReleased(MouseEvent e) { + // This method has no effect + } + } +} diff --git a/src/org/jalgo/module/em/gui/UIConstants.java b/src/org/jalgo/module/em/gui/UIConstants.java new file mode 100644 index 0000000..b0c6fb2 --- /dev/null +++ b/src/org/jalgo/module/em/gui/UIConstants.java @@ -0,0 +1,131 @@ +package org.jalgo.module.em.gui; + +import java.awt.Font; + +import javax.swing.ImageIcon; +import javax.swing.UIManager; + +import org.jalgo.main.util.Messages; + +/** + * The class {@code UIConstants} holds UI constants for the em module, such as + * different fonts for presentation mode and normal mode. + * + * @author Tobias Nett + * + */ +public interface UIConstants { + + /** + * Big presentation mode font with pixel size 32 in the systems default + * font. + */ + public static final Font BEAMER_FONT = new Font(UIManager.getDefaults() + .getFont("TextField.font").getFontName(), Font.PLAIN, 32); + /** + * Bold presentation mode font with pixel size 32 in the systems default + * font. + */ + public static final Font BEAMER_FONT_BOLD = new Font(UIManager + .getDefaults().getFont("TextField.font").getFontName(), Font.BOLD, + 32); + + /** + * Smaller presentation mode font with pixel size 16 + */ + public static final Font PRESENTATION_FONT = new Font(UIManager + .getDefaults().getFont("TextField.font").getFontName(), Font.PLAIN, + 16); + /** + * Smaller bold presentation mode font with pixel size 16 + */ + public static final Font PRESENTATION_FONT_BOLD = new Font(UIManager + .getDefaults().getFont("TextField.font").getFontName(), Font.BOLD, + 16); + + /** + * Medium sized presentation mode font for partition table with pixel size 24. + */ + public static final Font PRESENTATION_PARTITION_FONT = new Font(UIManager + .getDefaults().getFont("TextField.font").getFontName(), Font.PLAIN, + 24); + /** + * Medium sized bold presentation mode font for partition table with pixel size 24. + */ + public static final Font PRESENTATION_PARTITION_FONT_BOLD = new Font( + UIManager.getDefaults().getFont("TextField.font").getFontName(), + Font.BOLD, 24); + + /** + * Default system font. + */ + public static final Font DEFAULT_FONT = UIManager.getDefaults().getFont( + "Label.font"); + /** + * Default bold system font. + */ + public static final Font DEFAULT_FONT_BOLD = new Font( + DEFAULT_FONT.getFontName(), Font.BOLD, DEFAULT_FONT.getSize()); + + //////////////////////////////////// + ///////// Icon constants ///////// + //////////////////////////////////// + + /** + * Forward icon for input panels in presentation mode. Right arrow with rounded edges. + */ + public static final ImageIcon FORWARD_ICON = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bForward")); + /** + * Forward icon for input panels in standard mode. Right arrow with rounded edges. + */ + public static final ImageIcon FORWARD_ICON_SMALL = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bForward.small")); + + /** + * Back icon for input panels in presentation mode. Left arrow with rounded edges. + */ + public static final ImageIcon BACK_ICON = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bBack")); + /** + * Back icon for input panels in standard mode. Left arrow with rounded edges. + */ + public static final ImageIcon BACK_ICON_SMALL = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bBack.small")); + + /** + * Minus icon used for remove buttons. Icon for presentation mode. + */ + public static final ImageIcon REMOVE_ICON = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bRemove")); + + /** + * Minus icon used for remove buttons. Icon for standard mode. + */ + public static final ImageIcon REMOVE_ICON_SMALL = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bRemove.small")); + + /** + * Plus icon used for add buttons. Icon for presentation mode. + */ + public static final ImageIcon PLUS_ICON = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bNew")); + + /** + * Plus icon used for add buttons. Icon for normal mode. + */ + public static final ImageIcon PLUS_ICON_SMALL = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bNew.small")); + + /** + * Shield icon used for fill buttons. Icon for presentation mode. + */ + public static final ImageIcon SHIELD_ICON = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bFill")); + + /** + * Shield icon used for fill buttons. Icon for normal mode. + */ + public static final ImageIcon SHIELD_ICON_SMALL = new ImageIcon(Messages.getResourceURL("em", + "ButtonIcon.bFill.small")); +} diff --git a/src/org/jalgo/module/em/gui/input/CVS/Entries b/src/org/jalgo/module/em/gui/input/CVS/Entries new file mode 100644 index 0000000..b01fd98 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/CVS/Entries @@ -0,0 +1,13 @@ +/InputPanel.java/1.1/Mon Jan 30 18:56:51 2012// +/InputStringParser.java/1.1/Mon Jan 30 18:56:51 2012// +/P0InputPanel.java/1.1/Mon Jan 30 18:56:51 2012// +/P0InputTableModel.java/1.1/Mon Jan 30 18:56:51 2012// +/PartitionListModel.java/1.1/Mon Jan 30 18:56:51 2012// +/PartitionPanel.java/1.1/Mon Jan 30 18:56:51 2012// +/PartitionTable.java/1.1/Mon Jan 30 18:56:51 2012// +/PartitionTableModel.java/1.1/Mon Jan 30 18:56:51 2012// +/XInputPanel.java/1.1/Mon Jan 30 18:56:51 2012// +/YFrequencyCellEditor.java/1.1/Mon Jan 30 18:56:51 2012// +/YFrequencyPanel.java/1.1/Mon Jan 30 18:56:51 2012// +/YFrequencyTableModel.java/1.1/Mon Jan 30 18:56:51 2012// +/package-info.java/1.1/Mon Jan 30 18:56:51 2012// diff --git a/src/org/jalgo/module/em/gui/input/CVS/Repository b/src/org/jalgo/module/em/gui/input/CVS/Repository new file mode 100644 index 0000000..ea165b4 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/gui/input diff --git a/src/org/jalgo/module/em/gui/input/CVS/Root b/src/org/jalgo/module/em/gui/input/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/gui/input/InputPanel.java b/src/org/jalgo/module/em/gui/input/InputPanel.java new file mode 100644 index 0000000..fe126da --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/InputPanel.java @@ -0,0 +1,32 @@ +package org.jalgo.module.em.gui.input; + +import javax.swing.JButton; + +/** + * Interface for all input panels in j-Algo's em-module. Offers access to two + * buttons (back/forward). + * + * @author Tobias Nett + * + */ +public interface InputPanel { + + /** + * Returns the button that should lead to the next view. + * No ActionListener is registered to this button. + * + * @return forward button - should lead to the next view. Returns + * null if there is no button. + */ + public JButton getForwardButton(); + + /** + * Returns the button that should lead to the previous view. No + * ActionListener is registered to this button. + * + * @return back button - should lead to the previous view. Returns + * null if there is no button. + */ + public JButton getBackButton(); + +} diff --git a/src/org/jalgo/module/em/gui/input/InputStringParser.java b/src/org/jalgo/module/em/gui/input/InputStringParser.java new file mode 100644 index 0000000..b068b3b --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/InputStringParser.java @@ -0,0 +1,85 @@ +package org.jalgo.module.em.gui.input; + +/** + * Offers a method for converting a string input into a double value. The method + * is static so it can be used without instancing an object of this class. + * + * @author Tobias Nett + * + */ +public class InputStringParser { + + /** + * Converts a {@code String} that represents a FlotingPointNumber in the + * specified range from {@code min} to {@code max} to double. + *

          + * Accepted {@code String} formats are "0,1323", "0.1323", "1/12". + * WhiteSpace is ignored. + * + * @param string + * String that should be parsed + * @param min + * the minimal valid double value + * @param max + * the maximal valid double value + * @return if input is correct, the corresponding double Value; otherwise an + * exception is raised + * + * @throws NumberFormatException + * is raised if the input characters are valid but a parsing + * error occurs + * + * @throws IllegalArgumentException + * is raised if the input string is invalid, for example '1/3/9' + * or '1,5.9' or the entered value is out of the specified + * borders of {@code min} and {@code max}. + * + */ + public static double parseInputString(final String string, double min, + double max) throws NumberFormatException, IllegalArgumentException { + StringBuffer input = new StringBuffer(string); + + int index = 0; + // Remove WhiteSpace + while (index < input.length()) { + if (input.charAt(index) == ' ') { + input.deleteCharAt(index); + } else { + index++; + } + } + index = 0; + // Replaces ',' with '.' + while (index < input.length()) { + if (input.charAt(index) == ',') { + input.setCharAt(index, '.'); + } else { + index++; + } + } + + // Splits in Case of '/' + if (input.toString().split("/").length == 2) { + double numerator = Double + .parseDouble(input.toString().split("/")[0]); + double denominator = Double + .parseDouble(input.toString().split("/")[1]); + if ((numerator / denominator > max) + || (numerator / denominator < min)) { + throw new IllegalArgumentException(); + } + return numerator / denominator; + + } else if (input.toString().split("\\.").length <= 2) { + // "." has to commented because it is used as a regular expression + // from split method + double value = Double.parseDouble(input.toString()); + if (value < min || value > max) { + throw new IllegalArgumentException(); + } + return value; + } else { + throw new IllegalArgumentException(); + } + } +} diff --git a/src/org/jalgo/module/em/gui/input/P0InputPanel.java b/src/org/jalgo/module/em/gui/input/P0InputPanel.java new file mode 100644 index 0000000..8bc32dd --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/P0InputPanel.java @@ -0,0 +1,794 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.swing.DefaultCellEditor; +import javax.swing.GroupLayout; +import javax.swing.GroupLayout.Group; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.JViewport; +import javax.swing.ListSelectionModel; +import javax.swing.border.Border; +import javax.swing.border.LineBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.control.EMModule; +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.UIConstants; + +/** + * Panel that gives the user the ability to enter at least one + * StartProbabilityDistribution. Checks the Input and Stores it to the + * StartParameters + * + * @author Kilian Gebhardt + * + */ +public class P0InputPanel extends JPanel implements InputPanel, UIConstants { + + private static final String BUTTON_BACKWARD = Messages.getString("em", + "InputPanel.bBack"); + private static final String BUTTON_FORWARD = Messages.getString("em", + "InputPanel.bForward"); + private static final String LABEL_P0_INPUT = Messages.getString("em", + "P0InputPanel.description"); + // Strings and Icons for Labels: + private static final ImageIcon RANDOM_ICON = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bRandomFilling")); + private static final ImageIcon RANDOM_ICON_SMALL = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bRandomFilling.small")); + private static final String ERROR_TITLE = Messages.getString("em", + "P0InputPanel.ErrorMessageTitle"); + private static final String ERROR_MESSAGE_SUM_NOT_1 = Messages.getString( + "em", "P0InputPanel.ErrorMessageDescriptionSumNot1"); + private static final String ERROR_MESSAGE_NO_SELECTION = Messages + .getString("em", "P0InputPanel.ErrorMessageDescriptionNoSelection"); + private static final String ERROR_MESSAGE_NO_DOUBLE = Messages.getString( + "em", "P0InputPanel.ErrorMessageDescriptionNoDouble"); + private static final String ERROR_MESSAGE_NO_P0 = Messages.getString("em", + "P0InputPanel.ErrorMessageDescriptionNoP0"); + private static final String HEADING_P0_INPUT = Messages.getString("em", + "P0InputPanel.lP0Input"); + private static final String RANDOM_FILLING_TEXT = Messages.getString("em", + "P0InputPanel.bRandomFilling"); + private static final String EQUIPARTITION_TEXT = Messages.getString("em", + "P0InputPanel.bEquipartition"); + private static final String REMOVE_P0_TEXT = Messages.getString("em", + "P0InputPanel.bRemoveP0"); + private static final String ADD_P0_TEXT = Messages.getString("em", + "P0InputPanel.bAddP0"); + private static final String ADD_P0_TOOLTIP = Messages.getString("em", + "P0InputPanel.bAddP0ToolTip"); + private static final String REMOVE_P0_TOOLTIP = Messages.getString("em", + "P0InputPanel.bRemoveP0ToolTip"); + private static final String BFORWARD_TOOLTIP = Messages.getString("em", + "P0InputPanel.bForwardToolTip"); + private static final String BBACK_TOOLTIP = Messages.getString("em", + "P0InputPanel.bBackToolTip"); + private static final String RANDOM_FILLING_TOOLTIP = Messages.getString( + "em", "P0InputPanel.bRandomFillingToolTip"); + private static final String EQUIPARTITION_TOOLTIP = Messages.getString( + "em", "P0InputPanel.bEquipartitionToolTip"); + + private static final long serialVersionUID = -6221723009063005967L; + private int lastSelectedColumn; + private boolean sumNot1Error; + + // Labels + private JLabel lHeading; + private JLabel description; + + // Objects for the table + private JScrollPane tablePanel; + private JPanel tableCollector; + private List p0Tables; + private GroupLayout tableLayout; + private JViewport columnHeader; + private JTable lastSelectedTable; + + // Buttons + private JButton bAddP0; + private JButton bRemoveP0; + private JButton bForward; + private JButton bForwardDummy; + private JButton bBackward; + private JButton bEquipartition; + private JButton bRandomFilling; + private GroupLayout layout; + + // Startparameters + private StartParameters startParameters; + + /** + * Editor that accepts only DoubleValues and Fractions in the Range of 0 .. + * 1 in following Representations: "0,14242..." "0.4241" " 132/324". + * Whitespace is ignored + * + * Colors the Cell Red, if the input was incorrect. Colors the Cell Black + * otherwise. + * + * @author Kilian Gebhardt + * + */ + private static class MyTableCellEditor extends DefaultCellEditor { + + private static final long serialVersionUID = -4429068854127869668L; + private static final Border red = new LineBorder(Color.red); + private static final Border black = new LineBorder(Color.black); + private JTextField textField; + + // This is the component that will handle the editing of the cell value + public MyTableCellEditor() { + super(new JTextField()); + textField = (JTextField) getComponent(); + textField.setHorizontalAlignment(JTextField.LEFT); + } + + @Override + public Component getTableCellEditorComponent(final JTable table, + final Object value, final boolean isSelected, final int row, + final int column) { + textField.setBorder(black); + return super.getTableCellEditorComponent(table, value, isSelected, + row, column); + } + + @Override + public boolean stopCellEditing() { + if ((P0InputTableModel + .parseInputString(((JTextField) getComponent()).getText()) < 0) + && !(((JTextField) getComponent()).getText().equals(""))) { + ((JTextField) getComponent()).setBorder(red); + return false; + } + return super.stopCellEditing(); + } + } + + /** + * Creates new Instance of P0InputPanel. Sets the functions for all Buttons. + * + * @param startParameters + * {@code StartParameters} object that has to be filled with data + * @param beamerMode + * specifies if beamer mode is enabled or not + */ + public P0InputPanel(final StartParameters startParameters, + final boolean beamerMode) { + this.startParameters = startParameters; + tablePanel = new JScrollPane(); + lastSelectedTable = null; + lastSelectedColumn = -1; + init(); + + // Create Heading and Label + lHeading = new JLabel(HEADING_P0_INPUT); + description = new JLabel(LABEL_P0_INPUT); + + // adding bAddP0 Button + ActionListener + bAddP0 = new JButton(ADD_P0_TEXT); + bAddP0.setToolTipText(ADD_P0_TOOLTIP); +// bAddP0.setMinimumSize(bAddP0.getPreferredSize()); + bAddP0.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + addColumn(); + updateTable(); + setColumnWidth(); + lastSelectedColumn = -1; + lastSelectedTable = null; + } + }); + + // adding bRemoveP0 Button + ActionListener + bRemoveP0 = new JButton(REMOVE_P0_TEXT); + bRemoveP0.setToolTipText(REMOVE_P0_TOOLTIP); +// bRemoveP0.setMinimumSize(bRemoveP0.getPreferredSize()); + bRemoveP0.addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent e) { + if ((lastSelectedColumn != -1) && (lastSelectedTable != null)) { + removeColumn(lastSelectedColumn); + updateTable(); + setColumnWidth(); + } else { + showErrorMessage(ERROR_MESSAGE_NO_SELECTION); + } + lastSelectedColumn = -1; + lastSelectedTable = null; + } + }); + + // adding bEqualpartition Button + Actionlistener + bEquipartition = new JButton(EQUIPARTITION_TEXT); + bEquipartition.setToolTipText(EQUIPARTITION_TOOLTIP); + bEquipartition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent e) { + if ((lastSelectedColumn > 0) && (lastSelectedTable != null)) { + if (lastSelectedTable.isEditing() + && !lastSelectedTable.getCellEditor() + .stopCellEditing()) { + lastSelectedTable.getCellEditor().cancelCellEditing(); + } + + double toFill = 1 - ((P0InputTableModel) lastSelectedTable + .getModel()).getColumnSum(lastSelectedColumn); + if (toFill >= 0) { + int toFillNumber = 0; + for (int i = 0; i < lastSelectedTable.getRowCount(); i++) { + if (P0InputTableModel + .parseInputString((String) lastSelectedTable + .getValueAt(i, lastSelectedColumn)) < 0) { + toFillNumber++; + } + } + for (int i = 0; i < lastSelectedTable.getRowCount(); i++) { + if (P0InputTableModel + .parseInputString((String) lastSelectedTable + .getValueAt(i, lastSelectedColumn)) < 0) { + lastSelectedTable.getModel().setValueAt( + ((Double) (toFill / toFillNumber)) + .toString(), i, + lastSelectedColumn); + } + } + } else { + showErrorMessage(ERROR_MESSAGE_SUM_NOT_1); + } + } else { + showErrorMessage(ERROR_MESSAGE_NO_SELECTION); + } + lastSelectedColumn = -1; + lastSelectedTable = null; + } + }); + + // adding bRandomFilling Button + ActionListener + bRandomFilling = new JButton(RANDOM_FILLING_TEXT); + bRandomFilling.setToolTipText(RANDOM_FILLING_TOOLTIP); + bRandomFilling.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if ((lastSelectedColumn > 0) && (lastSelectedTable != null)) { + if (lastSelectedTable.isEditing() + && !lastSelectedTable.getCellEditor() + .stopCellEditing()) { + lastSelectedTable.getCellEditor().cancelCellEditing(); + } + + double toFill = 1 - ((P0InputTableModel) lastSelectedTable + .getModel()).getColumnSum(lastSelectedColumn); + + if (toFill >= 0) { + double rand[] = new double[lastSelectedTable + .getRowCount()]; + double randSum = 0; + for (int i = 0; i < rand.length; i++) { + if (P0InputTableModel + .parseInputString((String) lastSelectedTable + .getValueAt(i, lastSelectedColumn)) < 0) { + rand[i] = Math.random(); + } else { + rand[i] = 0; + } + } + for (int i = 0; i < rand.length; i++) { + randSum += rand[i]; + } + for (int i = 0; i < rand.length; i++) { + if (P0InputTableModel + .parseInputString((String) lastSelectedTable + .getValueAt(i, lastSelectedColumn)) < 0) { + lastSelectedTable.getModel().setValueAt( + ((Double) (toFill * rand[i] / randSum)) + .toString(), i, + lastSelectedColumn); + } + } + } else { + showErrorMessage(ERROR_MESSAGE_SUM_NOT_1); + } + } else { + showErrorMessage(ERROR_MESSAGE_NO_SELECTION); + } + lastSelectedColumn = -1; + lastSelectedTable = null; + } + + }); + + // creating bForward Button and a listener for Checking the Input + bForward = new JButton(BUTTON_FORWARD); + bForward.setToolTipText(BFORWARD_TOOLTIP); + bForward.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + if (p0Tables.get(0).getColumnCount() < 2) { + showErrorMessage(ERROR_MESSAGE_NO_P0); + bAddP0.doClick(); + } else if (checkInput()) { + bForwardDummy.doClick(); + } else if (sumNot1Error) { + showErrorMessage(ERROR_MESSAGE_SUM_NOT_1); + } else { + showErrorMessage(ERROR_MESSAGE_NO_DOUBLE); + } + } + }); + + // creating other buttons + bBackward = new JButton(BUTTON_BACKWARD); + bBackward.setToolTipText(BBACK_TOOLTIP); + bForwardDummy = new JButton(); + + setBeamerMode(beamerMode); + + // Setting up Group Layout for the Panel + layout = new GroupLayout(this); + this.setLayout(layout); + + layout.setAutoCreateGaps(true); + layout.setAutoCreateContainerGaps(true); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addComponent(lHeading) + .addComponent(description) + .addComponent(tablePanel) + .addGroup( + layout.createSequentialGroup().addComponent(bBackward) + .addContainerGap(400, 600).addComponent(bAddP0) + .addComponent(bRemoveP0) + .addComponent(bEquipartition) + .addComponent(bRandomFilling) + .addContainerGap(400, 600) + .addComponent(bForward))); + layout.setVerticalGroup(layout + .createSequentialGroup() + .addComponent(lHeading) + .addComponent(description) + .addComponent(tablePanel) + .addGroup( + layout.createParallelGroup(GroupLayout.Alignment.CENTER) + .addComponent(bBackward).addComponent(bAddP0) + .addComponent(bRemoveP0) + .addComponent(bEquipartition) + .addComponent(bRandomFilling) + .addComponent(bForward))); + } + + /** + * adds a column to all Tables. + */ + private void addColumn() { + for (JTable table : p0Tables) { + ((P0InputTableModel) table.getModel()).addColumn(); + table.getColumnModel().getColumn(table.getColumnCount() - 1) + .setCellEditor(new MyTableCellEditor()); + } + } + + /** + * Checks whether the sum of the probabilities for each Single Experiment is + * 1. Marks the first Column with a incorrect input. + * + * @return true, if the Input is correct; false otherwise + */ + private final boolean checkInput() { + for (JTable table : p0Tables) { + int column = ((P0InputTableModel) table.getModel()).checkColumns(); + if (column != -1) { + + if ((lastSelectedTable != null) + && lastSelectedTable.isEditing() + && !lastSelectedTable.getCellEditor().stopCellEditing()) { + lastSelectedTable.getCellEditor().cancelCellEditing(); + } + int row = 0; + for (int rowIndex = 0; rowIndex < table.getRowCount(); rowIndex++) { + if (P0InputTableModel.parseInputString((String) table + .getValueAt(rowIndex, column)) < 0) { + row = rowIndex; + break; + } + } + if (P0InputTableModel.parseInputString((String) table + .getValueAt(row, column)) < 0) { + sumNot1Error = false; + } else { + sumNot1Error = true; + } + table.editCellAt(row, column); + try { + ((JTextField) table.getCellEditor() + .getTableCellEditorComponent(table, + table.getCellEditor().getCellEditorValue(), + false, row, column)).requestFocus(); + unselectColumns(null); + lastSelectedColumn = column; + lastSelectedTable = table; + } catch (NullPointerException e) { + + } + return false; + } + } + return true; + } + + @Override + public final JButton getBackButton() { + return bBackward; + } + + /** + * Returns the ForwardButton. + * + * @return the forward button + */ + @Override + public final JButton getForwardButton() { + return bForwardDummy; + } + + /** + * Initializes the Table and updates the Layout of P0InputPanel. + */ + public void init() { + p0Tables = new ArrayList(); + + /* + * Try - Catch - Block is used, to prevent from crashing in case, that + * startParameters don't contain any events or Parameters in + * startParameters are not initialized yet. + * + * This is the case, if P0InputTable is instanced, before the previous + * Input-Steps were completed correctly + */ + try { + for (int objectIndex = 0; objectIndex < startParameters + .getObjectCount(); objectIndex++) { + p0Tables.add(new JTable(new P0InputTableModel(startParameters, + objectIndex))); + } + } catch (Exception e) { + } + + // Adding blank Columns to some of the Tables + int maxPreColumns = 2; + for (JTable table : p0Tables) { + if (maxPreColumns < table.getColumnCount()) { + maxPreColumns = table.getColumnCount(); + } + } + for (JTable table : p0Tables) { + while (table.getColumnCount() < maxPreColumns) { + ((P0InputTableModel) table.getModel()).addColumn(); + ((P0InputTableModel) table.getModel()) + .fireTableStructureChanged(); + } + } + MyTableCellEditor editor = new MyTableCellEditor(); + + for (JTable table : p0Tables) { + for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) { + table.getColumnModel().getColumn(columnIndex) + .setCellEditor(editor); + } + } + + FocusListener focusListener = new FocusListener() { + @Override + public void focusLost(final FocusEvent e) { + if (e.getSource() instanceof JTable) { + JTable table = (JTable) e.getSource(); + if (table.isEditing() + && !table.getCellEditor().stopCellEditing()) { + table.getCellEditor().cancelCellEditing(); + } + lastSelectedTable = table; + lastSelectedColumn = table.getSelectedColumn(); + table.clearSelection(); + } + } + + @Override + public void focusGained(final FocusEvent e) { + if (e.getSource() instanceof JTable) { + JTable table = (JTable) e.getSource(); + unselectColumns(table); + if (table.getColumnModel().getSelectionModel() + .getLeadSelectionIndex() > 0) { + table.setColumnSelectionInterval(table.getColumnModel() + .getSelectionModel().getLeadSelectionIndex(), + table.getColumnModel().getSelectionModel() + .getLeadSelectionIndex()); + } + } + } + }; + + // Adjusting some style settings for all tables + for (JTable table : p0Tables) { + // Header + table.getTableHeader().setResizingAllowed(false); + table.getTableHeader().setSize(200, 400); + table.getTableHeader().setReorderingAllowed(false); + + // Font / Sizes + table.getColumnModel().getColumn(0).setPreferredWidth(200); + table.getColumnModel().getColumn(1).setPreferredWidth(120); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + table.setRowHeight(23); + + // Set Selection + table.setRowSelectionAllowed(false); + table.setColumnSelectionAllowed(false); + table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + table.addFocusListener(focusListener); + } + + setColumnWidth(); + + // Setting up the Container, that hold all tables + tableCollector = new JPanel(); + + tableLayout = new GroupLayout(tableCollector); + tableCollector.setLayout(tableLayout); + + tableLayout.setAutoCreateGaps(true); + + Group horizontalGroup = tableLayout.createParallelGroup( + GroupLayout.Alignment.LEADING, false); + Group verticalGroup = tableLayout.createSequentialGroup(); + + for (JTable p0Table : p0Tables) { + horizontalGroup.addComponent(p0Table); + verticalGroup.addComponent(p0Table); + } + tableLayout.setHorizontalGroup(horizontalGroup); + tableLayout.setVerticalGroup(verticalGroup); + + // Scroll Pane in which tableCollector with all tables can be scrolled + JScrollPane oldtablePanel = tablePanel; + tablePanel = new JScrollPane(tableCollector); + columnHeader = new JViewport(); + if (p0Tables.size() > 0) { + columnHeader.add(p0Tables.get(0).getTableHeader()); + } + tablePanel.setColumnHeader(columnHeader); + + if (layout != null) { + layout.replace(oldtablePanel, tablePanel); + } + } + + /** + * removes a specified Column from all Tables. + * + * @param column + * the Index of the Column + */ + private void removeColumn(final int column) { + for (JTable table : p0Tables) { + ((P0InputTableModel) table.getModel()).removeColumn(column); + } + } + + /** + * Sets the UI mode to beamer or normal mode. Call the method with + * true to enter beamer mode or with false to + * leave it. + *

          + * In beamer mode, all button texts are replaced with icons and the font + * size is increased. + * + * @param modeOn + * true if the beamer mode should be started, + * false if view should be set to standard view + */ + public void setBeamerMode(boolean modeOn) { + if (modeOn) { + bForward.setIcon(FORWARD_ICON); + bForward.setText(null); + + bBackward.setIcon(BACK_ICON); + bBackward.setText(null); + + bAddP0.setIcon(PLUS_ICON); + bAddP0.setText(null); + bAddP0.setToolTipText(ADD_P0_TEXT); + bAddP0.setMinimumSize(bAddP0.getPreferredSize()); + + bRemoveP0.setIcon(REMOVE_ICON); + bRemoveP0.setText(null); + bRemoveP0.setToolTipText(REMOVE_P0_TEXT); + bRemoveP0.setMinimumSize(bRemoveP0.getPreferredSize()); + + bEquipartition.setIcon(SHIELD_ICON); + bEquipartition.setText(null); + bEquipartition.setToolTipText(EQUIPARTITION_TEXT); + + bRandomFilling.setIcon(RANDOM_ICON); + bRandomFilling.setText(null); + bRandomFilling.setToolTipText(RANDOM_FILLING_TEXT); + + lHeading.setFont(PRESENTATION_FONT); + description.setFont(PRESENTATION_FONT); + for (JTable table : p0Tables) { + table.getTableHeader().setFont(PRESENTATION_FONT); + table.setFont(PRESENTATION_FONT); + } + } else { + bForward.setText(BUTTON_FORWARD); + bForward.setIcon(FORWARD_ICON_SMALL); + + bBackward.setText(BUTTON_BACKWARD); + bBackward.setIcon(BACK_ICON_SMALL); + + bRemoveP0.setText(REMOVE_P0_TEXT); + bRemoveP0.setIcon(REMOVE_ICON_SMALL); + bRemoveP0.setMinimumSize(bRemoveP0.getPreferredSize()); + + bAddP0.setText(ADD_P0_TEXT); + bAddP0.setIcon(PLUS_ICON_SMALL); + bAddP0.setMinimumSize(bAddP0.getPreferredSize()); + + bEquipartition.setText(EQUIPARTITION_TEXT); + bEquipartition.setIcon(SHIELD_ICON_SMALL); + + bRandomFilling.setText(RANDOM_FILLING_TEXT); + bRandomFilling.setIcon(RANDOM_ICON_SMALL); + + lHeading.setFont(DEFAULT_FONT); + description.setFont(DEFAULT_FONT); + + for (JTable table : p0Tables) { + table.getTableHeader().setFont(DEFAULT_FONT); + table.setFont(DEFAULT_FONT); + } + } + } + + /** + * Sets all TableColumns to a predefined width. + */ + private void setColumnWidth() { + for (JTable table : p0Tables) { + table.getColumnModel().getColumn(0).setPreferredWidth(200); + for (int i = 1; i < table.getModel().getColumnCount(); i++) { + table.getColumnModel().getColumn(i).setPreferredWidth(120); + } + } + } + + /** + * Displays an ErrorMessage. + * + * @param errorMessage + * The Message that shall be displayed. + */ + private void showErrorMessage(String errorMessage) { + JOptionPane.showMessageDialog(null, errorMessage, ERROR_TITLE, + JOptionPane.ERROR_MESSAGE); + } + + /** + * unselects all tables but one. + * + * @param ignore + * the table that should be ignored + */ + private final void unselectColumns(final JTable ignore) { + for (JTable table : p0Tables) { + if (table != ignore) { + // table.getCellEditor().cancelCellEditing(); + table.clearSelection(); + // table.updateUI(); + } + } + } + + /** + * updates all Tables after Data or StructureChanges. + */ + private void updateTable() { + for (JTable table : p0Tables) { + ((P0InputTableModel) table.getModel()).fireTableDataChanged(); + ((P0InputTableModel) table.getModel()).fireTableStructureChanged(); + for (int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) { + table.getColumnModel().getColumn(columnIndex) + .setCellEditor(new MyTableCellEditor()); + } + } + } + + /** + * Writes the probably incorrect Input to StartParameters. This Function is + * used, when BackButton is pressed every Probability that wasn't inserted, + * will be set to -1.0 + */ + public void writeTempP0ToStartParameters() { + List p0DataList = new ArrayList(); + + // Creating p0 Distributions + for (int p0Distribution = 1; p0Distribution < (p0Tables.get(0) + .getModel().getColumnCount()); p0Distribution++) { + Map singleEventStartProbability = new HashMap(); + for (int objectIndex = 0; objectIndex < startParameters + .getObjectCount(); objectIndex++) { + for (int objectSide = 1; objectSide <= startParameters + .getExperiment().get(objectIndex); objectSide++) { + singleEventStartProbability.put(new Point(objectSide, + objectIndex), + P0InputTableModel + .parseInputString(((String) p0Tables + .get(objectIndex) + .getModel() + .getValueAt(objectSide - 1, + p0Distribution)))); + } + } + EMData p0Data = new EMData(null, null, null, null, + singleEventStartProbability, null); + p0DataList.add(p0Data); + } + startParameters.setP0EMState(new EMState(p0DataList)); + + } + + /** + * Creates the first EMState, by reading the Data from the TableModel and + * set it to P0EMState of StartParameters. + */ + public final void writeP0ToStartParameters() { + List p0DataList = new ArrayList(); + + // Creating p0 Distributions + for (int p0Distribution = 1; p0Distribution < (p0Tables.get(0) + .getModel().getColumnCount()); p0Distribution++) { + Map singleEventStartProbability = new HashMap(); + for (int objectIndex = 0; objectIndex < startParameters + .getObjectCount(); objectIndex++) { + for (int objectSide = 1; objectSide <= startParameters + .getExperiment().get(objectIndex); objectSide++) { + singleEventStartProbability.put(new Point(objectSide, + objectIndex), + P0InputTableModel + .parseInputString(((String) p0Tables + .get(objectIndex) + .getModel() + .getValueAt(objectSide - 1, + p0Distribution)))); + } + } + EMData p0Data = EMModule.calcFirstStep(singleEventStartProbability, + startParameters); + p0DataList.add(p0Data); + } + startParameters.setP0EMState(new EMState(p0DataList)); + } +} diff --git a/src/org/jalgo/module/em/gui/input/P0InputTableModel.java b/src/org/jalgo/module/em/gui/input/P0InputTableModel.java new file mode 100644 index 0000000..e51247a --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/P0InputTableModel.java @@ -0,0 +1,258 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.table.AbstractTableModel; +import org.jalgo.module.em.data.StartParameters; + +/** + * Stores the Content of the Table in a List> and provides some + * InputValidation Functionality. + * + * @author Kilian Gebhardt + */ +public class P0InputTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + private List> data; + + /** + * Initializes the TableModel with the X-Column and one blank p0 Column. + * + * @param startParameters + * StartParamters object that has to be filled with + * data + * @param objectIndex + * the Index of the single Experiment + */ + public P0InputTableModel(final StartParameters startParameters, + final int objectIndex) { + data = new ArrayList>(); + List X = new ArrayList(); + for (int objectSide = 1; objectSide <= startParameters.getExperiment() + .get(objectIndex); objectSide++) { + X.add(startParameters.singleEventToString(new Point(objectSide, objectIndex))); + } + data.add(X); + + // tries to find valid existing P0 input + if ((startParameters.getP0EMState() != null) + && (startParameters.getP0EMState().getEMData() != null) + && (startParameters.getP0EMState().getEMData().get(0) + .getPForSingleEvent().containsKey(new Point(1, + objectIndex))) + && (startParameters.getP0EMState().getEMData().get(0) + .getPForSingleEvent().containsKey(new Point( + startParameters.getExperiment().get(objectIndex), + objectIndex))) + && !(startParameters.getP0EMState().getEMData().get(0) + .getPForSingleEvent().containsKey(new Point( + startParameters.getExperiment().get(objectIndex) + 1, + objectIndex)))) { + for (int p0 = 0; p0 < startParameters.getP0EMState().getEMData() + .size(); p0++) { + List x2 = new ArrayList(); + for (int objectSide = 1; objectSide <= startParameters + .getExperiment().get(objectIndex); objectSide++) { + if (startParameters.getP0EMState().getEMData().get(p0) + .getPForSingleEvent() + .get(new Point(objectSide, objectIndex)) > 0) { + x2.add(startParameters.getP0EMState().getEMData() + .get(p0).getPForSingleEvent() + .get(new Point(objectSide, objectIndex)) + .toString()); + } else { + x2.add(""); + } + } + data.add(x2); + } + } + + if (data.size() < 2) { + addColumn(); + } + } + + @Override + public final int getColumnCount() { + return data.size(); + } + + @Override + public final int getRowCount() { + return data.get(0).size(); + } + + @Override + public final Object getValueAt(final int row, final int column) { + if (column < getColumnCount()) { + if (row < data.get(column).size()) { + return data.get(column).get(row); + } + } + return null; + } + + /** + * Adds a blank Column. + */ + public final void addColumn() { + List p = new ArrayList(); + for (int row = 0; row < data.get(0).size(); row++) { + p.add(""); + } + data.add(p); + } + + /** + * Removes a column. + * + * @param column + * the Index of the column + */ + public final void removeColumn(int column) { + if ((getColumnCount() > column) && (column > 0)) { + data.remove(column); + } + } + + /** + * creates the Name of the Column for the Table Header. + * + * @return the Name "p0" + the Number of the p0 + */ + @Override + public final String getColumnName(final int columnIndex) { + if (columnIndex == 0) { + return "X"; + } else { + return "p0 " + ((Integer) columnIndex).toString() + ""; + } + } + + /** + * + */ + @Override + public final boolean isCellEditable(final int rowIndex, + final int columnIndex) { + if (columnIndex == 0) { + return false; + } + return true; + } + + /** + * Updates Table, if a Double Value was inserted, and the 0 < value < 1.0 + * Otherwise the Cell stays in EditMode + */ + @Override + public final void setValueAt(final Object value, final int rowIndex, + final int columnIndex) { + data.get(columnIndex).set(rowIndex, (String) value); + fireTableCellUpdated(rowIndex, columnIndex); + } + + /** + * Checks all Cells, if Double Values were inserted and checks if the sum of + * each Row is 1.0. + * + * @return the Index of the first column, that misses these requirements or + * '-1' if everything is OK + */ + public final int checkColumns() { + for (int i = 1; i < data.size(); i++) { + List p0 = data.get(i); + double p0sum = 0; + for (String px : p0) { + if (parseInputString(px) < 0) { + return i; + } else { + p0sum += parseInputString(px); + } + } + + if (Math.abs(p0sum - 1.0) > 0.001) { + return i; + } + } + return -1; + } + + /** + * @param columnIndex + * the index of the column whose values are to be added up + * @return the added up values of the specified column + */ + public final double getColumnSum(final int columnIndex) { + double columnSum = 0.0; + for (int rowIndex = 0; rowIndex < getRowCount(); rowIndex++) { + if (parseInputString((String) getValueAt(rowIndex, columnIndex)) != -1) { + columnSum += parseInputString((String) getValueAt(rowIndex, + columnIndex)); + } + } + return columnSum; + } + + /** + * Converts a String that represents a FlotingPointNumber in the Range of + * 0..1 in one of the following ways to double: "0,1323", "0.1323", "1/12". + * WhiteSpace is ignored. + * + * @param string + * String that should be parsed + * @return if input is correct, the corresponding double Value; otherwise + * -1.0 + */ + public static double parseInputString(final String string) { + StringBuffer input = new StringBuffer(string); + try { + int index = 0; + // Remove WhiteSpace + while (index < input.length()) { + if (input.charAt(index) == ' ') { + input.deleteCharAt(index); + } else { + index++; + } + } + index = 0; + // Replaces ',' with '.' + while (index < input.length()) { + if (input.charAt(index) == ',') { + input.setCharAt(index, '.'); + } else { + index++; + } + } + + // Splits in Case of '/' + if (input.toString().split("/").length == 2) { + double numerator = Double.parseDouble(input.toString().split( + "/")[0]); + double denominator = Double.parseDouble(input.toString().split( + "/")[1]); + if ((numerator / denominator > 1) + || (numerator / denominator < 0)) { + return -1.0; + } + return numerator / denominator; + } else { + double value = Double.parseDouble(input.toString()); + if (value <= 0 || value > 1) { + return -1; + } + return value; + } + // If the Standard Double.parseDouble() won't work, + // the Input is invalid. + } catch (Exception e) { + return -1.0; + } + } + +} diff --git a/src/org/jalgo/module/em/gui/input/PartitionListModel.java b/src/org/jalgo/module/em/gui/input/PartitionListModel.java new file mode 100644 index 0000000..556939b --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/PartitionListModel.java @@ -0,0 +1,31 @@ +package org.jalgo.module.em.gui.input; + +import java.util.Set; + +import javax.swing.DefaultListModel; + +import org.jalgo.module.em.data.Partition; + +/** + * A specified ListModel which offers a method for setting the data to + * specific elements. + * + * @author Tobias Nett + * + */ +public class PartitionListModel extends DefaultListModel { + + private static final long serialVersionUID = -5061338496640971667L; + + /** + * Sets the model's data to the specified set of partitions. + * + * @param observations set of partitions of the event set + */ + public void setElements(Set observations){ + this.clear(); + for (Partition partition : observations) { + this.addElement(partition); + } + } +} diff --git a/src/org/jalgo/module/em/gui/input/PartitionPanel.java b/src/org/jalgo/module/em/gui/input/PartitionPanel.java new file mode 100644 index 0000000..3c6a301 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/PartitionPanel.java @@ -0,0 +1,1229 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; + +import javax.swing.ButtonGroup; +import javax.swing.DefaultComboBoxModel; +import javax.swing.GroupLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.LayoutStyle; +import javax.swing.ListModel; +import javax.swing.SwingConstants; +import javax.swing.table.DefaultTableColumnModel; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.UIConstants; + +/** + * Panel which contains all UI elements for partitioning an experiments events. + *

          + * The user can choose out of various predefined partitions or can create an own + * partition (if the experiments consists of not more than 2 objects). + * + * @author Tobias Nett + * + */ +public class PartitionPanel extends JPanel implements InputPanel, + ActionListener, UIConstants { + + private static final long serialVersionUID = 433929721669238472L; + + private static final int LISTWIDTH = 180; + + private static final int SAMESIDE = 1; + private static final int SIDECOUNT = 2; + private static final int SUM = 3; + private static final int PROPERTY = 4; + private static final int CUSTOM = 5; + + private int[] observationType; + + private StartParameters params; + + private JPanel buttonPanel; + private JPanel selectionPanel; + private JPanel tablePanel; + private JPanel listPanel; + + // ButtonPanel + private JButton bForward; + private JButton bBack; + + // SelectionPanel + private JLabel lSelection; + private JRadioButton bSameSide; + private JRadioButton bSideCount; + private JRadioButton bObjectProperty; + private JRadioButton bSum; + private JRadioButton bCustomize; + private JComboBox cSideSelection; + private JComboBox cObjectSelection; + private JComboBox cPropertySelection; + + // ListPanel + private JLabel lList; + private JButton bRemove; + private JList partitionList; + private ListModel listModel; + + // TablePanel + private JLabel lTable; + private JButton bNew; + private JButton bFill; + private PartitionTable table; + + private Set observations; + + private boolean beamerMode = false; + + /** + * Creates a new object of this panel with the given parameters. Initializes + * all UI elements. + * + * @param params + * StartParamters object that has to be filled with + * data + * @param beamerMode + * specifies if beamer mode is enabled or not + */ + public PartitionPanel(final StartParameters params, boolean beamerMode) { + this.params = params; + this.beamerMode = beamerMode; + observationType = params.getObservationType(); + // observations = new HashSet(); + this.init(); + } + + @Override + public final void actionPerformed(final ActionEvent e) { + Object src = e.getSource(); + if (src instanceof JRadioButton) { + disableButtons(); + disableCustomizeButtons(); + bForward.setEnabled(true); + showTable(false); + } + // Same Side + if (src == bSameSide) { + this.setObservation(SAMESIDE, 0, 0, 0); + } + // Side Count + else if (src == bSideCount) { + cSideSelection.setEnabled(true); + this.setObservation(SIDECOUNT, + cSideSelection.getSelectedIndex() + 1, 0, 0); + } else if (src == cSideSelection) { + this.setObservation(SIDECOUNT, + cSideSelection.getSelectedIndex() + 1, 0, 0); + } + // Object Property + else if (src == bObjectProperty) { + cObjectSelection.setEnabled(true); + cPropertySelection.setEnabled(true); + this.setObservation(PROPERTY, 0, + cObjectSelection.getSelectedIndex(), + cPropertySelection.getSelectedIndex() + 1); + } else if (src == cObjectSelection) { + cPropertySelection.setModel(new DefaultComboBoxModel(this + .properties(cObjectSelection.getSelectedIndex()))); + this.setObservation(PROPERTY, 0, + cObjectSelection.getSelectedIndex(), + cPropertySelection.getSelectedIndex() + 1); + } else if (src == cPropertySelection) { + this.setObservation(PROPERTY, 0, + cObjectSelection.getSelectedIndex(), + cPropertySelection.getSelectedIndex() + 1); + } + // Sum + else if (src == bSum) { + this.setObservation(SUM, 0, 0, 0); + } + // own partitioning + else if (src == bCustomize) { + bNew.setEnabled(true); + bFill.setEnabled(true); + // disable forward button, so the user cannot continue until he + // defines valid partitions + bForward.setEnabled(false); + + this.clearObservation(); + + table.setModel(new PartitionTableModel(params.getEvents())); + packColumns(table, 5); + table.revalidate(); + + observationType[0] = CUSTOM; + + showTable(true); + } else if (src == bNew) { + this.createNewPartition(); + } else if (src == bRemove) { + removePartition(); + bForward.setEnabled(false); + } else if (src == bFill) { + fillUpPartitions(); + } + checkIfPartitionsAreValid(); + fireTableDataChanged(); + } + + /** + * Calculates a partitioning in which one partition holds all tuple where + * xi shows side s, where i is specified by 'object' + * and s is specified by 'property'. + * + * @param object + * The object to be viewed. + * @param property + * The side the viewed object should show. + * + * @return Partitioning of the Events, represented by a Set + */ + private Set calcPropterty(final Integer object, + final Integer property) { + + Set events = params.getEvents(); + Map map = new HashMap(); + for (Event event : events) { + boolean hasProperty = event.getTuple().get(object) + .compareTo(property) == 0; + if (!map.containsKey(hasProperty)) { + Partition p = new Partition(); + // build the name depending on the object's properties + StringBuilder name = new StringBuilder( + params.getObjectName(object)); + name.append(" "); + if (hasProperty) { + name.append(Messages.getString("em", + "Partition.Name.Property")); + } else { + name.append(Messages.getString("em", + "Partition.Name.PropertyNot")); + } + name.append(" "); + name.append(property); + + p.setName(name.toString()); + + map.put(hasProperty, p); + } + map.get(hasProperty).addElement(event); + } + + observationType[0] = PROPERTY; + observationType[1] = object; + observationType[2] = property; + + return new HashSet(map.values()); + } + + /** + * Calculates two partitions, where one holds all doublets, the other one + * holds all the rest. + * + * @return Partitioning of Events, represented by a Set + */ + private Set calcSameSide() { + Set events = params.getEvents(); + Map map = new HashMap(); + + Vector tupel; + boolean equal; + Integer comp; + + for (Event event : events) { + equal = true; + tupel = event.getTuple(); + comp = tupel.firstElement(); + + for (Integer i : tupel) { + if (i.compareTo(comp) != 0) { + equal = false; + break; + } + } + if (map.containsKey(equal)) { + map.get(equal).addElement(event); + } else { + Partition p = new Partition(); + if (equal) { + p.setName(Messages + .getString("em", "Partition.Name.Doublet")); + } else { + p.setName(Messages.getString("em", + "Partition.Name.NoDoublet")); + } + p.addElement(event); + map.put(equal, p); + } + } + observationType[0] = SAMESIDE; + + return new HashSet(map.values()); + } + + /** + * Calculates a partitioning where the count of one side is the criterion. + * + * @param side + * The side to be viewed. + * + * @return Partitioning of Events, represented by a Set + */ + private Set calcSideCount(final Integer side) { + Set events = params.getEvents(); + Vector tupel; + Integer count; + Map map = new TreeMap(); + + for (Event event : events) { + count = 0; + tupel = event.getTuple(); + + for (Integer i : tupel) { + if (i.compareTo(side) == 0) { + count++; + } + } + + if (map.containsKey(count)) { + map.get(count).addElement(event); + } else { + Partition p = new Partition(); + p.setName(count + + Messages.getString("em", "Partition.Name.SideCount") + + " " + side); + p.addElement(event); + map.put(count, p); + } + } + observationType[0] = SIDECOUNT; + observationType[1] = side; + + return new HashSet(map.values()); + } + + /** + * Calculates a partitioning based on the sum of the shown sides. + * + * @return Partitioning of Events, represented by a Set + */ + private Set calcSum() { + Set events = params.getEvents(); + Vector tupel; + Integer sum; + Map map = new TreeMap(); + + for (Event event : events) { + sum = 0; + tupel = event.getTuple(); + + for (Integer i : tupel) { + sum += i; + } + + if (map.containsKey(sum)) { + map.get(sum).addElement(event); + } else { + Partition p = new Partition(); + p.setName(Messages.getString("em", "Partition.Name.Sum") + sum); + p.addElement(event); + map.put(sum, p); + } + } + + observationType[0] = SUM; + return new HashSet(map.values()); + } + + /** + * Checks if the current observation set is valid which means all events are + * partitioned and each event is only yielded to one partition. Enables the + * forward button if the observation set is valid. + */ + private void checkIfPartitionsAreValid() { + int sum = 0; + Set all = new HashSet(); + for (Partition p : observations) { + sum += p.getElements().size(); + all.addAll(p.getElements()); + } + if (sum == params.getEvents().size() && all.equals(params.getEvents())) { + bForward.setEnabled(true); + bNew.setEnabled(false); + bFill.setEnabled(false); + } + } + + /** + * Clear the observations (removes all partitions and deletes all yield that + * were set). Sets the + */ + private void clearObservation() { + for (Partition p : observations) { + p.remove(); + } + observations.clear(); + PartitionListModel lm = ((PartitionListModel) partitionList.getModel()); + lm.setElements(observations); + } + + /** + * Creates a new Partition object out of the selected table + * cells. The created partition is added to the observation set. Asks the + * user to enter a name for the partition. The action can be canceled in + * this dialog. If no cell is selected, no partition is created. + * + *

          + * Enables the remove button if a partition is added to the observation set. + */ + private void createNewPartition() { + + if (!(table.getSelecetedEvents().isEmpty())) { + Partition p = new Partition(table.getSelecetedEvents()); + String name = showNameDialog(Messages.getString("em", + "PartitionPanel.DefaultPartitionName") + + "" + + (observations.size() + 1)); + if (name != null) { + p.setName(name); + observations.add(p); + ((PartitionListModel) partitionList.getModel()) + .setElements(observations); + + bRemove.setEnabled(true); + } else { + p.remove(); + } + table.clearSelection(); + } + } + + /** + * Disables buttons for the user (e.g. ComboBox) + */ + private void disableButtons() { + cObjectSelection.setEnabled(false); + cPropertySelection.setEnabled(false); + cSideSelection.setEnabled(false); + + } + + /** + * Disables (grey out) all buttons related to the "own partitioning" option + * (e.g. new/delete partition) + */ + private void disableCustomizeButtons() { + if (params.getObjectCount() > 2) + // bCustomize.setEnabled(false); + bNew.setEnabled(false); + bRemove.setEnabled(false); + bFill.setEnabled(false); + } + + private void showTable(boolean mode) { + GroupLayout layout = new GroupLayout(this); + this.setLayout(layout); + if (!mode) { + bRemove.setVisible(false); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addComponent( + selectionPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent( + listPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addComponent( + buttonPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addContainerGap())); + + layout.setVerticalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addComponent(selectionPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addComponent(listPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addContainerGap())); + } else { + bRemove.setVisible(true); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addComponent( + selectionPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent( + tablePanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent( + listPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE)) + .addComponent( + buttonPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addContainerGap())); + + layout.setVerticalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addComponent(selectionPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addComponent(tablePanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addComponent(listPanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addContainerGap())); + } + } + + /** + * Fills the observation set up with a 'rest' partition, consisting of all + * unpartitioned events. Asks the user to enter a name for the partition. + * The action can be canceled in this dialog. + */ + private void fillUpPartitions() { + Set rest = new TreeSet(table.getUnpartitionedEvents()); + if (!rest.isEmpty()) { + Partition p = new Partition(rest); + + String name = showNameDialog(Messages.getString("em", + "PartitionPanel.DefaultPartitionName") + + "" + + (observations.size() + 1)); + if (name != null) { + p.setName(name); + observations.add(p); + ((PartitionListModel) partitionList.getModel()) + .setElements(observations); + + bRemove.setEnabled(true); + } else { + p.remove(); + } + + table.clearSelection(); + } + } + + /** + * Fires a TableDataChanged Event for the partition table so that its view + * is updated. + */ + private void fireTableDataChanged() { + PartitionTableModel m = (PartitionTableModel) table.getModel(); + m.fireTableDataChanged(); + } + + @Override + public final JButton getBackButton() { + return bBack; + } + + @Override + public final JButton getForwardButton() { + return bForward; + } + + /** + * Initialize all UI elements. + */ + public final void init() { + + this.initButtonPanel(); + this.initSelectionPanel(); + this.initListPanel(); + this.initTablePanel(); + + // initialize buttons and selected combobox + this.disableCustomizeButtons(); + this.disableButtons(); + + this.observations = params.getObservations(); + + showTable(false); + + switch (observationType[0]) { + case SAMESIDE: + bSameSide.setSelected(true); + break; + case SIDECOUNT: + bSideCount.setSelected(true); + cSideSelection.setSelectedItem(observationType[1] - 1); + break; + case SUM: + bSum.setSelected(true); + break; + case PROPERTY: + bObjectProperty.setSelected(true); + cObjectSelection.setSelectedItem(observationType[1]); + cPropertySelection.setSelectedItem(observationType[2] - 1); + break; + case CUSTOM: + bCustomize.setSelected(true); + + table.setModel(new PartitionTableModel(params.getEvents())); + bRemove.setEnabled(true); + bNew.setEnabled(false); + bFill.setEnabled(false); + showTable(true); + break; + default: + observations = new HashSet(); + bSameSide.setSelected(true); + this.calcSameSide(); + // initialize list + this.setObservation(SAMESIDE, 0, 0, 0); + + } + PartitionListModel lm = ((PartitionListModel) partitionList.getModel()); + lm.setElements(observations); + + this.setBeamerMode(beamerMode); + } + + /** + * Initializes the button panel which contains the 'back' and 'next' button. + * The 'back' button is placed on the left side, the next button is place + * opposite on the right side. + */ + private void initButtonPanel() { + buttonPanel = new JPanel(); + + // labels the buttons in the specified language + bForward = new JButton(Messages.getString("em", "InputPanel.bForward")); + bBack = new JButton(Messages.getString("em", "InputPanel.bBack")); + + GroupLayout l = new GroupLayout(buttonPanel); + buttonPanel.setLayout(l); + + l.setHorizontalGroup(l.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + l.createSequentialGroup() + .addContainerGap() + .addComponent(bBack) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED, 245, + Short.MAX_VALUE).addComponent(bForward) + .addContainerGap())); + + l.setVerticalGroup(l.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + l.createSequentialGroup().addGroup( + l.createParallelGroup( + GroupLayout.Alignment.BASELINE) + .addComponent(bBack) + .addComponent(bForward)))); + } + + /** + * Initializes the List Panel which shows the generated Partitions in a + * list. Standard representation for Partitions is as a set of tuples. + * Alternatively, a user given name of the partition is shown. + */ + private void initListPanel() { + listPanel = new JPanel(); + lList = new JLabel(Messages.getString("em", "PartitionPanel.lList")); + bRemove = new JButton( + Messages.getString("em", "PartitionPanel.bRemove")); + partitionList = new JList(); + JScrollPane sp = new JScrollPane(partitionList); + + listModel = new PartitionListModel(); + partitionList.setModel(listModel); + + partitionList.addMouseListener(new MouseAdapter() { + + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + int index = partitionList.locationToIndex(e.getPoint()); + PartitionListModel lm = (PartitionListModel) partitionList + .getModel(); + Partition p = (Partition) lm.get(index); + partitionList.ensureIndexIsVisible(index); + String name = showNameDialog(p.getName()); + if (name != null) { + p.setName(name); + } + } + } + + }); + + GroupLayout layout = new GroupLayout(listPanel); + listPanel.setLayout(layout); + + layout.setAutoCreateGaps(true); + layout.setAutoCreateContainerGaps(true); + + layout.setHorizontalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.TRAILING) + .addComponent(lList, + GroupLayout.Alignment.LEADING) + .addComponent(sp, + GroupLayout.Alignment.LEADING, + GroupLayout.DEFAULT_SIZE, + LISTWIDTH, Short.MAX_VALUE) + .addComponent(bRemove, + GroupLayout.Alignment.LEADING, + GroupLayout.DEFAULT_SIZE, + LISTWIDTH, Short.MAX_VALUE)) + .addContainerGap())); + + layout.setVerticalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addComponent(lList) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(sp, GroupLayout.PREFERRED_SIZE, + 284, Short.MAX_VALUE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(bRemove).addContainerGap())); + bRemove.addActionListener(this); + } + + /** + * Initializes the Selection Panel which offers the user predefined + * partitions. + */ + private void initSelectionPanel() { + selectionPanel = new JPanel(); + + lSelection = new JLabel(Messages.getString("em", + "PartitionPanel.lSelection")); + // initialize RadioButtons + bSameSide = new JRadioButton(Messages.getString("em", + "PartitionPanel.bSameSide")); + bSideCount = new JRadioButton(Messages.getString("em", + "PartitionPanel.bSideCount")); + bObjectProperty = new JRadioButton(Messages.getString("em", + "PartitionPanel.bObjectProperty")); + bSum = new JRadioButton(Messages.getString("em", "PartitionPanel.bSum")); + bCustomize = new JRadioButton(Messages.getString("em", + "PartitionPanel.bCustomize")); + // add RadioButtons to ButtonGroup + ButtonGroup group = new ButtonGroup(); + group.add(bSameSide); + group.add(bSideCount); + group.add(bObjectProperty); + group.add(bSum); + group.add(bCustomize); + // create and fill ComboBoxes + cSideSelection = new JComboBox(this.sides()); + cObjectSelection = new JComboBox(params.getObjectNames()); + cPropertySelection = new JComboBox(this.properties(0)); + + GroupLayout layout = new GroupLayout(selectionPanel); + selectionPanel.setLayout(layout); + // enable automatic gaps + layout.setAutoCreateGaps(true); + layout.setAutoCreateContainerGaps(true); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addComponent(lSelection) + .addComponent(bSameSide) + .addComponent(bSideCount) + .addGroup( + layout.createSequentialGroup() + .addGap(21, 21, + 21) + .addComponent( + cSideSelection, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE)) + .addComponent(bObjectProperty) + .addGroup( + layout.createSequentialGroup() + .addGap(21, 21, + 21) + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addComponent( + cObjectSelection, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addComponent( + cPropertySelection, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE))) + .addComponent(bSum) + .addComponent(bCustomize)))); + + layout.setVerticalGroup(layout + .createSequentialGroup() + .addComponent(lSelection) + .addComponent(bSameSide) + .addComponent(bSideCount) + .addComponent(cSideSelection, GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(bObjectProperty) + .addComponent(cObjectSelection, GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(cPropertySelection, GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(bSum).addComponent(bCustomize)); + + layout.linkSize(SwingConstants.HORIZONTAL, cObjectSelection, + cPropertySelection, cSideSelection); + + bSameSide.addActionListener(this); + bSideCount.addActionListener(this); + cSideSelection.addActionListener(this); + bObjectProperty.addActionListener(this); + cObjectSelection.addActionListener(this); + cPropertySelection.addActionListener(this); + bSum.addActionListener(this); + bCustomize.addActionListener(this); + } + + /** + * Generates the Table Panel which offers the user the ability to make a + * custom partitioning for two objects. Otherwise it won't be active. + */ + private void initTablePanel() { + tablePanel = new JPanel(); + lTable = new JLabel(Messages.getString("em", "PartitionPanel.lTable")); + bNew = new JButton(Messages.getString("em", "PartitionPanel.bNew")); + bFill = new JButton(Messages.getString("em", "PartitionPanel.bFill")); + + PartitionTableModel model = new PartitionTableModel(params.getEvents()); + + table = new PartitionTable(model); + table.setTableHeader(null); + // table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + + this.packColumns(table, 5); + + GroupLayout layout = new GroupLayout(tablePanel); + tablePanel.setLayout(layout); + + layout.setAutoCreateGaps(true); + layout.setAutoCreateContainerGaps(true); + + JScrollPane sp = new JScrollPane(table); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap(34, Short.MAX_VALUE) + .addComponent(bFill) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(bNew).addContainerGap()) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addComponent( + sp, + GroupLayout.PREFERRED_SIZE, + 216, Short.MAX_VALUE) + .addComponent(lTable)) + .addContainerGap())); + layout.setVerticalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addComponent(lTable) + .addPreferredGap( + LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(sp, GroupLayout.DEFAULT_SIZE, + 247, Short.MAX_VALUE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.BASELINE) + .addComponent(bNew) + .addComponent(bFill)) + .addContainerGap())); + + bNew.addActionListener(this); + bFill.addActionListener(this); + } + + /** + * Gives a String Array with the possible sides of a given object, e.g. + * coin: 'head', 'tail'. + * + * @param object + * The index of the viewed object in the experiment. + * + * @return Array with String representations of the object's possible sides. + */ + private String[] properties(final int object) { + Integer sides = params.getExperiment().get(object); + String[] s = new String[sides]; + if (sides == 2) { + s[0] = Messages.getString("em", "PartitionPanel.coin.head"); + s[1] = Messages.getString("em", "PartitionPanel.coin.tail"); + } else { + for (int i = 0; i < sides; i++) { + s[i] = (i + 1) + ""; + } + } + return s; + } + + /** + * Removes the selected (in the list) partitions from the current + * partitioning and clears the yield. If multiple list entries are selected, + * all of them are deleted. + */ + private void removePartition() { + if (partitionList.getSelectedValues() != null) { + for (Object o : partitionList.getSelectedValues()) { + Partition p = (Partition) o; + p.remove(); + observations.remove(p); + } + PartitionListModel lm = ((PartitionListModel) partitionList + .getModel()); + lm.setElements(observations); + ((PartitionTableModel) table.getModel()).fireTableDataChanged(); + + bFill.setEnabled(true); + bNew.setEnabled(true); + } + } + + /** + * Sets the UI mode to beamer or normal mode. Call the method with + * true to enter beamer mode or with false to + * leave it. + *

          + * In beamer mode, all button texts are replaced with icons and the font + * size is increased. + * + * @param modeOn + * true if the beamer mode should be started, + * false if view should be set to standard view + */ + public void setBeamerMode(boolean modeOn) { + beamerMode = modeOn; + if (beamerMode) { + for (Component c : selectionPanel.getComponents()) { + c.setFont(PRESENTATION_FONT); + } + table.setFont(PRESENTATION_PARTITION_FONT); + table.setRowHeight(table.getFont().getSize() + 8); + this.packColumns(table, 5); + lTable.setFont(PRESENTATION_FONT); + partitionList.setFont(PRESENTATION_FONT); + + bRemove.setIcon(REMOVE_ICON); + bRemove.setText(null); + + bNew.setIcon(PLUS_ICON); + bNew.setText(null); + + bFill.setIcon(SHIELD_ICON); + bFill.setText(null); + + bForward.setIcon(FORWARD_ICON); + bForward.setText(null); + bBack.setIcon(BACK_ICON); + bBack.setText(null); + + } else { + for (Component c : selectionPanel.getComponents()) { + c.setFont(DEFAULT_FONT); + } + table.setFont(DEFAULT_FONT); + lTable.setFont(DEFAULT_FONT); + table.setRowHeight(table.getFont().getSize() + 4); + this.packColumns(table, 5); + + partitionList.setFont(DEFAULT_FONT); + + bRemove.setIcon(REMOVE_ICON_SMALL); + bRemove.setText(Messages.getString("em", "PartitionPanel.bRemove")); + + bNew.setIcon(PLUS_ICON_SMALL); + bNew.setText(Messages.getString("em", "PartitionPanel.bNew")); + + bFill.setIcon(SHIELD_ICON_SMALL); + bFill.setText(Messages.getString("em", "PartitionPanel.bFill")); + + bForward.setText(Messages.getString("em", "InputPanel.bForward")); + bForward.setIcon(FORWARD_ICON_SMALL); + + bBack.setText(Messages.getString("em", "InputPanel.bBack")); + bBack.setIcon(BACK_ICON_SMALL); + } + table.revalidate(); + } + + /** + * Sets the intern partitioning to the specified values. The single + * partitions are calculated after this method is called. + * + * @param option + * defines the needed values - SAMESIDE, SIDECOUNT, + * SUM and PROPERTY are valid constants + * @param side + * number of sides. Required by the option SIDECOUNT + * @param object + * index of the viewed object. Required by PROPERTY + * @param property + * 'side' of the viewed object. Required by PROPERTY + */ + private void setObservation(final int option, final Integer side, + final Integer object, final Integer property) { + PartitionListModel lm = ((PartitionListModel) partitionList.getModel()); + observations.clear(); + switch (option) { + case SAMESIDE: + observations = this.calcSameSide(); + break; + case SIDECOUNT: + observations = this.calcSideCount(side); + break; + case SUM: + observations = this.calcSum(); + break; + case PROPERTY: + observations = this.calcPropterty(object, property); + default: + break; + } + lm.setElements(observations); + } + + /** + * @return the name the user entered for this partition - null + * if the user canceled the dialog + */ + private String showNameDialog(String defaultName) { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + String name = (String) JOptionPane.showInputDialog(frame, + "Geben Sie einen Namen für die Partition ein:", + "Partition benennen:", JOptionPane.PLAIN_MESSAGE, null, null, + defaultName); + return name; + } + + /** + * Gives a String representation of the possible sides, which means the + * maximum side count of the experiment's objects. + * + * @return Array with String representations of the possible sides. + */ + private String[] sides() { + Integer max = Collections.max(params.getExperiment()); + String[] s = new String[max]; + if (max == 2 && Collections.min(params.getExperiment()) == 2) { + s[0] = Messages.getString("em", "PartitionPanel.coin.tail"); + s[1] = Messages.getString("em", "PartitionPanel.coin.head"); + } else { + for (int i = 0; i < max; i++) { + s[i] = (i + 1) + ""; + } + if (params.getExperiment().contains(2)) { + s[0] += "/" + + Messages.getString("em", "PartitionPanel.coin.tail"); + s[1] += "/" + + Messages.getString("em", "PartitionPanel.coin.head"); + } + } + return s; + } + + /** + * Writes the current calculated partitioning to the StartParameters. Has to + * be called when the PartitionPanel is left. + */ + public final void writeObservation() { + params.setObservations(observations); + params.setObservationType(observationType); + } + + /** + * Packs all columns of the specified table with additional width of the + * specified margin amount. + * + * @param table + * the {@code JTable} whose columns are to be packed + * @param margin + * the margin amount + */ + public void packColumns(JTable table, int margin) { + for (int c = 0; c < table.getColumnCount(); c++) { + packColumn(table, c, margin); + } + } + + /** + * Sets the preferred width of the visible column specified by + * {@code vColIndex}. The column will be just wide enough to show the column + * head and the widest cell in the column. Margin pixels are added to the + * left and right (resulting in an additional width of 2*margin pixels). + * + * @param table + * the {@code JTable} in which the column is located + * @param vColIndex + * the index the column that is to be packed + * @param margin + * the margin amount for packing + */ + public void packColumn(JTable table, int vColIndex, int margin) { + DefaultTableColumnModel colModel = (DefaultTableColumnModel) table + .getColumnModel(); + TableColumn col = colModel.getColumn(vColIndex); + + int width = 0; + + // Get width of column header + TableCellRenderer renderer = col.getHeaderRenderer(); + /* + * if (renderer == null) { renderer = + * table.getTableHeader().getDefaultRenderer(); } Component comp = + * renderer.getTableCellRendererComponent(table, col.getHeaderValue(), + * false, false, 0, 0); width = comp.getPreferredSize().width; + */ + + // Get maximum width of column data + for (int r = 0; r < table.getRowCount(); r++) { + renderer = table.getCellRenderer(r, vColIndex); + Component comp = renderer.getTableCellRendererComponent(table, + table.getValueAt(r, vColIndex), false, false, r, vColIndex); + width = Math.max(width, comp.getPreferredSize().width); + } + + // Add margin + width += 2 * margin; + + // Set the width + col.setPreferredWidth(width); + col.setMinWidth(width); + } +} diff --git a/src/org/jalgo/module/em/gui/input/PartitionTable.java b/src/org/jalgo/module/em/gui/input/PartitionTable.java new file mode 100644 index 0000000..717d6d6 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/PartitionTable.java @@ -0,0 +1,272 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Point; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.HashSet; +import java.util.Set; +import java.util.TreeSet; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.DefaultTableModel; + +import org.jalgo.module.em.data.Event; + +/** + * Table for customizing a partition. Offers a specified behavior for clicking + * dragging. Disables events which are already yielded to a partition. + * + * @author Tobias Nett + * + */ +public class PartitionTable extends JTable { + + private static final long serialVersionUID = 1559624150462345709L; + + private Set selected; + private boolean dragging; + + /** + * Creates a new empty Table with no data. + */ + public PartitionTable() { + initTable(); + } + + /** + * Creates a new table with the specified data. + *

          + * Generates a PartitionTableModel out of the given data. + * + * @param rowData + * the row data, namely different events + * @param columnNames + * the column names for this table + */ + public PartitionTable(Object[][] rowData, Object[] columnNames) { + // TODO create PartitionTableModel from data + initTable(); + } + + /** + * Creates a new table with the specified table model. + *

          + * The model must be a PartitionTableModel which consists of + * the experiment's events. + * + * @param model + * TableModel containing the experiments events + */ + public PartitionTable(PartitionTableModel model) { + super(model); + initTable(); + } + + /** + * Returns a set of the selected events that are presented in the table + * cells. If no cells are selected, the returned set is empty. + * + * @return set of selected events - empty set if no cell is selected + */ + public Set getSelecetedEvents() { + TreeSet s = new TreeSet(); + for (Point p : selected) { + s.add((Event) this.getModel().getValueAt(p.x, p.y)); + } + return s; + } + + @Override + public boolean getScrollableTracksViewportWidth() { + final Container viewport = getParent(); + return viewport.getWidth() > getMinimumSize().getWidth(); + } + + @Override + public boolean getScrollableTracksViewportHeight() { + final Container viewport = getParent(); + return viewport.getHeight() > getMinimumSize().getHeight(); + } + + @Override + public void clearSelection() { + if (selected != null) + selected.clear(); + } + + /** + * Returns true if the specified Event is not yielded to a + * partition. If the specified Event is already part of a + * partition, false is returned. + * + * @param row + * the row whose cell is queried + * @param column + * the column whose cell is queried + * @return true if the cell's event is not yielded to a partition, false + * else + */ + @Override + public boolean isCellSelected(final int row, final int column) { + Point p = new Point(row, column); + if (((Event) this.getModel().getValueAt(row, column)).getYield() != null) + return false; + if (selected.contains(p)) + return true; + if (dragging) { + return super.isCellSelected(row, column); + } + return false; + } + + /** + * Returns false for every cell. The user cannot edit the cells' values. + * + * @param row + * the row whose cell is queried + * @param column + * the column whose cell is queried + * @return false - no cell is editable + */ + @Override + public boolean isCellEditable(int row, int column) { + // return !(parted.contains(new Point(row, column))); + return false; + } + + /** + * Initializes the table with a new CellRenderer. + */ + private void initTable() { + selected = new HashSet(); + + this.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { + + private static final long serialVersionUID = 1L; + + @Override + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, + int row, int column) { + + if (table.getModel().getValueAt(row, column) instanceof Event) { + Event e = (Event) table.getModel().getValueAt(row, column); + if (e.getYield() != null) { + isSelected = false; + hasFocus = false; + } + } + Component c = super.getTableCellRendererComponent(table, value, + isSelected, hasFocus, row, column); + + if (c instanceof JLabel) { + ((JLabel) c).setHorizontalAlignment(SwingConstants.CENTER); + } + + if (((Event) table.getModel().getValueAt(row, column)) + .getYield() == null) { + c.setBackground(Color.WHITE); + c.setForeground(Color.BLACK); + if (isSelected) + c.setBackground(new Color(0x40, 0xFF, 0x40)); + } else { + c.setBackground(Color.LIGHT_GRAY); + c.setForeground(Color.GRAY); + } + return c; + } + }); + + MouseAdapter mouseHandler = new TableMouseAdapter(); + this.addMouseListener(mouseHandler); + this.addMouseMotionListener(mouseHandler); + this.setRowSelectionAllowed(false); + this.setRowSelectionAllowed(false); + this.setCellSelectionEnabled(true); + } + + private class TableMouseAdapter extends MouseAdapter { + + @Override + public void mousePressed(final MouseEvent me) { + if (SwingUtilities.isLeftMouseButton(me)) { + Point p = me.getPoint(); + int row = rowAtPoint(p); + int col = columnAtPoint(p); + Point cell = new Point(row, col); + if (getValueAt(row, col) instanceof Event) { + if (((Event) getValueAt(row, col)).getYield() == null) { + if (selected.contains(cell)) { + selected.remove(cell); + } else { + selected.add(cell); + } + ((DefaultTableModel)getModel()).fireTableCellUpdated(row, col); + } + } + } else if (SwingUtilities.isRightMouseButton(me)) { + selected.clear(); + ((PartitionTableModel) getModel()).fireTableDataChanged(); + } + } + + @Override + public void mouseDragged(final MouseEvent me) { + if (!me.isControlDown()) { + //selected.clear(); + dragging = true; + me.consume(); + } + } + + @Override + public void mouseReleased(final MouseEvent me) { + if (dragging) { + completeSelections(); + dragging = false; + } + } + + private void completeSelections() { + int[] rows = getSelectedRows(); + int[] cols = getSelectedColumns(); + Set tmp = new HashSet(); + for (int row : rows) { + for (int col : cols) { + if (((Event) getValueAt(row, col)).getYield() == null) { + tmp.add(new Point(row, col)); + } + } + } + selected.addAll(tmp); + } + } + + /** + * Searches for all events that are currently not partitioned (the event's + * yield is null). Returns an empty set if all events are + * partitioned. + * + * @return set of all unpartitioned events, empty set if no elements were + * found + */ + public Set getUnpartitionedEvents() { + Set unpartitioned = new TreeSet(); + for (int r = 0; r < this.getRowCount(); r++) { + for (int c = 0; c < this.getColumnCount(); c++) { + Event e = (Event) this.getValueAt(r, c); + if (e.getYield() == null) { + unpartitioned.add(e); + } + } + } + return unpartitioned; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/em/gui/input/PartitionTableModel.java b/src/org/jalgo/module/em/gui/input/PartitionTableModel.java new file mode 100644 index 0000000..9357088 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/PartitionTableModel.java @@ -0,0 +1,110 @@ +package org.jalgo.module.em.gui.input; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.TreeMap; + +import javax.swing.table.DefaultTableModel; + +import org.jalgo.module.em.data.Event; + +/** + * A TableModel that works on the experiments event set. + * Sets the properties for cell being 'unselectable'. + * + * @author Tobias Nett + * + */ +public class PartitionTableModel extends DefaultTableModel { + + private static final long serialVersionUID = 1L; + private List> colData; + + /** + * @param events set of events which should be displayed in the table. + */ + public PartitionTableModel(Set events) { +// TreeMap> map = new TreeMap>(); +// for (Event event : events) { +// int i = event.getTuple().firstElement() - 1; +// if (!(map.containsKey(i))) { +// map.put(i, new ArrayList()); +// } +// map.get(i).add(event); +// } +// for (List l : map.values()) { +// Collections.sort(l); +// } +// rowData = new ArrayList>(map.values()); + + TreeMap> cols = new TreeMap>(); + for (Event event : events){ + int columnIndex = event.getTuple().firstElement() - 1; + if (!(cols.containsKey(columnIndex))) { + cols.put(columnIndex, new ArrayList()); + } + cols.get(columnIndex).add(event); + } + for (List l : cols.values()) { + Collections.sort(l); + } + colData = new ArrayList>(cols.values()); + } + + /** + * @return number of elements in a row, 0 if there are no events + */ + @Override + public int getColumnCount() { +// List firstRow = rowData.get(0); +// if (firstRow != null) +// return firstRow.size(); +// return 0; + if (colData != null) + return colData.size(); + return 0; + } + + /** + * @return number of elements in one column + */ + @Override + public int getRowCount() { +// if (rowData != null) +// return rowData.size(); +// return 0; + List firstColumn; + try { + firstColumn = colData.get(0); + if (firstColumn != null) + return firstColumn.size(); + } catch (Exception e) { + + } + return 0; + } + + @Override + public Object getValueAt(int row, int column) { +// if (row < this.getRowCount() && column < this.getColumnCount() ) +// try { +// return rowData.get(row).get(column); +// } catch (ArrayIndexOutOfBoundsException e) { +// } +// return null; + if (row < this.getRowCount() && column < this.getColumnCount() ) + try { + return colData.get(column).get(row); + } catch (ArrayIndexOutOfBoundsException e) { + } + return null; + } + + @Override + public boolean isCellEditable(int row, int column) { + return false; + } + +} diff --git a/src/org/jalgo/module/em/gui/input/XInputPanel.java b/src/org/jalgo/module/em/gui/input/XInputPanel.java new file mode 100644 index 0000000..8b73516 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/XInputPanel.java @@ -0,0 +1,608 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.Vector; + +import javax.swing.GroupLayout; +import javax.swing.ImageIcon; +import javax.swing.InputVerifier; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.LayoutStyle; +import javax.swing.SwingConstants; +import javax.swing.text.JTextComponent; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.UIConstants; + +/** + * A JPanel which contains all UI elements for creating a new experiment by + * adding n-sided objects to the experiment. + *

          + * If there is an icon available, the user will get a graphical representation + * of the object, if not a textual representation of an 'n-sided dice' is shown. + * + * @author Tobias Nett + * + */ +public class XInputPanel extends JPanel implements InputPanel, ActionListener, + UIConstants { + + private static final ImageIcon ADD_ICON = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAdd")); + + private static final ImageIcon ADD_DICE_ICON = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAddDice")); + + private static final ImageIcon ADD_COIN_ICON = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAddCoin")); + + private static final ImageIcon ADD_ICON_SMALL = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAdd.small")); + + private static final ImageIcon ADD_DICE_ICON_SMALL = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAddDice.small")); + + private static final ImageIcon ADD_COIN_ICON_SMALL = new ImageIcon( + Messages.getResourceURL("em", "ButtonIcon.bAddCoin.small")); + + /** + * The {@code SideVerifier} accepts only integer value greater 0. + * + * @author Tobias Nett + * + */ + static class SideVerifier extends InputVerifier { + + @Override + public boolean shouldYieldFocus(JComponent input) { + if (!verify(input)) { + input.requestFocus(); + if (input instanceof JTextComponent) { + ((JTextComponent) input).selectAll(); + } + return false; + } else { + return true; + } + } + + @Override + public boolean verify(JComponent input) { + boolean wasValid = true; + int sides = 0; + try { + sides = Integer.parseInt(((JTextField) input).getText()); + } catch (NumberFormatException e) { + wasValid = false; + } + if (sides < 1) { + wasValid = false; + } + return wasValid; + } + + } + + private static final long serialVersionUID = -6075272644553822013L; + + // error codes for input error types + private static final int FORMAT_ERROR = 0; + private static final int NEGATIVE_AMOUNT = 1; + + private boolean beamerMode = false; + + // Control Panel + private JPanel controlPanel; + private JButton bAdd; + private JButton bAddDice; + private JButton bAddCoin; + + // private JButton bRemove; + private JButton bRemoveLast; + // Picture Panel + private List objects; + private JPanel picturePanel; + private JPanel imagePane; + + private JLabel lHeading; + private JLabel description; + + // experiment vector + private Vector experiment; + // ButtonPanel + private JPanel buttonPanel; + + private JButton bForward; + + private JTextField tSides; + + private StartParameters params; + + /** + * Creates a new XInputPanel object. + * + * @param params + * StartParamter object in which the XInput has to be saved + * @param beamerMode + * specifies if beamer mode is enabled or not + */ + public XInputPanel(StartParameters params, boolean beamerMode) { + this.params = params; + objects = new ArrayList(); + experiment = new Vector(); + this.beamerMode = beamerMode; + this.init(); + // restore old experiment from StartParameters + if (params.getExperiment() != null) { + this.objectsFromExperiment(params.getExperiment()); + } + } + + /** + * Initializes the images for the objects represented by this experiment + * vector. + * + * @param experiment + * the vector whose values should be shown in the panel + */ + private void objectsFromExperiment(Vector experiment) { + for (Integer sides : experiment) { + this.addX(sides); + } + + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == bAddCoin) { + this.addX(2); + } + if (e.getSource() == bAddDice) { + this.addX(6); + } + if (e.getSource() == bAdd || e.getSource() == tSides) { + this.addObject(); + } + if (e.getSource() == bRemoveLast) { + if (objects.size() > 0) { + imagePane.remove(objects.size() - 1); + objects.remove(objects.size() - 1); + experiment.remove(experiment.size() - 1); + } + if (experiment.size() < 1) + bForward.setEnabled(false); + imagePane.updateUI(); + } + } + + private void addObject() { + int errorCode = FORMAT_ERROR; + try { + Integer sides = Integer.parseInt(tSides.getText()); + if (sides < 1) + errorCode = NEGATIVE_AMOUNT; + this.addX(sides); + } catch (IllegalArgumentException ex) { + if (errorCode == NEGATIVE_AMOUNT) { + JOptionPane.showMessageDialog(null, Messages.getString("em", + "XInputPanel.ErrorMessageDescriptionNegative"), + Messages.getString("em", + "XInputPanel.ErrorMessageTitle"), + JOptionPane.ERROR_MESSAGE); + } else if (errorCode == FORMAT_ERROR) { + JOptionPane.showMessageDialog(null, Messages.getString("em", + "XInputPanel.ErrorMessageDescription"), Messages + .getString("em", "XInputPanel.ErrorMessageTitle"), + JOptionPane.ERROR_MESSAGE); + } + tSides.requestFocus(); + tSides.selectAll(); + } + } + + /** + * Adds a new n-sided object to the experiment, where n is given by + * sides. The object must have at least 1 side. + * + * @param sides + * count of object's sides + * @throws IllegalArgumentException + * is raised if {@code sides} is less 1 + */ + public void addX(int sides) throws IllegalArgumentException { + if (sides < 1) + throw new IllegalArgumentException(); + JLabel picLabel = null; + try { + picLabel = new JLabel(new ImageIcon(Messages.getResourceURL("em", + "Object." + sides))); + } catch (NullPointerException e1) { + picLabel = new JLabel("W" + sides); + picLabel.setFont(new Font(picLabel.getFont().getFontName(), + Font.BOLD, 75)); + } + objects.add(picLabel); + imagePane.add(picLabel); + imagePane.updateUI(); + // add object to experiment vector + experiment.add(sides); + // enable forward button + bForward.setEnabled(true); + } + + /** + * Calculates the cartesian product AxB of a set A and a tupel + * B. + * + * @param a + * set of vectors, set A + * @param b + * tupel of Integer, tupel B + * @return the cartesian product of a and b as Set> + */ + private Set> cartesianProduct(Set> a, + Vector b) { + Set> product = new HashSet>(); + for (Vector v1 : a) { + for (Integer i : b) { + Vector v = new Vector(v1); + v.add(i); + product.add(v); + } + } + return product; + } + + /** + * Because there is no back button in the first input panel, this methods + * returns null on every call. Be aware of + * NullPointerException. + * + * @return null there is no need to go back from here. + */ + @Override + public JButton getBackButton() { + return null; + } + + @Override + public JButton getForwardButton() { + return bForward; + } + + /** + * Initializes this view and its components. Therefore the picture panel + * with the heading is placed on the top, the control elements will be in + * the middle and the 'next' button is located at the bottom. + */ + public void init() { + + this.initButtonPanel(); + this.initControlPanel(); + this.initPicturePanel(); + + // Layout + GroupLayout layout = new GroupLayout(this); + this.setLayout(layout); + + layout.setHorizontalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.TRAILING) + .addComponent(picturePanel, + GroupLayout.Alignment.LEADING, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addComponent(controlPanel, + GroupLayout.Alignment.LEADING, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addComponent(buttonPanel, + GroupLayout.Alignment.LEADING, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE)) + .addContainerGap())); + + layout.setVerticalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addComponent(picturePanel, + GroupLayout.DEFAULT_SIZE, + GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(controlPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonPanel, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addContainerGap())); + + bForward.setEnabled(false); + this.setBeamerMode(beamerMode); + } + + /** + * Initializes the button panel which contains the 'next' button. The 'next' + * button is placed on the right side. + */ + private void initButtonPanel() { + buttonPanel = new JPanel(); + + // labels the button in the specified language + String bForwardText = Messages.getString("em", "InputPanel.bForward"); + bForward = new JButton(bForwardText); + bForward.setToolTipText(bForwardText); + + GroupLayout l = new GroupLayout(buttonPanel); + buttonPanel.setLayout(l); + + l.setHorizontalGroup(l.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + l.createSequentialGroup().addContainerGap(499, Short.MAX_VALUE) + .addComponent(bForward).addContainerGap())); + + l.setVerticalGroup(l.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + l.createParallelGroup(GroupLayout.Alignment.BASELINE) + .addComponent(bForward))); + } + + /** + * Initializes the control panel which contains all control elements for + * adding or removing new objects to the experiment. + */ + private void initControlPanel() { + controlPanel = new JPanel(); + tSides = new JTextField(); + tSides.setInputVerifier(new SideVerifier()); + + bAddCoin = new JButton(Messages.getString("em", "XInputPanel.bAddCoin")); + bAddCoin.setToolTipText(Messages + .getString("em", "XInputPanel.bAddCoin")); + bAddDice = new JButton(Messages.getString("em", "XInputPanel.bAddDice")); + bAddDice.setToolTipText(Messages + .getString("em", "XInputPanel.bAddDice")); + bAdd = new JButton(Messages.getString("em", "XInputPanel.bAdd")); + bAdd.setToolTipText(Messages.getString("em", "XInputPanel.bAdd")); + bRemoveLast = new JButton(Messages.getString("em", + "XInputPanel.bRemoveLast")); + bRemoveLast.setToolTipText(Messages.getString("em", + "XInputPanel.bRemoveLast")); + + GroupLayout layout = new GroupLayout(controlPanel); + controlPanel.setLayout(layout); + + layout.setHorizontalGroup(layout + .createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addComponent(bAddCoin) + .addPreferredGap( + LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(bAddDice) + .addPreferredGap( + LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(bAdd) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED) + .addComponent(tSides, + 30, 120, + GroupLayout.PREFERRED_SIZE) + .addPreferredGap( + LayoutStyle.ComponentPlacement.UNRELATED, + 93, Short.MAX_VALUE) + .addComponent(bRemoveLast).addContainerGap())); + + layout.setVerticalGroup(layout.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap(GroupLayout.DEFAULT_SIZE, + Short.MAX_VALUE) + .addGroup( + layout.createParallelGroup( + GroupLayout.Alignment.BASELINE) + .addComponent(bAddCoin) + .addComponent(bAddDice) + .addComponent(bAdd) + .addComponent(tSides, + GroupLayout.PREFERRED_SIZE, + GroupLayout.DEFAULT_SIZE, + GroupLayout.PREFERRED_SIZE) + .addComponent(bRemoveLast)) + .addContainerGap())); + + layout.linkSize(SwingConstants.VERTICAL, bAdd, tSides); + + bAddCoin.addActionListener(this); + bAddDice.addActionListener(this); + bAdd.addActionListener(this); + bRemoveLast.addActionListener(this); + tSides.addActionListener(this); + } + + /** + * Initializes the picture panel, which contains a label with the heading of + * this section and a scroll pane which will hold the figurative + * representation of the objects. + */ + private void initPicturePanel() { + picturePanel = new JPanel(); + lHeading = new JLabel(Messages.getString("em", "XInputPanel.lXInput")); + description = new JLabel(Messages.getString("em", + "XInputPanel.description")); + imagePane = new JPanel(); + JScrollPane sp = new JScrollPane(imagePane); + + GroupLayout layout = new GroupLayout(picturePanel); + picturePanel.setLayout(layout); + layout.setHorizontalGroup(layout + .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup( + javax.swing.GroupLayout.Alignment.TRAILING, + layout.createSequentialGroup() + .addContainerGap() + .addGroup( + layout.createParallelGroup( + javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent( + sp, + javax.swing.GroupLayout.Alignment.LEADING, + javax.swing.GroupLayout.DEFAULT_SIZE, + 605, Short.MAX_VALUE) + .addComponent( + lHeading, + javax.swing.GroupLayout.Alignment.LEADING) + .addComponent( + description, + javax.swing.GroupLayout.Alignment.LEADING, + javax.swing.GroupLayout.DEFAULT_SIZE, + 605, Short.MAX_VALUE)) + .addContainerGap())); + layout.setVerticalGroup(layout + .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup( + layout.createSequentialGroup() + .addContainerGap() + .addComponent(lHeading) + .addPreferredGap( + javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(description) + .addPreferredGap( + javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(sp, + javax.swing.GroupLayout.PREFERRED_SIZE, + 160, + javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap())); + } + + /** + * Sets the UI mode to beamer or normal mode. Call the method with + * true to enter beamer mode or with false to + * leave it. + *

          + * In beamer mode, all button texts are replaced with icons and the font + * size is increased. + * + * @param modeOn + * true if the beamer mode should be started, + * false if view should be set to standard view + */ + public void setBeamerMode(boolean modeOn) { + beamerMode = modeOn; + if (beamerMode) { + bAddCoin.setIcon(ADD_COIN_ICON); + bAddCoin.setText(null); + bAddDice.setIcon(ADD_DICE_ICON); + bAddDice.setText(null); + bAdd.setIcon(ADD_ICON); + bAdd.setText(null); + bRemoveLast.setIcon(REMOVE_ICON); + bRemoveLast.setText(null); + tSides.setFont(BEAMER_FONT); + + bForward.setIcon(FORWARD_ICON); + bForward.setText(null); + + description.setFont(PRESENTATION_FONT); + } else { + bAddCoin.setIcon(ADD_COIN_ICON_SMALL); + bAddCoin.setText(Messages.getString("em", "XInputPanel.bAddCoin")); + bAddDice.setIcon(ADD_DICE_ICON_SMALL); + bAddDice.setText(Messages.getString("em", "XInputPanel.bAddDice")); + bAdd.setIcon(ADD_ICON_SMALL); + bAdd.setText(Messages.getString("em", "XInputPanel.bAdd")); + bRemoveLast.setIcon(REMOVE_ICON_SMALL); + bRemoveLast.setText(Messages.getString("em", + "XInputPanel.bRemoveLast")); + tSides.setFont(DEFAULT_FONT); + + bForward.setText(Messages.getString("em", "InputPanel.bForward")); + bForward.setIcon(FORWARD_ICON_SMALL); + + description.setFont(DEFAULT_FONT); + } + } + + /** + * Calculates all Events based on the specified objects and writes the into + * the StartParameter object. + */ + public void writeExperiment() { + // if the events to this experiment vector are already calculated and + // saved in StartParameters, this method has nothing to do + if (experiment.equals(params.getExperiment())) { + if (params.getEvents() != null) + return; + } + + params.setExperiment(experiment); + + Set events = new TreeSet(); + Set> tupel = new HashSet>(); + List> start = new ArrayList>(); + + for (Integer sides : experiment) { + Vector v = new Vector(); + for (int i = 1; i <= sides; i++) { + v.add(i); + } + start.add(v); + } + for (Integer i : start.get(0)) { + Vector v = new Vector(); + v.add(i); + tupel.add(v); + } + // calculate single event vectors if there is more than one object + if (experiment.size() > 1) { + for (int i = 1; i < experiment.size(); i++) { + tupel = this.cartesianProduct(tupel, start.get(i)); + } + } + for (Vector t : tupel) { + events.add(new Event(t, experiment)); + } + params.setEvents(events); + + // if the event set has to be recalculated, the observation must be + // cleared. + params.setObservations(null); + int[] observationType = { 0, -1, -1}; + params.setObservationType(observationType); + } +} diff --git a/src/org/jalgo/module/em/gui/input/YFrequencyCellEditor.java b/src/org/jalgo/module/em/gui/input/YFrequencyCellEditor.java new file mode 100644 index 0000000..7d1ba43 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/YFrequencyCellEditor.java @@ -0,0 +1,90 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Color; + +import javax.swing.BorderFactory; +import javax.swing.DefaultCellEditor; +import javax.swing.InputVerifier; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTextField; +import javax.swing.text.JTextComponent; + +import org.jalgo.main.util.Messages; + +/** + * The {@code YFrequencyCellEditor} is a specialized CellEditor for the + * frequency input table. It verifies cell inputs via + * {@link org.jalgo.module.em.gui.input.InputStringParser#parseInputString(String, double, double)} + * method. + * + * @author Tobias Nett + * + */ +public class YFrequencyCellEditor extends DefaultCellEditor { + + private static final long serialVersionUID = 1L; + private JTextField tf; + private FrequencyVerifier v; + + /** + * Creates a CellEditor, which checks the input using an + * InputVerifier. If the entered value is valid or not is + * checked when the cell editing is stopped. The cell's values are displayed + * in a normal JTextField. + */ + public YFrequencyCellEditor() { + super(new JTextField()); + tf = (JTextField) getComponent(); + v = new FrequencyVerifier(); + tf.setInputVerifier(v); + } + + @Override + public boolean stopCellEditing() { + if (!v.verify(tf)) { + tf.setBorder(BorderFactory.createLineBorder(Color.red)); + JOptionPane.showMessageDialog(null, Messages.getString("em", + "YFrequencyPanel.ErrorMessageDescription"), Messages + .getString("em", "YFrequencyPanel.ErrorMessageTitle"), + JOptionPane.ERROR_MESSAGE); + return false; + } + return super.stopCellEditing(); + } + + /** + * @author Tobias Nett + * + * Specified InputVerifier for double values entered in + * the YFrequencyTable. + */ + static class FrequencyVerifier extends InputVerifier { + + @Override + public boolean verify(JComponent input) { + boolean wasValid = true; + double freq = 0; +// String text = "0"; + String text = ""; + if (input instanceof JTextComponent){ + JTextComponent textComponent = (JTextComponent) input; + text = textComponent.getText(); + } + try { + freq = InputStringParser.parseInputString( + text, 0, Double.MAX_VALUE); + } catch (NumberFormatException e) { + wasValid = false; + } catch (IllegalArgumentException e2) { + wasValid = false; + } + if (freq < 0) { + wasValid = false; + } + return wasValid; + } + + } + +} diff --git a/src/org/jalgo/module/em/gui/input/YFrequencyPanel.java b/src/org/jalgo/module/em/gui/input/YFrequencyPanel.java new file mode 100644 index 0000000..b14e6c2 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/YFrequencyPanel.java @@ -0,0 +1,282 @@ +package org.jalgo.module.em.gui.input; + +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.EventObject; + +import javax.swing.DefaultCellEditor; +import javax.swing.GroupLayout; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.LayoutStyle; +import javax.swing.SwingUtilities; +import javax.swing.event.TableModelEvent; +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; +import javax.swing.text.JTextComponent; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.StartParameters; +import org.jalgo.module.em.gui.UIConstants; + +/** + * A special panel for frequency input for partitions. + * + * @author Tobias Nett + * + */ +public class YFrequencyPanel extends JPanel implements InputPanel, UIConstants { + + private static final long serialVersionUID = -8903979650436463706L; + + private boolean beamerMode = false; + + private StartParameters params; + + private JLabel lHeading; + private JLabel lDescription; + + // Button Panel + private JPanel buttonPanel; + private JButton bForward; + private JButton bBack; + + private Container tablePanel; + + private JTable frequencyTable; + + /** + * Creates a new object of YFrequencyPanel which offers the user an interface + * to define specific frequency for the partitions. + * + * @param params StartParameters, object which is used to store and transfer the input data + * @param beamerMode specifies if beamer mode is enabled or not + */ + public YFrequencyPanel(StartParameters params, boolean beamerMode) { + this.params = params; + this.beamerMode = beamerMode; + this.init(); + } + + /** + * Initializes the YFrequencyPanel (containing a table to edit the values) and + * the button panel (containing back/forward buttons). + */ + public void init() { + this.initTablePanel(); + this.initButtonPanel(); + + checkInput(); + + GroupLayout layout = new GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) + .addComponent(tablePanel, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(buttonPanel, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(tablePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + this.setBeamerMode(beamerMode); + } + + private void initTablePanel() { + tablePanel = new JPanel(); + + lHeading = new JLabel(Messages.getString("em", "YFrequencyPanel.lHeading")); + lDescription = new JLabel(Messages.getString("em", "YFrequencyPanel.lDescription")); + + TableModel model = new YFrequencyTableModel(params.getObservations()); + + /** + * Customized JTable so that the value of a cell is selected when entering + * edit mode. + * + * @author tobias + * + */ + class MyTable extends JTable { + private static final long serialVersionUID = 1L; + + public MyTable(TableModel model){ + super(model); + } + + @Override + public boolean editCellAt(int row, int column, EventObject e) { + boolean result = super.editCellAt(row, column, e); + final Component editor = getEditorComponent(); + if (!(editor == null || !(editor instanceof JTextComponent))){ + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + ((JTextComponent)editor).selectAll(); + //((JTextComponent)editor).setText(""); + } + }); + } + return result; + } + } + + frequencyTable = new MyTable(model); + + frequencyTable.setDefaultEditor(Object.class, new YFrequencyCellEditor()); + frequencyTable.setRowHeight(frequencyTable.getFontMetrics(frequencyTable.getFont()).getHeight() + 10); + // enable single click editing + ((DefaultCellEditor)frequencyTable.getDefaultEditor(Object.class)).setClickCountToStart(1); + + frequencyTable.getModel().addTableModelListener(new TableModelListener() { + + @Override + public void tableChanged(TableModelEvent e) { + checkInput(); + } + }); + + JScrollPane sp = new JScrollPane(frequencyTable); + + javax.swing.GroupLayout tablePanelLayout = new javax.swing.GroupLayout(tablePanel); + tablePanel.setLayout(tablePanelLayout); + tablePanelLayout.setHorizontalGroup( + tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tablePanelLayout.createSequentialGroup() + .addContainerGap() + .addGroup(tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(sp, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 605, Short.MAX_VALUE) + .addComponent(lHeading, javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(lDescription, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 605, Short.MAX_VALUE) + ) + .addContainerGap()) + ); + tablePanelLayout.setVerticalGroup( + tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(tablePanelLayout.createSequentialGroup() + .addContainerGap() + .addComponent(lHeading) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(lDescription) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(sp, javax.swing.GroupLayout.PREFERRED_SIZE, 261, Short.MAX_VALUE) + .addContainerGap()) + ); + } + + /** + * Initializes the button panel which contains the 'back' and 'next' button. + * The 'back' button is placed on the left side, the next button is place + * opposite on the right side. + */ + private void initButtonPanel() { + buttonPanel = new JPanel(); + + // labels the buttons in the specified language + bForward = new JButton(Messages.getString("em", "InputPanel.bForward")); + bBack = new JButton(Messages.getString("em", "InputPanel.bBack")); + + GroupLayout l = new GroupLayout(buttonPanel); + buttonPanel.setLayout(l); + + l.setHorizontalGroup(l.createParallelGroup( + GroupLayout.Alignment.LEADING).addGroup( + l.createSequentialGroup() + .addContainerGap() + .addComponent(bBack) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED, 245, + Short.MAX_VALUE).addComponent(bForward) + .addContainerGap())); + + l.setVerticalGroup(l.createParallelGroup(GroupLayout.Alignment.LEADING) + .addGroup( + GroupLayout.Alignment.TRAILING, + l.createSequentialGroup().addGroup( + l.createParallelGroup( + GroupLayout.Alignment.BASELINE) + .addComponent(bBack) + .addComponent(bForward)))); + + ActionListener al = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (frequencyTable.getEditingRow() != -1) { + // stops cell editing only if a cell is edited at the moment + frequencyTable.getDefaultEditor(Object.class).stopCellEditing(); + } + } + }; + + bForward.addActionListener(al); + bBack.addActionListener(al); + } + + @Override + public JButton getForwardButton() { + return bForward; + } + + @Override + public JButton getBackButton() { + return bBack; + } + + private void checkInput() { + if (((YFrequencyTableModel)frequencyTable.getModel()).getFrequencySum() <= 0){ + bForward.setEnabled(false); + } else { + bForward.setEnabled(true); + } + } + + /** + * Sets the UI mode to beamer or normal mode. Call the method with true + * to enter beamer mode or with false to leave it. + *

          In beamer mode, all button texts are replaced with icons and the font size is increased. + * + * @param modeOn true if the beamer mode should be started, + * false if view should be set to standard view + */ + public void setBeamerMode(boolean modeOn) { + beamerMode = modeOn; + if (beamerMode){ + for (Component c : tablePanel.getComponents()) { + c.setFont(PRESENTATION_FONT); + } + frequencyTable.setFont(PRESENTATION_FONT); + frequencyTable.getTableHeader().setFont(PRESENTATION_FONT); + + bForward.setIcon(FORWARD_ICON); + bForward.setText(null); + bBack.setIcon(BACK_ICON); + bBack.setText(null); + } else { + for (Component c : tablePanel.getComponents()) { + c.setFont(DEFAULT_FONT); + } + frequencyTable.setFont(DEFAULT_FONT); + frequencyTable.getTableHeader().setFont(DEFAULT_FONT); + + bForward.setText(Messages.getString("em", "InputPanel.bForward")); + bForward.setIcon(FORWARD_ICON_SMALL); + bBack.setText(Messages.getString("em", "InputPanel.bBack")); + bBack.setIcon(BACK_ICON_SMALL); + } + } +} diff --git a/src/org/jalgo/module/em/gui/input/YFrequencyTableModel.java b/src/org/jalgo/module/em/gui/input/YFrequencyTableModel.java new file mode 100644 index 0000000..ba2be99 --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/YFrequencyTableModel.java @@ -0,0 +1,168 @@ +package org.jalgo.module.em.gui.input; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import javax.swing.table.AbstractTableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.Partition; + +/** + * TableModel for the FrequencyPanel. The table data is created out of a set of + * Partition (observations). + *

          + * The model displays the name/mathematical representation in one column and the + * frequency in another. + * + * @author Tobias Nett + */ +public class YFrequencyTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 2539673847879777440L; + + private List observations; + private Vector> data; + + /** + * Creates a new object of YFrequencyTableModel by calculating + * the table data out of the given set of partitions. + *

          + * Consists of three columns, one for the name, the second for the + * mathematical representation and the last for the frequency. + * + * @param observations + * set of partitions to show + */ + public YFrequencyTableModel(Set observations) { + this.observations = new ArrayList(observations); + data = new Vector>(); + + for (Partition partition : observations) { + Vector v = new Vector(); + v.add(partition.getName()); // name of the partition + v.add(partition.getMathSet()); // mathematical representation of the + // element set + v.add(Double.toString(partition.getFrequency())); // partition's frequency + data.add(v); + } + + } + + /** + * Returns '3' on every call. This model consists of exactly three columns. + * + * @return 3 static column count for this table model + */ + @Override + public int getColumnCount() { + return 3; + } + + /** + * Returns the number of rows in this model which is the count of + * partitions. + * + * @return number of partitions for this experiment + */ + @Override + public int getRowCount() { + if (observations != null) + return observations.size(); + return 0; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + if (rowIndex < getRowCount() && columnIndex < getColumnCount()) { + return data.get(rowIndex).get(columnIndex); + + } + return null; + } + + /** + * The name of specified column. The name is either 'Name', 'Observation' or + * 'Frequency'. + * + * @param column + * index of column + * @return name of the specified column + */ + @Override + public String getColumnName(int column) { + switch (column) { + case 0: + return Messages.getString("em", + "YFrequencyTableModel.PartitionName"); + case 1: + return Messages.getString("em", + "YFrequencyTableModel.PartitionElements"); + case 2: + return Messages.getString("em", "YFrequencyTableModel.Frequency"); + default: + return null; + } + } + + /** + * Returns true if columnIndex equals 2 (index of the + * frequency column. + * + * @param rowIndex + * the row whose value is to be queried + * @param columnIndex + * the column whose value is to be queried + * @return true if columnIndex is 2 (frequency column) + */ + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + if (columnIndex == 2) + return true; + return false; + } + + /** + * Sets the object value for the cell at column and + * row. value is the new value which is directly + * saved into the partition. + *

          + * Because of isCellEditable the only editable cells are the + * frequency cells. + * + * @param value + * the new value + * @param rowIndex + * the row whose value is to be changed + * @param columnIndex + * he column whose value is to be changed + */ + @Override + public void setValueAt(Object value, int rowIndex, int columnIndex) { + data.get(rowIndex).set(columnIndex, (String) value); + // write change directly to the partition + // observations.get(rowIndex).setFrequency( + // Double.parseDouble((String) value)); + observations.get(rowIndex).setFrequency( + InputStringParser.parseInputString((String) value, 0, + Double.MAX_VALUE)); + fireTableCellUpdated(rowIndex, columnIndex); + } + + /** + * Returns the sum of the partitions' frequencies. This sum is always + * greater or equal 0. + * + * @return sum of the partitions frequencies + */ + public double getFrequencySum() { + double sum = 0; + for (Partition p : observations) { + sum += p.getFrequency(); + } + return sum; + } + +} diff --git a/src/org/jalgo/module/em/gui/input/package-info.java b/src/org/jalgo/module/em/gui/input/package-info.java new file mode 100644 index 0000000..f8ff3ef --- /dev/null +++ b/src/org/jalgo/module/em/gui/input/package-info.java @@ -0,0 +1,6 @@ +/** + * This package contains all relevant classes for the input, e.g. XInput, + * PartitionPanel or P0Input. + * For details have a look on the specific classes. + */ +package org.jalgo.module.em.gui.input; diff --git a/src/org/jalgo/module/em/gui/output/CVS/Entries b/src/org/jalgo/module/em/gui/output/CVS/Entries new file mode 100644 index 0000000..d61e89b --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/CVS/Entries @@ -0,0 +1,2 @@ +D/diagram//// +D/table//// diff --git a/src/org/jalgo/module/em/gui/output/CVS/Repository b/src/org/jalgo/module/em/gui/output/CVS/Repository new file mode 100644 index 0000000..ae303f4 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/gui/output diff --git a/src/org/jalgo/module/em/gui/output/CVS/Root b/src/org/jalgo/module/em/gui/output/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/gui/output/diagram/CVS/Entries b/src/org/jalgo/module/em/gui/output/diagram/CVS/Entries new file mode 100644 index 0000000..352c0de --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/CVS/Entries @@ -0,0 +1,3 @@ +/DiagramFactory.java/1.1/Mon Jan 30 18:56:52 2012// +/DiagramPanel.java/1.1/Mon Jan 30 18:56:52 2012// +/package-info.java/1.1/Mon Jan 30 18:56:52 2012// diff --git a/src/org/jalgo/module/em/gui/output/diagram/CVS/Repository b/src/org/jalgo/module/em/gui/output/diagram/CVS/Repository new file mode 100644 index 0000000..7448f76 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/gui/output/diagram diff --git a/src/org/jalgo/module/em/gui/output/diagram/CVS/Root b/src/org/jalgo/module/em/gui/output/diagram/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/gui/output/diagram/DiagramFactory.java b/src/org/jalgo/module/em/gui/output/diagram/DiagramFactory.java new file mode 100644 index 0000000..d8548af --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/DiagramFactory.java @@ -0,0 +1,544 @@ +package org.jalgo.module.em.gui.output.diagram; + + +import static java.lang.Math.PI; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Point; +import java.util.LinkedList; +import java.util.List; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.control.LogState; +import org.math.plot.Plot2DPanel; +import org.math.plot.Plot3DPanel; +import org.math.plot.PlotPanel; +import org.math.plot.utils.Array; +/** + * The Factory builds groups of graphs to show the functions of the Emalgo + * @author Tom Schumann + * @version 1.0 + * + */ +public class DiagramFactory{ + + private org.jalgo.module.em.control.LogState logState; + + private double[] xRangeFor3D; + private double[] yRangeFor3D; + private double[] xRangeFor3DLog; + private double[] yRangeFor3DLog; + + private double[] xRangeFor2D; + private double[] xRangeFor2DDots; + private double[] xRangeFor2D_d_h; + private double[] xRangeFor2D_d_hDots; + private double[] axisSlicing; + + private double[][] mountains; + private double[][] mountains3D; + + private Color[] colors = {Color.BLUE,Color.RED,Color.CYAN, + Color.MAGENTA,Color.ORANGE,Color.PINK, + Color.YELLOW, Color.BLACK}; + + + /** + * + * @param logstate for the informations they needed too build graphs + */ + public DiagramFactory(LogState logstate){ + this.logState = logstate; + + } + + + /** + * build the requested graphs + * @return the builded plots + */ + public PlotPanel[] draw(){ + PlotPanel[] plotParts = new PlotPanel[6]; + Plot2DPanel plot2DForL = new Plot2DPanel(); + Plot2DPanel plot2DForP = new Plot2DPanel(); + Plot2DPanel plot2DForH = new Plot2DPanel(); + Plot2DPanel plot2DForD = new Plot2DPanel(); + Plot2DPanel plot2DForPSingle = new Plot2DPanel(); + Plot3DPanel plot3D = new Plot3DPanel(); + Font f = org.jalgo.module.em.gui.UIConstants.DEFAULT_FONT; + + + // Calculating the axis Slicing + int steps = logState.getStepCount(); + int delta = 20; + int scaling = ((steps-1)/delta)+1; + axisSlicing = org.math.array.DoubleArray.increment(0.0, scaling, steps + scaling + ((steps % scaling == 0) ? 0 : scaling)); + + //configure the plotPanels + //Plot2DForL + String logPostfix = + (logState.isLogarithmicLikelihoodRepresentationEnabled()) + ? " (log)": ""; + String[] names2d = {"Iteration","Likelihood"+logPostfix}; + plot2DForL.setAxisLabels(names2d); + plot2DForL.setLegendOrientation("SOUTH"); + plot2DForL.setFont(new Font("Courier", Font.BOLD, 12)); + // customize X axe + // rotate light labels + plot2DForL.getAxis(0).setLightLabelAngle(-PI / 4); + // change axe title position relatively to the base of the plot + plot2DForL.getAxis(0).setLabelPosition(0.5, -0.15); + plot2DForL.getAxis(0).setColor(Color.black); + plot2DForL.getAxis(0).setLabelFont(f); + // customize Y axe + // rotate light labels + plot2DForL.getAxis(1).setLightLabelAngle(-PI / 4); + // change axe title position relatively to the base of the plot + plot2DForL.getAxis(1).setLabelPosition(-0.15, 0.5); + // change axe title angle + plot2DForL.getAxis(1).setLabelAngle(-PI / 2); + plot2DForL.getAxis(1).setColor(Color.black); + plot2DForL.getAxis(1).setLabelFont(f); + //Changing the Color of the Axis Scale Labels for each axis: + plot2DForL.getAxis(0).setLightLabelColor(Color.black); + plot2DForL.getAxis(1).setLightLabelColor(Color.black); + //Setting the Slicing on for the Step-Axis of the L-Plot + plot2DForL.getAxis(0).setCustomSlicing(axisSlicing, axisSlicing); + //Disable editing of the legend + plot2DForL.setEditable(false); + + names2d[1] = Messages.getString("em", "DiagramPanel.d"); + plot2DForD.setAxisLabels(names2d); + plot2DForD.setLegendOrientation("SOUTH"); + plot2DForD.setFont(new Font("Courier", Font.BOLD, 12)); + plot2DForD.getAxis(0).setLightLabelAngle(-PI / 4); + plot2DForD.getAxis(0).setLabelPosition(0.5, -0.15); + plot2DForD.getAxis(0).setColor(Color.black); + plot2DForD.getAxis(0).setLabelFont(f); + plot2DForD.getAxis(1).setLightLabelAngle(-PI / 4); + plot2DForD.getAxis(1).setLabelPosition(-0.15, 0.5); + plot2DForD.getAxis(1).setLabelAngle(-PI / 2); + plot2DForD.getAxis(1).setColor(Color.black); + plot2DForD.getAxis(0).setLightLabelColor(Color.black); + plot2DForD.getAxis(1).setLightLabelColor(Color.black); + plot2DForD.getAxis(1).setLabelFont(f); + plot2DForD.getAxis(0).setCustomSlicing(axisSlicing, axisSlicing); + plot2DForD.setEditable(false); + + names2d[1] = Messages.getString("em", "DiagramPanel.h"); + plot2DForH.setAxisLabels(names2d); + plot2DForH.setLegendOrientation("SOUTH"); + plot2DForH.setFont(new Font("Courier", Font.BOLD, 12)); + plot2DForH.getAxis(0).setLightLabelAngle(-PI / 4); + plot2DForH.getAxis(0).setLabelPosition(0.5, -0.15); + plot2DForH.getAxis(0).setColor(Color.black); + plot2DForH.getAxis(0).setLightLabelColor(Color.black); + plot2DForH.getAxis(1).setLightLabelColor(Color.black); + plot2DForH.getAxis(0).setLabelFont(f); + plot2DForH.getAxis(1).setLightLabelAngle(-PI / 4); + plot2DForH.getAxis(1).setLabelPosition(-0.15, 0.5); + plot2DForH.getAxis(1).setLabelAngle(-PI / 2); + plot2DForH.getAxis(1).setColor(Color.black); + plot2DForH.getAxis(1).setLabelFont(f); + plot2DForH.getAxis(0).setCustomSlicing(axisSlicing, axisSlicing); + plot2DForH.setEditable(false); + + names2d[1] = Messages.getString("em", "DiagramPanel.p"); + plot2DForP.setAxisLabels(names2d); + plot2DForP.setLegendOrientation("SOUTH"); + plot2DForP.setFont(new Font("Courier", Font.BOLD, 12)); + plot2DForP.getAxis(0).setLightLabelAngle(-PI / 4); + plot2DForP.getAxis(0).setLabelPosition(0.5, -0.15); + plot2DForP.getAxis(0).setColor(Color.black); + plot2DForP.getAxis(0).setLightLabelColor(Color.black); + plot2DForP.getAxis(1).setLightLabelColor(Color.black); + plot2DForP.getAxis(0).setLabelFont(f); + plot2DForP.getAxis(1).setLightLabelAngle(-PI / 4); + plot2DForP.getAxis(1).setLabelPosition(-0.15, 0.5); + plot2DForP.getAxis(1).setLabelAngle(-PI / 2); + plot2DForP.getAxis(1).setColor(Color.black); + plot2DForP.getAxis(1).setLabelFont(f); + plot2DForP.getAxis(0).setCustomSlicing(axisSlicing, axisSlicing); + plot2DForP.setEditable(false); + + names2d[1] = Messages.getString("em", "DiagramPanel.psingle"); + plot2DForPSingle.setAxisLabels(names2d); + plot2DForPSingle.setLegendOrientation("SOUTH"); + plot2DForPSingle.setFont(new Font("Courier", Font.BOLD, 12)); + plot2DForPSingle.getAxis(0).setLightLabelAngle(-PI / 4); + plot2DForPSingle.getAxis(0).setLabelPosition(0.5, -0.15); + plot2DForPSingle.getAxis(0).setColor(Color.black); + plot2DForPSingle.getAxis(0).setLightLabelColor(Color.black); + plot2DForPSingle.getAxis(1).setLightLabelColor(Color.black); + plot2DForPSingle.getAxis(0).setLabelFont(f); + plot2DForPSingle.getAxis(1).setLightLabelAngle(-PI / 4); + plot2DForPSingle.getAxis(1).setLabelPosition(-0.15, 0.5); + plot2DForPSingle.getAxis(1).setLabelAngle(-PI / 2); + plot2DForPSingle.getAxis(1).setColor(Color.black); + plot2DForPSingle.getAxis(1).setLabelFont(f); + plot2DForPSingle.getAxis(0).setCustomSlicing(axisSlicing, axisSlicing); + plot2DForPSingle.setEditable(false); + + //Plot3D + String[] names3d = {Messages.getString("em", "DiagramPanel.3DAxisX"), + Messages.getString("em", "DiagramPanel.3DAxisY"), + Messages.getString("em", "DiagramPanel.l")}; + plot3D.setAxisLabels(names3d); + plot3D.setLegendOrientation("SOUTH"); + plot3D.setForeground(Color.LIGHT_GRAY); + plot3D.setFont(new Font("Courier", Font.BOLD, 12)); + plot3D.getAxis(0).setColor(Color.black); + plot3D.getAxis(1).setColor(Color.black); + plot3D.getAxis(2).setColor(Color.black); + plot3D.getAxis(0).setLightLabelColor(Color.black); + plot3D.getAxis(1).setLightLabelColor(Color.black); + plot3D.getAxis(2).setLightLabelColor(Color.black); + plot3D.getAxis(0).setLabelFont(f); + plot3D.getAxis(1).setLabelFont(f); + plot3D.getAxis(2).setLabelFont(f); + plot3D.getAxis(1).setLightLabelAngle(-PI/4); + plot3D.getAxis(0).setLabelPosition(1.0,-0.25,0.5); + plot3D.getAxis(1).setLabelPosition(-0.25,1.0,0.5); + plot3D.getAxis(2).setLabelPosition(0.1,0.1,1.1); + plot3D.setEditable(false); + + //add PlotPanel to plotParts + //Liklihood - Iteration + plotParts[0] = plot2DForL; + + //d-Iteration + plotParts[1] = plot2DForD; + + //h-Iteration + plotParts[2] = plot2DForH; + + //p-Iteration + plotParts[3] = plot2DForP; + + //pSingle-Iteration + plotParts[4] = plot2DForPSingle; + + this.range(); + + if(this.logState.getStepCount() >= 0){ + //Create plots: + //2D Plots: + //Likelihood - Iteration + this.plot2DForL(plot2DForL); + + //d-Iteration + this.plot2DForD(plot2DForD); + + //h-Iteration + this.plot2DForH(plot2DForH); + + //p-Iteration + this.plot2DForP(plot2DForP); + + //pSingle-Iteration + this.plot2DForPSingle(plot2DForPSingle); + } + + //3D Plot: + if(this.logState.activate3D()) { + this.mountains(plot3D); + if(this.logState.getStepCount()>= 0){ + this.plot3D(plot3D); + } + plotParts[5] = plot3D; + } + else { + plotParts[5] = null; + } + + //Calculating the upper X Bound + int upperXBound = (logState.getStepCount() / 10 + 1) * 10; + if ((upperXBound - logState.getStepCount()) > 9) { + upperXBound -= 10; + } + if (steps == 0) { + upperXBound = 10; + } + if (upperXBound < steps + (scaling - (steps % scaling)) * ((steps % scaling != 0) ? 1 : 0)) { + upperXBound += 10; + } + //Setting the upper X Bound + plot2DForL.setFixedBounds(0, 0, upperXBound); + plot2DForD.setFixedBounds(0, 0, upperXBound); + plot2DForH.setFixedBounds(0, 0, upperXBound); + plot2DForP.setFixedBounds(0, 0, upperXBound); + plot2DForPSingle.setFixedBounds(0, 0, upperXBound); + + return plotParts; + } + + /** + * controls the range of the scales + */ + private void range(){ + this.xRangeFor2D = org.math.array.DoubleArray.increment(0.0, 1.0, this.logState.getStepCount()+1); + this.xRangeFor2DDots = Array.copy(axisSlicing); + if (this.xRangeFor2DDots[this.xRangeFor2DDots.length - 1] > this.logState.getStepCount()){ + this.xRangeFor2DDots[this.xRangeFor2DDots.length -1] = this.logState.getStepCount(); + } + this.xRangeFor2D_d_h = org.math.array.DoubleArray.increment(1.0, 1.0, this.logState.getStepCount()+1); + this.xRangeFor2D_d_hDots = new double[xRangeFor2DDots.length - 1]; + for (int i = 0; i < xRangeFor2D_d_hDots.length; i++){ + xRangeFor2D_d_hDots[i] = xRangeFor2DDots[i + 1]; + } + } + + /** + * Plots the lines and dots for the Likelihood. + * @param plot2D The Plot2DPanel in which the Curves and Lines shall be plotted. + */ + private void plot2DForL(Plot2DPanel plot2D){ + List dotLegends = new LinkedList(); + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] yLine = new double[this.xRangeFor2D.length]; + double[] yDots = new double[this.xRangeFor2DDots.length]; + for(int iterationStep = 0; iterationStep <= this.logState.getStepCount(); iterationStep++){ + yLine[iterationStep] = this.logState.getL(p0, iterationStep); + } + for (int dotIndex = 0; dotIndex < yDots.length; dotIndex ++){ + yDots[dotIndex] = yLine[(int) xRangeFor2DDots[dotIndex]]; + } + + if(this.logState.getStepCount() > 0){ + dotLegends.add(plot2D.addScatterPlot("p0["+(p0 + 1)+"]", this.colors[(p0%this.colors.length)+1], this.xRangeFor2DDots, yDots)); + plot2D.addLinePlot("p0["+(p0 + 1)+"]", this.colors[(p0%this.colors.length)+1], this.xRangeFor2D, yLine); + } else { + plot2D.addScatterPlot("p0["+(p0 + 1)+"]", this.colors[(p0%this.colors.length)+1], this.xRangeFor2D, yLine); + } + } + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot2D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + + /** + * Plots the lines and dots for the Event Statistical Analyzer. + * @param plot2D The Plot2DPanel in which the Curves and Lines shall be plotted. + */ + private void plot2DForD(Plot2DPanel plot2D){ + if(this.logState.getStepCount() == 0) { + } else{ + List dotLegends = new LinkedList(); + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++) { + double[] yLine = new double[this.xRangeFor2D_d_h.length]; + double[] yDots = new double[this.xRangeFor2D_d_hDots.length]; + for(org.jalgo.module.em.data.Event event : this.logState.getEvents()){ + for(int iterationStep = 1; iterationStep <= this.logState.getStepCount(); iterationStep++){ + yLine[iterationStep - 1] = this.logState.getD(p0, iterationStep, event); + } + for (int dotIndex = 0; dotIndex < yDots.length; dotIndex ++){ + yDots[dotIndex] = yLine[(int) xRangeFor2D_d_hDots[dotIndex] - 1]; + } + if(this.logState.getStepCount() > 1){ + dotLegends.add(plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_hDots, yDots)); + plot2D.addLinePlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_h, yLine); + } else if (logState.getStepCount() > 0){ + plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_h, yLine); + } + } + } + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot2D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + } + + /** + * Plots the lines and dots for the Event Frequency. + * @param plot2D The Plot2DPanel in which the Curves and Lines shall be plotted. + */ + private void plot2DForH(Plot2DPanel plot2D) { + if(this.logState.getStepCount() == 0){ + } else { + List dotLegends = new LinkedList(); + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] yLine = new double[this.xRangeFor2D_d_h.length]; + double[] yDots = new double[this.xRangeFor2D_d_hDots.length]; + for(org.jalgo.module.em.data.Event event : this.logState.getEvents()){ + for(int iterationStep = 1; iterationStep <= this.logState.getStepCount(); iterationStep++){ + yLine[iterationStep - 1] = this.logState.getH(p0, iterationStep, event); + } + for (int dotIndex = 0; dotIndex < yDots.length; dotIndex ++){ + yDots[dotIndex] = yLine[(int) xRangeFor2D_d_hDots[dotIndex] - 1]; + } + if(this.logState.getStepCount() > 1){ + dotLegends.add(plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_hDots, yDots)); + plot2D.addLinePlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_h, yLine); + } else if (logState.getStepCount() > 0){ + plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D_d_h, yLine); + } + } + } + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot2D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + } + + /** + * Plots the lines and dots for the Event Probability. + * @param plot2D The Plot2DPanel in which the Curves and Lines shall be plotted. + */ + private void plot2DForP(Plot2DPanel plot2D) { + List dotLegends = new LinkedList(); + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] yLine = new double[this.xRangeFor2D.length]; + double[] yDots = new double[this.xRangeFor2DDots.length]; + for(org.jalgo.module.em.data.Event event : this.logState.getEvents()){ + for(int iterationStep = 0; iterationStep <= this.logState.getStepCount(); iterationStep++){ + yLine[iterationStep] = this.logState.getP(p0, iterationStep, event); + } + for (int dotIndex = 0; dotIndex < yDots.length; dotIndex ++){ + yDots[dotIndex] = yLine[(int) xRangeFor2DDots[dotIndex]]; + } + + if(this.logState.getStepCount() > 0){ + dotLegends.add(plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2DDots, yDots)); + plot2D.addLinePlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D, yLine); + } else { + plot2D.addScatterPlot(event.toString(), this.colors[p0%this.colors.length], this.xRangeFor2D, yLine); + } + } + } + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot2D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + + + /** + * Plots the lines and dots for the SingleEvent Probability. + * @param plot2D The Plot2DPanel in which the Curves and Lines shall be plotted. + */ + private void plot2DForPSingle(Plot2DPanel plot2D) { + List dotLegends = new LinkedList(); + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] yLine = new double[this.xRangeFor2D.length]; + double[] yDots = new double[this.xRangeFor2DDots.length]; + for (int objectIndex = 0; objectIndex < this.logState.getExperiment().size(); objectIndex ++) { + for (int side = 1; side <= this.logState.getExperiment().get(objectIndex); side ++) { + Point singleEvent = new Point(side, objectIndex); + for(int iterationStep = 0; iterationStep <= this.logState.getStepCount(); iterationStep++){ + yLine[iterationStep] = this.logState.getPSingleEvent(p0, iterationStep, singleEvent); + } + for (int dotIndex = 0; dotIndex < yDots.length; dotIndex ++){ + yDots[dotIndex] = yLine[(int) xRangeFor2DDots[dotIndex]]; + } + String name = ((LogState) this.logState).singleEventToString(singleEvent); + + if(this.logState.getStepCount() > 0){ + dotLegends.add(plot2D.addScatterPlot(name, this.colors[p0%this.colors.length], this.xRangeFor2DDots, yDots)); + plot2D.addLinePlot(name, this.colors[p0%this.colors.length], this.xRangeFor2D, yLine); + } else { + plot2D.addScatterPlot(name, this.colors[p0%this.colors.length], this.xRangeFor2D, yLine); + } + } + } + } + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot2D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + + /** + * plots the lines and dots into the 3D Plot. + */ + private void plot3D(org.math.plot.Plot3DPanel plot3D){ + List dotLegends = new LinkedList(); + + if(this.logState.getStepCount() == 0){ + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] xRange = new double [this.logState.getStepCount() + 1]; + double[] yRange = new double [this.logState.getStepCount() + 1]; + double[] zRange = new double [this.logState.getStepCount() + 1]; + for(int iterationStep = 0; iterationStep <= this.logState.getStepCount(); iterationStep++){ + xRange[iterationStep] = this.logState.getPSingleEvent(p0, iterationStep, new Point(2,0)); + yRange[iterationStep] = this.logState.getPSingleEvent(p0, iterationStep, new Point(2,1)); + zRange[iterationStep] = this.logState.getL(p0, iterationStep); + } + plot3D.addScatterPlot("p0["+(p0 + 1)+"]",this.colors[p0%this.colors.length], xRange, yRange, zRange); + } + } + else { + for(int p0 = 0; p0 < this.logState.getP0Count(); p0++){ + double[] xRange = new double [this.logState.getStepCount() + 1]; + double[] yRange = new double [this.logState.getStepCount() + 1]; + double[] zRange = new double [this.logState.getStepCount() + 1]; + for(int iterationStep = 0; iterationStep <= this.logState.getStepCount(); iterationStep++){ + xRange[iterationStep] = this.logState.getPSingleEvent(p0, iterationStep, new Point(2,0)); + yRange[iterationStep] = this.logState.getPSingleEvent(p0, iterationStep, new Point(2,1)); + zRange[iterationStep] = this.logState.getL(p0, iterationStep); + } + //In Case of no Change => no line can be drawn + if (xRange[0] == xRange[1]) { + + plot3D.addScatterPlot("p0["+(p0 + 1)+"]",this.colors[p0%this.colors.length], xRange, yRange, zRange); + + } else { + dotLegends.add(plot3D.addScatterPlot("p0["+(p0 + 1)+"]",this.colors[p0%this.colors.length], xRange, yRange, zRange)); + plot3D.addLinePlot("p0["+(p0 + 1)+"]",this.colors[p0%this.colors.length], xRange, yRange, zRange); + } + } + } + + for (int i = dotLegends.size() - 1; i >= 0; i--) { + ((JPanel) plot3D.plotLegend.getComponent(0)).remove(dotLegends.get(i)); + } + } + + + /** + * Build the ground of the 3D-Graph. + */ + private void mountains(org.math.plot.Plot3DPanel plot3D){ + double[][] mountains; + double [] xRangeFor3D; + double [] yRangeFor3D; + if (logState.isLogarithmicLikelihoodRepresentationEnabled()) { + mountains = this.mountains3D; + xRangeFor3D = this.xRangeFor3DLog; + yRangeFor3D = this.yRangeFor3DLog; + } else { + mountains = this.mountains; + xRangeFor3D = this.xRangeFor3D; + yRangeFor3D = this.yRangeFor3D; + } + if (mountains == null){ + if (! logState.isLogarithmicLikelihoodRepresentationEnabled()) { + this.xRangeFor3D = org.math.array.DoubleArray.increment(0.0, 0.025, 1.026); + this.yRangeFor3D = org.math.array.DoubleArray.increment(0.0, 0.025, 1.026); + xRangeFor3D = this.xRangeFor3D; + yRangeFor3D = this.yRangeFor3D; + } else { + this.xRangeFor3DLog = org.math.array.DoubleArray.increment(0.0, 0.025, 1.026); + this.xRangeFor3DLog[0] = 0.005; + this.xRangeFor3DLog[xRangeFor3DLog.length - 1] = 0.995; + this.yRangeFor3DLog = org.math.array.DoubleArray.increment(0.0, 0.025, 1.026); + this.yRangeFor3DLog[0] = 0.005; + this.yRangeFor3DLog[xRangeFor3DLog.length - 1] = 0.995; + xRangeFor3D = this.xRangeFor3DLog; + yRangeFor3D = this.yRangeFor3DLog; + } + mountains = new double[this.xRangeFor3D.length][this.yRangeFor3D.length]; + for(int x = 0; x < xRangeFor3D.length;x++){ + for(int y = 0; y< yRangeFor3D.length;y++){ + mountains[y][x] = this.logState.getL3DGraph(xRangeFor3D[x], yRangeFor3D[y]); + } + } + if (logState.isLogarithmicLikelihoodRepresentationEnabled()) { + this.mountains3D = mountains; + } else { + this.mountains = mountains; + } + } + plot3D.addGridPlot("Ground", Color.gray, xRangeFor3D, yRangeFor3D, mountains); + } + +} diff --git a/src/org/jalgo/module/em/gui/output/diagram/DiagramPanel.java b/src/org/jalgo/module/em/gui/output/diagram/DiagramPanel.java new file mode 100644 index 0000000..db1f97d --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/DiagramPanel.java @@ -0,0 +1,286 @@ +package org.jalgo.module.em.gui.output.diagram; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Map; +import java.util.TreeMap; + +import javax.swing.JButton; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.control.LogState; +import org.math.plot.PlotPanel; +import org.math.plot.canvas.Plot3DCanvas; +import org.math.plot.canvas.PlotCanvas; + + +/** + * Controls the shown Graphs and command the graph factory. + * + * @author Tom Schumann + * @version 1.0 + * + */ +public class DiagramPanel extends JPanel implements ActionListener{ + + private static final long serialVersionUID = -9192842176882009609L; + private DiagramFactory diafactory; + + private JPanel toolBar = new JPanel(); + private JButton bStandartZoom = new JButton(); + private JButton bIterationToLiklihood = new JButton(); + private JButton bIterationToD = new JButton(); + private JButton bIterationToH = new JButton(); + private JButton bIterationToP = new JButton(); + private JButton bIterationToPSingle = new JButton(); + private JButton bTwoCoinsPlot = new JButton(); + private PlotPanel[] usedplot; + private JPanel legende = new JPanel(); + private Map plotHistory; + private Map plotHistorylog; + private Map scalesHistory; + + private BorderLayout layout = new BorderLayout(); + private int controlPlots; + private LogState logState; + private boolean usedScales; + + private double phi; + private double theta; + + /** + * Build the Panel and its factory. + * @param logstate The LogState that provides the Data that shall be visualized. + */ + public DiagramPanel(org.jalgo.module.em.control.LogState logstate){ + init(); + this.logState = logstate; + this.plotHistory = new TreeMap(); + this.plotHistorylog = new TreeMap(); + this.scalesHistory = new TreeMap(); + this.diafactory = new DiagramFactory(logstate); + this.controlPlots = 0; + if(!logstate.activate3D()){ + remove(this.bTwoCoinsPlot); + this.bTwoCoinsPlot.setVisible(false); + } + this.usedScales = this.logState.isLogarithmicLikelihoodRepresentationEnabled(); + this.scalesHistory.put(this.logState.getStepCount(), this.usedScales); + if(!this.logState.isLogarithmicLikelihoodRepresentationEnabled()){ + this.plotHistory.put(logstate.getStepCount(), this.diafactory.draw()); + }else + { + this.plotHistorylog.put(logstate.getStepCount(), this.diafactory.draw()); + } + this.usedplot = this.plotHistory.get(logstate.getStepCount()); + } + + /** + * Build the basics of this panel + */ + public void init(){ + setLayout(this.layout); + add(this.toolBar, BorderLayout.NORTH); + + this.toolBar.add(this.bStandartZoom); + this.toolBar.add(this.bIterationToLiklihood); + this.toolBar.add(this.bTwoCoinsPlot); + + this.bIterationToLiklihood.addActionListener(this); + this.bIterationToD.addActionListener(this); + this.bIterationToH.addActionListener(this); + this.bIterationToP.addActionListener(this); + this.bIterationToPSingle.addActionListener(this); + this.bStandartZoom.addActionListener(this); + this.bTwoCoinsPlot.addActionListener(this); + + this.bStandartZoom.setText(Messages.getString("em", "DiagramPanel.StandartZoom")); + this.bIterationToLiklihood.setText(Messages.getString("em", "DiagramPanel.l")); + this.bIterationToD.setText(Messages.getString("em", "DiagramPanel.d")); + this.bIterationToH.setText(Messages.getString("em", "DiagramPanel.h")); + this.bIterationToP.setText(Messages.getString("em", "DiagramPanel.p")); + this.bIterationToPSingle.setText(Messages.getString("em", "DiagramPanel.psingle")); + this.bTwoCoinsPlot.setText(Messages.getString("em", "DiagramPanel.twoCoinsPlot")); + + this.bStandartZoom.setToolTipText(Messages.getString("em", "DiagramPanel.StandartZoom")); + this.bIterationToLiklihood.setToolTipText(Messages.getString("em", "DiagramPanel.l")); + this.bIterationToD.setToolTipText(Messages.getString("em", "DiagramPanel.d")); + this.bIterationToH.setToolTipText(Messages.getString("em", "DiagramPanel.h")); + this.bIterationToP.setToolTipText(Messages.getString("em", "DiagramPanel.p")); + this.bIterationToPSingle.setToolTipText(Messages.getString("em", "DiagramPanel.psingle")); + this.bTwoCoinsPlot.setToolTipText(Messages.getString("em", "DiagramPanel.twoCoinsPlot")); + + + this.toolBar.add(this.bStandartZoom); + this.toolBar.add(this.bIterationToLiklihood); + this.toolBar.add(this.bIterationToD); + this.toolBar.add(this.bIterationToH); + this.toolBar.add(this.bIterationToP); + this.toolBar.add(this.bIterationToPSingle); + this.toolBar.add(this.bTwoCoinsPlot); +// Dimension maximumSize = new Dimension(); +// maximumSize.width = 100; +// maximumSize.height = 50; +// this.legende.setAutoscrolls(true); +// this.legende.setMinimumSize(maximumSize); + this.legende.setBackground(Color.WHITE); +// this.legende.setMaximumSize(maximumSize); + this.legende.setVisible(true); + this.setAutoscrolls(true); + this.add(this.legende, BorderLayout.SOUTH); + } + + /** + * Updates the panel, to apply step or logarithmicLikelihoodRepresentation changes. + */ + public void upDate(){ + if (this.usedplot != null) { + if (this.controlPlots == 5) { + this.saveViewCoords(); + } + } + + //Makes the d and h diagram synchron to the singleSteps. + int shift = 0; + if (((this.controlPlots == 1) && (this.logState.getSingleStepCount() > 0)) + || ((this.controlPlots == 2) && (this.logState.getSingleStepCount() > 1))) { + shift = 1; + logState.stepForward(); + } + + if(!this.logState.isLogarithmicLikelihoodRepresentationEnabled()){ + if(this.plotHistory.containsKey(this.logState.getStepCount())){ + this.usedplot = this.plotHistory.get(this.logState.getStepCount()); + } + else { + this.usedplot = this.diafactory.draw(); + this.plotHistory.put(this.logState.getStepCount(), this.usedplot); + this.scalesHistory.put(this.logState.getStepCount(), this.logState.isLogarithmicLikelihoodRepresentationEnabled()); + } + } + else{ + if(this.plotHistorylog.containsKey(this.logState.getStepCount())){ + this.usedplot = this.plotHistorylog.get(this.logState.getStepCount()); + } + else{ + this.usedplot = this.diafactory.draw(); + this.plotHistorylog.put(this.logState.getStepCount(), this.usedplot); + this.scalesHistory.put(this.logState.getStepCount(), this.logState.isLogarithmicLikelihoodRepresentationEnabled()); + } + } + this.change(); + if (shift == 1) { + logState.stepBackward(); + } + } + + /** + * Changes the Diagram and Legend, if the step was changed or a different Diagram type chosen. + */ + public void change(){ + if (this.layout.getLayoutComponent(BorderLayout.CENTER) != null){ + this.remove(this.layout.getLayoutComponent(BorderLayout.CENTER)); + } + if (this.layout.getLayoutComponent(BorderLayout.SOUTH) != null){ + this.remove(this.layout.getLayoutComponent(BorderLayout.SOUTH)); + } + this.legende.removeAll(); + if (this.controlPlots == 5) { + Plot3DCanvas canvas = ((Plot3DCanvas) usedplot[5].plotCanvas); + ((org.math.plot.render.Projection3D) ((org.math.plot.render.AWTDrawer3D) canvas.getDraw()).getProjection()).setView(theta, phi); + } + this.add(this.usedplot[this.controlPlots].plotCanvas, BorderLayout.CENTER); + this.legende.add(this.usedplot[this.controlPlots].plotLegend); + if((this.controlPlots < 4) && (this.controlPlots > 0)) { + if(this.logState.getEvents().size() * this.logState.getP0Count() <= 40) { + this.add(this.legende, BorderLayout.SOUTH); + } + } + if ((this.controlPlots == 4) && (this.logState.getSingleEvents().size() * this.logState.getP0Count() <= 40)) { + this.add(this.legende, BorderLayout.SOUTH); + } + if((this.controlPlots == 0) || (this.controlPlots == 5)) { + this.add(this.legende, BorderLayout.SOUTH); + } + this.updateUI(); + } + + /** + * Controls the buttons in this panel and management the events + * @param ActionEvent Event that + */ + @Override + public void actionPerformed(ActionEvent arg) { + if(arg.getSource() == this.bStandartZoom){ +// System.out.println("control Plots : "+controlPlots); + PlotPanel panel = usedplot[controlPlots]; + PlotCanvas canvas = panel.plotCanvas; + canvas.resetBase(); + } + if(arg.getSource() == this.bIterationToLiklihood){ + this.controlPlots = 0; + this.upDate(); + } + if(arg.getSource() == this.bIterationToD){ + this.controlPlots = 1; + this.upDate(); + } + if(arg.getSource() == this.bIterationToH){ + this.controlPlots = 2; + this.upDate(); + } + if(arg.getSource() == this.bIterationToP){ + this.controlPlots = 3; + this.upDate(); + } + if(arg.getSource() == this.bIterationToPSingle){ + this.controlPlots = 4; + this.upDate(); + } + if(arg.getSource() == this.bTwoCoinsPlot){ + this.controlPlots = 5; + this.upDate(); + } + } + + /** + * Saves the current view angle of the 3D Graph. + */ + public void saveViewCoords() { + if (usedplot[5] != null){ + Plot3DCanvas canvas = ((Plot3DCanvas) usedplot[5].plotCanvas); + phi = ((org.math.plot.render.Projection3D) ((org.math.plot.render.AWTDrawer3D) canvas.getDraw()).getProjection()).getPhi(); + theta = ((org.math.plot.render.Projection3D) ((org.math.plot.render.AWTDrawer3D) canvas.getDraw()).getProjection()).getTheta(); + } + + } + + /** + * Shrinks the buttons, if the JPanel is smaller than 1070px, + * to make them fit into it. + * @author Kilian Gebhardt + */ + public void resetButtons() { + if (this.getWidth() > 1070) { + this.bStandartZoom.setText(Messages.getString("em", "DiagramPanel.StandartZoom")); + this.bIterationToLiklihood.setText(Messages.getString("em", "DiagramPanel.l")); + this.bIterationToD.setText(Messages.getString("em", "DiagramPanel.d")); + this.bIterationToH.setText(Messages.getString("em", "DiagramPanel.h")); + this.bIterationToP.setText(Messages.getString("em", "DiagramPanel.p")); + this.bIterationToPSingle.setText(Messages.getString("em", "DiagramPanel.psingle")); + this.bTwoCoinsPlot.setText(Messages.getString("em", "DiagramPanel.twoCoinsPlot")); + } else { + this.bStandartZoom.setText(Messages.getString("em", "DiagramPanel.StandartZoom")); + this.bIterationToLiklihood.setText(Messages.getString("em", "DiagramPanel.l.short")); + this.bIterationToD.setText(Messages.getString("em", "DiagramPanel.d.short")); + this.bIterationToH.setText(Messages.getString("em", "DiagramPanel.h.short")); + this.bIterationToP.setText(Messages.getString("em", "DiagramPanel.p.short")); + this.bIterationToPSingle.setText(Messages.getString("em", "DiagramPanel.psingle.short")); + this.bTwoCoinsPlot.setText(Messages.getString("em", "DiagramPanel.twoCoinsPlot.short")); + } + } + +} diff --git a/src/org/jalgo/module/em/gui/output/diagram/package-info.java b/src/org/jalgo/module/em/gui/output/diagram/package-info.java new file mode 100644 index 0000000..8e76a86 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/diagram/package-info.java @@ -0,0 +1,8 @@ +package org.jalgo.module.em.gui.output.diagram; + +/** + * This package contains all relevant classes for the diagram output, e.g. DiagramPanel. + * + * For details have a look on the specific classes. + */ + diff --git a/src/org/jalgo/module/em/gui/output/table/CVS/Entries b/src/org/jalgo/module/em/gui/output/table/CVS/Entries new file mode 100644 index 0000000..878659c --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/CVS/Entries @@ -0,0 +1,4 @@ +/TableModel.java/1.1/Mon Jan 30 18:56:52 2012// +/TableModelLike.java/1.1/Mon Jan 30 18:56:52 2012// +/TableModelSE.java/1.1/Mon Jan 30 18:56:52 2012// +/TableViewPanel.java/1.1/Mon Jan 30 18:56:52 2012// diff --git a/src/org/jalgo/module/em/gui/output/table/CVS/Repository b/src/org/jalgo/module/em/gui/output/table/CVS/Repository new file mode 100644 index 0000000..3a3bdb2 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/em/gui/output/table diff --git a/src/org/jalgo/module/em/gui/output/table/CVS/Root b/src/org/jalgo/module/em/gui/output/table/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/em/gui/output/table/TableModel.java b/src/org/jalgo/module/em/gui/output/table/TableModel.java new file mode 100644 index 0000000..50f1706 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/TableModel.java @@ -0,0 +1,146 @@ +package org.jalgo.module.em.gui.output.table; + +import java.util.ArrayList; +import java.util.IllegalFormatPrecisionException; +import java.util.List; +import java.util.Set; + +import javax.swing.table.AbstractTableModel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.em.data.Event; + +public class TableModel extends AbstractTableModel{ + /** + * Stores the Content of the Table in an List> + * @author Meinhardt Branig + */ + private static final long serialVersionUID = 1L; + private List> data; + private int index = 0; + + /** + * produces the first Column with Partitionnames + * @param eventSet + */ + public TableModel(Set eventSet){ + data = new ArrayList>(); + List X = new ArrayList(); + for(Event aktEvent : eventSet){ + X.add(aktEvent.toString()); + } + data.add(X); + } + + /** + * @return amount of columns + */ + @Override + public int getColumnCount() { + return data.size(); + } + + /** + * @return amount of rows + */ + @Override + public int getRowCount() { + return data.get(0).size(); + } + + /** + * set the index of the first column + * @param index + */ + public void setIndex(int index){ + this.index = index; + } + + /** + * @param row + * @param column + * @return object in the chosen cell + */ + @Override + public Object getValueAt(int row, int column) { + if (column < getColumnCount()){ + if (row < data.get(column).size()){ + return data.get(column).get(row); + } + } + return null; + } + + /** + * adds a blank column + */ + public void addColumn(){ + List p = new ArrayList(); + for(int i=0; i column) && (column>0)){ + data.remove(column); + } + } + + /** + * Returns the Name of the Column. + * @param columnIndex + * @return name of the column + */ + @Override + public String getColumnName(int columnIndex){ + if (columnIndex >= 0 && columnIndex < this.getColumnCount()){ + if (columnIndex==0){ + return Messages.getString("em", "TableViewPanel.Event"); + } else if (columnIndex % 3 == 0) { + return "p" + ((index * 3 + columnIndex - 1) / 3) + ""; + } else if (columnIndex % 3 == 1) { + return "d" + ((index * 3 + columnIndex - 1) / 3) + ""; + } else + return "h" + ((index * 3 + columnIndex - 1) / 3) + ""; + } else + return null; + } + + /** + * @return returns always false (cell is not editable) + */ + @Override + public boolean isCellEditable(int rowIndex, int columnIndex){ + return false; + } + + /** + * Set value of a cell and updates table. + * @param value + * @param rowIndex + * @param columnIndex + */ + @Override + public void setValueAt(Object value, int rowIndex, int columnIndex){ + try { + double px = Double.parseDouble(((String) value)); + + data.get(columnIndex).set(rowIndex, String.format("%.9f", px)); + fireTableCellUpdated( rowIndex, columnIndex ); + } + catch (IllegalFormatPrecisionException e) { + data.get(columnIndex).set(rowIndex, (String) value); + fireTableCellUpdated( rowIndex, columnIndex ); + } + catch (NumberFormatException e) { + data.get(columnIndex).set(rowIndex, (String) value); + fireTableCellUpdated(rowIndex, columnIndex); + } + } +} diff --git a/src/org/jalgo/module/em/gui/output/table/TableModelLike.java b/src/org/jalgo/module/em/gui/output/table/TableModelLike.java new file mode 100644 index 0000000..ef9bd00 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/TableModelLike.java @@ -0,0 +1,159 @@ +package org.jalgo.module.em.gui.output.table; + +import java.util.ArrayList; +import java.util.IllegalFormatPrecisionException; +import java.util.List; + +import javax.swing.table.AbstractTableModel; + +/** + * Stores the Content of the Table in an List> + * + * @author Meinhardt Branig + */ +public class TableModelLike extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + + private List data; + private int index = 0; + private String log = ""; + + /** + * initializes the table + */ + public TableModelLike() { + data = new ArrayList(); + String X = " "; + data.add(X); + } + + /** + * @return amount of columns + */ + @Override + public int getColumnCount() { + return data.size(); + } + + /** + * Returns the value for the cell at {@code row} and {@code column}. + * + * @param row + * the row whose value is to be queried + * @param column + * the column whose value is to be queried + * @return object in the chosen cell + */ + @Override + public Object getValueAt(int row, int column) { + if (column < getColumnCount()) { + return data.get(column); + + } + return null; + } + + /** + * adds a blank column + */ + public void addColumn() { + String p = " "; + data.add(p); + } + + /** + * removes the column at the specified index {@code column}. + * + * @param column + * the index of the column that is to be removed + */ + public void removeColumn(int column) { + if ((getColumnCount() > column) && (column > 0)) { + data.remove(column); + } + } + + /** + * set the index of the first column + * @param index + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * change between Likelihood and logarithmic Likelihood + * @param set + */ + public void setLog(boolean set) { + if (set) { + log = "log"; + } else { + log = ""; + } + } + + /** + * + * @param columnIndex + * @return name of the column + */ + @Override + public String getColumnName(int columnIndex) { + if (columnIndex >= 0 && columnIndex < this.getColumnCount()) { + if (columnIndex == 0) { + return ""+log + " L "; + } + // else return "L "+((Integer) index[columnIndex-1]).toString(); + // else return "L "+index[columnIndex]; + else + return ""+log + " L" + (index + columnIndex - 1) + ""; + } + return null; + } + + /** + * Returns false for every cell. + * + * @return {@code false} - no cell editable + */ + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + /** + * Set the value of a cell and updates the table. + * + * @param value the new value + * @param rowIndex the row whose value is to be changed + * @param columnIndex the column whose value is to be changed + */ + @Override + public void setValueAt(Object value, int rowIndex, int columnIndex) { + try { + double px = Double.parseDouble(((String) value)); + data.set(columnIndex, String.format("%.30f", px)); + fireTableCellUpdated(rowIndex, columnIndex); + } + catch (IllegalFormatPrecisionException e) { + data.set(columnIndex, (String) value); + fireTableCellUpdated(rowIndex, columnIndex); + } + catch (NumberFormatException e) { + data.set(columnIndex, (String) value); + fireTableCellUpdated(rowIndex, columnIndex); + } + } + + /** + * Returns the number of rows. As the likelihood table is only one single row the return value is 1 always. + * + * @return amount of rows, always 1 for {@code TableModelLike} + */ + @Override + public int getRowCount() { + return 1; + } +} diff --git a/src/org/jalgo/module/em/gui/output/table/TableModelSE.java b/src/org/jalgo/module/em/gui/output/table/TableModelSE.java new file mode 100644 index 0000000..3425606 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/TableModelSE.java @@ -0,0 +1,156 @@ +package org.jalgo.module.em.gui.output.table; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.IllegalFormatPrecisionException; +import java.util.List; + +import javax.swing.table.AbstractTableModel; + +import org.jalgo.module.em.control.LogState; + +public class TableModelSE extends AbstractTableModel{ + /** + * Stores the Content of the Table in an List> + * @author Meinhardt Branig + */ + private static final long serialVersionUID = 1L; + private List> data; + private int index = 0; + private LogState log; + private int objectIndex; + + /** + * initializes the table + * @param log + * @param objectIndex + */ + public TableModelSE(LogState log, int objectIndex){ + this.log = log; + this.objectIndex = objectIndex; + data = new ArrayList>(); + List X = new ArrayList(); + + for (int objectSide = 1; objectSide <= log.getExperiment() + .get(objectIndex); objectSide++) { + X.add(log.singleEventToString(new Point(objectSide, objectIndex))); + } + + data.add(X); + } + + /** + * @return amount of columns + */ + @Override + public int getColumnCount() { + return data.size(); + } + + /** + * @return amount of rows + */ + @Override + public int getRowCount() { + return data.get(0).size(); + } + + public void setIndex(int index){ + this.index = index; + } + + /** + * @param row + * @param column + * @return object in the chosen cell + */ + @Override + public Object getValueAt(int row, int column) { + if (column < getColumnCount()){ + if (row < data.get(column).size()){ + return data.get(column).get(row); + } + } + return null; + } + + /** + * adds a blank column + */ + public void addColumn(){ + List p = new ArrayList(); + for(int i=0; i column) && (column>0)){ + data.remove(column); + } + } + + /** + * + * @param columnIndex + * @return name of the column + */ + @Override + public String getColumnName(int columnIndex){ + if (columnIndex >= 0 && columnIndex < this.getColumnCount()){ + if (columnIndex==0){ + return log.getObjectNames()[objectIndex]; + } + else { + return " p" + (index + columnIndex - 1) + ""; + } + } + + else return null; + } + + /** + * @return returns always false (cell is not editable) + */ + @Override + public boolean isCellEditable(int rowIndex, int columnIndex){ + return false; + } + + /** + * set value of a cell and updates table + * @param value + * @param rowIndex + * @param columnIndex + */ + @Override + public void setValueAt(Object value, int rowIndex, int columnIndex){ +// try { +// double px = Double.parseDouble(((String) value)); +// +// data.get(columnIndex).set(rowIndex, (String) value); +// fireTableCellUpdated( rowIndex, columnIndex ); +// } +// catch (NumberFormatException e) { +// } + try { + double px = Double.parseDouble(((String) value)); + + data.get(columnIndex).set(rowIndex, String.format("%.30f", px)); + fireTableCellUpdated( rowIndex, columnIndex ); + } + catch (IllegalFormatPrecisionException e) { + data.get(columnIndex).set(rowIndex, (String) value); + fireTableCellUpdated( rowIndex, columnIndex ); + } + catch (NumberFormatException e) { + data.get(columnIndex).set(rowIndex, (String) value); + fireTableCellUpdated(rowIndex, columnIndex); + } + } +} diff --git a/src/org/jalgo/module/em/gui/output/table/TableViewPanel.java b/src/org/jalgo/module/em/gui/output/table/TableViewPanel.java new file mode 100644 index 0000000..f8b99a1 --- /dev/null +++ b/src/org/jalgo/module/em/gui/output/table/TableViewPanel.java @@ -0,0 +1,586 @@ +package org.jalgo.module.em.gui.output.table; + +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Point; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.JTableHeader; + +import org.jalgo.module.em.control.LogState; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.gui.UIConstants; + +/** + * Table View Panel + * @author Meinhardt Branig + */ +public class TableViewPanel extends JPanel{ + /** + * + */ + private static final long serialVersionUID = 1L; + + private JScrollPane[] tblPanelLike; + private JScrollPane[][] tblPanelSE; + private JScrollPane[] tblPanel; + private TableModelLike[] tblModLike; + private TableModelSE[][] tblModSE; + private TableModel[] tblMod; + private JTable[] tblLike; + private JTable[][] tblSE; + private JTable[] tbl; + private LogState log; + private int shownum = 4; //number of shown steps + private int index; //Index der ersten Spalte z.B. p0|d0|h0||p1|d1|h1||... + private int click = 0; + private boolean beam; + + private MouseAdapter tableSizingListener = null; + + private int TABLE_ROW_PADDING = 10; + + + public class ColumnHeaderListener extends MouseAdapter { + public void mouseClicked(MouseEvent evt) { + click = (click +1) %4; + clickLike(); + tableSizingListener.mouseClicked(null); + } + } + + /** + * switch on or off the presentation mode + * @param beam + */ + public void setBeamerMode(boolean beam) { + this.beam = beam; + sizeTable(); + } + + /** + * set the number of shown columns + * @param number of shown columns + */ + public void setShownum(int shownum) { + this.shownum = shownum; + //initializes the tables + for (int i=0; i<=(log.getP0Count()-1); i++ ){ + this.drawTbl(i); + } + clickLike(); + updateUI(); + } + + /** + * TableViewPanel only displays the Likelihood table + */ + public void setViewLike() { + click = 0; + this.removeAll(); + GridBagLayout gridbag = new GridBagLayout(); + this.setLayout(gridbag); + GridBagConstraints c = new GridBagConstraints(); + + for (int num=0; num<=(log.getP0Count()-1); num++ ){ + c.gridx=0; + c.gridy=num; + this.add(tblPanelLike[num], c); + } + + this.updateUI(); + } + + /** + * TableViewPanel displays the Likelihood table and the SingleEvent table + */ + public void setViewLikeSingle() { + click = 1; + this.removeAll(); + GridBagLayout gridbag = new GridBagLayout(); + this.setLayout(gridbag); + GridBagConstraints c = new GridBagConstraints(); + + int anzSE=0; + for (int num=0; num<=(log.getP0Count()-1); num++ ){ + c.gridx=0; + c.gridy=2*num+anzSE; + this.add(tblPanelLike[num], c); + for (int i=0; i 0) {fullSteps = shownum - 2;} + else {fullSteps = shownum-1;} + + if (steps < fullSteps){ + fullSteps = steps; + } + + /*---kleine anzuzeigende Schritte ausrechnen---*/ + if ((steps < shownum) && (singleSteps == 0)) {firstStep = 0;} + else {firstStep = steps - fullSteps;} + + index = firstStep; + + for (int num = 0; num<=(log.getP0Count() -1); num++){ //für jede P0-Tabelle + curStep = firstStep; //aktueller Schritt ist am Anfang der erste + /*----fill full steps----*/ + for (int col=0; (col) <= fullSteps; col++){ + tblModLike[num].setValueAt((log.getL(num, curStep)).toString(), 0, col+1); + for (int i=0; i d,h,p; + private Map pForSingleEvent; + private Map pForPartition; + private double likelihood; + + @Override + protected void setUp() throws Exception { + //Creating Events + Set events = new HashSet(); + Vector kkEventVector = new Vector(3); + Vector kzEventVector = new Vector(3); + Vector zkEventVector = new Vector(3); + Vector zzEventVector = new Vector(3); + kkEventVector.setSize(2); + kzEventVector.setSize(2); + zkEventVector.setSize(2); + zzEventVector.setSize(2); + + kkEventVector.setElementAt(2, 0); + kkEventVector.setElementAt(2, 1); + kzEventVector.setElementAt(2, 0); + kzEventVector.setElementAt(1, 1); + zkEventVector.setElementAt(1, 0); + zkEventVector.setElementAt(2, 1); + zzEventVector.setElementAt(1, 0); + zzEventVector.setElementAt(1, 1); + + Event kkEvent = new Event(kkEventVector); + Event kzEvent = new Event(kzEventVector); + Event zkEvent = new Event(zkEventVector); + Event zzEvent = new Event(zzEventVector); + + events.add(zzEvent); + events.add(zkEvent); + events.add(kzEvent); + events.add(kkEvent); + + p = new HashMap(); + double pValue = 0.0; + for (Event event : events){ + p.put(event, pValue); + pValue += 1.0; + } + + d = new HashMap(); + for (Event event : events){ + d.put(event, pValue); + pValue += 1.0; + } + + h = new HashMap(); + for (Event event : events){ + h.put(event, pValue); + pValue += 1.0; + } + + + Set elements1 = new HashSet(); + Set elements2 = new HashSet(); + Set elements3 = new HashSet(); + + elements1.add(kkEvent); + elements2.add(kzEvent); + elements2.add(zkEvent); + elements3.add(zzEvent); + + Partition partition1 = new Partition(elements1, "0 mal Zahl"); //KK; h = 2 + Partition partition2 = new Partition(elements2, "1 mal Zahl"); //KZ , ZK; h = 9 + Partition partition3 = new Partition(elements3, "2 mal Zahl"); //ZZ; h = 4 + Set partitions = new HashSet(); + partitions.add(partition1); + partitions.add(partition2); + partitions.add(partition3); + + pForPartition = new HashMap(); + pValue = 0.0; + for (Partition partition : partitions){ + pForPartition.put(partition, pValue); + pValue += 1.0; + } + + + likelihood = 17.3; + + pForSingleEvent = new HashMap(); + pForSingleEvent.put(new Point(2,0), 0.5); + pForSingleEvent.put(new Point(1,0), 0.5); + pForSingleEvent.put(new Point(2,1), 0.5); + pForSingleEvent.put(new Point(1,1), 0.5); + instance = new EMData(d, h, p, pForPartition, pForSingleEvent, likelihood); + + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test of getP method, of class EMData. + */ + public void testGetP() { + Map expResult = p; + Map result = instance.getP(); + for (Event event : expResult.keySet()){ + assertEquals(expResult.get(event), result.get(event)); + } + } + + /** + * Test of getD method, of class EMData. + */ + public void testGetD() { + Map expResult = d; + Map result = instance.getD(); + assertEquals(expResult, result); + } + + /** + * Test of getH method, of class EMData. + */ + public void testGetH() { + Map expResult = h; + Map result = instance.getH(); + assertEquals(expResult, result); + } + + /** + * Test of getPForPartition method, of class EMData. + */ + public void testGetPForPartition() { + Map expResult = pForPartition; + Map result = instance.getPForPartition(); + assertEquals(expResult, result); + } + + /** + * Test of getPForSingleEvent method, of class EMData. + */ + public void testGetPForSingleEvent() { + Map expResult = pForSingleEvent; + Map result = instance.getPForSingleEvent(); + assertEquals(expResult, result); + } + + /** + * Test of getLikelihood method, of class EMData. + */ + public void testGetLikelihood() { + Double expResult = likelihood; + Double result = instance.getLikelihood(); + assertEquals(expResult, result); + } +} diff --git a/src/org/jalgo/module/em/test/EMModuleTest.java b/src/org/jalgo/module/em/test/EMModuleTest.java new file mode 100644 index 0000000..d40f39e --- /dev/null +++ b/src/org/jalgo/module/em/test/EMModuleTest.java @@ -0,0 +1,223 @@ +package org.jalgo.module.em.test; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.jalgo.module.em.control.EMModule; +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; +import org.junit.Test; + +/** + * Test class for the {@code EMModule} class. + * + */ +public class EMModuleTest extends TestCase { + private StartParameters startParameters; + private EMState p0EMState; + private Event kkEvent; + private Event kzEvent; + private Event zkEvent; + private Event zzEvent; + private Map singleEventStartProbability; + + @Override + protected void setUp() throws Exception { + super.setUp(); + startParameters = new StartParameters(); + + // Creating Events + Set events = new HashSet(); + Vector kkEventVector = new Vector(3); + Vector kzEventVector = new Vector(3); + Vector zkEventVector = new Vector(3); + Vector zzEventVector = new Vector(3); + kkEventVector.setSize(2); + kzEventVector.setSize(2); + zkEventVector.setSize(2); + zzEventVector.setSize(2); + + kkEventVector.setElementAt(2, 0); + kkEventVector.setElementAt(2, 1); + kzEventVector.setElementAt(2, 0); + kzEventVector.setElementAt(1, 1); + zkEventVector.setElementAt(1, 0); + zkEventVector.setElementAt(2, 1); + zzEventVector.setElementAt(1, 0); + zzEventVector.setElementAt(1, 1); + + kkEvent = new Event(kkEventVector); + kzEvent = new Event(kzEventVector); + zkEvent = new Event(zkEventVector); + zzEvent = new Event(zzEventVector); + + events.add(zzEvent); + events.add(zkEvent); + events.add(kzEvent); + events.add(kkEvent); + + Vector experimentVector = new Vector(); + experimentVector.setSize(2); + experimentVector.set(0, 2); + experimentVector.set(1, 2); + startParameters.setExperiment(experimentVector); + + startParameters.setEvents(events); + Set elements1 = new HashSet(); + Set elements2 = new HashSet(); + Set elements3 = new HashSet(); + + elements1.add(kkEvent); + elements2.add(kzEvent); + elements2.add(zkEvent); + elements3.add(zzEvent); + + // Creating Partitions + Partition partition1 = new Partition(elements1, "0 mal Zahl"); // KK; h + // = 2 + Partition partition2 = new Partition(elements2, "1 mal Zahl"); // KZ , + // ZK; h + // = 9 + Partition partition3 = new Partition(elements3, "2 mal Zahl"); // ZZ; h + // = 4 + + partition1.setFrequency(2); + partition2.setFrequency(9); + partition3.setFrequency(4); + + Set observations = new HashSet(); + observations.add(partition1); + observations.add(partition2); + observations.add(partition3); + startParameters.setObservations(observations); + + // Set Yield + for (Partition partition : startParameters.getObservations()) { + for (Event event : partition.getElements()) { + event.setYield(partition); + } + } + + List p0DataList = new ArrayList(); + + // Creating p0 Distributions + // p0 No. 1 + singleEventStartProbability = new HashMap(); + singleEventStartProbability.put(new Point(2, 0), 0.5); + singleEventStartProbability.put(new Point(1, 0), 0.5); + singleEventStartProbability.put(new Point(2, 1), 0.5); + singleEventStartProbability.put(new Point(1, 1), 0.5); + EMData p0Data = EMModule.calcFirstStep(singleEventStartProbability, + startParameters); + + p0DataList.add(p0Data); + + // p0 No. 2 + Map singleEventStartProbability2 = new HashMap(); + singleEventStartProbability2.put(new Point(2, 0), 0.3); + singleEventStartProbability2.put(new Point(1, 0), 0.7); + singleEventStartProbability2.put(new Point(2, 1), 0.4); + singleEventStartProbability2.put(new Point(1, 1), 0.6); + EMData p0Data2 = EMModule.calcFirstStep(singleEventStartProbability2, + startParameters); + p0DataList.add(p0Data2); + + // p0 No. 3 + Map singleEventStartProbability3 = new HashMap(); + singleEventStartProbability3.put(new Point(2, 0), 0.1); + singleEventStartProbability3.put(new Point(1, 0), 0.9); + singleEventStartProbability3.put(new Point(2, 1), 0.2); + singleEventStartProbability3.put(new Point(1, 1), 0.8); + EMData p0Data3 = EMModule.calcFirstStep(singleEventStartProbability3, + startParameters); + p0DataList.add(p0Data3); + + p0EMState = new EMState(p0DataList); + startParameters.setP0EMState(p0EMState); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test method for + * {@link org.jalgo.module.em.control.EMModule#calcNextEMData(EMData, int, StartParameters)} + * . + */ + @Test + public void testCalcNextEMData() { + EMData data0 = EMModule.calcNextEMData(p0EMState.getEMData().get(0), 0, + startParameters); + // Testing Calculation of D + double[] dArray = { 1.0, 0.5, 0.5, 1.0 }; + assertEquals(dArray[0], data0.getD().get(kkEvent)); + assertEquals(dArray[1], data0.getD().get(kzEvent)); + assertEquals(dArray[2], data0.getD().get(zkEvent)); + assertEquals(dArray[3], data0.getD().get(zzEvent)); + + // Testing Calculation of H + double[] hArray = { 2.0, 4.5, 4.5, 4.0 }; + assertEquals(hArray[0], data0.getH().get(kkEvent)); + assertEquals(hArray[1], data0.getH().get(kzEvent)); + assertEquals(hArray[2], data0.getH().get(zkEvent)); + assertEquals(hArray[3], data0.getH().get(zzEvent)); + + // Testing Calculation of P + double[] pArray = { (6.5 * 6.5) / 225.0, 6.5 * 8.5 / 225.0, + 6.5 * 8.5 / 225.0, 8.5 * 8.5 / 225.0 }; + assertEquals(true, + Math.abs(pArray[0] - data0.getP().get(kkEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[1] - data0.getP().get(kzEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[2] - data0.getP().get(zkEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[3] - data0.getP().get(zzEvent)) < 0.0001); + + // Testing Calculation of Likelihood + assertEquals( + true, + Math.abs(6.2306e-007 - Math.pow(10, data0.getLikelihood())) < 0.00000000001); + + } + + /** + * Test method for + * {@link org.jalgo.module.em.control.EMModule#calcFirstStep(Map, StartParameters)} + * . + */ + @Test + public void testCalcFirstStep() { + EMData data0 = EMModule.calcFirstStep(singleEventStartProbability, + startParameters); + // Testing Calculation of P + double[] pArray = { 0.25, 0.25, 0.25, 0.25 }; + assertEquals(true, + Math.abs(pArray[0] - data0.getP().get(kkEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[1] - data0.getP().get(kzEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[2] - data0.getP().get(zkEvent)) < 0.0001); + assertEquals(true, + Math.abs(pArray[3] - data0.getP().get(zzEvent)) < 0.0001); + + // Testing Calculation of Likelihood + assertEquals( + true, + Math.abs(4.76837158e-007 - Math.pow(10, data0.getLikelihood())) < 0.000000000000001); + + } +} diff --git a/src/org/jalgo/module/em/test/EMStateTest.java b/src/org/jalgo/module/em/test/EMStateTest.java new file mode 100644 index 0000000..53e1865 --- /dev/null +++ b/src/org/jalgo/module/em/test/EMStateTest.java @@ -0,0 +1,43 @@ +package org.jalgo.module.em.test; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; + +/** + * @author kilian + */ +public class EMStateTest extends TestCase { + private List emDataList; + private EMState eMDataTestInstance; + + @Override + protected void setUp() throws Exception { + emDataList = new ArrayList(); + for (int i = 0; i<5; i++){ + emDataList.add(new EMData(null, null, null, null, null, null)); + } + eMDataTestInstance = new EMState(emDataList); + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test of getEMData method, of class EMState. + */ + public void testGetEMData() { +// System.out.println("getEMData"); + EMState instance = eMDataTestInstance; + List expResult = emDataList; + List result = instance.getEMData(); + assertEquals(expResult, result); + } +} diff --git a/src/org/jalgo/module/em/test/EventTest.java b/src/org/jalgo/module/em/test/EventTest.java new file mode 100644 index 0000000..398173b --- /dev/null +++ b/src/org/jalgo/module/em/test/EventTest.java @@ -0,0 +1,143 @@ +/** + * + */ +package org.jalgo.module.em.test; + +import java.util.Vector; + +import junit.framework.TestCase; + +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.junit.Before; +import org.junit.Test; + +/** + * Test class for the Event class. Test all constructors and methods. + * + * @author Tobias Nett + * + */ +public class EventTest extends TestCase{ + + private Event event, eventLess, eventGreater; + private Vector tuple, tupleLess, tupleGreater; + private Partition partition; + + /** + * Initializes the test elements. Creates a new tuple (1,2,3) and creates an Event out of + * this tuple. + * Creates a new empty Partition. + */ + @Before + public void setUp(){ + tuple = new Vector(); + tupleLess = new Vector(); + tupleGreater = new Vector(); + // create an event vector: (1,2,3) + for (int i = 1; i < 4; i++){ + tuple.add(i); + tupleLess.add(1); + tupleGreater.add(i+1); + } + // create the event + event = new Event(tuple); + eventLess = new Event(tupleLess); + eventGreater = new Event(tupleGreater); + // create the (empty) partition + partition = new Partition(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#Event(java.util.Vector)}. + *

          Constructor test method. The tuple should be the passed tuple, the yield should be null. + * + */ + @Test + public void testEvent() { + assertEquals(tuple, event.getTuple()); + assertEquals(null, event.getYield()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#setYield(org.jalgo.module.em.data.Partition)}. + *

          The event's yield should be the Partition which is transfered to the method. + */ + @Test + public void testSetYield() { + event.setYield(partition); + assertEquals(partition, event.getYield()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#setYield(org.jalgo.module.em.data.Partition)}. + *

          The event's yield should be null (event is not part of any partition anymore). + */ + @Test + public void testSetNullYield() { + event.setYield(null); + assertEquals(null, event.getYield()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#clearYield()}. + *

          clearYield should set the event's yield to null (event is not part of any partition anymore). + */ + @Test + public void testClearYield() { + event.setYield(partition); + assertEquals(partition, event.getYield()); + event.clearYield(); + assertEquals(null, event.getYield()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#toString()}. + *

          The String representation of the event should be in the form + * "(x1,x2,x3,...)" with space after + * each comma. + */ + @Test + public void testToString() { + String expected = "(1, 2, 3)"; + assertEquals(expected, event.toString()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#getYield()}. + *

          Should return null after the event is created and the + * yielded partition after the yield is set. + */ + @Test + public void testGetYield() { + assertEquals(null, event.getYield()); + event.setYield(partition); + assertEquals(partition, event.getYield()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Event#getTuple()}. + *

          Should return the event represented as a tuple + * (Vector of Integer). + */ + @Test + public void testGetTuple() { + assertEquals(tuple, event.getTuple()); + } + /** + * Test method for {@link org.jalgo.module.em.data.Event#compareTo(Event)}. + *

          Compares the event (1,2,3) to the events (1,1,1) and (2,3,4) - method + * to test should return 0, a value less and and a value greater 0. + */ + @Test + public void testComparable(){ + assertEquals(0, event.compareTo(event)); + assertEquals(true, event.compareTo(eventGreater)<0); + assertEquals(true, event.compareTo(eventLess)>0); + } + +} diff --git a/src/org/jalgo/module/em/test/LogStateTest.java b/src/org/jalgo/module/em/test/LogStateTest.java new file mode 100644 index 0000000..9feb9e6 --- /dev/null +++ b/src/org/jalgo/module/em/test/LogStateTest.java @@ -0,0 +1,64 @@ +package org.jalgo.module.em.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class LogStateTest { + + @Test + public void testGetL() { + fail("Not yet implemented"); + } + + @Test + public void testGetPSingleEvent() { + fail("Not yet implemented"); + } + + @Test + public void testGetD() { + fail("Not yet implemented"); + } + + @Test + public void testGetH() { + fail("Not yet implemented"); + } + + @Test + public void testGetP() { + fail("Not yet implemented"); + } + + @Test + public void testGetL3DGraph() { + fail("Not yet implemented"); + } + + @Test + public void testActivate3D() { + fail("Not yet implemented"); + } + + @Test + public void testGetP0Count() { + fail("Not yet implemented"); + } + + @Test + public void testGetYield() { + fail("Not yet implemented"); + } + + @Test + public void testGetStepCount() { + fail("Not yet implemented"); + } + + @Test + public void testGetSingleStepCount() { + fail("Not yet implemented"); + } + +} diff --git a/src/org/jalgo/module/em/test/PartitionTest.java b/src/org/jalgo/module/em/test/PartitionTest.java new file mode 100644 index 0000000..d7d3ad1 --- /dev/null +++ b/src/org/jalgo/module/em/test/PartitionTest.java @@ -0,0 +1,266 @@ +/** + * + */ +package org.jalgo.module.em.test; + +import java.util.HashSet; +import java.util.Set; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Tobias Nett + * + */ +public class PartitionTest extends TestCase { + + private static final double DELTA = 0.001; + + private Partition partition; + private Set elements; + private String name; + private Event kk,kz,zk,zz; + + @Before + public void setUp(){ + elements = new HashSet(); + // create Events + Vector v = new Vector(); + v.add(1); v.add(1); + kk = new Event(v); + v = new Vector(); + v.add(1); v.add(2); + kz = new Event(v); + v = new Vector(); + v.add(2); v.add(1); + zk = new Event(v); + v = new Vector(); + v.add(2); v.add(2); + zz = new Event(v); + + elements.add(kk); + elements.add(kz); + elements.add(zk); + elements.add(zz); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#Partition()}. + */ + @Test + public void testPartition() { + partition = new Partition(); + assertEquals("Eine leere Partition ohne Namen soll erzeugt werden", + "" , partition.getName()); + assertEquals("Eine leere Partition mit Häufigkeit 0 soll erzeugt werden", + 0, partition.getFrequency(), DELTA); + assertEquals("Eine leere Partition ohne zugeordnete Elemente soll erzeugt werden", + true, partition.getElements().isEmpty()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#Partition(java.util.Set)}. + */ + @Test + public void testPartitionSetOfEvent() { + partition = new Partition(elements); + assertEquals("Eine Partition ohne Namen soll erzeugt werden", + "" , partition.getName()); + assertEquals("Eine Partition mit Häufigkeit 0 soll erzeugt werden", + 0, partition.getFrequency(), DELTA); + assertEquals("Die Partition soll die übergebenen Elemente enhalten.", + elements, partition.getElements()); + + try { + partition = new Partition(null); + fail("null argument should raise NPE"); + } catch (NullPointerException e) { } + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#Partition(java.util.Set, java.lang.String)}. + */ + @Test + public void testPartitionSetOfEventString() { + name = "TestName"; + partition = new Partition(elements, name); + assertEquals("Eine Partition mit Name und Elementen soll erzeugt werden", + name , partition.getName()); + assertEquals("Eine Partition mit Häufigkeit 0 soll erzeugt werden", + 0, partition.getFrequency(), DELTA); + assertEquals("Die Partition soll die übergebenen Elemente enhalten.", + elements, partition.getElements()); + // if the name is null, a null pointer exception should be raised + try { + partition = new Partition(elements, null); + fail("null argument should raise NPE"); + } catch (NullPointerException e) { } + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#addElement(org.jalgo.module.em.data.Event)}. + */ + @Test + public void testAddElement() { + partition = new Partition(); + partition.addElement(zk); + // adding an element to the partition + assertEquals("Die Partition muss das hinzugefügte Element enhalten.", true, partition.getElements().contains(zk)); + Set rest = partition.getElements(); + rest.remove(zk); + // only one element should be added to the partition + assertEquals("Die Partition sollte keine weiteren Elemente enthalten", true, rest.isEmpty()); + // an element could only once be added to a partition + partition = new Partition(); + partition.addElement(zk); + partition.addElement(zk); + assertEquals("Event darf nur einmal hinzugefügt werden", 1, partition.getElements().size()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#removeElement(org.jalgo.module.em.data.Event)}. + */ + @Test + public void testRemoveElement() { + partition = new Partition(elements); + partition.removeElement(zk); + assertEquals("Anzahl der Elemente muss kleiner werden", 3, partition.getElements().size()); + assertEquals("Entferntes Element darf nich mehr enthalten sein", false, partition.getElements().contains(zk)); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#getName()}. + */ + @Test + public void testGetName() { + partition = new Partition(); + assertEquals("", partition.getName()); + partition.setName("TestName"); + assertEquals("TestName", partition.getName()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#setName(java.lang.String)}. + */ + @Test + public void testSetName() { + partition = new Partition(); + String name = "TestName"; + partition.setName(name); + assertEquals(name, partition.getName()); + try { + partition.setName(null); + fail("null argument should raise NPE"); + } catch (NullPointerException e) { } + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#getFrequency()}. + */ + @Test + public void testGetFrequency() { + partition = new Partition(); + assertEquals(0, partition.getFrequency(), DELTA); + partition.setFrequency(Double.MAX_VALUE); + assertEquals(Double.MAX_VALUE, partition.getFrequency(), DELTA); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#setFrequency(double)}. + */ + @Test + public void testSetFrequency() { + + partition = new Partition(); + partition.setFrequency(Double.MAX_VALUE); + assertEquals(Double.MAX_VALUE, partition.getFrequency(), DELTA); + + partition.setFrequency(0); + assertEquals(0, partition.getFrequency(), DELTA); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#setFrequency(double)}. + */ + @Test (expected = IllegalArgumentException.class) + public void testNegativeFrequency() { + final int NEGATIVE_FREQUENCY = -3; + partition = new Partition(); + try { + partition.setFrequency(NEGATIVE_FREQUENCY); + fail("Negative amount should raise IllegalArgumentException"); + } catch (IllegalArgumentException e) { + + } + + + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#getElements()}. + */ + @Test + public void testGetElements() { + partition = new Partition(elements); + assertEquals(elements, partition.getElements()); + partition = new Partition(new HashSet()); + assertEquals(true, partition.getElements().isEmpty()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#toString()}. + */ + @Test + public void testToString() { + partition = new Partition(); + assertEquals("empty", partition.toString()); + partition = new Partition(elements, "TestName"); + + String expected = "TestName
          { (1, 1), (1, 2), (2, 1), (2, 2) }"; + assertEquals(expected, partition.toString()); + + assertEquals(true, partition.toString().startsWith("")); + assertEquals(true, partition.toString().endsWith("")); + + assertEquals(true, partition.toString().contains("{ (")); + assertEquals(true, partition.toString().contains(") }")); + + assertEquals(true, partition.toString().contains(partition.getName())); + + assertEquals(true, partition.toString().contains("(1, 1)")); + assertEquals(true, partition.toString().contains("(1, 2)")); + assertEquals(true, partition.toString().contains("(2, 1)")); + assertEquals(true, partition.toString().contains("(2, 2)")); + + assertEquals(66, partition.toString().length()); + } + + /** + * Test method for {@link org.jalgo.module.em.data.Partition#getMathSet()}. + */ + public void testGetMathSet(){ + partition = new Partition(elements); + + assertEquals(true, partition.getMathSet().startsWith("{ ")); + assertEquals(true, partition.getMathSet().endsWith(" }")); + + assertEquals(true, partition.toString().contains("(1, 1)")); + assertEquals(true, partition.toString().contains("(1, 2)")); + assertEquals(true, partition.toString().contains("(2, 1)")); + assertEquals(true, partition.toString().contains("(2, 2)")); + + assertEquals(34, partition.getMathSet().length()); + } +} + diff --git a/src/org/jalgo/module/em/test/StartParametersTest.java b/src/org/jalgo/module/em/test/StartParametersTest.java new file mode 100644 index 0000000..94fd9aa --- /dev/null +++ b/src/org/jalgo/module/em/test/StartParametersTest.java @@ -0,0 +1,297 @@ +package org.jalgo.module.em.test; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import junit.framework.TestCase; + +import org.jalgo.module.em.control.EMModule; +import org.jalgo.module.em.data.EMData; +import org.jalgo.module.em.data.EMState; +import org.jalgo.module.em.data.Event; +import org.jalgo.module.em.data.Partition; +import org.jalgo.module.em.data.StartParameters; + +/** + * + * @author Kilian + */ +public class StartParametersTest extends TestCase { + private StartParameters startParameters; + private Set events; + private EMState p0EMState; + private Set observations; + private Vector experimentVector; + + @Override + protected void setUp() throws Exception { + startParameters = new StartParameters(); + + //Creating Events + events = new HashSet(); + Vector kkEventVector = new Vector(3); + Vector kzEventVector = new Vector(3); + Vector zkEventVector = new Vector(3); + Vector zzEventVector = new Vector(3); + kkEventVector.setSize(2); + kzEventVector.setSize(2); + zkEventVector.setSize(2); + zzEventVector.setSize(2); + + kkEventVector.setElementAt(2, 0); + kkEventVector.setElementAt(2, 1); + kzEventVector.setElementAt(2, 0); + kzEventVector.setElementAt(1, 1); + zkEventVector.setElementAt(1, 0); + zkEventVector.setElementAt(2, 1); + zzEventVector.setElementAt(1, 0); + zzEventVector.setElementAt(1, 1); + + Event kkEvent = new Event(kkEventVector); + Event kzEvent = new Event(kzEventVector); + Event zkEvent = new Event(zkEventVector); + Event zzEvent = new Event(zzEventVector); + + events.add(zzEvent); + events.add(zkEvent); + events.add(kzEvent); + events.add(kkEvent); + + experimentVector = new Vector(); + experimentVector.setSize(2); + experimentVector.set(0, 2); + experimentVector.set(1, 2); + startParameters.setExperiment(experimentVector); + + startParameters.setEvents(events); + Set elements1 = new HashSet(); + Set elements2 = new HashSet(); + Set elements3 = new HashSet(); + + elements1.add(kkEvent); + elements2.add(kzEvent); + elements2.add(zkEvent); + elements3.add(zzEvent); + + //Creating Partitions + Partition partition1 = new Partition(elements1, "0 mal Zahl"); //KK; h = 2 + Partition partition2 = new Partition(elements2, "1 mal Zahl"); //KZ , ZK; h = 9 + Partition partition3 = new Partition(elements3, "2 mal Zahl"); //ZZ; h = 4 + + partition1.setFrequency(2); + partition2.setFrequency(9); + partition3.setFrequency(4); + + observations = new HashSet(); + observations.add(partition1); + observations.add(partition2); + observations.add(partition3); + startParameters.setObservations(observations); + + //Set Yield + for(Partition partition : startParameters.getObservations()){ + for (Event event : partition.getElements()){ + event.setYield(partition); + } + } + + + + + List p0DataList = new ArrayList(); + + //Creating p0 Distributions + // p0 No. 1 + Map singleEventStartProbability = new HashMap(); + singleEventStartProbability.put(new Point(2,0), 0.5); + singleEventStartProbability.put(new Point(1,0), 0.5); + singleEventStartProbability.put(new Point(2,1), 0.5); + singleEventStartProbability.put(new Point(1,1), 0.5); + EMData p0Data = EMModule.calcFirstStep(singleEventStartProbability, startParameters); + + p0DataList.add(p0Data); + + //p0 No. 2 + Map singleEventStartProbability2 = new HashMap(); + singleEventStartProbability2.put(new Point(2,0), 0.3); + singleEventStartProbability2.put(new Point(1,0), 0.7); + singleEventStartProbability2.put(new Point(2,1), 0.4); + singleEventStartProbability2.put(new Point(1,1), 0.6); + EMData p0Data2 = EMModule.calcFirstStep(singleEventStartProbability2, startParameters); + p0DataList.add(p0Data2); + + //p0 No. 3 + Map singleEventStartProbability3 = new HashMap(); + singleEventStartProbability3.put(new Point(2,0), 0.1); + singleEventStartProbability3.put(new Point(1,0), 0.9); + singleEventStartProbability3.put(new Point(2,1), 0.2); + singleEventStartProbability3.put(new Point(1,1), 0.8); + EMData p0Data3 = EMModule.calcFirstStep(singleEventStartProbability3, startParameters); + p0DataList.add(p0Data3); + + + p0EMState = new EMState(p0DataList); + startParameters.setP0EMState(p0EMState); + + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Test of getEvents method, of class StartParameters. + */ + public void testGetEvents() { +// System.out.println("getEvents"); + StartParameters instance = new StartParameters(); + Set expResult = null; + Set result = instance.getEvents(); + assertEquals(expResult, result); + + instance = startParameters; + expResult = events; + result = instance.getEvents(); + assertEquals(expResult, result); + + } + + /** + * Test of setEvents method, of class StartParameters. + */ + public void testSetEvents() { +// System.out.println("setEvents"); + Set events = this.events; + StartParameters instance = new StartParameters(); + instance.setEvents(events); + assertEquals(events, instance.getEvents()); + } + + /** + * Test of setP0EMState method, of class StartParameters. + */ + public void testSetP0EMState() { +// System.out.println("setP0EMState"); + EMState p0EMState = this.p0EMState; + StartParameters instance = new StartParameters(); + instance.setP0EMState(p0EMState); + assertEquals(p0EMState, instance.getP0EMState()); + } + + /** + * Test of getObservations method, of class StartParameters. + */ + public void testGetObservations() { +// System.out.println("getObservations"); + StartParameters instance = startParameters; + Set expResult = observations; + Set result = instance.getObservations(); + assertEquals(expResult, result); + } + + /** + * Test of setObservations method, of class StartParameters. + */ + public void testSetObservations() { +// System.out.println("setObservations"); + Set observations = this.observations; + StartParameters instance = new StartParameters(); + instance.setObservations(observations); + assertEquals(observations, instance.getObservations()); + } + + /** + * Test of getFrequencySum method, of class StartParameters. + */ + public void testGetFrequencySum() { +// System.out.println("getFrequencySum"); + StartParameters instance = startParameters; + double expResult = 0; + for (Partition partition : observations){ + expResult += partition.getFrequency(); + } + Double result = instance.getFrequencySum(); + assertEquals(new Double(expResult), result); + + } + + /** + * Test of getObjectCount method, of class StartParameters. + */ + public void testGetObjectCount() { +// System.out.println("getObjectCount"); + StartParameters instance = startParameters; + int expResult = experimentVector.size(); + int result = instance.getObjectCount(); + assertEquals(expResult, result); + } + + /** + * Test of getExperiment method, of class StartParameters. + */ + public void testGetExperiment() { +// System.out.println("getExperiment"); + StartParameters instance = this.startParameters; + Vector expResult = this.experimentVector; + Vector result = instance.getExperiment(); + assertEquals(expResult, result); + } + + /** + * Test of getP0EMState method, of class StartParameters. + */ + public void testGetP0EMState() { +// System.out.println("getP0EMState"); + StartParameters instance = this.startParameters; + EMState expResult = this.p0EMState; + EMState result = instance.getP0EMState(); + assertEquals(expResult, result); + } + + /** + * Test of getSingleExperiments method, of class StartParameters. + */ + public void testGetSingleExperiments() { +// System.out.println("getSingleExperiments"); + StartParameters instance = this.startParameters; + Set expResult = new HashSet(); + expResult.add(new Point(2,0)); + expResult.add(new Point(1,0)); + expResult.add(new Point(2,1)); + expResult.add(new Point(1,1)); + Set result = instance.getSingleExperiments(); + assertEquals(expResult, result); + } + + /** + * Test of setExperiment method, of class StartParameters. + */ + public void testSetExperiment() { +// System.out.println("setExperiment"); + Vector experiment = this.experimentVector; + StartParameters instance = new StartParameters(); + instance.setExperiment(experiment); + assertEquals(experiment, instance.getExperiment()); + } + + /** + * Test of getObjectNames method, of class StartParameters. + */ + public void testGetObjectNames() { +// System.out.println("getObjectNames"); + StartParameters instance = startParameters; + String[] expResult = {"!ObjectName!2 1", "!ObjectName!2 2"}; + String[] result = instance.getObjectNames(); + for (int i = 0; i)this.ctrl.getModel()).addListener(this); + // default: lecture mode + this.ctrl.setLecture(true); + } + + public void run() { + // start thread + thread = new Thread(new UpdateThread()); + thread.start(); + } + + public void dispose() { + state.dispose(); + thread = null; + renderer.dispose(); + } + + public void stateChanged() { + lecture.setSelected(ctrl.isLecture()); + state.updateButtons(); + } + + public void modelChanged() { + state.modelChanged(); + } + + private void setState(GState s) { + state.dispose(); + state = null; + state = s; + } + + private interface GState { + void updateButtons(); + void modelChanged(); + void dispose(); + } + + private class InputState implements GState { + + private JPanel inputPane; + private JLabel label; + private JTextField edit; + private JButton addButton; + private JButton startButton; + private JTextArea hints; + private boolean waserror = false; + + public InputState() { + inputPane = new JPanel(new GridBagLayout()); + inputPane.setBorder(BorderFactory.createTitledBorder(Util.getString("Gui.Input_title"))); + GridBagConstraints c = new GridBagConstraints(); + c.insets = new Insets(1,1,2,1); + + label = new JLabel(Util.getString("Gui.Input_label")); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + inputPane.add(label, c); + + edit = new JTextField(2); + edit.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if (!edit.getText().equals("")) { + addButton.doClick(); + edit.setText(""); + } + else + startButton.doClick(); + } + + }); + c.gridx = 2; + c.gridy = 0; + c.gridwidth = 1; + inputPane.add(edit, c); + + addButton = new JButton(Util.getString("Gui.Input_add")); + addButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + synchronized(root) { + try { + int i = Integer.parseInt(edit.getText()); + if ((i > 0) && (i < 100)) + ((org.jalgo.module.heapsort.model.Heapsort)ctrl.getModel()).addNumber(i); + if (waserror) { + hints.setText(""); + waserror = false; + } + } + catch (NumberFormatException e1) { + ; // just ignore non-numeric input + } + catch (IllegalArgumentException e1) { + hints.setText(Util.getString("Gui.Hint_double")); + waserror = true; + } + } + } + + }); + c.gridx = 0; + c.gridy = 1; + c.gridwidth = GridBagConstraints.REMAINDER; + inputPane.add(addButton, c); + + startButton = new JButton(Util.getString("Gui.Input_start")); + startButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + synchronized(root) { + ctrl.cont(); + setState(new DerivationState()); + } + } + + }); + c.gridx = 0; + c.gridy = 2; + inputPane.add(startButton, c); + + hints = new JTextArea(17, 10); + hints.setBackground(inputPane.getBackground()); + hints.setFont(label.getFont()); + hints.setEditable(false); + hints.setLineWrap(true); + hints.setWrapStyleWord(true); + hints.setText(Util.getString("Gui.Hint_instructions")); + c.gridx = 0; + c.gridy = 3; + c.fill = GridBagConstraints.HORIZONTAL; + c.insets = new Insets(12, 1, 1, 1); + inputPane.add(hints, c); + + rootPane.add(inputPane, BorderLayout.EAST); + edit.requestFocus(); + } + + public void dispose() { + rootPane.remove(inputPane); + inputPane.removeAll(); + inputPane = null; + label = null; + edit = null; + addButton = null; + startButton = null; + hints = null; + rootPane.validate(); + } + + public void updateButtons() { + addButton.setEnabled(ctrl.canModelChange() && + (((HeapsortState)ctrl.getCurrentState()).sequence.size() < 31)); + startButton.setEnabled(ctrl.isStepPossible()); + if (!ctrl.isStepPossible()) + edit.requestFocus(); + } + + public void modelChanged() { + if (((HeapsortState)ctrl.getCurrentState()).sequence.size() >= 31) { + hints.setText(Util.getString("Gui.Hint_limit")); + addButton.setEnabled(false); + } + } + + } + + private class DerivationState implements GState, SequencerListener { + + private JToolbarButton reset; + private JToolbarButton macroback; + private JToolbarButton back; + private JToolbarButton suspend; + private JToolbarButton cont; + private JToolbarButton macrostep; + private JToolbarButton finish; + private JPanel logPane; + private JList logList; + private DefaultListModel logger; + + public DerivationState() { + reset = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Undo_all")), + Util.getString("Gui.reset"), ""); + reset.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + ctrl.reset(); + logger.clear(); // FIXME should be done in some (not yet existing) listener + } + } + }); + + macroback = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Undo_blockstep")), + Util.getString("Gui.macroback"), ""); + macroback.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + timeroot.setScale(1); + ctrl.macroBack(0); + } + } + }); + + back = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Undo_step")), + Util.getString("Gui.back"), ""); + back.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + timeroot.setScale(1); + ctrl.back(); + } + } + }); + + suspend = new JToolbarButton( + new ImageIcon(Util.getResourceURL("Icon.Suspend")), + Util.getString("Gui.suspend"), ""); + suspend.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + ctrl.suspend(); + } + } + }); + + cont = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Perform_step")), + Util.getString("Gui.step"), ""); + cont.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + System.gc(); // XXX let's see whether this helps + timeroot.setScale(1); + ctrl.cont(); + } + } + }); + + macrostep = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Perform_blockstep")), + Util.getString("Gui.macrostep"), ""); + macrostep.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + System.gc(); // XXX let's see whether this helps + timeroot.setScale(1); + ctrl.macroStep(0); + } + } + }); + + finish = new JToolbarButton( + new ImageIcon(Util.getMainResourceURL("Icon.Finish_algorithm")), + Util.getString("Gui.finish"), ""); + finish.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + synchronized(root) { + System.gc(); // XXX let's see whether this helps + timeroot.setScale(0.7); + ctrl.macroStep(-1); + } + } + }); + + logPane = new JPanel(new BorderLayout()); + logPane.setBorder(BorderFactory.createTitledBorder(Util.getString("Gui.Log_title"))); + logPane.add(new JLabel(""+ + Util.getString("Gui.Log_header")+"
          "+ + Util.getString("Gui.Log_header2")+""), + BorderLayout.NORTH); + logger = new DefaultListModel(); + logList = new JList(logger); + logList.setLayoutOrientation(JList.VERTICAL); + logList.setVisibleRowCount(-1); + logList.setFixedCellWidth(50); + JScrollPane sp = new JScrollPane(logList); + logPane.add(sp, BorderLayout.CENTER); + logPane.setVisible(!ctrl.isLecture()); + + toolbar.add(reset); + toolbar.add(macroback); + toolbar.add(back); + toolbar.add(suspend); + toolbar.add(cont); + toolbar.add(macrostep); + toolbar.add(finish); + toolbar.validate(); + rootPane.add(logPane, BorderLayout.EAST); + rootPane.validate(); + + ctrl.addListener(this); + } + + public void dispose() { + ctrl.removeListener(this); + toolbar.remove(reset); + toolbar.remove(macroback); + toolbar.remove(back); + toolbar.remove(suspend); + toolbar.remove(cont); + toolbar.remove(macrostep); + toolbar.remove(finish); + rootPane.remove(logPane); + logPane = null; + logger = null; + } + + public void updateButtons() { + ctrl.derive(); + reset.setEnabled(ctrl.isResetPossible()); + macroback.setEnabled(ctrl.isBackPossible()); + back.setEnabled(ctrl.isBackPossible()); + suspend.setEnabled(ctrl.isSuspendPossible()); + cont.setEnabled(ctrl.isStepPossible()); + macrostep.setEnabled(ctrl.isMacroStepPossible()); + finish.setEnabled(ctrl.isMacroStepPossible()); + if (logPane.isVisible() == ctrl.isLecture()) { + logPane.setVisible(!ctrl.isLecture()); + rootPane.validate(); + } + } + + public void modelChanged() { + assert(false); // not expected to happen + } + + public void back(State q, Action a, State q1) { + if (logger.getSize() > 0) { + ListItem li = (ListItem)logger.get(logger.getSize()-1); + if (li.q == q1) + logger.remove(logger.getSize()-1); + } + } + + public void step(State q, Action a, State q1) { + if (Actions.isSwap(a)) { + ListItem li = new ListItem(); + li.q = q; + li.i = ((Phase12sl)q).i; + li.j = ((Phase12sl)q1).i; + logger.addElement(li); + logList.ensureIndexIsVisible(logger.getSize()-1); + } + } + + public void stepAvail() { + } + + } + + // this describes a sinkenlassen step + private static class ListItem { + public State q; + public int i; + public int j; + + @Override + public String toString() { + return String.format("%d/%d", i, j); + } + } + + private class UpdateThread implements Runnable { + + public void run() { + Thread me = Thread.currentThread(); + while (thread == me) { + synchronized(root) { + // animate... + timeroot.update(0.000000001d*System.nanoTime()); + // display... + // (should do nothing if nothing happened) + Rectangle r; + do { + r = renderer.getVisible(); + if (!renderer.validate()) + r = r.intersection(root.computeDirtyRegion()); + renderer.renderVisible(root, r); + } while (!renderer.show(r)); + root.clearDirtyRegion(); + } + // breathe... + try { + Thread.sleep(20); + } + catch (InterruptedException e) { + break; + } + } + thread = null; + } + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/HeapsortApplet.java b/src/org/jalgo/module/heapsort/HeapsortApplet.java new file mode 100644 index 0000000..7ac1fc7 --- /dev/null +++ b/src/org/jalgo/module/heapsort/HeapsortApplet.java @@ -0,0 +1,155 @@ +/** + * + */ +package org.jalgo.module.heapsort; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import javax.swing.JApplet; +import javax.swing.JFrame; + +import org.jalgo.module.heapsort.anim.TimeEntity; +import org.jalgo.module.heapsort.anim.TimeRoot; +import org.jalgo.module.heapsort.model.Model; +import org.jalgo.module.heapsort.renderer.CanvasEntity; +import org.jalgo.module.heapsort.renderer.CanvasEntityFactory; +import org.jalgo.module.heapsort.renderer.Renderer; +import org.jalgo.module.heapsort.vis.Controller; +import org.jalgo.module.heapsort.vis.Visualisation; + +/** + * @author mbue + * + */ +public final class HeapsortApplet extends JApplet { + + private Renderer renderer; + private CanvasEntity root; + private TimeEntity timeroot; + private Controller ctrl; + private Thread thread; + + /** + * + */ + private static final long serialVersionUID = 5192815393184014419L; + + private static final int[] sequence = { 7,15,14,8,13,18,24,9,5,16,21 }; + + @Override + public void init() { + Model model; + Visualisation vis; + CanvasEntityFactory f; + + // connect everything... + model = new org.jalgo.module.heapsort.model.Heapsort(); + for (int i: sequence) + ((org.jalgo.module.heapsort.model.Heapsort)model).addNumber(i); + renderer = new org.jalgo.module.heapsort.renderer.RenderJava2D(); + f = renderer.createFactory(); + root = f.createRoot(); + vis = new org.jalgo.module.heapsort.vis.Heapsort(root, f); + timeroot = new TimeRoot(); + ctrl = new Controller(model, vis, timeroot); + setLayout(new BorderLayout()); + renderer.init(this); + addMouseListener(new MouseListener() { + + public void mouseClicked(MouseEvent e) { + synchronized (root) { + if (ctrl.isBackPossible() && !ctrl.isStepPossible()) + ctrl.reset(); + else { + if (ctrl.isMacroStepPossible()) { + timeroot.setScale(0.7); + ctrl.macroStep(-1); + } + else + ctrl.suspend(); + } + } + } + + public void mouseEntered(MouseEvent e) { + } + + public void mouseExited(MouseEvent e) { + } + + public void mousePressed(MouseEvent e) { + } + + public void mouseReleased(MouseEvent e) { + } + + }); + } + + @Override + public void start() { + thread = new Thread(new UpdateThread()); + thread.start(); + } + + @Override + public synchronized void stop() { + thread = null; + } + + public static void main(String argv[]) { + final HeapsortApplet app = new HeapsortApplet(); + app.init(); + JFrame f = new JFrame("Heapsort Demo -- click in the window to start/pause/reset"); + f.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { System.exit(0); } + public void windowDeiconified(WindowEvent e) { app.start(); } + public void windowIconified(WindowEvent e) { app.stop(); } + }); + f.getContentPane().add("Center", app); + f.pack(); + f.setSize(new Dimension(790,495)); + f.setVisible(true); + app.start(); + } + + + private class UpdateThread implements Runnable { + + public void run() { + Thread me = Thread.currentThread(); + while (thread == me) { + synchronized(root) { + // animate... + timeroot.update(0.000000001d*System.nanoTime()); + // display... + // (should do nothing if nothing happened) + Rectangle r; + do { + r = renderer.getVisible(); + if (!renderer.validate()) + r = r.intersection(root.computeDirtyRegion()); + renderer.renderVisible(root, r); + } while (!renderer.show(r)); + root.clearDirtyRegion(); + } + // breathe... + try { + Thread.sleep(20); + } + catch (InterruptedException e) { + break; + } + } + thread = null; + } + + } + +} diff --git a/src/org/jalgo/module/heapsort/ModuleConnector.java b/src/org/jalgo/module/heapsort/ModuleConnector.java new file mode 100644 index 0000000..04a4a31 --- /dev/null +++ b/src/org/jalgo/module/heapsort/ModuleConnector.java @@ -0,0 +1,139 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.InternalErrorException; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.heapsort.anim.TimeEntity; +import org.jalgo.module.heapsort.anim.TimeRoot; +import org.jalgo.module.heapsort.model.Model; +import org.jalgo.module.heapsort.model.ModelListener; +import org.jalgo.module.heapsort.renderer.CanvasEntity; +import org.jalgo.module.heapsort.renderer.CanvasEntityFactory; +import org.jalgo.module.heapsort.renderer.Renderer; +import org.jalgo.module.heapsort.vis.Controller; +import org.jalgo.module.heapsort.vis.Visualisation; + +/* MODULE TO-DO LIST (de todo un poco...) + * + * TODO study mode animations + */ + +/** + * As demanded by j-Algo specification. + * + * @author mbue + */ +public class ModuleConnector extends AbstractModuleConnector { + + private Model model; + private GuiController gui; + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#getDataForFile() + */ + @Override + public ByteArrayOutputStream getDataForFile() { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + model.serialize(os); + } + catch (IOException e) { + throw new InternalErrorException(e.getMessage()); + } + return os; + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#init() + */ + @Override + public void init() { + Visualisation vis; + Renderer renderer; + CanvasEntityFactory f; + CanvasEntity root; + TimeEntity timeroot; + Controller ctrl; + + // connect everything... + model = new org.jalgo.module.heapsort.model.Heapsort(); + renderer = new org.jalgo.module.heapsort.renderer.RenderJava2D(); + f = renderer.createFactory(); + root = f.createRoot(); + vis = new org.jalgo.module.heapsort.vis.Heapsort(root, f); + timeroot = new TimeRoot(); + ctrl = new Controller(model, vis, timeroot); + gui = new GuiController( + JAlgoGUIConnector.getInstance().getModuleComponent(this), + JAlgoGUIConnector.getInstance().getModuleToolbar(this), + JAlgoGUIConnector.getInstance().getModuleMenu(this), + ctrl, renderer, root, timeroot); + ((Subject)model).addListener(new ModelListener() { + public void modelChanged() { + setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + }); + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#print() + */ + @Override + public void print() { + // XXX ATM printing is not supported by j-Algo + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#run() + */ + @Override + public void run() { + gui.run(); + } + + @Override + public boolean close() { + //gui.dispose(); XXX don't do this here + return true; + } + + /* (non-Javadoc) + * @see org.jalgo.main.AbstractModuleConnector#setDataFromFile(java.io.ByteArrayInputStream) + */ + @Override + public void setDataFromFile(ByteArrayInputStream data) { + try { + model.deserialize(data); + } + catch (IOException e) { + throw new InternalErrorException(e.getMessage()); + } + } + +} diff --git a/src/org/jalgo/module/heapsort/ModuleInfo.java b/src/org/jalgo/module/heapsort/ModuleInfo.java new file mode 100644 index 0000000..cdfe59f --- /dev/null +++ b/src/org/jalgo/module/heapsort/ModuleInfo.java @@ -0,0 +1,98 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; + +/** + * As demanded by j-Algo specification. + * + * @author mbue + * + */ +public final class ModuleInfo implements IModuleInfo { + + private static IModuleInfo instance = null; + + private ModuleInfo() { + super(); + } + + public static synchronized IModuleInfo getInstance() { + if (instance == null) + instance = new ModuleInfo(); + return instance; + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getAuthor() + */ + public String getAuthor() { + return Util.getString("Module_authors"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getDescription() + */ + public String getDescription() { + return Util.getString("Module_description"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getHelpSetURL() + */ + public URL getHelpSetURL() { + return Util.getResourceURL("HelpSet_Name"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getLicense() + */ + public String getLicense() { + return Util.getString("Module_license"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getLogoURL() + */ + public URL getLogoURL() { + return Util.getResourceURL("Module_logo"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getName() + */ + public String getName() { + return Util.getString("Module_name"); + } + + /* (non-Javadoc) + * @see org.jalgo.main.IModuleInfo#getVersion() + */ + public String getVersion() { + return Util.getString("Module_version"); + } + +} diff --git a/src/org/jalgo/module/heapsort/Subject.java b/src/org/jalgo/module/heapsort/Subject.java new file mode 100644 index 0000000..5973ce8 --- /dev/null +++ b/src/org/jalgo/module/heapsort/Subject.java @@ -0,0 +1,80 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort; + +import java.util.ArrayList; +import java.util.List; + +/** + *

          Some super-sick, weird, and fucked up implementation of the Observer pattern. + * Sorry but it's all Java's fault. (However, this not as sick as + * java.lang.Observable.)

          + * + *

          Usage: Define your Listener interface, e.g. MyListener. + * Derive your subject class from Subject<MyListener>. + * In your subject, implement a Notifier<MyListener> for each + * of MyListener's methods. That enables you to use + * notifyAll.

          + * + *

          See? Java is a big monster.

          + * + *

          BTW, this shit is not thread-safe! TODO Need to find a suspendUpdates semantics + * suitable for threading.

          + * + * @author mbue + * + */ +public class Subject { + protected List listeners; + private int update = 0; // only notify if <= 0 + + public void addListener(Listener l) { + if (listeners == null) + listeners = new ArrayList(); + listeners.add(l); + } + + public void removeListener(Listener l) { + if (listeners != null) + listeners.remove(l); + } + + protected void notifyAll(Notifier n) { + if ((listeners != null) && (update <= 0)) { + for (Listener l: listeners) + n.invoke(l); + } + } + + protected void suspendUpdates() { + update++; + } + + protected void resumeUpdates() { + update--; + } + + protected interface Notifier { + void invoke(Listener l); + } +} diff --git a/src/org/jalgo/module/heapsort/Util.java b/src/org/jalgo/module/heapsort/Util.java new file mode 100644 index 0000000..3336dad --- /dev/null +++ b/src/org/jalgo/module/heapsort/Util.java @@ -0,0 +1,51 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort; + +import java.net.URL; + +import org.jalgo.main.util.Messages; + +/** + * Utility class for resources and localisation. + * + * @author mbue + */ +public final class Util { + + private static final String main = "main"; + private static final String module = "heapsort"; + + public static String getString(String key) { + return Messages.getString(module, key); + } + + public static URL getMainResourceURL(String key) { + return Messages.getResourceURL(main, key); + } + + public static URL getResourceURL(String key) { + return Messages.getResourceURL(module, key); + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/Animation.java b/src/org/jalgo/module/heapsort/anim/Animation.java new file mode 100644 index 0000000..5236dd6 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/Animation.java @@ -0,0 +1,58 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + *

          This interface models animations on a canvas. + * Required canvas entities can be set up on init, + * they can be disposed of in done, + * and animated entities can be updated on update.

          + * + *

          Time values presented to the animation for update + * are in the closed real interval [0..1]. The reason for this is that + * the boundaries of that interval are contained in the floating point + * domain. The animation is garuanteed to be called with these exact + * values by the AnimationTimeEntity.

          + * + *

          The recommended policy for implementors is as follows: + * canvas entities needed temporarily in this animation can be created + * in the constructor, others be passed to it. All "new" entities can + * and should be added to the parent node on init, but by + * no means before. In addition, you may assume that the animation won't + * be used any longer after a call to done.

          + * + *

          Nothing is determined as to how the canvas entities are to be + * created. Implementors could use some kind of context (surrounding + * class), which would hold a reference to a canvas entity factory. + * In most cases, temporary canvas entities are not needed and thus + * this is no issue anyway.

          + * + * @author mbue + * + */ +public interface Animation { + void init(); + void done(); + void update(double time); + double getDuration(); +} diff --git a/src/org/jalgo/module/heapsort/anim/AnimationListener.java b/src/org/jalgo/module/heapsort/anim/AnimationListener.java new file mode 100644 index 0000000..d7a1238 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/AnimationListener.java @@ -0,0 +1,32 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * Listener interface for the AnimationTimeEntity class. + * + * @author mbue + */ +public interface AnimationListener { + void animationComplete(Animation a); +} diff --git a/src/org/jalgo/module/heapsort/anim/AnimationTimeEntity.java b/src/org/jalgo/module/heapsort/anim/AnimationTimeEntity.java new file mode 100644 index 0000000..6eeed0c --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/AnimationTimeEntity.java @@ -0,0 +1,140 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + + +/** + *

          This time entity controls an animation. The animation is being run + * for local times in the real interval [0..1]. The time transformation + * is set up in the constructor according to the absolute start + * time desired for the animation as well as the duration it reports.

          + * + *

          This class does only support at most one listener for two reasons: + * a) this should suffice in most cases, and otherwise, the listener + * could act as subject to other listeners; b) it's the easiest way of + * getting around the multiple inheritance problem.

          + * + * @author mbue + */ +public final class AnimationTimeEntity extends TimeEntity implements Animation { + private Animation anim; + private AnimationListener listener; + private State state = new State1(); + // XXX maybe we should create all states at once because they will be created anyway + + public AnimationTimeEntity(Animation anim, double start) { + super(); + this.anim = anim; + this.offset = start; + this.scale = anim.getDuration(); + } + + public void setListener(AnimationListener l) { + listener = l; + } + + protected void doUpdate(double tloc) { + state.doUpdate(tloc); + } + + private interface State { + void doUpdate(double tloc); + } + + /** + * pre-init state + * + * @author mbue + */ + private class State1 implements State { + public void doUpdate(double tloc) { + // BUGFIX: handle tloc > 1.0 + // if this ate is used in a composite animation, + // it might get called with -5 and then with 5 + // because of some time trouble, the outer animation is + // only called with 0.0 and 1.0 + if (tloc >= 1.0) { + state = new State3(); + anim.update(1.0); + // changed to ease composition + //done() is called outside + //anim.done(); + if (listener != null) + listener.animationComplete(anim); + } + else if (tloc >= 0.0) { + state = new State2(); + // changed to ease composition: + //init() is called outside + //anim.init(); + anim.update(0.0); + } + } + } + + /** + * running animation + * + * @author mbue + */ + private class State2 implements State { + public void doUpdate(double tloc) { + if (tloc < 1.0) { + anim.update(tloc); + } + else { + state = new State3(); + anim.update(1.0); + // changed to ease composition + //done() is called outside + //anim.done(); + if (listener != null) + listener.animationComplete(anim); + } + } + } + + /** + * post-done state + * + * @author mbue + */ + private class State3 implements State { + public void doUpdate(double tloc) { + // this animation is done! + } + } + + public void done() { + anim.done(); + } + + public double getDuration() { + return anim.getDuration(); + } + + public void init() { + anim.init(); + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/Animations.java b/src/org/jalgo/module/heapsort/anim/Animations.java new file mode 100644 index 0000000..c294314 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/Animations.java @@ -0,0 +1,450 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +import java.awt.geom.Point2D; + +import org.jalgo.module.heapsort.renderer.MarkingRect; +import org.jalgo.module.heapsort.renderer.Node; +import org.jalgo.module.heapsort.renderer.SequenceElement; +import org.jalgo.module.heapsort.renderer.Text; + +/** + * A (static) factory class for common animations. There are several + * facilities (read: classes) to compose animations: ProxyAnimation + * if you just want to add some init or done code, ParallelAnimation + * for animations running completely in parallel, SequentialAnimation + * for a sequence of animations, and most flexible (and expensive) + * CompositeAnimation, which allows for arbitrary composition. + * + * @author mbue + */ +public final class Animations { + + public interface CrossfaderFactory { + Animation invoke(Fadeable f1, Fadeable f2); + } + + public interface CrossmoverFactory { + Animation invoke(Moveable m1, Moveable m2, Point2D p1, Point2D p2); + } + + public static final CrossfaderFactory LINEAR_FADER = new LinearCrossfaderFactory(); + public static final CrossfaderFactory SMOOTH_FADER = new SmoothCrossfaderFactory(); + + public static final CrossmoverFactory LINEAR_MOVER = new LinearCrossmoverFactory(); + public static final CrossmoverFactory SMOOTH_MOVER = new SmoothCrossmoverFactory(); + + /** + * Creates a crossfading animation. The duration of the animation + * will be a token 1.0, so just use your own scale. + * + * @param f1 + * @param f2 + * @return + */ + public static Animation createCrossfader(CrossfaderFactory fac, + Fadeable f1, Fadeable f2) { + return fac.invoke(f1, f2); + } + + public static Animation createInFader(CrossfaderFactory fac, Fadeable f) { + return fac.invoke(null, f); + } + + public static Animation createOutFader(CrossfaderFactory fac, Fadeable f) { + return fac.invoke(f, null); + } + + public static Animation createCrossmover(CrossmoverFactory fac, + Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + return fac.invoke(m1, m2, p1, p2); + } + + public static Animation createMover(CrossmoverFactory fac, + Moveable m, Point2D p1, Point2D p2) { + return fac.invoke(m, null, p1, p2); + } + + public static Animation createZoomer(Scalable s1, Scalable s2, double factor) { + return new Zoomer(s1, s2, factor); + } + + public static Animation createCrossBlinker(Fadeable f1, Fadeable f2, double periods) { + return new SmoothBlinker(f1, f2, periods); + } + + public static Animation createBlinker(Fadeable f1, double periods) { + return new SmoothBlinker(f1, null, periods); + } + + // adapter stuff + + public static Animation createCrossfader(CrossfaderFactory fac, + MarkingRect f1, MarkingRect f2) { + return fac.invoke(new MarkingRectAdapter(f1), new MarkingRectAdapter(f2)); + } + + public static Animation createInFader(CrossfaderFactory fac, Text t) { + return fac.invoke(null, new TextAdapter(t)); + } + + public static Animation createInFader(CrossfaderFactory fac, MarkingRect mr) { + return fac.invoke(null, new MarkingRectAdapter(mr)); + } + + public static Animation createInFader(CrossfaderFactory fac, Node n) { + return fac.invoke(null, new NodeAdapter(n)); + } + + public static Animation createInFader(CrossfaderFactory fac, SequenceElement s) { + return fac.invoke(null, new SequenceElementAdapter(s)); + } + + public static Animation createOutFader(CrossfaderFactory fac, Text t) { + return fac.invoke(new TextAdapter(t), null); + } + + public static Animation createOutFader(CrossfaderFactory fac, MarkingRect mr) { + return fac.invoke(new MarkingRectAdapter(mr), null); + } + + public static Animation createOutFader(CrossfaderFactory fac, Node n) { + return fac.invoke(new NodeAdapter(n), null); + } + + public static Animation createOutFader(CrossfaderFactory fac, SequenceElement s) { + return fac.invoke(new SequenceElementAdapter(s), null); + } + + public static Animation createCrossmover(CrossmoverFactory fac, + Node m1, Node m2, Point2D p1, Point2D p2) { + return fac.invoke(new NodeAdapter(m1), new NodeAdapter(m2), p1, p2); + } + + public static Animation createCrossmover(CrossmoverFactory fac, + SequenceElement m1, SequenceElement m2, Point2D p1, Point2D p2) { + return fac.invoke(new SequenceElementAdapter(m1), new SequenceElementAdapter(m2), p1, p2); + } + + public static Animation createMover(CrossmoverFactory fac, + Text m, Point2D p1, Point2D p2) { + return fac.invoke(new TextAdapter(m), null, p1, p2); + } + + public static Animation createZoomer(Node s1, Node s2, double factor) { + return new Zoomer(new NodeAdapter(s1), new NodeAdapter(s2), factor); + } + + public static Animation createZoomer( + SequenceElement s1, SequenceElement s2, double factor) { + return new Zoomer(new SequenceElementAdapter(s1), new SequenceElementAdapter(s2), factor); + } + + public static Animation createBlinker(MarkingRect f1, double periods) { + return new SmoothBlinker(new MarkingRectAdapter(f1), null, periods); + } + + // private (implementation) stuff follows + + private static class LinearCrossfaderFactory implements CrossfaderFactory { + public Animation invoke(Fadeable f1, Fadeable f2) { + return new LinearCrossfader(f1, f2); + } + } + + private static class SmoothCrossfaderFactory implements CrossfaderFactory { + public Animation invoke(Fadeable f1, Fadeable f2) { + return new SmoothCrossfader(f1, f2); + } + } + + private static class LinearCrossmoverFactory implements CrossmoverFactory { + public Animation invoke(Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + return new LinearCrossmover(m1, m2, p1, p2); + } + } + + private static class SmoothCrossmoverFactory implements CrossmoverFactory { + public Animation invoke(Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + return new SmoothCrossmover(m1, m2, p1, p2); + } + } + + private static abstract class AbstractCrossfader implements Animation { + protected Fadeable f1; + protected Fadeable f2; + + protected AbstractCrossfader(Fadeable f1, Fadeable f2) { + this.f1 = f1; + this.f2 = f2; + } + + public void done() { + /**XX bug fix: if the animation is done, set the state + // (necessary if update does not get called, which can happen + f1.setState(0.0f); + f2.setState(1.0f);*/ + // we don't want to hold the fadeables longer than necessary + // (note that this method will be called automatically, + // which can not be said about deleting the reference to us) + f1 = null; + f2 = null; + } + + public double getDuration() { + return 1.0; + } + + public void init() { + } + + } + + private static final class LinearCrossfader extends AbstractCrossfader implements Animation { + + public LinearCrossfader(Fadeable f1, Fadeable f2) { + super(f1, f2); + } + + public void update(double time) { + float f = (float)time; + if (f1 != null) + f1.setState(1.0f-f); + if (f2 != null) + f2.setState(f); + } + + } + + private static final class SmoothCrossfader extends AbstractCrossfader implements Animation { + + public SmoothCrossfader(Fadeable f1, Fadeable f2) { + super(f1, f2); + } + + public void update(double time) { + float f = (float)(0.5*Math.cos(Math.PI*time)); + if (f1 != null) + f1.setState(0.5f+f); + if (f2 != null) + f2.setState(0.5f-f); + } + } + + private static final class SmoothBlinker extends AbstractCrossfader implements Animation { + private double periods; + + public SmoothBlinker(Fadeable f1, Fadeable f2, double periods) { + super(f1, f2); + this.periods = periods; + } + + /*public void done() { + f1.setState(1.0f); + f2.setState(0.0f); + f1 = null; + f2 = null; + }*/ + + public void update(double time) { + float f = (float)(0.5*Math.cos(2*periods*Math.PI*time)); + if (f1 != null) + f1.setState(0.5f+f); + if (f2 != null) + f2.setState(0.5f-f); + } + } + + private static final class Zoomer implements Animation { + private Scalable s1; + private Scalable s2; + private double factor; + + public Zoomer(Scalable s1, Scalable s2, double factor) { + this.s1 = s1; + this.s2 = s2; + this.factor = factor; + } + + public void update(double time) { + double f = factor*Math.sin(Math.PI*time); + if (s1 != null) + s1.setScale(1.0-f); + if (s2 != null) + s2.setScale(1.0+f); + } + + public void done() { + s1 = null; + s2 = null; + } + + public double getDuration() { + return 1.0; + } + + public void init() { + + } + } + + private static abstract class AbstractCrossmover implements Animation { + protected Moveable m1; + protected Moveable m2; + protected Point2D p1; + protected Point2D p2; + + public AbstractCrossmover(Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + this.m1 = m1; + this.m2 = m2; + this.p1 = p1; + this.p2 = p2; + } + + public void done() { + m1 = null; + m2 = null; + } + + public double getDuration() { + return 1.0; + } + + public void init() { + + } + + } + + private static final class LinearCrossmover extends AbstractCrossmover implements Animation { + + public LinearCrossmover(Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + super(m1, m2, p1, p2); + } + + public void update(double time) { + double t2 = time; + double t1 = 1.0-t2; + if (m1 != null) + m1.setPosition(t1*p1.getX()+t2*p2.getX(), t1*p1.getY()+t2*p2.getY()); + if (m2 != null) + m2.setPosition(t2*p1.getX()+t1*p2.getX(), t2*p1.getY()+t1*p2.getY()); + } + + } + + private static final class SmoothCrossmover extends AbstractCrossmover implements Animation { + + public SmoothCrossmover(Moveable m1, Moveable m2, Point2D p1, Point2D p2) { + super(m1, m2, p1, p2); + } + + public void update(double time) { + double t = 0.5*Math.cos(Math.PI*time); + double t1 = 0.5+t; + double t2 = 0.5-t; + if (m1 != null) + m1.setPosition(t1*p1.getX()+t2*p2.getX(), t1*p1.getY()+t2*p2.getY()); + if (m2 != null) + m2.setPosition(t2*p1.getX()+t1*p2.getX(), t2*p1.getY()+t1*p2.getY()); + } + + } + + // adapters + // note: using one adapter class for several + // interfaces (like Moveable, Fadable) saves us keystrokes + // ---but remember: canvas entities may offer more than one + // property suitable for fading... and then we will need + // more adapter classes anyway + + private static class TextAdapter implements Fadeable, Moveable { + private final Text text; + + public TextAdapter(Text text) { + this.text = text; + } + + public void setState(float state) { + text.setOpacity(state); + } + + public void setPosition(double x, double y) { + text.setPosition(x, y); + } + } + + private static class NodeAdapter implements Fadeable, Moveable, Scalable { + private final Node node; + + public NodeAdapter(Node node) { + this.node = node; + } + + public void setState(float state) { + node.setHighlight(state); + } + + public void setPosition(double x, double y) { + node.setPosition(x, y); + } + + public void setScale(double scale) { + node.setScale(scale); + } + } + + private static class SequenceElementAdapter implements Fadeable, Moveable, Scalable { + private final SequenceElement se; + + public SequenceElementAdapter(SequenceElement se) { + this.se = se; + } + + public void setState(float state) { + se.setHighlight(state); + } + + public void setPosition(double x, double y) { + se.setPosition(x, y); + } + + public void setScale(double scale) { + se.setScale(scale); + } + } + + private static class MarkingRectAdapter implements Fadeable { + private final MarkingRect mr; + + public MarkingRectAdapter(MarkingRect mr) { + this.mr = mr; + } + + public void setState(float state) { + mr.setOpacity(state); + } + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/CVS/Entries b/src/org/jalgo/module/heapsort/anim/CVS/Entries new file mode 100644 index 0000000..af447d0 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/CVS/Entries @@ -0,0 +1,13 @@ +/Animation.java/1.4/Wed Jan 30 12:23:34 2008// +/AnimationListener.java/1.4/Wed Jan 30 12:23:34 2008// +/AnimationTimeEntity.java/1.5/Fri Feb 1 13:10:45 2008// +/Animations.java/1.6/Wed Feb 6 20:21:15 2008// +/CompositeAnimation.java/1.4/Wed Jan 30 12:23:34 2008// +/Fadeable.java/1.4/Wed Jan 30 12:23:34 2008// +/Moveable.java/1.3/Wed Jan 30 12:23:34 2008// +/ParallelAnimation.java/1.3/Wed Jan 30 12:23:34 2008// +/ProxyAnimation.java/1.6/Wed Feb 6 20:21:15 2008// +/Scalable.java/1.4/Wed Jan 30 12:23:34 2008// +/SequentialAnimation.java/1.6/Wed Feb 6 20:21:15 2008// +/TimeEntity.java/1.4/Wed Jan 30 12:23:34 2008// +/TimeRoot.java/1.4/Wed Jan 30 12:23:34 2008// diff --git a/src/org/jalgo/module/heapsort/anim/CVS/Repository b/src/org/jalgo/module/heapsort/anim/CVS/Repository new file mode 100644 index 0000000..ad4a4d4 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/heapsort/anim diff --git a/src/org/jalgo/module/heapsort/anim/CVS/Root b/src/org/jalgo/module/heapsort/anim/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/heapsort/anim/CompositeAnimation.java b/src/org/jalgo/module/heapsort/anim/CompositeAnimation.java new file mode 100644 index 0000000..b9a0f57 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/CompositeAnimation.java @@ -0,0 +1,126 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + *

          This class can be used to compose a new animation out of existing ones. + * Stakeholder: Animation designer...

          + * + *

          The composition capability is obtained by subclassing TimeEntity. + * In terms of the time entity, the closed real interval [0..1], which is the + * local time domain for the animation, marks the absolute time values(!). This + * makes it a bit hard to understand the influence of the time transformation + * applied by this. Except in the rare case that you want to shift + * or stretch the whole resulting composite animation (without changing its + * actual duration), there will be no need nor use to change it from being + * identity.

          + * + *

          Use addChild(TimeEntity, double, double) if you want to + * specify everything in absolute measures wrt. to the animation, not the time + * entity (recommended). E.g. if the animation has a duration of 12, and you want + * to add a time entity t at position 2 for a duration of 3, you just + * call addChild(t, 2, 3), and the offset and + * scale of t will be set to 2/12 and 3/12, respectively. + * (This example assumes that the time transformation of this is + * identity.)

          + * + *

          Naturally, to add animations to this entity, you would use + * AnimationTimeEntity instances.

          + * + * @author mbue + */ +public abstract class CompositeAnimation extends TimeEntity implements Animation { + + /** + * Call done() on the children. Override this to implement + * your own disposal procedures, but don't forget to call super()
          . + * + * @see org.jalgo.module.heapsort.anim.Animation#done() + */ + public void done() { + for (TimeEntity e: children) { + if (e instanceof Animation) + ((Animation)e).done(); + } + } + + /** + * Call init() on the children. Override this to implement + * your own initialisation procedures, but don't forget to call super(). + * + * @see org.jalgo.module.heapsort.anim.Animation#init() + */ + public void init() { + for (TimeEntity e: children) { + if (e instanceof Animation) + ((Animation)e).init(); + } + } + + /** + *

          Adds t to the children of this + * animation. Sets offset and scale + * values of t such that + * an absolute time (wrt. to the animation) of + * start will be transformed to the + * local time 0.0 (wrt. to t), and respectively + * for start+dur and 1.0.

          + * + *

          Note: If t is an AnimationTimeEntity, + * its scale will most likely be set according to its animation's + * duration. However, in most cases this duration is not relevant + * for composition.

          + * + *

          Restrictions of addChild(TimeEntity) apply.

          + * + * @param t + * @param start + * @param dur + */ + public void addChild(TimeEntity t, double start, double dur) { + /* we can just pretend that this.scale + * would also account for the duration + * + * two equations, two variables + * s1 is this.scale, s2 is t.scale + * o1 is this.offset, o2 is t.offset + * use transformation equations for + * start,0 and start+dur,1 + * + * start = s1*s2*0+s1*o2+o1 (1) + * start+dur = s1*s2*1+s1*o2+o1 (2) + * + * (1) --> o2 = (start-o1)/s1 + * (2)-(1) --> s2 = dur/s1 + */ + double oneover = 1/(scale*getDuration()); + addChild(t); + t.offset = oneover*(start-offset); + t.scale = oneover*dur; + } + + public void add(Animation a, double start, double dur) { + addChild(new AnimationTimeEntity(a, 0), start, dur); + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/Fadeable.java b/src/org/jalgo/module/heapsort/anim/Fadeable.java new file mode 100644 index 0000000..ecb683d --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/Fadeable.java @@ -0,0 +1,30 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * @author mbue + */ +public interface Fadeable { + void setState(float state); +} diff --git a/src/org/jalgo/module/heapsort/anim/Moveable.java b/src/org/jalgo/module/heapsort/anim/Moveable.java new file mode 100644 index 0000000..df127f7 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/Moveable.java @@ -0,0 +1,30 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * @author mbue + */ +public interface Moveable { + void setPosition(double x, double y); +} diff --git a/src/org/jalgo/module/heapsort/anim/ParallelAnimation.java b/src/org/jalgo/module/heapsort/anim/ParallelAnimation.java new file mode 100644 index 0000000..1bcc212 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/ParallelAnimation.java @@ -0,0 +1,65 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +import java.util.LinkedList; +import java.util.List; + +/** + * Subclass this if your animations run in parallel. + * Don't forget the super calls! + * + * @author mbue + */ +public class ParallelAnimation implements Animation { + private List anim; + private double duration; + + public ParallelAnimation(double duration) { + anim = new LinkedList(); + this.duration = duration; + } + + protected void add(Animation a) { + anim.add(a); + } + + public void done() { + for (Animation a: anim) + a.done(); + } + + public double getDuration() { + return duration; + } + + public void init() { + for (Animation a: anim) + a.init(); + } + + public void update(double time) { + for (Animation a: anim) + a.update(time); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/anim/ProxyAnimation.java b/src/org/jalgo/module/heapsort/anim/ProxyAnimation.java new file mode 100644 index 0000000..a731919 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/ProxyAnimation.java @@ -0,0 +1,58 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * Subclass this if you want to decorate an existing animation. + * + * @author mbue + */ +public class ProxyAnimation implements Animation { + + protected Animation delegate; + + protected ProxyAnimation() { + // have a hidden empty constructor to allow easy subclassing + } + + public ProxyAnimation(Animation delegate) { + this.delegate = delegate; + } + + public void done() { + delegate.done(); + } + + public double getDuration() { + return delegate.getDuration(); + } + + public void init() { + delegate.init(); + } + + public void update(double time) { + delegate.update(time); + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/Scalable.java b/src/org/jalgo/module/heapsort/anim/Scalable.java new file mode 100644 index 0000000..3c56d90 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/Scalable.java @@ -0,0 +1,30 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * @author mbue + */ +public interface Scalable { + void setScale(double scale); +} diff --git a/src/org/jalgo/module/heapsort/anim/SequentialAnimation.java b/src/org/jalgo/module/heapsort/anim/SequentialAnimation.java new file mode 100644 index 0000000..7d37f6d --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/SequentialAnimation.java @@ -0,0 +1,116 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +/** + * Subclass this if your animation consists of a sequence of animations. + * Don't forget the super calls! + * + * @author mbue + */ +public class SequentialAnimation implements Animation { + // Actually, I hate this implementation... + // I wanted it to be more efficient than using CompositeAnimation with lots of + // AnimationTimeEntities, so I had to pass on the idea of using too many inner + // classes, even if we have quite some state involved + + private static class AnimItem { + public Animation a; + public double start; + public double dur; + public AnimItem next; + } + + private AnimItem anim; + private AnimItem head; + private AnimItem cur; + private double duration = 0.0; + + public SequentialAnimation() { + anim = null; + } + + /** + * Add an animation to this sequential composition. + * dur must be greater 0! + * + * @param a + * @param dur + */ + protected void add(Animation a, double dur) { + if (head == null) { + head = new AnimItem(); + anim = head; + } + else { + head.next = new AnimItem(); + head = head.next; + } + head.a = a; + head.dur = dur; + head.start = duration; + duration += dur; + } + + public void done() { + if (cur != null) { + cur.a.update(1.0); + cur.a.done(); + } + } + + public double getDuration() { + return duration; + } + + public void init() { + cur = anim; + if (cur != null) { + cur.a.init(); + cur.a.update(0.0); + } + } + + public void update(double time) { + // ok folks, we are going to use the BREAK statement here, so fasten seatbelts + // (the loop is necessary because we are not garuanteed to be called often enough + // to bring every animation to 1.0, which is required.) + while (cur != null) { + double tloc = (time*duration-cur.start)/cur.dur; + if (tloc < 1.0) { + cur.a.update(tloc); + break; // <--- HERE IT IS + } + else { + cur.a.update(1.0); + cur.a.done(); + cur = cur.next; + if (cur != null) { + cur.a.init(); + cur.a.update(0.0); + } + } + } + } + +} diff --git a/src/org/jalgo/module/heapsort/anim/TimeEntity.java b/src/org/jalgo/module/heapsort/anim/TimeEntity.java new file mode 100644 index 0000000..17f4be1 --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/TimeEntity.java @@ -0,0 +1,122 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + +import java.util.HashSet; +import java.util.Set; + +/** + *

          An entity which cares about time. Similar to the way locations are handled + * with canvas entities, time entities have a local and an absolute time, for now denoted + * by t_loc and t_abs, respectively. The + * defining equation is + * + * t_abs = scale*t_loc + offset, where scale and + * offset are members of this class and scale > 0.

          + * + *

          Since in any case, absolute time is given and local time is wanted, we use + * another form of the equation: t_loc = 1/scale*(t_abs - offset). + * + * @author mbue + * + */ +public class TimeEntity { + protected TimeEntity parent = null; + protected double offset = 0.0; + protected double scale = 1.0; + protected Set children = null; + + /** + * Adds t to the children of this time + * entity. Will not prevent you from adding the same + * entity twice into the same tree. Just don't do it. + * + * @param t time entity to be added + */ + public void addChild(TimeEntity t) { + if (children == null) + children = new HashSet(); + children.add(t); + t.parent = this; + } + + /** + * Returns current local time, provided that the parent node does so correctly. + * Use a TimeRoot instance as root node to make this work. + * + * @return + */ + public double now() { + if (parent == null) + return 0.0; + else + return 1/scale*(parent.now()-offset); + } + + /** + * If t is a direct successor of this node, + * remove it. + * + * @param t time entity to be removed + */ + public void removeChild(TimeEntity t) { + if (t.parent == this) { + children.remove(t); + t.parent = null; + } + } + + /** + * Virtual method called when local time has changed. + * Override this when subclassing. The default implementation + * does nothing, so there is no need to call super. + * + * @param tloc local time + */ + protected void doUpdate(double tloc) { + + } + + /** + * Called by the system to update the time entity wrt. + * to absolute time. Also implements composite pattern. + * Note: This method is final. When subclassing, override + * doUpdate. + * + * @param tabs absolute time + */ + public final void update(double tabs) { + double tloc = 1/scale*(tabs-offset); + doUpdate(tloc); + if (children != null) { + for (TimeEntity c: children) + c.update(tloc); + } + } + + public void setScale(double scale) { + if (scale <= 0.0) + throw new IllegalArgumentException("scale must be greater than 0"); + this.scale = scale; + } +} diff --git a/src/org/jalgo/module/heapsort/anim/TimeRoot.java b/src/org/jalgo/module/heapsort/anim/TimeRoot.java new file mode 100644 index 0000000..b1bc47d --- /dev/null +++ b/src/org/jalgo/module/heapsort/anim/TimeRoot.java @@ -0,0 +1,67 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.anim; + + +/** + * A time entity which saves the time supplied to it on update and returns + * it on a call to now. Use this class for your root nodes + * to make the now method work for the whole tree. + * + * @author mbue + */ +public class TimeRoot extends TimeEntity { + private double now_; + + @Override + public double now() { + return now_; + } + + @Override + protected void doUpdate(double tloc) { + // that is totally correct: + // now has to be expressed in local time + // (absolute wrt. children) + now_ = tloc; + } + + /** + * Set scale of this time root. Will reset offset such that + * there will be no seam wrt. now(). + * + * @see org.jalgo.module.heapsort.anim.TimeEntity#setScale(double) + */ + @Override + public void setScale(double scale) { + /* Ansatz: + * absolute time and local time don't change + * + * s1*tloc + o1 = s2*tloc + o2 + * --> o2 = (s1-s2)*tloc + 1 + */ + double s1 = this.scale; + super.setScale(scale); + offset += (s1-scale)*now_; + } +} diff --git a/src/org/jalgo/module/heapsort/de.properties b/src/org/jalgo/module/heapsort/de.properties new file mode 100644 index 0000000..a968de0 --- /dev/null +++ b/src/org/jalgo/module/heapsort/de.properties @@ -0,0 +1,28 @@ +Module_name=Heapsort +Module_version=1.0 +Module_authors=Matthias Büchse +Module_license=GNU General Public License +Module_description=Dieses Modul behandelt den Sortieralgorithmus Heapsort. + +Gui.Input_title=Eingabe der Folge +Gui.Input_label=Neue Zahl +Gui.Input_add=Hinzufügen +Gui.Input_start=Algorithmus starten + +Gui.Menu_lecture=Vorlesungsmodus + +Gui.reset=Zurück zum Anfang +Gui.back=Schritt zurückgehen +Gui.macroback=Makroschritt zurückgehen +Gui.step=Schritt vorwärtsgehen +Gui.macrostep=Makroschritt vorwärtsgehen +Gui.finish=Algorithmus zuendeführen +Gui.suspend=Makroschritt unterbrechen + +Gui.Hint_instructions=Geben Sie bis zu 31 paarweise verschiedene natürliche Zahlen zwischen 1 und 99 ein.\n\nEnter bestätigt die eingebene Zahl. Bei leerer Eingabe wird der Algorithmus gestartet. +Gui.Hint_double=Es sind keine doppelten Einträge erlaubt! +Gui.Hint_limit=Sie haben 31 Zahlen eingegeben. + +Gui.Log_title=Protokoll +Gui.Log_header=Sinkenlassen +Gui.Log_header2=von/nach diff --git a/src/org/jalgo/module/heapsort/en.properties b/src/org/jalgo/module/heapsort/en.properties new file mode 100644 index 0000000..0ad849d --- /dev/null +++ b/src/org/jalgo/module/heapsort/en.properties @@ -0,0 +1,28 @@ +Module_name=Heapsort +Module_version=1.0 +Module_authors=Matthias Büchse +Module_license=GNU General Public License +Module_description=This module is all about the sorting algorithm Heapsort. + +Gui.Input_title=Input sequence +Gui.Input_label=New number +Gui.Input_add=Add +Gui.Input_start=Start algorithm + +Gui.Menu_lecture=Lecture mode + +Gui.reset=Go right to the beginning +Gui.back=Go back +Gui.macroback=Go back (macro step) +Gui.step=Make a step +Gui.macrostep=Make a macro step +Gui.finish=Finish algorithm +Gui.suspend=Suspend macro step animation + +Gui.Hint_instructions=Enter up to 31 unique natural numbers from 1 to 99.\n\nPress return to confirm your number. If the input field is empty, pressing return will start the algorithm. +Gui.Hint_double=Sequence items have to be distinct! +Gui.Hint_limit=You have entered 31 numbers. + +Gui.Log_title=Log +Gui.Log_header=Sinkenlassen +Gui.Log_header2=from/to diff --git a/src/org/jalgo/module/heapsort/model/Action.java b/src/org/jalgo/module/heapsort/model/Action.java new file mode 100644 index 0000000..1837216 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/Action.java @@ -0,0 +1,34 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +/** + * Just a token interface. Actions can be classes implementing this interface + * or even anonymous implementing classes used in the following way: + * myaction = new Action() {}. + * + * @author mbue + */ +public interface Action { + +} diff --git a/src/org/jalgo/module/heapsort/model/CVS/Entries b/src/org/jalgo/module/heapsort/model/CVS/Entries new file mode 100644 index 0000000..dfc5637 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/CVS/Entries @@ -0,0 +1,7 @@ +/Action.java/1.4/Wed Jan 30 12:23:35 2008// +/Heapsort.java/1.6/Tue Oct 6 08:39:33 2009// +/Model.java/1.4/Wed Jan 30 12:23:35 2008// +/ModelListener.java/1.4/Wed Jan 30 12:23:35 2008// +/Sequencer.java/1.5/Wed Feb 6 20:21:15 2008// +/SequencerListener.java/1.4/Wed Jan 30 12:23:35 2008// +/State.java/1.4/Wed Jan 30 12:23:35 2008// diff --git a/src/org/jalgo/module/heapsort/model/CVS/Repository b/src/org/jalgo/module/heapsort/model/CVS/Repository new file mode 100644 index 0000000..59b3b0a --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/heapsort/model diff --git a/src/org/jalgo/module/heapsort/model/CVS/Root b/src/org/jalgo/module/heapsort/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/heapsort/model/Heapsort.java b/src/org/jalgo/module/heapsort/model/Heapsort.java new file mode 100644 index 0000000..5fbda3c --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/Heapsort.java @@ -0,0 +1,619 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; +import java.util.Map.Entry; + +import org.jalgo.module.heapsort.Subject; + +/** + *

          This class models the Heapsort algorithm.

          + * + *

          The states are:

          + *
            + *
          • InitialState
          • + *
          • Phase0: Building the tree
          • + *
          • Phase1a: Before Sinkenlassen
          • + *
          • Phase1b: After Sinkenlassen
          • + *
          • Phase2a: Before swapping
          • + *
          • Phase2b: After swapping/before Sinkenlassen
          • + *
          • Phase12sla: Sinkenlassen before comparison
          • + *
          • Phase12slb: Sinkenlassen after comparison/before swapping
          • + *
          • Done
          • + *
          + * + *

          The actions are:

          + *
            + *
          • Startphase0: used in InitialState when Phase0 is launched
          • + *
          • Startphase1: used in Phase0 when Phase1a is launched
          • + *
          • Startphase2: used in Phase0 when Phase2s is launched (happens if sequence has length 1)
          • + *
          • Startsl: used in Phase1a and Phase2b when Phase12sla is launched
          • + *
          • Returnphase1: used in Phase12sl* when returning to Phase1b
          • + *
          • Returnphase2: used in Phase12sl* when returning to Phase2a
          • + *
          • Extend: used in Phase0 when level is increased
          • + *
          • Compare: used in Phase12sla when going to Phase12slb
          • + *
          • Swap: used in Phase12slb when going to Phase12sla (swapping nodes)
          • + *
          • Decli: used in Phase1b when going to Phase1a (decrementing pointer "Li")
          • + *
          • SwapDecre: used in Phase2a when going to Phase2b
          • + *
          • Finish: used in Phase12sl* and others when going to Done
          • + *
          + * + * @author mbue + * + */ +public class Heapsort extends Subject implements Model { + + private List sequence; + + public Heapsort() { + sequence = new ArrayList(); + } + + public void addNumber(int n) { + // this might be slow, but speed is not relevant here + for (Integer i: sequence) + if (i.intValue() == n) + throw new IllegalArgumentException(); + sequence.add(Integer.valueOf(n)); + notifyAll(ModelChangedNotifier.getInstance()); + } + + public State getInitialState() { + return new InitialState(sequence); + } + + @SuppressWarnings("unchecked") + public void deserialize(InputStream is) throws IOException { + ObjectInputStream ois = new ObjectInputStream(is); + try { + sequence = (List)ois.readObject(); + } + catch (ClassNotFoundException e) { + ; // XXX fail silently + // a) shouldn't happen anyway + // b) no big deal + } + notifyAll(ModelChangedNotifier.getInstance()); + } + + public void serialize(OutputStream os) throws IOException { + ObjectOutputStream oos = new ObjectOutputStream(os); + oos.writeObject(sequence); + oos.flush(); + oos = null; + oos.close(); + } + + public static void main(String[] args) { + int[] testdata = {7,15,14,8,13,18,24,9,5,16,21}; + //int[] testdata = {1, 2, 3, 4, 5}; + + Heapsort m = new Heapsort(); + for (int i: testdata) + m.addNumber(i); + + State s = m.getInitialState(); + while (s != null) { + Map succ = s.computeSuccessors(); + Iterator> i = succ.entrySet().iterator(); + System.out.println(s.toString()); + if (i.hasNext()) { + Entry e = i.next(); + s = e.getKey(); + System.out.println(e.getValue()); + } + else + s = null; + } + } + + // auxiliary methods + + /** + * Computes the number of levels of the binary tree + * corresponding to some list of length n + */ + public static int getLevels(int n) { + int l = 0; + while (n > 0) { + n >>= 1; + l++; + } + return l; + } + + // actions (the sick way of doing enum) + public static final class Actions { + // Initial->Phase0 + private static final Action startphase0 = new Action() { + public String toString() { + return "Start Phase 0"; + } + }; + // Phase0->Phase0 + private static final Action extend = new Action() { + public String toString() { + return "Extend"; + } + }; + // Phase0->Phase1a + private static final Action startphase1 = new Action() { + public String toString() { + return "Start Phase 1"; + } + }; + // Phase0->Phase2a, Phase1a->Phase2a + private static final Action startphase2 = new Action() { + public String toString() { + return "Start Phase 2"; + } + }; + // Phase1a->Phase12sla, Phase2b->Phase12sla + private static final Action startsl = new Action() { + public String toString() { + return "Start Sinkenlassen"; + } + }; + // Phase12sla->Phase1b, Phase12slb->Phase1b + private static final Action returnphase1 = new Action() { + public String toString() { + return "Return to Phase 1"; + } + }; + // Phase12sla->Phase2a, Phase12slb->Phase2a + private static final Action returnphase2 = new Action() { + public String toString() { + return "Return to Phase 2"; + } + }; + // Phase1b->Phase1a + private static final Action decli = new Action() { + public String toString() { + return "Decrement li"; + } + }; + // Phase2a->Phase2b + private static final Action swap_decre = new Action() { + public String toString() { + return "Swap a[0], a[re] and decrement re"; + } + }; + // Phase12slb->Phase12sla + private static final Action swap = new Action() { + public String toString() { + return "Swap a[i], a[j]"; + } + }; + // Phase12sla->Phase12slb + private static final Action compare = new Action() { + public String toString() { + return "Compare"; + } + }; + // Phase12sla->Done, Phase12slb->Done + private static final Action finish = new Action() { + public String toString() { + return "Finish"; + } + }; + + public static Action getExtend() { + return extend; + } + + public static Action getStartphase0() { + return startphase0; + } + + public static Action getStartphase1() { + return startphase1; + } + + public static Action getStartphase2() { + return startphase2; + } + + public static Action getStartsl() { + return startsl; + } + + public static Action getReturnphase1() { + return returnphase1; + } + + public static Action getReturnphase2() { + return returnphase2; + } + + public static Action getDecli() { + return decli; + } + + public static Action getSwapDecre() { + return swap_decre; + } + + public static Action getCompare() { + return compare; + } + + public static Action getSwap() { + return swap; + } + + public static Action getFinish() { + return finish; + } + + public static boolean isExtend(Action a) { + return a == extend; + } + + public static boolean isStartphase0(Action a) { + return a == startphase0; + } + + public static boolean isStartphase1(Action a) { + return a == startphase1; + } + + public static boolean isStartphase2(Action a) { + return a == startphase2; + } + + public static boolean isStartsl(Action a) { + return a == startsl; + } + + public static boolean isReturnphase1(Action a) { + return a == returnphase1; + } + + public static boolean isReturnphase2(Action a) { + return a == returnphase2; + } + + public static boolean isDecli(Action a) { + return a == decli; + } + + public static boolean isSwapDecre(Action a) { + return a == swap_decre; + } + + public static boolean isCompare(Action a) { + return a == compare; + } + + public static boolean isSwap(Action a) { + return a == swap; + } + + public static boolean isFinish(Action a) { + return a == finish; + } + } + + // states + public static class HeapsortState { + public final List sequence; + + protected HeapsortState(List sequence) { + this.sequence = sequence; + } + } + + public static class InitialState extends HeapsortState implements State { + @SuppressWarnings("unchecked") + public InitialState() { + this(Collections.EMPTY_LIST); + } + + public InitialState(List sequence) { + super(sequence); + } + + public Map computeSuccessors() { + Map result = new HashMap(); + if (sequence.size() > 1) + result.put(new Phase0(sequence), Actions.getStartphase0()); + else + result.put(new Done(sequence), Actions.getFinish()); + return result; + } + + public int getDetailLevel() { + return 0; + } + } + + // phase 0: artificially inserted + public static class Phase0 extends HeapsortState implements State { + public final int level; + + public Phase0(List sequence) { + this(sequence, 0); + } + + public Phase0(List sequence, int level) { + super(sequence); + this.level = level; + } + + public int getDetailLevel() { + return 1; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + if (level < getLevels(sequence.size())) + result.put(new Phase0(sequence, level+1), Actions.getExtend()); + else { + if (sequence.size() > 1) + result.put(new Phase1a(sequence), Actions.getStartphase1()); + else + result.put(new Phase2a(sequence, 0, sequence.size()-1), Actions.getStartphase2()); + } + return result; + } + + public String toString() { + return String.format("Phase 0: level %d, sequence %s", level, sequence.toString()); + } + } + + public static final class Done extends HeapsortState implements State { + + public Done(List sequence) { + super(sequence); + } + + public int getDetailLevel() { + return 0; + } + + public Map computeSuccessors() { + return new HashMap(); + } + + public String toString() { + return String.format("Done: sequence %s", new Object[] {sequence.toString()}); + } + } + + public static class Phase12 extends HeapsortState { + public final int li; + public final int re; + + protected Phase12(List sequence, int li, int re) { + super(sequence); + this.li = li; + this.re = re; + } + + public String toString() { + return String.format("%s: li %d, re %d, sequence %s", getClass() + .getName().substring( + "org.jalgo.module.heapsort.model.Heapsort$" + .length()), li, re, sequence.toString()); + } + } + + // --gophase1-> phase1 --startsl-> phase12sl --compare-> phase12sla (--swap-> phase12sl) --returnphase1-> phase1a --decli-> phase1 + // macro: x (x) x + + public static class Phase1 extends Phase12 { + protected Phase1(List sequence, int li, int re) { + super(sequence, li, re); + } + } + + public static final class Phase1a extends Phase1 implements State { + + public Phase1a(List sequence) { + super(sequence, sequence.size() / 2 - 1, sequence.size()-1); + } + + public Phase1a(List sequence, int li, int re) { + super(sequence, li, re); + } + + public int getDetailLevel() { + return 0; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + result.put(new Phase12sla(sequence, li, re), Actions.getStartsl()); + return result; + } + + } + + public static final class Phase1b extends Phase1 implements State { + + public Phase1b(List sequence, int li, int re) { + super(sequence, li, re); + } + + public int getDetailLevel() { + return 2; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + result.put(new Phase1a(sequence, li-1, re), Actions.getDecli()); + return result; + } + + } + + // --gophase2-> phase2 --swap_decre-> phase2a --startsl-> ... --returnphase2-> phase2 + // macro: x x + + public static class Phase2 extends Phase12 { + protected Phase2(List sequence, int li, int re) { + super(sequence, li, re); + } + } + + public static final class Phase2a extends Phase2 implements State { + + public Phase2a(List sequence, int li, int re) { + super(sequence, li, re); + } + + public int getDetailLevel() { + return 0; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + ArrayList sequenceprime = new ArrayList(sequence); + int a_0 = sequenceprime.get(0); + int a_re = sequenceprime.get(re); + sequenceprime.set(0, a_re); + sequenceprime.set(re, a_0); + result.put(new Phase2b(sequenceprime, li, re-1), Actions.getSwapDecre()); + return result; + } + + } + + public static final class Phase2b extends Phase2 implements State { + + public Phase2b(List sequence, int li, int re) { + super(sequence, li, re); + } + + public int getDetailLevel() { + return 0; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + result.put(new Phase12sla(sequence, li, re), Actions.getStartsl()); + return result; + } + + } + + public static class Phase12sl extends Phase12 { + public final int i; + + protected Phase12sl(List sequence, int li, int re, int i) { + super(sequence, li, re); + this.i = i; + } + + protected void addReturnState(Map m) { + if (li > 0) + m.put(new Phase1b(sequence, li, re), Actions.getReturnphase1()); + else { + if (re > 0) { + m.put(new Phase2a(sequence, li, re), Actions.getReturnphase2()); + } + else + m.put(new Done(sequence), Actions.getFinish()); + } + } + } + + public static final class Phase12sla extends Phase12sl implements State { + + public Phase12sla(List sequence, int li, int re) { + this(sequence, li, re, li); + } + + public Phase12sla(List sequence, int li, int re, int i) { + super(sequence, li, re, i); + } + + public int getDetailLevel() { + return 2; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + if (2*i+1 > re) + addReturnState(result); + else + result.put(new Phase12slb(sequence, li, re, i), Actions.getCompare()); + return result; + } + + } + + public static final class Phase12slb extends Phase12sl implements State { + + public Phase12slb(List sequence, int li, int re, int i) { + super(sequence, li, re, i); + } + + public int getDetailLevel() { + return 1; + } + + public Map computeSuccessors() { + Map result = new HashMap(); + int j = 2*i+1; + if ((j+1 <= re) && (sequence.get(j) sequenceprime = new ArrayList(sequence); + int a_i = sequenceprime.get(i); + int a_j = sequenceprime.get(j); + sequenceprime.set(i, a_j); + sequenceprime.set(j, a_i); + result.put(new Phase12sla(sequenceprime, li, re, j), Actions.getSwap()); + } + else + addReturnState(result); + return result; + } + + } + + public static class ModelChangedNotifier implements Notifier { + private static final ModelChangedNotifier arnie = new ModelChangedNotifier(); + + public static Notifier getInstance() { + return arnie; + } + + public void invoke(ModelListener l) { + l.modelChanged(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/model/Model.java b/src/org/jalgo/module/heapsort/model/Model.java new file mode 100644 index 0000000..b89655d --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/Model.java @@ -0,0 +1,47 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + *

          This interface is used for modelling algorithms and their runs. + * We adopt some kind of reduction semantics, meaning that we + * start in some initial state and iteratively derive successor + * states until we reach a final state. Implementing classes + * should offer the possibility to set the input data considered + * in the run starting with the state returned as initial.

          + * + *

          Implementing classes should be derived from + * Subject<ModelListener> and notify listeners + * of changes in the input data.

          + * + * @author mbue + */ +public interface Model { + void deserialize(InputStream is) throws IOException; + State getInitialState(); + void serialize(OutputStream os) throws IOException; +} diff --git a/src/org/jalgo/module/heapsort/model/ModelListener.java b/src/org/jalgo/module/heapsort/model/ModelListener.java new file mode 100644 index 0000000..86fb279 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/ModelListener.java @@ -0,0 +1,32 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +/** + * Listener interface for classes implementing Model. + * + * @author mbue + */ +public interface ModelListener { + void modelChanged(); +} diff --git a/src/org/jalgo/module/heapsort/model/Sequencer.java b/src/org/jalgo/module/heapsort/model/Sequencer.java new file mode 100644 index 0000000..05ffa82 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/Sequencer.java @@ -0,0 +1,248 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.Map.Entry; + +import org.jalgo.module.heapsort.Subject; + +/** + *

          The sequencer is used to construct a derivation. From a current state, it + * derives successor states and stores them. Following some derivation strategy, + * it will select the successor which will become the current state.

          + * + *

          Note: ATM, no elaborate strategy is implemented nor conceived. + * Thus, only deterministic algorithms are supported!

          + * + * @author mbue + */ +public final class Sequencer extends Subject { + /** + * A data structure needed in the derivation. It stores the successors of + * some state along with the index of the successor chosen by the strategy + * the be reduced further. + * + * @author mbue + */ + private static class Level { + /** + * The successor which was chosen by the strategy to be reduced further. + */ + public int current; + /** + * The data for the current successor. + */ + public Level next; + /** + * Parent. + */ + public Level prev; + /** + * The list of successors. + */ + public List> successors; + } + + /** + * Some token implementation of Map.Entry, which is needed for + * the initial level. (See constructor of Sequencer). + * + * @author mbue + * + * @param + * @param + */ + private static class MyEntry implements Entry { + + private K key; + private V value; + + public MyEntry(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + @SuppressWarnings("unchecked") + public Object setValue(Object arg0) { + V old = value; + value = (V)arg0; + return old; + } + + } + + private Level head = null; + private Level current = null; + + @SuppressWarnings("unchecked") + public Sequencer(State initial) { + head = new Level(); + head.current = 0; + head.next = null; + head.prev = null; + head.successors = new LinkedList>(); + head.successors.add(new MyEntry(initial, null)); + current = head; + } + + /** + * If not already done, reduce the current state. Does not change the current state, + * though---use step to achieve that. This method will trigger stepAvail + * iff derivation is possible. + */ + public void derive() { + if (current.next == null) { + Set> entries = + current.successors.get(current.current).getKey(). + computeSuccessors().entrySet(); + if (!entries.isEmpty()) { + Level tail = new Level(); + tail.next = null; + tail.prev = current; + tail.current = 0; + tail.successors = new LinkedList>(entries); + current.next = tail; + notifyAll(NotifyStepAvail.getInstance()); + } + } + } + + /** + * Make a derivation step. Uses derive() if necessary, but won't trigger + * stepAvailable. If a step is actually taken, step will + * be triggered. + * + * @return True iff some step could be taken. + */ + public boolean step() { + if (current.next == null) { + suspendUpdates(); + try { + derive(); + } + finally { + resumeUpdates(); + } + } + if (current.next != null) { + Entry e = null; + Level old = current; + + current = current.next; + + e = current.successors.get(current.current); + notifyAll(new NotifyStep(old.successors.get(old.current).getKey(), + e.getValue(), e.getKey())); + return true; + } + else + return false; + } + + /** + * Go backwards in the derivation, triggering back. + * Return false iff current state already is the initial state. + * + * @return True iff some step could be taken. + */ + public boolean back() { + if (current.prev != null) { + Entry e = current.successors.get(current.current); + current = current.prev; + + // arguments: ex-current state, action which got us there, ex-previous state + notifyAll(new NotifyBack(e.getKey(), e.getValue(), + current.successors.get(current.current).getKey())); + return true; + } + else + return false; + } + + public State getCurrentState() { + return current.successors.get(current.current).getKey(); + } + + public boolean isBackPossible() { + return current.prev != null; + } + + public boolean isStepPossible() { + return current.next != null; + } + + private static class NotifyStepAvail implements Notifier { + private static NotifyStepAvail arnie = new NotifyStepAvail(); + + public static NotifyStepAvail getInstance() { + return arnie; + } + + public void invoke(SequencerListener l) { + l.stepAvail(); + } + } + + private static class NotifyStep implements Notifier { + private State q; + private State q1; + private Action a; + + public NotifyStep(State q, Action a, State q1) { + this.q = q; + this.q1 = q1; + this.a = a; + } + + public void invoke(SequencerListener l) { + l.step(q, a, q1); + } + } + + private static class NotifyBack implements Notifier { + private State q; + private State q1; + private Action a; + + public NotifyBack(State q, Action a, State q1) { + this.q = q; + this.q1 = q1; + this.a = a; + } + + public void invoke(SequencerListener l) { + l.back(q, a, q1); + } + } +} diff --git a/src/org/jalgo/module/heapsort/model/SequencerListener.java b/src/org/jalgo/module/heapsort/model/SequencerListener.java new file mode 100644 index 0000000..00f400f --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/SequencerListener.java @@ -0,0 +1,59 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +/** + * Listener interface for the Sequencer class. + * + * @author mbue + */ +public interface SequencerListener { + /** + * This method will be called when it turns out that + * a derivation step can be made that was previously + * unaccounted for. You can use this to recheck whether + * a step can be made. In the current implementation, + * this is not really meaningful because states will + * immediately be derived when becoming current, and + * this will only be done once. + */ + void stepAvail(); + + /** + * Notification that the sequencer has made a step. + * + * @param q Previous state. + * @param a Action taken. + * @param q1 Next (now current) state. + */ + void step(State q, Action a, State q1); + + /** + * Notification that the sequencer has made a step back. + * + * @param q Previously current state. + * @param a Action taken (read: undone). + * @param q1 Now current state. + */ + void back(State q, Action a, State q1); +} diff --git a/src/org/jalgo/module/heapsort/model/State.java b/src/org/jalgo/module/heapsort/model/State.java new file mode 100644 index 0000000..efb33b0 --- /dev/null +++ b/src/org/jalgo/module/heapsort/model/State.java @@ -0,0 +1,50 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.model; + +import java.util.Map; + +/** + * The interface State is used to represent a state in the computation of the algorithm. + * Runs can be constructed by using the method computeSuccessors. Note + * that this restricts us to a finite branching factor, which excludes e. g. algorithms + * guessing natural numbers. + * + * @author mbue + */ +public interface State { + /** + * Returns the detail level of the state. The system might allow the user to + * automatically derive up to the next state which has at most a certain detail + * level (that is, not stopping when a state has a greater detail level). + * @return + */ + int getDetailLevel(); + + /** + * Computes a list of successor states. + * + * @return + */ + Map computeSuccessors(); +} diff --git a/src/org/jalgo/module/heapsort/renderer/CVS/Entries b/src/org/jalgo/module/heapsort/renderer/CVS/Entries new file mode 100644 index 0000000..7f47524 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CVS/Entries @@ -0,0 +1,10 @@ +/CanvasEntity.java/1.5/Wed Feb 6 20:21:15 2008// +/CanvasEntityFactory.java/1.4/Wed Jan 30 12:23:34 2008// +/CanvasEntityVisitor.java/1.4/Wed Jan 30 12:23:34 2008// +/Edge.java/1.5/Wed Feb 6 20:21:15 2008// +/MarkingRect.java/1.5/Wed Feb 6 20:21:15 2008// +/Node.java/1.5/Wed Feb 6 20:21:15 2008// +/RenderJava2D.java/1.7/Wed Feb 6 20:21:15 2008// +/Renderer.java/1.5/Wed Feb 6 20:21:15 2008// +/SequenceElement.java/1.5/Wed Feb 6 20:21:15 2008// +/Text.java/1.4/Wed Jan 30 12:23:33 2008// diff --git a/src/org/jalgo/module/heapsort/renderer/CVS/Repository b/src/org/jalgo/module/heapsort/renderer/CVS/Repository new file mode 100644 index 0000000..111da04 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/heapsort/renderer diff --git a/src/org/jalgo/module/heapsort/renderer/CVS/Root b/src/org/jalgo/module/heapsort/renderer/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/heapsort/renderer/CanvasEntity.java b/src/org/jalgo/module/heapsort/renderer/CanvasEntity.java new file mode 100644 index 0000000..0acbc14 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CanvasEntity.java @@ -0,0 +1,366 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Rectangle; +import java.awt.geom.AffineTransform; +import java.awt.geom.Point2D; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; + +/** + *

          The CanvasEntity class represents an object on the virtual canvas. Each such object has + * an affine transformation, which describes the relationship between the ("relative", or local) + * coordinates wrt. to the entity and the ("absolute") coordinates which are local to its parent. + *

          + * + *

          A canvas entity keeps a log of where the image has to be redrawn, the so-called dirty region. + * The dirty region is a rectangle expressed in absolute coordinates (which is needed in case + * the affine transform is changed, and in particular, when the new transform has no inverse). + * (Imagine how you would express some non-empty box in local coordinates when the transform + * maps everything to one particular point.) + *

          + * + *

          Furthermore, canvas entities have a bounding box (expressed in local coordinates) and an + * integer describing the position in the z order of the canvas. Note that, if the bounding box + * were in absolute coordinates, it could grow every time a non-quadrant rotation is applied. + * Besides, the transformation could not be reset, only concatenated.

          + * + * @author mbue + */ +public class CanvasEntity { + protected Rectangle bounds = new Rectangle(0,0,-1,-1); // nothing + protected Rectangle dirty = new Rectangle(0,0,-1,-1); // nothing + protected AffineTransform trans = new AffineTransform(); // identity + protected int zorder = 0; + + protected Set children = + new TreeSet(CanvasEntityComparator.getInstance()); + + // hide constructor to prevent people from forgetting to use the + // factory provided by the renderer + protected CanvasEntity() { + + } + + /** + *

          Adds canvas entity c to the children of this node. + * Does nothing if c already in this hierarchy.

          + *

          Note: This will of course not stop you from adding the same canvas + * entity twice to some tree by adding it to some node and then + * to another one which is deeper in the tree. Just don't do it.

          + * + * @param c canvas entity to be added + */ + public void addChild(CanvasEntity c) { + // dirty region need not be changed because it is + // computed recursively on demand + if (findParentOf(c) == null) + children.add(c); + } + + /** + * Finds the parent node of a given canvas entity c. + * Returns null iff this node is not contained in the + * subtrees below this. + * + * @param c + * @return parent of c, or null if + * c not in this hierarchy + */ + public CanvasEntity findParentOf(CanvasEntity c) { + // leaf node: can't be parent + if (children.isEmpty()) + return null; + // this is parent + if (children.contains(c)) + return this; + // one of the children could be parent + CanvasEntity result = null; + for (CanvasEntity ch: children) { + result = ch.findParentOf(c); + if (result != null) + return result; + } + return result; + } + + /** + * Remove c from the children of this node. + * Adjust dirty region accordingly. + * Does nothing if c is no child of this node. + * + * @param c canvas entity to be removed + */ + public void removeChild(CanvasEntity c) { + // check this for sake of failure atomicity + if (children.contains(c)) { + c.invalidate(); + dirty.add(transformBounds(c.dirty, trans)); + children.remove(c); + } + } + + /** + * Apply the visitor v to every canvas entity in this subtree. + * + * @param v + */ + public void fold(CanvasEntityVisitor v) { + fold(v, new AffineTransform()); + } + + protected void fold(CanvasEntityVisitor v, AffineTransform t) { + // t1 = t . trans + AffineTransform t1 = new AffineTransform(t); + t1.concatenate(trans); + v.invoke(this, t1, null); + for (CanvasEntity e: children) + e.fold(v, t1); + } + + /** + *

          Apply the visitor v to every canvas entity in this subtree, provided that + * they intersect with the rectangle r, which is regarded as being in absolute + * coordinates wrt. this.

          + * + *

          As an example scenario, the rectangle r could be the intersection of + * some visible area with the dirty region of this.

          + * + * @param v + * @param r + * @param t + */ + public void foldVisible(CanvasEntityVisitor v, Rectangle r) { + foldVisible(v, r, new AffineTransform()); + } + + protected void foldVisible(CanvasEntityVisitor v, Rectangle r, AffineTransform t) { + // t1 = t . trans + AffineTransform t1 = new AffineTransform(t); + t1.concatenate(trans); + // transform bounding box into absolute coordinates and test intersection + if (transformBounds(bounds, t1).intersects(r)) { + v.invoke(this, t1, r); + for (CanvasEntity e: children) + e.foldVisible(v, r, t1); + } + } + + /** + *

          Adds the bounding box to the dirty region causing this entity + * (and others underneath or above) to be redrawn.

          + * + *

          NOTE that if you change the transformation, you have to call + * this beforehands and afterwards! + */ + public void invalidate() { + dirty.add(transformBounds(bounds, trans)); + } + + /** + * Sets the bounding box of this canvas entity to newBounds, adding to + * the dirty region both the old and the new bounding box. + * + * @param newBounds + */ + public void setBounds(Rectangle newBounds) { + if (!bounds.equals(newBounds)) { + invalidate(); + bounds.setBounds(newBounds); + invalidate(); + } + } + + /** + * Returns the z order value. + * @return + */ + public int getZorder() { + return zorder; + } + + /** + * Changes the Z order of this entity. This will invalidate the current image of the entity. + * + * @param newz + */ + public void setZorder(int newz) { + if (newz != zorder) { + zorder = newz; + invalidate(); + } + } + + /** + * Compute the dirty region of the whole entity subtree (starting at this), + * which is the union of the dirty regions of the entities, transformed into the absolute + * coordinate system wrt. this. + * + * @return Union of dirty regions of subtree + */ + public Rectangle computeDirtyRegion() { + // start computation with our dirty region (this is already + // in absolute coordinates) + ComputeDirtyVisitor v = new ComputeDirtyVisitor(dirty); + // transform dirty regions of subtrees + fold(v); + return v.dirty; + } + + /** + * Clear the dirty regions of the whole entity subtree starting at this. + * + */ + public void clearDirtyRegion() { + fold(ClearDirtyVisitor.getInstance()); + } + + /** + * Compute the bounding box of the rectangle which is obtained by + * applying the AffineTransform t to the rectangle + * b. + * + * @param b + * @param t + * @return + */ + public static Rectangle transformBounds(Rectangle b, AffineTransform t) { + if (b.width < 0 || b.height < 0) + return b; + + // set up data structures for transformation + Point2D[] s = { + new Point2D.Double(b.x, b.y), + new Point2D.Double(b.x, b.y+b.height), + new Point2D.Double(b.x+b.width, b.y), + new Point2D.Double(b.x+b.width, b.y+b.height)}; + Point2D[] d = new Point2D.Double[4]; + + // transform b by t + t.transform(s, 0, d, 0, 4); + + // compute bounding box + double minx = d[0].getX(); + double maxx = d[0].getX(); + double miny = d[0].getY(); + double maxy = d[0].getY(); + + for (int i = 1; i<4; i++) { + if (d[i].getX() < minx) + minx = d[i].getX(); + + if (d[i].getX() > maxx) + maxx = d[i].getX(); + + if (d[i].getY() < miny) + miny = d[i].getY(); + + if (d[i].getY() > maxy) + maxy = d[i].getY(); + } + // FIXME make it a bit bigger because of rounding errors/lack of accuracy + return new Rectangle((int)minx-1, (int)miny-1, (int)(maxx-minx)+2, (int)(maxy-miny)+2); + } + + // auxiliary class used in computeDirtyRegion() + // this demonstrates the wordiness of Java + private static class ComputeDirtyVisitor implements CanvasEntityVisitor { + public Rectangle dirty = null; + + public ComputeDirtyVisitor() { + this(new Rectangle(0,0,-1,-1)); + } + + public ComputeDirtyVisitor(Rectangle dirty) { + this.dirty = dirty; + } + + public void invoke(CanvasEntity e, AffineTransform t, Rectangle clip) { + // the dirty regions of the children are in our + // local coordinate space, transform into global + // clip can be ignored! + for (CanvasEntity c: e.children) { + Rectangle dtrans = transformBounds(c.dirty, t); + dirty.add(dtrans); + } + } + } + + // auxiliary class used in clearDirtyRegion() + private static class ClearDirtyVisitor implements CanvasEntityVisitor { + // technical stuff: this visitor has no state and can therefore be allocated statically + private static ClearDirtyVisitor arnie = new ClearDirtyVisitor(); + + public void invoke(CanvasEntity e, AffineTransform t, Rectangle clip) { + // clip is ignored here as well + // -------------------------------------------- + // assume we render root.computeDirtyRegion() + // then the whole dirty region is accounted for + // and intersecting with clip would be neutral + // -------------------------------------------- + // assume we render some visible region + // then invisible parts of the dirty region + // would not matter because they will be marked + // dirty anyway when becoming visible + e.dirty.height = -1; + e.dirty.width = -1; + } + + public static ClearDirtyVisitor getInstance() { + return arnie; + } + } + + /** + *

          A comparator for canvas entities.

          + * + *

          c1 <= c2 iff
          + * + * c1.zorder <= c2.zorder or
          + * c1.zorder == c2.zorder implies c1.hashCode() <= c2.hashCode().

          + * + * @author mbue + */ + private static class CanvasEntityComparator implements Comparator { + private static CanvasEntityComparator comp = new CanvasEntityComparator(); + + public static Comparator getInstance() { + return comp; + } + + public int compare(CanvasEntity o1, CanvasEntity o2) { + // lexicographic order on direct product + // int x int + // (zorder, hashCode()) + int res = o1.zorder-o2.zorder; + if (res == 0) + return o1.hashCode()-o2.hashCode(); + else + return res; + } + + } + +} diff --git a/src/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.java b/src/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.java new file mode 100644 index 0000000..4cb1906 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CanvasEntityFactory.java @@ -0,0 +1,42 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Point; + +/** + *

          This interface defines the canvas entity classes supported + * by the system, which makes it sort of a reference. If you add + * a new canvas entity class, this has to be reflected here, + * forcing all renderers to implement this class.

          + * + * @author mbue + */ +public interface CanvasEntityFactory { + CanvasEntity createRoot(); + Node createNode(Point pos, String label); + Text createText(String text, int width, int height); + MarkingRect createMarkingRect(); + SequenceElement createSequenceElement(Point pos, String label); + Edge createEdge(Point from, Point to); +} diff --git a/src/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.java b/src/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.java new file mode 100644 index 0000000..7778784 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/CanvasEntityVisitor.java @@ -0,0 +1,52 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Rectangle; +import java.awt.geom.AffineTransform; + +/** + *

          Interface used to implement the visitor pattern for canvas entities. + * (A pattern not explicitly found in languages more capable than Java, + * like... Python or every other language.)

          + * + *

          Note: We will often call our visitor objects arnie, because Arnie is the + * one who visits people most effectively.

          + * + * @author mbue + * + */ +public interface CanvasEntityVisitor { + /** + * This method is called in the visiting process. The canvas entity + * to be visited is given by e, and trans is + * the affine transform yielding absolute coordinates wrt. to the root + * of the subtree on which the process is started. The third parameter, + * clip, determines a rectangle on which operations + * have to be limited. Often this will be null. + * + * @param e + * @param trans + */ + void invoke(CanvasEntity e, AffineTransform trans, Rectangle clip); +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/renderer/Edge.java b/src/org/jalgo/module/heapsort/renderer/Edge.java new file mode 100644 index 0000000..867583d --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/Edge.java @@ -0,0 +1,70 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Point; + +/** + * A canvas entity representing an edge in a tree. The following + * restriction applies: The to point must be below + * the from point in the sense that its y + * component must be larger. + * + * @author mbue + */ +public class Edge extends CanvasEntity { + protected Point from; + protected Point to; + protected float opacity = 1.0f; + + protected Edge(Point from, Point to) { + this.from = from; + this.to = to; + updateBounds(); // FIXME this will call update, which is not good in the half-constructed state + } + + private final void updateBounds() { + invalidate(); + if (to.x < from.x) + bounds.setBounds(to.x, from.y, from.x-to.x, to.y-from.y); + else + bounds.setBounds(from.x, from.y, to.x-from.x, to.y-from.y); + update(); + } + + /** + * @see Node#update() + */ + protected void update() { + } + + public final float getOpacity() { + return opacity; + } + + public final void setOpacity(float opacity) { + this.opacity = opacity; + invalidate(); + update(); + } +} diff --git a/src/org/jalgo/module/heapsort/renderer/MarkingRect.java b/src/org/jalgo/module/heapsort/renderer/MarkingRect.java new file mode 100644 index 0000000..d41f4b0 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/MarkingRect.java @@ -0,0 +1,111 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Color; +import java.awt.Point; + +/** + * A solid rectangular canvas entity which can be used to highlight + * canvas entities above it. + * + * @author mbue + */ +public class MarkingRect extends CanvasEntity { + private Color color = Color.GRAY; + private Point position = new Point(); + private float opacity = 1.0f; + private int width; + private int height; + + protected MarkingRect() { + super(); + } + + /** + * @see Node#update() + * + */ + protected void update() { + } + + public final Point getPosition() { + return position; + } + + public final void setPosition(Point position) { + if (!this.position.equals(position)) { + this.position.setLocation(position); + invalidate(); + trans.setToTranslation(position.x, position.y); + invalidate(); + } + } + + public final int getHeight() { + return height; + } + + public final void setHeight(int height) { + if (height != this.height) { + this.height = height; + invalidate(); + bounds.setBounds(0, 0, width, height); + invalidate(); + } + + } + + public final int getWidth() { + return width; + } + + public final void setWidth(int width) { + if (width != this.width) { + this.width = width; + invalidate(); + bounds.setBounds(0, 0, width, height); + invalidate(); + } + } + + public final float getOpacity() { + return opacity; + } + + public final void setOpacity(float opacity) { + this.opacity = opacity; + invalidate(); + update(); + } + + public final Color getColor() { + return color; + } + + public final void setColor(Color color) { + this.color = color; + update(); + } + +} diff --git a/src/org/jalgo/module/heapsort/renderer/Node.java b/src/org/jalgo/module/heapsort/renderer/Node.java new file mode 100644 index 0000000..f27caae --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/Node.java @@ -0,0 +1,128 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Point; + +/** + * A canvas entity representing a node as used in Heapsort; this means: + * a circle with a two-digit number in it. + * + * @author mbue + */ +public class Node extends CanvasEntity { + private float highlight = 0.0f; + private String label; + private Point position = new Point(); + private double scale = 1.0; + + public Node(Point pos, String label) { + bounds.setBounds(-20, -20, 40, 40); + // use a trick: + // if label == null, invalidation will only occur after setting + setPosition(pos); + // don't use setLabel: + // a) this.label is null (would crash) + // b) too early to invalidate + this.label = label; + } + + /** + *

          This is called whenever the visual appearance + * parameters have changed and can thus be used by + * the descendant class (typically rendering-specific) + * to update its internal structures (textures etc.)

          + * + *

          However, the renderer could as well detect changes + * on demand (lazily, so to speak), which would of + * course require caching the old values...

          + */ + protected void update() { + // "nothing is being done..." (Jeff Beck) + } + + public final float getHighlight() { + return highlight; + } + + public final void setHighlight(float value) { + if (value != highlight) { + highlight = value; + invalidate(); + update(); + } + } + + public final String getLabel() { + return label; + } + + public final void setLabel(String label) { + if (!this.label.equals(label)) { + this.label = label; + invalidate(); + update(); + } + } + + public final Point getPosition() { + return position; + } + + // newly added method just for allowing efficient animations + public final void setPosition(double x, double y) { + invalidate(); + this.position.setLocation(x, y); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + //update(); -- nothing is changed concerning the appearance + } + + public final void setPosition(Point position) { + if (!this.position.equals(position)) { + this.position.setLocation(position); + if (label != null) + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + //update(); -- nothing is changed concerning the appearance + } + } + + public final double getScale() { + return scale; + } + + public final void setScale(double scale) { + if (this.scale != scale) { + this.scale = scale; + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + update(); + } + } +} diff --git a/src/org/jalgo/module/heapsort/renderer/RenderJava2D.java b/src/org/jalgo/module/heapsort/renderer/RenderJava2D.java new file mode 100644 index 0000000..7554353 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/RenderJava2D.java @@ -0,0 +1,369 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Container; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Stroke; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.geom.AffineTransform; +import java.awt.image.VolatileImage; + +import javax.swing.JPanel; + +/** + *

          Java2D renderer. There are some restrictions, mainly: Transparency is faked by + * fading the color towards the background color. This is totally sufficient for + * our purposes and much more efficient.

          + * + *

          Currently, it uses a lightweight component for the output meaning that your nice + * little popup menus may also be lightweight.

          + * + * @author mbue + */ +public final class RenderJava2D implements Renderer, CanvasEntityFactory, ComponentListener { + + // definition of RenderCanvas to be found at the end of this class + private RenderCanvas c; + private VolatileImage backbuffer; + private RootJava2D root; + + // Renderer methods + + public void init(Container cc) { + c = new RenderCanvas(); + c.addComponentListener(this); + cc.add(c); + backbuffer = null; + //backbuffer = c.createVolatileImage(c.getWidth(), c.getHeight()); + } + + public void dispose() { + if (backbuffer != null) { + backbuffer.flush(); + backbuffer = null; + } + c.getParent().remove(c); + c = null; + } + + public CanvasEntityFactory createFactory() { + return this; + } + + public Rectangle getVisible() { + return new Rectangle(0, 0, c.getWidth(), c.getHeight()); + } + + public boolean validate() { + if (backbuffer == null) { + // component was not displayable last time we tried + // try again + try { + backbuffer = c.createVolatileImage(c.getWidth(), c.getHeight()); + } + catch (IllegalArgumentException e) { + ; // XXX do nothing + } + return true; + } + else { + if (c.getWidth() != backbuffer.getWidth() || c.getHeight() != backbuffer.getHeight()) { + backbuffer.flush(); + backbuffer = null; + backbuffer = c.createVolatileImage(c.getWidth(), c.getHeight()); + backbuffer.validate(c.getGraphicsConfiguration()); + return true; + } + else { + int rc = backbuffer.validate(c.getGraphicsConfiguration()); + if (rc == VolatileImage.IMAGE_INCOMPATIBLE) { + backbuffer.flush(); + backbuffer = null; + backbuffer = c.createVolatileImage(c.getWidth(), c.getHeight()); + return true; + } + return rc != VolatileImage.IMAGE_OK; + } + } + } + + public void renderVisible(CanvasEntity root, Rectangle r) { + if (backbuffer == null) + return; // BAIL OUT + Graphics2D g = (Graphics2D)backbuffer.getGraphics(); + try { + AffineTransform t = g.getTransform(); + g.setClip(r); + root.foldVisible(new RenderVisitor(g), r, t); + g.setTransform(t); + } + finally { + g.dispose(); + } + } + + public boolean show(Rectangle r) { + if (r == null) + c.repaint(); + else + c.repaint(r.x, r.y, r.width, r.height); + return true; + } + + // factory methods + + public CanvasEntity createRoot() { + if (root == null) + root = new RootJava2D(); + return root; + } + + public Node createNode(Point pos, String label) { + return new NodeJava2D(pos, label); + } + + public Text createText(String text, int width, int height) { + return new TextJava2D(text, width, height); + } + + public MarkingRect createMarkingRect() { + return new MarkingRectJava2D(); + } + + public SequenceElement createSequenceElement(Point pos, String label) { + return new SequenceElementJava2D(pos, label); + } + + public Edge createEdge(Point from, Point to) { + return new EdgeJava2D(from, to); + } + + // Last Action Renderer + + private class RenderVisitor implements CanvasEntityVisitor { + private Graphics2D g = null; + + public RenderVisitor(Graphics2D graphics) { + g = graphics; + g.setFont(defaultfont); + g.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + } + + public void invoke(CanvasEntity e, AffineTransform trans, Rectangle clip) { + if (e instanceof Renderable) { + g.setTransform(trans); + ((Renderable)e).render(g); + } + } + + } + + // Canvas Entities + + private interface Renderable { + void render(Graphics2D g); + } + + private static final Font defaultfont = new Font("sans", Font.BOLD, 16); + private static final Font regularfont = new Font("sans", 0, 14); + private static final Stroke ndstroke = new BasicStroke(2); + private static final Stroke seqstroke = new BasicStroke(1); + + private static class RootJava2D extends CanvasEntity implements Renderable { + + public void render(Graphics2D g) { + Rectangle r = bounds; + g.setColor(Color.WHITE); + //int c = (int)((System.nanoTime()>>23)&0xff); + //int c = children.size()*3; + //g.setColor(new Color(c|c<<8|c<<16)); + g.fillRect(r.x, r.y, r.width, r.height); + } + + } + + private static class NodeJava2D extends Node implements Renderable { + public NodeJava2D(Point pos, String label) { + super(pos, label); + } + + public void render(Graphics2D g) { + float f = getHighlight(); + float f1 = 1.0f-f; + FontMetrics fm = g.getFontMetrics(); + int w = fm.stringWidth(getLabel()); + int h = fm.getAscent(); + g.setStroke(ndstroke); + g.setColor(new Color(f1+f*(244.0f/255), f1+f*(184.0f/255), f1)); + g.fillOval(bounds.x, bounds.y, bounds.width-1, bounds.height-1); + g.setColor(Color.BLUE); + g.drawOval(bounds.x+1, bounds.y+1, bounds.width-3-1, bounds.height-3-1); + g.setColor(Color.BLACK); + //g.drawRect(bounds.x+(bounds.width-w)/2, bounds.y+(bounds.height-h)/2-2, + // w-1, h-1); + g.drawString(getLabel(), bounds.x+(bounds.width-w)/2, bounds.y+(bounds.height+h)/2-2); + } + } + + private static class TextJava2D extends Text implements Renderable { + public TextJava2D(String text, int width, int height) { + super(text, width, height); + } + + public void render(Graphics2D g) { + // XXX this is NOT failure atomic + if (isRegular()) + g.setFont(regularfont); + float f = 1.0f-getOpacity(); + FontMetrics fm = g.getFontMetrics(); + int w = fm.stringWidth(getText()); + int h = fm.getAscent(); + g.setColor(new Color(f, f, f)); + if (isRegular()) { + g.drawString(getText(), bounds.x+bounds.width-w, bounds.y+(bounds.height+h)/2-2); + g.setFont(defaultfont); + } + else + g.drawString(getText(), bounds.x+(bounds.width-w)/2, bounds.y+(bounds.height+h)/2-2); + } + } + + private static class MarkingRectJava2D extends MarkingRect implements Renderable { + + public void render(Graphics2D g) { + Color c1 = getColor(); + float f1 = getOpacity(); + //float f = 1.0f-0.3f*f1; + g.setStroke(seqstroke); + //g.setColor(new Color(f, f, f)); + g.setColor(new Color( + (float)1.0f+(c1.getRed()/255.0f-1.0f)*f1, + 1.0f+(c1.getGreen()/255.0f-1.0f)*f1, + 1.0f+(c1.getBlue()/255.0f-1.0f)*f1)); + g.fillRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1); + } + } + + private static class SequenceElementJava2D extends SequenceElement implements Renderable { + public SequenceElementJava2D(Point pos, String label) { + super(pos, label); + } + + public void render(Graphics2D g) { + float f = getHighlight(); + float f1 = 1.0f-f; + FontMetrics fm = g.getFontMetrics(); + int w = fm.stringWidth(getLabel()); + int h = fm.getAscent(); + g.setStroke(seqstroke); + g.setColor(new Color(f1+f*(244.0f/255), f1+f*(184.0f/255), f1)); + g.fillRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1); + g.setColor(Color.GRAY); + g.drawRect(bounds.x, bounds.y, bounds.width-1, bounds.height-1); + g.setColor(Color.BLACK); + g.drawString(getLabel(), bounds.x+(bounds.width-w)/2, bounds.y+(bounds.height+h)/2-2); + } + } + + private static class EdgeJava2D extends Edge implements Renderable { + public EdgeJava2D(Point from, Point to) { + super(from, to); + } + + public void render(Graphics2D g) { + float f = 1.0f-0.7f*getOpacity(); + g.setStroke(ndstroke); + g.setColor(new Color(f, f, f)); + g.drawLine(from.x, from.y, to.x, to.y); + } + } + + // component listener methods + + public void componentHidden(ComponentEvent e) { + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentResized(ComponentEvent e) { + // setting bounds to visible works + // as long as root.trans is identity + // FIXME we center the output here + // this is quick AND dirty! + synchronized (root) { + if (root != null) { + Rectangle r = getVisible(); + int dx = r.width/2; + root.trans.setToTranslation(dx, 0); + root.setBounds(new Rectangle(-dx, 0, r.width, r.height)); + } + } + } + + public void componentShown(ComponentEvent e) { + //if (root != null) + // root.setBounds(getVisible()); + componentResized(e); + } + + /** + * A Canvas descendant responsible for + * providing the backbuffer (via createVolatileImage) + * and updating its contents on the primary buffer. + * + * @author mbue + */ + @SuppressWarnings("serial") + private class RenderCanvas extends JPanel { + @Override + public void paint(Graphics g) { + if (backbuffer != null) { + if (!backbuffer.contentsLost()) + g.drawImage(backbuffer, 0, 0, null); + else + root.invalidate(); + } + } + + /*@Override + public void update(Graphics g) { + // we override update because in the default implementation + // update would clear the surface before calling paint + paint(g); + }*/ + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/renderer/Renderer.java b/src/org/jalgo/module/heapsort/renderer/Renderer.java new file mode 100644 index 0000000..1fdba60 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/Renderer.java @@ -0,0 +1,107 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Container; +import java.awt.Rectangle; + +/** + *

          This interface corresponds to a primary (=output) surface + * of a renderer. Actually, the renderer may and should use + * a backbuffer if applicable. From my current point of view, + * a Java2D renderer should use a backbuffer while a JOGL renderer + * need not, but I am not sure about this.

          + * + *

          Canvas entities are created wrt. to this because they could + * be requiring hardware resources.

          + * + * @author mbue + * + */ +public interface Renderer { + /** + * Initialize renderer. Creates a component which will be used to display + * everything. + * + * @param cc A container into which the output component will be placed. + */ + void init(Container cc); + + /** + * Finalise renderer. + */ + void dispose(); + + // -- factory stuff + + /** + * Returns a canvas entity factory for use with this renderer. + * + * @return + */ + CanvasEntityFactory createFactory(); + + // -- rendering stuff + /** + * Returns the rectangle describing the visible area, which can be + * used for intersection with some dirty region when calling + * renderVisible. + * + * @return + */ + Rectangle getVisible(); + + /** + * Returns whether the image was lost since the + * last time it was rendered. This MUST be called + * before renderVisible on every frame! + * + * @return + */ + boolean validate(); + + /** + *

          Render those canvas entities from the tree given by + * root which lie in the rectangle r. + * Dirty regions are left unchanged.

          + * + *

          Implementors might find CanvasEntity.foldVisible useful.

          + * + * @param root + * @param r + */ + void renderVisible(CanvasEntity root, Rectangle r); + + /** + *

          Update the part of the image on screen specified by the rectangle + * r. If the argument is null, + * update everything.

          + * + *

          This method is necessary for renderers using a back buffer and + * must be called after the rendering.

          + * + * @param r + * @return true + */ + boolean show(Rectangle r); +} diff --git a/src/org/jalgo/module/heapsort/renderer/SequenceElement.java b/src/org/jalgo/module/heapsort/renderer/SequenceElement.java new file mode 100644 index 0000000..c56d88b --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/SequenceElement.java @@ -0,0 +1,119 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Point; + +/** + * A canvas entity representing a sequence element as needed for Heapsort. + * + * @author mbue + */ +public class SequenceElement extends CanvasEntity { + private String label; + private Point position = new Point(); + private float highlight = 0.0f; + private double scale = 1.0; + + protected SequenceElement(Point pos, String label) { + bounds.setBounds(-15, -15, 30, 30); + // trick (see Node) + setPosition(pos); + // don't use setLabel: + // a) this.label is null (would crash) + // b) too early to invalidate + this.label = label; + } + + /** + * @see Node#update() + * + */ + protected void update() { + } + + public final float getHighlight() { + return highlight; + } + + public final void setHighlight(float value) { + if (value != highlight) { + highlight = value; + invalidate(); + update(); + } + } + + public final String getLabel() { + return label; + } + + public final void setLabel(String label) { + if (!this.label.equals(label)) { + this.label = label; + invalidate(); + update(); + } + } + + public final Point getPosition() { + return position; + } + + // newly added method just for allowing efficient animations + public final void setPosition(double x, double y) { + invalidate(); + this.position.setLocation(x, y); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + //update(); -- nothing is changed concerning the appearance + } + + public final void setPosition(Point position) { + if (!this.position.equals(position)) { + this.position.setLocation(position); + if (label != null) + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + //update(); -- nothing is changed concerning the appearance + } + } + + public final double getScale() { + return scale; + } + + public final void setScale(double scale) { + if (this.scale != scale) { + this.scale = scale; + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + update(); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/renderer/Text.java b/src/org/jalgo/module/heapsort/renderer/Text.java new file mode 100644 index 0000000..cfb5693 --- /dev/null +++ b/src/org/jalgo/module/heapsort/renderer/Text.java @@ -0,0 +1,162 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.renderer; + +import java.awt.Point; + +/** + * A canvas entity which displays text. It serves many purposes to some degree + * and no purpose fully. E. g., the "regular" property is a real mess, it's only + * there for displaying the sequence indices and it relies on the undocumented + * feature that the renderer uses another font. Well, now it is documented, + * but that doesn't really help it. + * + * @author mbue + */ +public class Text extends CanvasEntity { + + private String text; + private float opacity; + private Point position = new Point(); + private double scale = 1.0; + private boolean regular = false; + private int width; + private int height; + + protected Text(String text, int width, int height) { + // don't use setText: + // a) this.text is null (would crash) + // b) too early to invalidate + this.text = text; + opacity = 1.0f; + this.width = width; + this.height = height; + bounds.setBounds(-width/2, -height/2, width, height); + } + + /** + * @see Node#update() + * + */ + protected void update() { + } + + public float getOpacity() { + return opacity; + } + + public void setOpacity(float opacity) { + this.opacity = opacity; + invalidate(); + update(); + } + + public String getText() { + return text; + } + + public void setText(String text) { + if (!this.text.equals(text)) { + this.text = text; + invalidate(); + update(); + } + } + + public Point getPosition() { + return position; + } + + public void setPosition(double x, double y) { + this.position.setLocation(x, y); + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + } + + public void setPosition(Point position) { + if (!this.position.equals(position)) { + this.position.setLocation(position); + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + } + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + if (height != this.height) { + this.height = height; + invalidate(); + bounds.setBounds(0, 0, width, height); + invalidate(); + } + + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + if (width != this.width) { + this.width = width; + invalidate(); + bounds.setBounds(0, 0, width, height); + invalidate(); + } + } + + public double getScale() { + return scale; + } + + public void setScale(double scale) { + if (this.scale != scale) { + this.scale = scale; + invalidate(); + trans.setToTranslation(position.x, position.y); + trans.scale(scale, scale); + invalidate(); + update(); + } + } + + public boolean isRegular() { + return regular; + } + + public void setRegular(boolean regular) { + if (this.regular != regular) { + this.regular = regular; + invalidate(); + update(); + } + } + +} diff --git a/src/org/jalgo/module/heapsort/res.properties b/src/org/jalgo/module/heapsort/res.properties new file mode 100644 index 0000000..951ceb7 --- /dev/null +++ b/src/org/jalgo/module/heapsort/res.properties @@ -0,0 +1,5 @@ +Module_logo=/heapsort_pix/logo.gif + +HelpSet_Name=/help/jhelp/heapsort_help.hs + +Icon.Suspend=/heapsort_pix/suspend.gif diff --git a/src/org/jalgo/module/heapsort/vis/CVS/Entries b/src/org/jalgo/module/heapsort/vis/CVS/Entries new file mode 100644 index 0000000..22c483a --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/CVS/Entries @@ -0,0 +1,4 @@ +/Controller.java/1.7/Wed Feb 6 20:21:13 2008// +/ControllerListener.java/1.4/Wed Jan 30 12:23:33 2008// +/Heapsort.java/1.7/Wed Feb 6 20:21:13 2008// +/Visualisation.java/1.4/Wed Jan 30 12:23:33 2008// diff --git a/src/org/jalgo/module/heapsort/vis/CVS/Repository b/src/org/jalgo/module/heapsort/vis/CVS/Repository new file mode 100644 index 0000000..a8f476a --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/heapsort/vis diff --git a/src/org/jalgo/module/heapsort/vis/CVS/Root b/src/org/jalgo/module/heapsort/vis/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/heapsort/vis/Controller.java b/src/org/jalgo/module/heapsort/vis/Controller.java new file mode 100644 index 0000000..0e4ca40 --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/Controller.java @@ -0,0 +1,696 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.vis; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.heapsort.Subject; +import org.jalgo.module.heapsort.anim.Animation; +import org.jalgo.module.heapsort.anim.AnimationListener; +import org.jalgo.module.heapsort.anim.AnimationTimeEntity; +import org.jalgo.module.heapsort.anim.TimeEntity; +import org.jalgo.module.heapsort.model.Action; +import org.jalgo.module.heapsort.model.Model; +import org.jalgo.module.heapsort.model.ModelListener; +import org.jalgo.module.heapsort.model.Sequencer; +import org.jalgo.module.heapsort.model.SequencerListener; +import org.jalgo.module.heapsort.model.State; + +/** + *

          This class coordinates the derivation of the algorithm run + * and its animation. Thus, it links several parts of the module: + * the model, the renderer, and the visualisation. It would be + * legitimate to refer to it as the core of the application + * (apart from the gui).

          + * + *

          At any given time, the controller is in exactly one of several + * states: Ready (for further derivation commands), being in a macro + * step (i.e. automatically deriving until a certain point, and thus + * not taking any commands), playing an animation (not taking any + * commands either), or waiting for user acknowledgement (accepting + * only the "cont(inue)" command). The behaviour of the controller + * depends on a large part on the current state.

          + * + *

          The controller maintains a state stack, which is initialized + * with the ready state. When a derivation takes place, an animation + * is scheduled and the playing state is pushed on the stack. If the + * animation consists of several parts which require acknowledgement + * by the user, the waiting state is pushed in between the parts.

          + * + *

          The stack is necessary for two reasons: a) states + * are parametrised (e.g. with the animation to be played), meaning that + * in effect, there are a lot more states than just those (state classes) + * named here. Hence, returning to the previous state, which is desirable + * in many cases, requires direct knowledge of the previous state.

          + * + *

          b) Sometimes, even the state class of the previous + * state is not determined by the current state. Playing an animation can + * return to ready or to macro, depending on whether a macro derivation + * is taking place or not. A stack seems a much more elegant solution + * than variables indicating where to return to (effectively creating a + * playing-normal and a playing-macro state).

          + * + *

          The controller is linked to the model via the SequencerListener + * interface (so to speak in a "push" manner), and it is linked to the + * renderer by the root canvas entity, the canvas entity factory, and + * the root time entity. Completion of animations can be recognized + * thanks to the AnimationListener.

          + * + *

          Important technical note: The controller can not be seen as some + * kind of SequencerListener because the controller must own + * the sequencer in order to prevent anyone from using it while the + * animation is running. Therefore, the controller has in fact to act + * as a proxy to for sequencer (even though they don't implement a common + * interface).

          + * + * @author mbue + */ +public final class Controller extends Subject { + + // please find all those numerous inner classes at the end of + // the class definition + + private Model model; + private Visualisation vis; + private TimeEntity timeroot; + + private Sequencer seq; + + private Listener listener; + private LogListener loglistener; + private CState currentState = null; + private boolean lecture; + + public Controller(Model model, Visualisation vis, TimeEntity timeroot) { + // the model is used to create the initial state + this.model = model; + // the vis is used to create state rep and action anim + this.vis = vis; + // use timeroot to schedule animations + this.timeroot = timeroot; + + // the listeners capture events from underlying layers + listener = new Listener(); + loglistener = new LogListener(); + + pushState(new Initial()); + } + + public boolean isLecture() { + return lecture; + } + + public void setLecture(boolean lecture) { + this.lecture = lecture; + notifyAll(StateChangedNotifier.getInstance()); + } + + public State getCurrentState() { + return seq.getCurrentState(); + } + + public void derive() { + seq.derive(); + } + + public boolean isBackPossible() { + return currentState.isBackPossible(); + } + + public boolean isStepPossible() { + return currentState.isStepPossible(); + } + + public boolean isMacroStepPossible() { + return currentState.isMacroStepPossible(); + } + + public boolean isSuspendPossible() { + return currentState.isSuspendPossible(); + } + + public boolean isResetPossible() { + return canModelChange(); + } + + public boolean canModelChange() { + return currentState.canModelChange(); + } + + public Model getModel() { + return model; + } + + /** + * Public method corresponding to reset button + * ("go right to the beginning") + * + */ + public void reset() { + // This is one way of doing it. + currentState.modelChanged(); + } + + /** + * Public method corresponding to button "<" + * + */ + public void back() { + currentState.back(); + } + + /** + * Public method corresponding to button ">" + * + */ + public void cont() { + currentState.cont(); + } + + /** + * Public method corresponding to button "<<" + * (detailLevel would be an application constant) + * + * @param detailLevel + */ + public void macroBack(int detailLevel) { + currentState.macroBack(detailLevel); + } + + /** + * Public method corresponding to button ">>" + * (detailLevel would be an application constant) + * + * @param detailLevel + */ + public void macroStep(int detailLevel) { + currentState.macroStep(detailLevel); + } + + public void suspend() { + currentState.suspend(); + } + + public void addListener(SequencerListener l) { + loglistener.addListener(l); + } + + public void removeListener(SequencerListener l) { + loglistener.removeListener(l); + } + + private int inpushpopstate = 0; + + private synchronized void pushState(CState s) { + inpushpopstate++; + try { + s.prev = currentState; + currentState = s; + currentState.init(); + } + finally { + inpushpopstate--; + } + if (inpushpopstate == 0) + notifyAll(StateChangedNotifier.getInstance()); + } + + private synchronized void popState() { + inpushpopstate++; + try { + CState s = currentState; + currentState = s.prev; + s.done(); + currentState.ret(); + } + finally { + inpushpopstate--; + } + if (inpushpopstate == 0) + notifyAll(StateChangedNotifier.getInstance()); + } + + /// the rest (inner classes) + + /** + * Convenience interface to allow uniform handling of + * both directions: forward and backwards. This is used + * in the macro steps and it is only concerned about + * the derivation, not the animation. + * + * @author mbue + */ + private interface Direction { + void go(); + boolean canGo(); + } + + private class Forward implements Direction { + public boolean canGo() { + return seq.isStepPossible(); + } + + public void go() { + // don't call cont() here because this would + // call currentState.cont(), which would in turn + // eventually call this one + seq.step(); + // XXX think about this call + seq.derive(); + } + } + + private class Backwards implements Direction { + public boolean canGo() { + return seq.isBackPossible(); + } + + public void go() { + seq.back(); + } + } + + /** + * Controller state, e.g. being ready or playing an animation. + * Contains methods which depend on the current state. + * States will be managed on a stack, i.e. the "ready" state + * might spawn a "playing" state, which might then return + * to the ready state. + * + * @author mbue + */ + private class CState { + public CState prev; + + // we provide empty bodies here because this + // saves us many keystrokes + /** + * initialize state -- called after pushing on stack + * (do it afterwards so pushStack can be called in here) + */ + public void init() { + + } + /** + * tidy up -- called after popping from stack + */ + public void done() { + + } + /** + * notification that state becomes active again + */ + public void ret() { + + } + + public Animation[] createAnim(State q, Action a, State q1) { + // this time: don't factor everything out to use + // polymorphism instead of if-clauses... destroys locality + if (isLecture()) + return new Animation[] { vis.setupAnimationLecture(q, a, q1)}; + else + return vis.setupAnimation(q, a, q1); + } + + public boolean isBackPossible() { + return false; + } + + public boolean isStepPossible() { + return false; + } + + public boolean isMacroStepPossible() { + return false; + } + + public boolean isSuspendPossible() { + // go up in the stack (must be overridden by Ready) + return prev.isSuspendPossible(); + } + + public void back() { + + } + + public void cont() { + + } + + public void macroStep(int detailLevel) { + + } + + public void macroBack(int detailLevel) { + + } + + public void suspend() { + // go up in the stack (must be overridden by Ready) + prev.suspend(); + } + + public void modelChanged() { + + } + + /** + * Returns whether it is possible to change the model. + * Changing the model means restarting the derivation + * from scratch. + * + * @return + */ + public boolean canModelChange() { + return false; + } + } + + private final class Initial extends CState { + + @Override + public void init() { + modelChanged(); + ((Subject)model).addListener(listener); + } + + @Override + public void modelChanged() { + seq = new Sequencer(model.getInitialState()); + // XXX think about this call + seq.derive(); + seq.addListener(listener); + seq.addListener(loglistener); + pushState(new Ready()); + } + + @Override + public boolean canModelChange() { + return true; + } + + @Override + public void ret() { + modelChanged(); + } + } + + /** + * Controller is ready. + * + * @author mbue + */ + private final class Ready extends CState { + + @Override + public void init() { + vis.setupState(getCurrentState()); + } + + @Override + public void back() { + seq.back(); + + } + + @Override + public void cont() { + seq.step(); + // XXX think about this call + seq.derive(); + } + + private void macro(int detailLevel, Direction dir) { + // the first step of a macro step is always taken independent of the detail level + // otherwise, a macro step could result in a "no-step" + if (dir.canGo()) { + pushState(new MacroState(detailLevel, dir)); + dir.go(); + } + } + + @Override + public void macroStep(int detailLevel) { + macro(detailLevel, new Forward()); + } + + @Override + public void macroBack(int detailLevel) { + macro(detailLevel, new Backwards()); + } + + @Override + public boolean isBackPossible() { + return seq.isBackPossible(); + } + + @Override + public boolean isStepPossible() { + return seq.isStepPossible(); + } + + @Override + public boolean isMacroStepPossible() { + return seq.isStepPossible(); + } + + @Override + public boolean isSuspendPossible() { + return false; + } + + @Override + public void suspend() { + + } + + @Override + public void modelChanged() { + popState(); + } + + @Override + public boolean canModelChange() { + return true; + } + + } + + /** + * Playing animation until a certain detail level is reached. + * + * @author mbue + */ + private final class MacroState extends CState { + private int detailLevel; + private Direction direction; + private boolean suspended = false; + + public MacroState(int detailLevel, Direction direction) { + this.detailLevel = detailLevel; + this.direction = direction; + } + + public Animation[] createAnim(State q, Action a, State q1) { + return new Animation[] { vis.setupAnimationMacro(q, a, q1)}; + } + + @Override + public boolean isSuspendPossible() { + return true; + } + + @Override + public void suspend() { + suspended = true; + } + + /** + * playing animation has finished, so make a step + * or be done + */ + @Override + public void ret() { + // citing State#getDetailLevel Javadoc: + /* The program will allow the user to automatically + * derive up to the next state which has at most a + * certain detail level. */ + if (!suspended && (getCurrentState().getDetailLevel() > detailLevel) && direction.canGo()) { + direction.go(); + } + else + popState(); + } + + } + + /** + * Playing a sequence of animations. + * + * @author mbue + */ + private final class PlayAnimState extends CState implements AnimationListener { + private Animation[] anim; + private int current; + private AnimationTimeEntity cate; // current animation time entity + + public PlayAnimState(Animation[] anim) { + this.anim = anim; + current = 0; + } + + //@Override // unlike 1.6, Java 1.5 does not like this + public void animationComplete(Animation a) { + /* + * this will most likely be executed in a different thread + * but there is no concurrency involved because + * the normal thread won't do anything (significant) + */ + if (a == anim[current]) { + a.done(); + timeroot.removeChild(cate); + cate = null; + current++; + if (current < anim.length) + pushState(new AckWaitState()); + else + popState(); + } + } + + @Override + public void init() { + startAnim(); + } + + @Override + public void ret() { + startAnim(); + } + + private void startAnim() { + assert(cate == null); + + Animation aa = anim[current]; + cate = new AnimationTimeEntity(aa, timeroot.now()); + cate.setListener(this); + aa.init(); + aa.update(0.0); // XXX this is fucking depressing! + timeroot.addChild(cate); + } + + } + + /** + * Waiting for acknowledgement. + * + * @author mbue + */ + private final class AckWaitState extends CState { + @Override + public void cont() { + popState(); + } + + @Override + public boolean isStepPossible() { + return true; + } + } + + private final class Listener implements SequencerListener, ModelListener { + + public void back(State q, Action a, State q1) { + Animation aa = vis.setupAnimationBack(q, a, q1); + pushState(new PlayAnimState(new Animation[] { aa })); + } + + public void step(State q, Action a, State q1) { + Animation[] aa = currentState.createAnim(q, a, q1); + //System.out.println(a.toString()); + pushState(new PlayAnimState(aa)); + } + + public void stepAvail() { + // just ignore it + // we will just call step (not derive) and be done + + } + + public void modelChanged() { + currentState.modelChanged(); + } + + } + + private static final class LogListener implements SequencerListener { + + private List loggers; + + public void addListener(SequencerListener l) { + if (loggers == null) + loggers = new LinkedList(); + loggers.add(l); + } + + public void removeListener(SequencerListener l) { + if (loggers != null) + loggers.remove(l); + } + + public void back(State q, Action a, State q1) { + if (loggers != null) + for (SequencerListener l: loggers) + l.back(q, a, q1); + } + + public void step(State q, Action a, State q1) { + if (loggers != null) + for (SequencerListener l: loggers) + l.step(q, a, q1); + } + + public void stepAvail() { + if (loggers != null) + for (SequencerListener l: loggers) + l.stepAvail(); + } + + } + + private static final class StateChangedNotifier implements Notifier { + private static StateChangedNotifier arnie = new StateChangedNotifier(); + + public static StateChangedNotifier getInstance() { + return arnie; + } + + public void invoke(ControllerListener l) { + l.stateChanged(); + } + + } + +} diff --git a/src/org/jalgo/module/heapsort/vis/ControllerListener.java b/src/org/jalgo/module/heapsort/vis/ControllerListener.java new file mode 100644 index 0000000..6770665 --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/ControllerListener.java @@ -0,0 +1,37 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.vis; + +/** + * Listener interface for the controller. + * + * @author mbue + */ +public interface ControllerListener { + /** + * Called when the state of the controller changed. + * This amounts to the possibility of going forwards or backwards and + * lecture mode. + */ + void stateChanged(); +} diff --git a/src/org/jalgo/module/heapsort/vis/Heapsort.java b/src/org/jalgo/module/heapsort/vis/Heapsort.java new file mode 100644 index 0000000..4db63c0 --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/Heapsort.java @@ -0,0 +1,853 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.vis; + +import java.awt.Color; +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.heapsort.anim.Animation; +import org.jalgo.module.heapsort.anim.Animations; +import org.jalgo.module.heapsort.anim.CompositeAnimation; +import org.jalgo.module.heapsort.anim.Fadeable; +import org.jalgo.module.heapsort.anim.ParallelAnimation; +import org.jalgo.module.heapsort.anim.ProxyAnimation; +import org.jalgo.module.heapsort.anim.SequentialAnimation; +import org.jalgo.module.heapsort.model.Action; +import org.jalgo.module.heapsort.model.State; +import org.jalgo.module.heapsort.model.Heapsort.*; +import org.jalgo.module.heapsort.renderer.CanvasEntity; +import org.jalgo.module.heapsort.renderer.CanvasEntityFactory; +import org.jalgo.module.heapsort.renderer.Edge; +import org.jalgo.module.heapsort.renderer.MarkingRect; +import org.jalgo.module.heapsort.renderer.Node; +import org.jalgo.module.heapsort.renderer.SequenceElement; +import org.jalgo.module.heapsort.renderer.Text; + +/** + *

          This implements the actual Heapsort visualisation.

          + * + *

          The concept is as follows: When setting up a state on the + * root canvas, a so-called "state dictionary" is built which + * tells us which semantic object is represented by which + * canvas entity.

          + * + *

          Animations can use that dictionary to find the objects + * they have to modify, and they can add and remove objects + * from the dictionary as necessary for the state transition.

          + * + *

          This concept replaces the former one where the visualisation + * had no access to the root entity and the dictionary was modeled + * explicity by means of a canvas database (merely a hierarchical + * map String->CanvasEntity), which would be used to create the + * actual canvas entities for display. This was not to the point + * and overly complicated.

          + * + *

          P.S.: Don't look at the code that thoroughly. + * In contrast to the infrastructure code, this is rather messy. + * This is due to the fact that it just has to work, which it does. + * You know, the beauty lies outside (in the animations to be seen + * on screen).

          + * + * @author mbue + * + */ +public final class Heapsort implements Visualisation { + + // general + private HeapsortState current = null; + private HeapsortState next = null; + private CanvasEntity root; + private CanvasEntityFactory f; + // static appearance information + private static final int MAX_NODES = 31; // five levels + private static Point[] nodepos; + private static Point[] seqpos; + private static Point[] edgefrom; + private static Point[] edgeto; + private static Point lidisp = new Point(40,0); // li displacement + private static Color recol = new Color(192,192,192); + private static Color undercol = Color.RED; + // state dictionary + private List seq; + private List seqind; + private List nodes; + private List edges; + private MarkingRect under; + private Text li; + private List re; + private MarkingRect re2; + private Text cmpres; + private int first; // number of visible nodes + private int last; // number of visible nodes in next step + + public Heapsort(CanvasEntity root, CanvasEntityFactory f) { + this.root = root; + this.f = f; + // need fast indexing + seq = new ArrayList(); + seqind = new ArrayList(); + nodes = new ArrayList(); + edges = new ArrayList(); + re = new ArrayList(); + } + + // --- static stuff + + private static void computeNodepos(int i, int x, int y, int d) { + nodepos[i] = new Point(x, y); + if (i <= (MAX_NODES-3)/2) { + computeNodepos(2*i+1, x-d, y+75, 9*d/20); + computeNodepos(2*i+2, x+d, y+75, 9*d/20); + } + } + + { + nodepos = new Point[MAX_NODES]; + seqpos = new Point[MAX_NODES]; + edgefrom = new Point[MAX_NODES]; + edgeto = new Point[MAX_NODES]; + //computeNodepos(0, 350, 30, 175); + // assume 0 is center of screen + computeNodepos(0, 0, 30, 175+15+30); + for (int ind = 0; ind < MAX_NODES; ind++) + seqpos[ind] = new Point(-270+ind*40, 400); + for (int ind = 1; ind < MAX_NODES; ind++) { + edgefrom[ind] = nodepos[(ind-1)/2]; + edgeto[ind] = nodepos[ind]; + int dx = edgefrom[ind].x-edgeto[ind].x; + int dy = edgefrom[ind].y-edgeto[ind].y; + double oo = 1/Math.sqrt(dx*dx+dy*dy); + edgefrom[ind] = new Point( + (int)(edgefrom[ind].x-30*oo*dx), + (int)(edgefrom[ind].y-30*oo*dy)); + edgeto[ind] = new Point( + (int)(edgeto[ind].x+30*oo*dx), + (int)(edgeto[ind].y+30*oo*dy)); + } + } + + // --- state stuff + + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#setupState(org.jalgo.module.heapsort.model.State) + */ + public void setupState(State q) { + if (q != current) { + if (q instanceof HeapsortState) + setupState((HeapsortState)q); + else // XXX being lazy: postponing exception (will get null pointer exception) + teardown(); + } + } + + private void setupState(HeapsortState q) { + teardown(); + current = q; + setup(); + } + + /* the following methods fill the dictionary + * but they don't add anything to the canvas + * this allows us to use them in animations + * especially in composite ones + */ + + private void addLiPointer(int li) { + Text t = f.createText("\u2190", 20, 20); + Point p = nodepos[li]; + t.setPosition(new Point(p.x+lidisp.x, p.y+lidisp.y)); + t.setScale(1.7); + t.setZorder(1000); + this.li = t; + } + + private void addReMarking(int re, int n) { + // go backwards through the nodes + re++; // --> point at the first entry to be marked + n--; // --> point at the last entry to be marked + this.re.clear(); + while (re <= n) { + // get position of last entry (of current line) + Point p1 = nodepos[n]; + // find first position of this line + Point p2 = p1; // will be the wanted first position + Point p3 = p1; // will be the last position on the line above + while ((re <= n) && (p3.y == p1.y)) { + n--; + p2 = p3; + p3 = nodepos[n]; + } + MarkingRect mr = f.createMarkingRect(); + mr.setColor(recol); + mr.setPosition(new Point(p2.x-30,p2.y-30)); + mr.setWidth(p1.x-p2.x+60); + mr.setHeight(p1.y-p2.y+60); + this.re.add(mr); + } + } + + private int addCmpRes() { + Phase12sl q = (Phase12sl)current; + int j = 2*q.i+1; + if (j+1 <= q.re) { + String s; + if (q.sequence.get(j) < q.sequence.get(j+1)) { + s = "<"; + j++; + } + else + s = ">"; + // XXX uncomment the "if" if you want the comparison in any case + if (q.sequence.get(q.i) < q.sequence.get(j)) { + cmpres = f.createText(s, 20, 20); + cmpres.setPosition(new Point(nodepos[q.i].x, nodepos[2*q.i+1].y)); + cmpres.setScale(1.7); + } + } + + if (q.sequence.get(q.i) < q.sequence.get(j)) + return j; + else + return -1; + } + + private void addUnder(int first, int last) { + if (first < last) { + Point p = seqpos[first]; + Point p1 = seqpos[last-1]; + under = f.createMarkingRect(); + under.setColor(undercol); + under.setPosition(new Point(p.x-15, p.y+18)); + under.setWidth(p1.x-p.x+31); + under.setHeight(3); + } + } + + private void setup() { + // first: fill dictionary + + // sequence elements, their indices, nodes, edges + for (int ind = 0; ind < current.sequence.size(); ind++) { + SequenceElement se = f.createSequenceElement( + seqpos[ind], + String.valueOf(current.sequence.get(ind))); + se.setZorder(100+ind); + seq.add(se); + Text sei = f.createText(String.valueOf(ind), 16, 10); + sei.setPosition(seqpos[ind].x+6, seqpos[ind].y+30); + sei.setOpacity(0.5f); + sei.setRegular(true); + seqind.add(sei); + // XXX create node at seqpos... + Node nd = f.createNode(seqpos[ind], current.sequence.get(ind).toString()); + nd.setZorder(102+ind); // 102 instead of 100 to be on top of seq (extend anim) + nodes.add(nd); + if (ind > 0) { + Edge e = f.createEdge(edgefrom[ind], edgeto[ind]); + e.setZorder(1); + edges.add(e); + } + } + + // compute which nodes have to be shown + if (current instanceof InitialState) + first = 0; + else if (current instanceof Phase0) { + int level = ((Phase0)current).level; + first = 0; + while (level > 0) { + first = 2*first+1; + level--; + } + if (first > current.sequence.size()) + first = current.sequence.size(); + } + else + first = current.sequence.size(); + last = Math.min(2*first+1, current.sequence.size()); + + if (current instanceof Phase0) + addUnder(first, last); + // li pointer and re marker + if (current instanceof Phase12) { + int li = ((Phase12)current).li; + int re = ((Phase12)current).re; + + if (re == current.sequence.size()-1) { + if (!(current instanceof Phase2)) + addLiPointer(li); + } + else { + addReMarking(re, current.sequence.size()); + re2 = f.createMarkingRect(); + re2.setColor(recol); + re2.setPosition(new Point(seqpos[re+1].x-20, seqpos[re+1].y-20)); + re2.setHeight(40); + re2.setWidth(seqpos[current.sequence.size()-1].x-seqpos[re+1].x+40); + } + } + // highlights and stuff + if (current instanceof Phase12sl) { + int i = ((Phase12sl)current).i; + nodes.get(i).setHighlight(1.0f); + seq.get(i).setHighlight(1.0f); + if (current instanceof Phase12slb) { + int j = addCmpRes(); + if (j != -1) { + nodes.get(j).setHighlight(1.0f); + seq.get(j).setHighlight(1.0f); + } + } + } + + // second: put on screen + for (int ind = 0; ind < first; ind++) { + nodes.get(ind).setPosition(nodepos[ind]); + root.addChild(nodes.get(ind)); + } + for (int ind = 1; ind < first; ind++) + root.addChild(edges.get(ind-1)); + for (SequenceElement s: seq) + root.addChild(s); + for (Text s: seqind) + root.addChild(s); + for (MarkingRect m: re) + root.addChild(m); + if (under != null) + root.addChild(under); + if (re2 != null) + root.addChild(re2); + if (li != null) + root.addChild(li); + if (cmpres != null) + root.addChild(cmpres); + } + + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#teardown() + */ + public void teardown() { + if (current != null) { + for (Node n: nodes) + root.removeChild(n); + nodes.clear(); + first = 0; + for (Edge e: edges) + root.removeChild(e); + edges.clear(); + for (SequenceElement s: seq) + root.removeChild(s); + seq.clear(); + for (Text s: seqind) + root.removeChild(s); + seqind.clear(); + for (MarkingRect m: re) + root.removeChild(m); + re.clear(); + if (under != null) { + root.removeChild(under); + under = null; + } + if (re2 != null) { + root.removeChild(re2); + re2 = null; + } + if (li != null) { + root.removeChild(li); + li = null; + } + if (cmpres != null) { + root.removeChild(cmpres); + cmpres = null; + } + current = null; + } + } + + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#createActionAnimation(org.jalgo.module.heapsort.vis.CanvasDb, org.jalgo.module.heapsort.renderer.CanvasEntityFactory, org.jalgo.module.heapsort.model.State, org.jalgo.module.heapsort.model.Action, org.jalgo.module.heapsort.model.State) + */ + public Animation[] setupAnimation(State q, Action a, State q1) { + return new Animation [] { setupAnimationLecture(q, a, q1) }; + } + + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#createActionAnimationBack(org.jalgo.module.heapsort.vis.CanvasDb, org.jalgo.module.heapsort.renderer.CanvasEntityFactory, org.jalgo.module.heapsort.model.State, org.jalgo.module.heapsort.model.Action, org.jalgo.module.heapsort.model.State) + */ + public Animation setupAnimationBack(State q, Action a, State q1) { + setupState(q); + next = (HeapsortState)q1; + return new BackAnim(); + } + + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#createActionAnimationLecture(org.jalgo.module.heapsort.vis.CanvasDb, org.jalgo.module.heapsort.renderer.CanvasEntityFactory, org.jalgo.module.heapsort.model.State, org.jalgo.module.heapsort.model.Action, org.jalgo.module.heapsort.model.State) + */ + public Animation setupAnimationLecture(State q, Action a, State q1) { + // this call won't harm because state should not have changed + setupState(q); + next = (HeapsortState)q1; + Animation result = null; + // don't tell me that this looks ugly... + // it works, that's enough -- don't want any more "invoke" + if (Actions.isExtend(a)) + result = new ExtendAnim(); + if (Actions.isStartphase0(a)) + result = new Startphase0Anim(); + if (Actions.isStartphase1(a)) + result = new Startphase1Anim(); + if (Actions.isDecli(a)) + result = new DecliAnim(); + if (Actions.isReturnphase1(a) || Actions.isReturnphase2(a)) + result = new ReturnAnim(); + if (Actions.isStartphase2(a)) + result = new Startphase2Anim(); + if (Actions.isSwapDecre(a)) + result = new SwapDecreAnim(); + if (Actions.isFinish(a)) + result = new FinishAnim(); + if (Actions.isStartsl(a)) + result = new StartslAnim(); + if (Actions.isCompare(a)) + result = new CompareAnim(); + if (Actions.isSwap(a)) + result = new TheSwapAnim(); + assert(result != null); + result = new ProxyAnimation(result) { + public void done() { + super.done(); + current = next; + next = null; + } + }; + return result; + } + + // ignore macro, this is the same as lecture! + /* (non-Javadoc) + * @see org.jalgo.module.heapsort.vis.Visualisation#createActionAnimationMacro(org.jalgo.module.heapsort.vis.CanvasDb, org.jalgo.module.heapsort.renderer.CanvasEntityFactory, org.jalgo.module.heapsort.model.State, org.jalgo.module.heapsort.model.Action, org.jalgo.module.heapsort.model.State) + */ + public Animation setupAnimationMacro(State q, Action a, State q1) { + return setupAnimationLecture(q, a, q1); + } + + + // --- animations (backwards) + + private class BackAnim implements Animation { + + public void done() { + setupState(next); + next = null; + } + + public double getDuration() { + return 0.1; + } + + public void init() { + } + + public void update(double time) { + } + + } + + + // --- animations (Lecture) + + // startphase0: --> show under + private class Startphase0Anim extends ProxyAnimation { + + public Startphase0Anim() { + addUnder(first, last); + delegate = Animations.createInFader(Animations.SMOOTH_FADER, under); + } + + public void init() { + root.addChild(under); + super.init(); + } + + public double getDuration() { + return 0.4; + } + + } + + // extend: --> "copy" sequence elements as nodes + private class ExtendAnim extends SequentialAnimation { + private MarkingRect oldunder; + private int newlast = Math.min(2*last+1, current.sequence.size()); + + public ExtendAnim() { + oldunder = under; + under = null; + addUnder(last, newlast); + // move in nodes + add(new ProxyAnimation(Animations.createOutFader( + Animations.SMOOTH_FADER, new Fadeable() { + public void setState(float state) { + float f1 = state; + float f2 = 1.0f - state; + for (int ind = first; ind < last; ind++) { + Point p1 = seqpos[ind]; + Point p2 = nodepos[ind]; + nodes.get(ind).setPosition( + f1 * p1.x + f2 * p2.x, + f1 * (p1.y - 15) + f2 * p2.y); + } + } + })) { + public void init() { + for (int ind = first; ind < last; ind++) + root.addChild(nodes.get(ind)); + } + }, 1.5); + // fade in edges + if (first > 0) + add(new ProxyAnimation(Animations.createInFader( + Animations.SMOOTH_FADER, new Fadeable() { + public void setState(float state) { + for (int ind = first; ind < last; ind++) + edges.get(ind - 1).setOpacity(state); + } + })) { + public void init() { + for (int ind = first; ind < last; ind++) + root.addChild(edges.get(ind - 1)); + } + }, 0.5); + // show underbars + if (under == null) + add(Animations.createOutFader(Animations.SMOOTH_FADER, oldunder), 0.5); + else { + under.setOpacity(0.0f); + add(Animations.createCrossfader(Animations.SMOOTH_FADER, oldunder, under), 0.5); + add(Animations.createBlinker(under, 2), 0.4); + } + } + + public void init() { + if (under != null) { + under.setOpacity(0.0f); + root.addChild(under); + } + super.init(); + } + + @Override + public void done() { + super.done(); + root.removeChild(oldunder); + first = last; + last = newlast; + } + + } + + // startphase1: --> fade in li pointer + private class Startphase1Anim extends ProxyAnimation { + + public Startphase1Anim() { + addLiPointer(((Phase1)next).li); + delegate = Animations.createInFader(Animations.SMOOTH_FADER, li); + } + + public double getDuration() { + return 0.4; + } + + public void init() { + root.addChild(li); + super.init(); + } + } + + // startphase2: --> fade out li pointer + private class Startphase2Anim extends ProxyAnimation { + + public Startphase2Anim() { + delegate = Animations.createOutFader(Animations.SMOOTH_FADER, li); + } + + public void done() { + super.done(); + root.removeChild(li); + li = null; + } + + public double getDuration() { + return 0.4; + } + } + + // startsl --> fade in highlight + private class StartslAnim extends ParallelAnimation { + + public StartslAnim() { + super(1.0); + int i = ((Phase12sl)next).i; + add(Animations.createInFader(Animations.SMOOTH_FADER, nodes.get(i))); + add(Animations.createInFader(Animations.SMOOTH_FADER, seq.get(i))); + } + + } + + // returnphase* --> fade out highlight + private class ReturnAnim extends ParallelAnimation { + public ReturnAnim() { + this(((Phase12sl)current).i); + } + + public ReturnAnim(int i) { + super(1.0); + add(Animations.createOutFader(Animations.SMOOTH_FADER, nodes.get(i))); + add(Animations.createOutFader(Animations.SMOOTH_FADER, seq.get(i))); + if ((next instanceof Phase2) && (li != null)) + add(new Startphase2Anim()); + } + } + + // decli: --> move li pointer + private class DecliAnim extends ProxyAnimation { + public DecliAnim() { + Point p1 = nodepos[((Phase12)current).li]; + Point p2 = nodepos[((Phase12)next).li]; + delegate = Animations.createMover(Animations.SMOOTH_MOVER, li, + new Point(p1.x+lidisp.x, p1.y+lidisp.y), + new Point(p2.x+lidisp.x, p2.y+lidisp.y)); + } + + public double getDuration() { + return 1; + } + } + + // finish --> fade out marking + private class FinishAnim extends ParallelAnimation { + private List re_; + private MarkingRect re2_; + + public FinishAnim() { + super(1.0); + re_ = new ArrayList(re); + re.clear(); + add(Animations.createOutFader(Animations.SMOOTH_FADER, new Fadeable() { + public void setState(float state) { + for (MarkingRect m: re_) + m.setOpacity(state); + } + })); + if (re2 != null) { + re2_ = re2; + add(Animations.createOutFader(Animations.SMOOTH_FADER, re2_)); + } + if (current instanceof Phase12sl) { + int i = ((Phase12sl)current).i; + add(Animations.createOutFader(Animations.SMOOTH_FADER, nodes.get(i))); + add(Animations.createOutFader(Animations.SMOOTH_FADER, seq.get(i))); + } + + } + + public void done() { + super.done(); + for (MarkingRect m: re_) + root.removeChild(m); + if (re2_ != null) + root.removeChild(re2_); + } + } + + // + private class SwapAnim extends ParallelAnimation { + private int i; + private int j; + private Node ndi; + private Node ndj; + private SequenceElement sei; + private SequenceElement sej; + + public SwapAnim(int i, int j) { + super(1.0); + this.i = i; + this.j = j; + ndi = nodes.get(i); + ndj = nodes.get(j); + sei = seq.get(i); + sej = seq.get(j); + add(Animations.createCrossmover(Animations.SMOOTH_MOVER, ndi, ndj, nodepos[i], nodepos[j])); + add(Animations.createCrossmover(Animations.SMOOTH_MOVER, sei, sej, seqpos[i], seqpos[j])); + add(Animations.createZoomer(ndi, ndj, 0.6)); + add(Animations.createZoomer(sei, sej, 0.6)); + } + + public void done() { + super.done(); + // changing zorder --> we have to remove + root.removeChild(ndi); + root.removeChild(ndj); + root.removeChild(sei); + root.removeChild(sej); + nodes.set(i, ndj); + nodes.set(j, ndi); + ndi.setZorder(100+j); + ndj.setZorder(100+i); + seq.set(i, sej); + seq.set(j, sei); + sei.setZorder(100+j); + sej.setZorder(100+i); + root.addChild(ndi); + root.addChild(ndj); + root.addChild(sei); + root.addChild(sej); + } + } + + // decre: ... + private class DecreAnim implements Animation { + private Point p = new Point(); + private Point np; // nodepos[re] + private Point sp; // seqpos[re] + private Point npi; // initial position of re + private Point spi; // initial position of re2 + private int nwi; // initial width of re + private int swi; // initial width of re2 + + public void done() { + } + + public double getDuration() { + return 1; + } + + public void init() { + int re_ = ((Phase12)current).re; + np = nodepos[re_]; + sp = seqpos[re_]; + if ((re.size() == 0) || + (re.get(re.size()-1).getPosition().y != np.y-30)) { + p.setLocation(np.x+30, np.y-30); + MarkingRect mr = f.createMarkingRect(); + mr.setColor(recol); + mr.setPosition(p); + mr.setHeight(60); + mr.setWidth(0); + re.add(mr); + root.addChild(mr); + } + if (re2 == null) { + re2 = f.createMarkingRect(); + p.setLocation(sp.x+20, sp.y-20); + re2.setColor(recol); + re2.setPosition(p); + re2.setHeight(40); + re2.setWidth(0); + root.addChild(re2); + } + npi = new Point(re.get(re.size()-1).getPosition()); + nwi = re.get(re.size()-1).getWidth(); + spi = new Point(re2.getPosition()); + swi = re2.getWidth(); + } + + public void update(double time) { + double t1 = 1.0-time; + double t2 = time; + p.setLocation(t1*npi.x+t2*(np.x-30),t1*npi.y+t2*(np.y-30)); + MarkingRect mr = re.get(re.size()-1); + mr.setPosition(p); + mr.setWidth(npi.x-p.x+nwi); + p.setLocation(t1*spi.x+t2*(sp.x-20),t1*spi.y+t2*(sp.y-20)); + re2.setPosition(p); + re2.setWidth(spi.x-p.x+swi); + } + } + + // swap_decre: --> swap, extend marker + private class SwapDecreAnim extends SequentialAnimation { + + public SwapDecreAnim() { + add(new SwapAnim(0, ((Phase12)current).re), 1); + add(new DecreAnim(), 1); + } + + } + + // compare: --> fade in cmp_result + private class CompareAnim extends ParallelAnimation { + private int j; + + public CompareAnim() { + super(1.0); + j = addCmpRes(); + if (cmpres != null) + add(Animations.createInFader(Animations.SMOOTH_FADER, cmpres)); + if (j != -1) { + add(Animations.createInFader(Animations.SMOOTH_FADER, nodes.get(j))); + add(Animations.createInFader(Animations.SMOOTH_FADER, seq.get(j))); + } + } + + public void init() { + if (cmpres != null) + root.addChild(cmpres); + super.init(); + } + } + + // swap --> swap, take care of highlight + private class TheSwapAnim extends CompositeAnimation { + + public TheSwapAnim() { + int i = ((Phase12sl)current).i; + int j = ((Phase12sl)next).i; + add(new SwapAnim(i, j), 0, 1); + // use next.i because of swapping + add(Animations.createOutFader(Animations.SMOOTH_FADER, nodes.get(j)), 1, 0.5); + add(Animations.createOutFader(Animations.SMOOTH_FADER, seq.get(j)), 1, 0.5); + if (cmpres != null) + add(new ProxyAnimation() { + private Text cmpres_ = cmpres; + + { + cmpres = null; + delegate = Animations.createOutFader(Animations.SMOOTH_FADER, cmpres_); + } + + public void done() { + root.removeChild(cmpres_); + super.done(); + } + }, 1, 0.5); + } + + public double getDuration() { + return 1.5; + } + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/heapsort/vis/Visualisation.java b/src/org/jalgo/module/heapsort/vis/Visualisation.java new file mode 100644 index 0000000..ffe3b59 --- /dev/null +++ b/src/org/jalgo/module/heapsort/vis/Visualisation.java @@ -0,0 +1,68 @@ +/* + * j-Algo - a visualization tool for algorithm runs, especially useful for + * students and lecturers of computer science. j-Algo is written in Java and + * thus platform independent. Development is supported by Technische Universität + * Dresden. + * + * Copyright (C) 2004-2008 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.heapsort.vis; + +import org.jalgo.module.heapsort.anim.Animation; +import org.jalgo.module.heapsort.model.Action; +import org.jalgo.module.heapsort.model.State; + +/** + *

          This interface is used to implement the visual appearance of an + * algorithm run.

          + * + *

          Implementing classes will be provided with a root canvas entity + * and a canvas entity factory used to display everything. (At the moment, + * this is not made explicit using a factory because that would be overkill.) + *

          + * + * @author mbue + */ +public interface Visualisation { + /** + * Configures root canvas entity and children for state q. + * @param q + */ + void setupState(State q); + + /** + * Remove everything from canvas. + */ + void teardown(); + + /** + * Configures root canvas entity and children for transition from + * state q to q1 and returns animation + * object. + * + * @param q + * @param a + * @param q1 + * @return + */ + Animation[] setupAnimation(State q, Action a, State q1); + + Animation setupAnimationLecture(State q, Action a, State q1); + Animation setupAnimationMacro(State q, Action a, State q1); + Animation setupAnimationBack(State q, Action a, State q1); + +} diff --git a/src/org/jalgo/module/hoare/CVS/Entries b/src/org/jalgo/module/hoare/CVS/Entries new file mode 100644 index 0000000..4f3f621 --- /dev/null +++ b/src/org/jalgo/module/hoare/CVS/Entries @@ -0,0 +1,10 @@ +/ModuleConnector.java/1.3/Wed Aug 27 13:02:24 2008// +/ModuleInfo.java/1.3/Wed Aug 27 13:02:23 2008// +D/constants//// +D/control//// +/de.properties/1.2/Wed Aug 27 13:02:23 2008// +/en.properties/1.2/Wed Aug 27 13:02:24 2008// +D/gui//// +D/model//// +/res.properties/1.2/Wed Aug 27 13:02:23 2008// +D/view//// diff --git a/src/org/jalgo/module/hoare/CVS/Repository b/src/org/jalgo/module/hoare/CVS/Repository new file mode 100644 index 0000000..cf6261b --- /dev/null +++ b/src/org/jalgo/module/hoare/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare diff --git a/src/org/jalgo/module/hoare/CVS/Root b/src/org/jalgo/module/hoare/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/ModuleConnector.java b/src/org/jalgo/module/hoare/ModuleConnector.java new file mode 100644 index 0000000..f86d344 --- /dev/null +++ b/src/org/jalgo/module/hoare/ModuleConnector.java @@ -0,0 +1,105 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and platform + * independant. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.hoare; + +/** +* +* @author Tomas +* +* Manipulated testModule.ModuleConnector +* +*/ + + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.control.Controller; + + +public class ModuleConnector +extends AbstractModuleConnector { + + View view; + Model model; + Controller controller; + + @Override + public void init() { + + model = new Model(); + //view = new View(this); + view = new View(this); + controller = new Controller(view, model, this); + + model.addObserver(view); + view.setModel(model); + view.setConroller(controller); + } + + @Override + public void run() { + view.installWelcomeScreen(); + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + try { + ObjectInputStream input = new ObjectInputStream(data); + controller.load(input); + input.close(); + } catch (IOException e) { + view.setStatusText(Messages.getString("hoare", "out.loadError")); + e.printStackTrace(); + } catch (ClassNotFoundException e){ + view.setStatusText(Messages.getString("hoare", "out.loadError")); + e.printStackTrace(); + } + } + + @Override + public ByteArrayOutputStream getDataForFile() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + ObjectOutputStream output = new ObjectOutputStream(baos); + controller.save(output); + output.close(); + } catch (IOException e) { + view.setStatusText(Messages.getString("hoare", "out.saveError")); + e.printStackTrace(); + } + return baos; + } + + @Override + public void print() { + // here is no action performed in test module + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/ModuleInfo.java b/src/org/jalgo/module/hoare/ModuleInfo.java new file mode 100644 index 0000000..2ecf7af --- /dev/null +++ b/src/org/jalgo/module/hoare/ModuleInfo.java @@ -0,0 +1,90 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer sience. It is written in Java and platform + * independant. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.hoare; + +/** +* +* @author Tomas +* +* Manipulated testModule.ModuleInfo +* +*/ + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return Messages.getString("hoare", "Module_name"); + } + + public String getVersion() { + return Messages.getString("hoare", "Module_version"); + } + + public String getAuthor() { + return Messages.getString("hoare", "Module_authors"); + } + + public String getDescription() { + return Messages.getString("hoare", "Module_description_1"); + } + + public URL getLogoURL() { + return Messages.getResourceURL("hoare", "Module_logo"); + } + + public String getLicense() { + return Messages.getString("hoare", "Module_license"); + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("hoare","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/constants/CVS/Entries b/src/org/jalgo/module/hoare/constants/CVS/Entries new file mode 100644 index 0000000..42235a0 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/CVS/Entries @@ -0,0 +1,7 @@ +/CodeDimension.java/1.1/Wed Aug 27 13:02:42 2008// +/Event.java/1.1/Wed Aug 27 13:02:41 2008// +/ParserAccess.java/1.1/Wed Aug 27 13:02:41 2008// +/Rule.java/1.1/Wed Aug 27 13:02:42 2008// +/Status.java/1.1/Wed Aug 27 13:02:43 2008// +/TextStyle.java/1.1/Wed Aug 27 13:02:41 2008// +/package-info.java/1.1/Wed Aug 27 13:02:42 2008// diff --git a/src/org/jalgo/module/hoare/constants/CVS/Repository b/src/org/jalgo/module/hoare/constants/CVS/Repository new file mode 100644 index 0000000..47abe8e --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/constants diff --git a/src/org/jalgo/module/hoare/constants/CVS/Root b/src/org/jalgo/module/hoare/constants/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/constants/CodeDimension.java b/src/org/jalgo/module/hoare/constants/CodeDimension.java new file mode 100644 index 0000000..4c6b620 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/CodeDimension.java @@ -0,0 +1,18 @@ +package org.jalgo.module.hoare.constants; + +import java.io.Serializable; + +/** + * Represents our own structure for saving the beginning and + * the ending of substring + * + * @author Uwe + * + */ +public class CodeDimension implements Serializable{ + + private static final long serialVersionUID = 3084330719512535676L; + + public int start; + public int end; +} diff --git a/src/org/jalgo/module/hoare/constants/Event.java b/src/org/jalgo/module/hoare/constants/Event.java new file mode 100644 index 0000000..d733d0c --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/Event.java @@ -0,0 +1,20 @@ +package org.jalgo.module.hoare.constants; + +/** + * Representation of all Events of the Hoare module send from the + * View to the Controller. + * + * @author Johannes + * + */ + +public enum Event { + APPLYRULE, + EDITPREASSERTION, + EDITPOSTASSERTION, + DELETENODE, + UNDO, + REDO, + PARSECODE, + REINIT +} diff --git a/src/org/jalgo/module/hoare/constants/ParserAccess.java b/src/org/jalgo/module/hoare/constants/ParserAccess.java new file mode 100644 index 0000000..5c03e9f --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/ParserAccess.java @@ -0,0 +1,110 @@ +package org.jalgo.module.hoare.constants; + +import org.lsmp.djep.xjep.XJep; +import org.nfunk.jep.Node; +import org.nfunk.jep.ParseException; +import org.jalgo.main.util.Messages; + +/** + * This class consists exclusively of static methods that use the XJep Framework. + * + * @author Uwe + * + */ +public class ParserAccess { + + + private static XJep parser = initParser(new XJep()); + + + + /** + * Initializes the given instance of XJep. + * + * @param parser instance of XJep + * @return the initialized instance of XJep + */ + private static XJep initParser(XJep parser) { + parser = new XJep(); + parser.addStandardFunctions(); + parser.setAllowAssignment(true); + parser.setAllowUndeclared(true); + return parser; + } + + /** + * Parses the given string expression with the static parser + * and some additional internal criteria + * and returns the top node of the created XJep expression tree. + * + * @param s the expression to be parsed + * @return the top node of the created XJep expression tree + * @throws ParseException if there are some grammatical errors in the expression + */ + public static Node parse(String s) throws ParseException { + return parse(parser, s); + } + + /** + * Parses the given string expression with the static parser + * and some additional internal criteria + * and returns the top node of the created XJep expression tree. + * + * @param s the expression to be parsed + * @return the top node of the created XJep expression tree + * @throws ParseException if there are some grammatical errors in the expression + */ + public static String parseToString(String s) throws ParseException { + return parser.toString(parse(s)); + } + + /** + * Parses the given string expression with the given parser + * and some additional internal criteria + * and returns the top node of the created XJep expression tree. + * + * @param parser the parser that should be used to parse the string expression + * @param s the expression to be parsed + * @return the top node of the created XJep expression tree + * @throws ParseException if there are some grammatical errors in the expression + */ + public static Node parse(XJep parser, String s) throws ParseException { + Node result = parser.parse(s); + isCorrect(s); + return result; + } + + /** + * Returns a string representation of the XJep node tree + * represented by the given top node. + * + * @param node top node of the XJep node tree + * @return the string representation of the given node + */ + public static String getString(Node node) { + return parser.toString(node); + } + + /** + * Returns a new and initialized instance of XJep. + * + * @return an initialized instance of XJep + */ + public static XJep createParser() { + return initParser(new XJep()); + } + + /** + * Internal method which checks some additional internal + * criteria of the given expression + * + * @param s the expression to be checked + * @throws ParseException if there are some grammatical errors in the expression + */ + private static void isCorrect(String s) throws ParseException { + if (s.matches(".*((([<>=]|!)=)|[<>=])[^\\&\\|<>=]+((([<>=]|!)=)|[<>=]).*")) { + throw new ParseException(Messages.getString("hoare", "parserAccess.newParseException")); + } + } + +} diff --git a/src/org/jalgo/module/hoare/constants/Rule.java b/src/org/jalgo/module/hoare/constants/Rule.java new file mode 100644 index 0000000..7881666 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/Rule.java @@ -0,0 +1,20 @@ +package org.jalgo.module.hoare.constants; + +/** + * Representation of all rules of the Hoare algorithm + * + * @author Thomas + * + */ +public enum Rule { + + ASSIGN, + IF, + IFELSE, + COMPOUND, + STATSEQ, + ITERATION, + STRONGPRE, + WEAKPOST, + +} diff --git a/src/org/jalgo/module/hoare/constants/Status.java b/src/org/jalgo/module/hoare/constants/Status.java new file mode 100644 index 0000000..ae1902f --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/Status.java @@ -0,0 +1,25 @@ +package org.jalgo.module.hoare.constants; + +/** + * Representation of the Status of a verification node
          + * UNCHANGED : shows that a verification node has not + * been checked after the node has changed
          + * WAITING : shows that a verification node waits + * for the result of an evaluation + * RESULTWRONG: marks the verification node as tested + * but not correct
          + * RESULTOK : marks the verification node as tested + * and correct
          + * + * + * @author Uwe + * + */ +public enum Status { + + UNCHANGED, + WAITING, + RESULTWRONG, + RESULTOK + +} diff --git a/src/org/jalgo/module/hoare/constants/TextStyle.java b/src/org/jalgo/module/hoare/constants/TextStyle.java new file mode 100644 index 0000000..0bf60e5 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/TextStyle.java @@ -0,0 +1,20 @@ +package org.jalgo.module.hoare.constants; + +/** + * This enum is used for the styling of Text
          + * SHORT : Performs the Text to be shown in a short form with many variables
          + * FULL : Performs the Text to be shown in a full version. + * Every variable will be resolved.
          + * SOURCE: Performs the Text to be shown in a full an C0-conform style.
          + * EDITOR: Returns the Text to the original given style + * + * @author Thomas + * + */ +public enum TextStyle { + + SHORT, + FULL, + SOURCE, + EDITOR +} diff --git a/src/org/jalgo/module/hoare/constants/package-info.java b/src/org/jalgo/module/hoare/constants/package-info.java new file mode 100644 index 0000000..23bd555 --- /dev/null +++ b/src/org/jalgo/module/hoare/constants/package-info.java @@ -0,0 +1,5 @@ +/** + * This package contains all constants and enumerations used + * by the whole hoare-module. + */ +package org.jalgo.module.hoare.constants; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/control/CVS/Entries b/src/org/jalgo/module/hoare/control/CVS/Entries new file mode 100644 index 0000000..a8a7cd0 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/CVS/Entries @@ -0,0 +1,7 @@ +/Controller.java/1.2/Mon Aug 16 12:05:49 2010// +/Evaluation.java/1.2/Wed Aug 27 13:02:28 2008// +/EvaluationThread.java/1.2/Wed Aug 27 13:02:29 2008// +/JepEvaluator.java/1.2/Wed Aug 27 13:02:36 2008// +/UndoableEdit.java/1.2/Wed Aug 27 13:02:28 2008// +D/edits//// +/package-info.java/1.1/Wed Aug 27 13:02:31 2008// diff --git a/src/org/jalgo/module/hoare/control/CVS/Repository b/src/org/jalgo/module/hoare/control/CVS/Repository new file mode 100644 index 0000000..b130a78 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/control diff --git a/src/org/jalgo/module/hoare/control/CVS/Root b/src/org/jalgo/module/hoare/control/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/control/Controller.java b/src/org/jalgo/module/hoare/control/Controller.java new file mode 100644 index 0000000..03a98df --- /dev/null +++ b/src/org/jalgo/module/hoare/control/Controller.java @@ -0,0 +1,566 @@ +package org.jalgo.module.hoare.control; + +import javax.swing.SwingUtilities; +import javax.swing.undo.UndoManager; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.CannotRedoException; +import java.security.InvalidParameterException; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.IOException; +import java.io.File; +import java.io.FileReader; +import java.io.BufferedReader; +import java.util.Map; +import java.util.HashMap; +import java.util.regex.Pattern; + +import o3b.antlr.runtime.RecognitionException; +import org.jalgo.main.util.Messages; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.module.hoare.ModuleConnector; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.Event; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jalgo.module.hoare.view.View; +import org.jalgo.module.hoare.control.edits.ApplyRule; +import org.jalgo.module.hoare.control.edits.AssertionEdit; +import org.jalgo.module.hoare.control.edits.DeleteNode; + +import c00.AST; +import c00.AST.ASTTree; + +/** + * This is the main controller of the Program, which manages the communication between + * View and Model. + * + * @author Johannes + */ +public class Controller { + + private Model model; + private View view; + private ModuleConnector mc; + private UndoManager undoManager; + private Evaluation evaluator; + private int lastSave; + + /** + * creates a new instance of Controller. + */ + public Controller(View view, Model model, ModuleConnector mc){ + this.view = view; + this.model = model; + this.mc = mc; + undoManager = new UndoManager(); + evaluator = new JepEvaluator(50, 15, this); + init(); + } + + /** + * initiates the Model and the UndoManager + */ + private void init(){ + lastSave = 0; + undoManager.discardAllEdits(); + setStatusText(""); + //view.installWelcomeScreen(); + view.grayUndo(true); + view.grayRedo(true); + } + + /** + * for loading a project. + * should be called by ModuleConnector + * Warning: If the implementation of the Map of VerificationFormulas in Model changes, this method has to be changed, too. + * + * @param input + * stream to load from + */ + public void load(ObjectInputStream input) throws IOException, ClassNotFoundException{ + if( input == null ) + throw new IOException(); + + int rootId = input.readInt(); + + Object tmp = input.readObject(); + if( !(tmp instanceof HashMap) ) + throw new IOException(); + Map formulas = (HashMap) tmp; + + model.init( formulas.get(rootId) ); + view.installWorkScreen(); + + model.setAllChanged(); + model.notifyObservers(); + + if( mc != null ) + mc.setSaveStatus(SaveStatus.NO_CHANGES); + lastSave = 0; + } + + /** + * saving a project. + * should be called by ModuleConnector + * + * @param output + * stream to save to + */ + public void save(ObjectOutputStream output) throws IOException { + if( output == null ) + throw new IOException(); + + output.writeInt(model.getRoot().getId()); + output.writeObject(model.getFormulas()); + + if( mc != null ) + mc.setSaveStatus(SaveStatus.NO_CHANGES); + lastSave=0; + } + + /** + * internal function for everything to do at undo + */ + private void undo(){ + if( undoManager.canUndo() ){ + try { + undoManager.undo(); + lastSave--; + view.grayRedo(false); + } catch(CannotUndoException e){ + setStatusText(Messages.getString("hoare","out.UndoError")); + } + + if( undoManager.canUndo() ){ + view.grayUndo(false); + } + else { + view.grayUndo(true); + } + if( mc != null ){ + if( lastSave != 0 ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + else + mc.setSaveStatus(SaveStatus.NO_CHANGES); + } + } + else { + setStatusText(Messages.getString("hoare","out.UndoImpossible")); + } + } + + /** + * internal function for everything to do at redo + */ + private void redo(){ + if( undoManager.canRedo() ){ + try { + undoManager.redo(); + lastSave++; + view.grayUndo(false); + } catch(CannotRedoException e){ + setStatusText(Messages.getString("hoare", "out.RedoError")); + } + if( mc != null ){ + if( lastSave != 0 ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + else + mc.setSaveStatus(SaveStatus.NO_CHANGES); + } + + if( undoManager.canRedo() ) + view.grayRedo(false); + else + view.grayRedo(true); + } + else { + setStatusText(Messages.getString("hoare", "out.RedoImpossible")); + } + } + + /** + * applys a rule to the tree + * + * @param id + * index of the node/VerificationFormula to edit + * @param type + * Rule to apply + */ + private void applyRule(int id, Rule type) throws InvalidParameterException { + UndoableEdit edit; + boolean everythingsFine = true; + + switch(type){ + case ASSIGN: + case IF: + case IFELSE: + case COMPOUND: + case STATSEQ: + case ITERATION: + case STRONGPRE: + case WEAKPOST: + edit = new ApplyRule( model, id, type, this ); + break; + default: + throw new InvalidParameterException(Messages.getString("hoare", "control.unknownRule")); + } + + try { + edit.apply(); + } catch( InvalidParameterException e ){ + everythingsFine = false; + setStatusText(e.getMessage()); + } + + if( everythingsFine ){ + undoManager.addEdit( edit ); + view.grayUndo(false); + if( mc != null ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + lastSave++; + } + } + + /** + * edits Assertion, given from the View + * + * @param id + * index of the node/VerificationFormula to edit + * @param preAssertion + * String to set as preAssertion + * @param postAssertion + * String to set as postAssertion + */ + private void editAssertion(int id, String preAssertion, String postAssertion){ + UndoableEdit edit = new AssertionEdit( model, id, preAssertion, postAssertion, evaluator, this); + boolean everythingsFine = true; + + try { + edit.apply(); + } catch( InvalidParameterException e ){ + everythingsFine = false; + setStatusText(e.getMessage()); + } + + if( everythingsFine ){ + undoManager.addEdit( edit ); + view.grayUndo(false); + if( mc != null ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + lastSave++; + } + } + + /** + * deletes a node from the model + * + * @param id + * index of the node/VerificationFormula to delete + */ + private void deleteNode(int id){ + UndoableEdit edit = new DeleteNode(model, id, this); + boolean everythingsFine = true; + + try { + edit.apply(); + } catch(InvalidParameterException e) { + setStatusText(e.getMessage()); + everythingsFine = false; + } + + if( everythingsFine ){ + undoManager.addEdit( edit ); + view.grayUndo(false); + if( mc != null ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + lastSave++; + } + } + + /** + * gets the reports from the evaluator and takes according actions. + * sets result in model and sends errormessages to view + * + * @param id + * index of the node/VerificationFormula that was evaluated + * @param result + * result of the evaluation, errors and incorrect are false + * @param message + * String to send to View on error or incorrect + */ + public void report(int id, boolean result, String message){ + if( model.getVerificationFormula(id) == null ) + return; + + while( model.getVerificationFormula(id).hasChanged() ){ + try { + Thread.sleep(10); + } catch( InterruptedException e ){ + } + } + + // set result in model + if( result ){ + model.getVerificationFormula(id).setStatus(Status.RESULTOK); + } + else { + model.getVerificationFormula(id).setStatus(Status.RESULTWRONG); + + if( message != null && !message.equals("") ) + setStatusText(message); + } + + checkVfParentStatus(id); + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + model.notifyObservers(); + } + }); + //model.notifyObservers(); + if( mc != null ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + + /** + * might be called by View if neither id nor parameter is needed for an Event + * + * @see handleEvent(Event, Object, int) + */ + public void handleEvent(Event event) throws InvalidParameterException { + handleEvent(event, null, -1); + } + + /** + * might be called by View if one does not need an id + * + * @param event + * Event to act on + * @param parameter + * data needed for the specific Event, will be casted accordingly + * @see handleEvent(Event, Object, int) + */ + public void handleEvent(Event event, Object parameter) throws InvalidParameterException { + handleEvent(event, parameter, -1); + } + + /** + * might be called by View if one does not need a parameter + * + * @param event + * Event to act on + * @param id + * Id of the node/VerfificationFormula, the Event may work on + * @see handleEvent(Event, Object, int) + */ + public void handleEvent(Event event, int id) throws InvalidParameterException { + handleEvent(event, null, id); + } + + /** + * called by View for any action, that needs more than GUI-internals. + * + * @param event + * Event to act on + * @param parameter + * data accepted for the specific Event - will be casted accordingly + *
            + *
          • Rule for APPLYRULE + *
          • String for EDITPREASSERTION, EDITPOSTASSERTION, PARSECODE + *
          • File for PARSECODE + *
          • not needed for any other + *
          + * @param id + * Id of the node/VerfificationFormula, the Event may work on - + * may be -1 if not needed + */ + public void handleEvent(Event event, Object parameter, int id ) throws InvalidParameterException { + if( event == null ) + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.noSuchEvent")); + + // view likes to have this ... + view.bleechStatusText(); + + switch(event){ + case UNDO: + undo(); + break; + case REDO: + redo(); + break; + case APPLYRULE: + if( parameter == null || ! (parameter instanceof Rule) ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.ParameterError")); + } + if( id == -1 || model.getVerificationFormula(id) == null ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.IdError")); + } + applyRule( id, (Rule)parameter ); + break; + case EDITPREASSERTION: + if( parameter == null || ! (parameter instanceof String) ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.ParameterError")); + } + if( id == -1 || model.getVerificationFormula(id) == null ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.IdError")); + } + editAssertion( id, (String)parameter, model.getVerificationFormula(id).getPostAssertion(TextStyle.SOURCE) ); + break; + case EDITPOSTASSERTION: + // + if( parameter == null || ! (parameter instanceof String) ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.ParameterError")); + } + if( id == -1 || model.getVerificationFormula(id) == null ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.IdError")); + } + + editAssertion( id, model.getVerificationFormula(id).getPreAssertion(TextStyle.SOURCE), (String)parameter ); + break; + case DELETENODE: + if( id == -1 || model.getVerificationFormula(id) == null ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.IdError")); + } + deleteNode( id ); + break; + case PARSECODE: + if( parameter == null || !(parameter instanceof String) && !(parameter instanceof File) ){ + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.ParameterError")); + } + if( parameter instanceof File ){ + String code = new String(); + BufferedReader reader; + + try { + reader = new BufferedReader(new FileReader((File)parameter) ); + while( reader.ready() ){ + code += reader.readLine(); + } + } catch( IOException e ){ + setStatusText(Messages.getString("hoare","control.handleEvent.FileReadError")); + throw new InvalidParameterException(Messages.getString("hoare","control.handleEvent.FileReadError")); + } + // save source without whitespace + parseCode( code ); + } + else { + parseCode( (String)parameter ); + } + + if( mc != null ) + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + lastSave++; + + //model.setAllChanged(); + model.notifyObservers(); + break; + case REINIT: + init(); + model.clear(); + model.notifyObservers(); + break; + default: + throw new InvalidParameterException(Messages.getString("hoare", "control.handleEvent.noSuchEvent")); + } + } + + /** + * will parse in the code an fill the model with it + * + * @param code + * a String that contains the source-code + */ + private void parseCode(String code){ + init(); + + // scanf und printf entfernen: + code = Pattern.compile("(scanf|printf).*?;").matcher(code).replaceAll(""); + + // jedes WhiteSpace Zeichen entfernen + code = code.replaceAll("\\s", ""); + //Problem bei if-else ohne {} bzw. if oder while + code = code.replaceAll("else([^{])","else $1"); + code = code.replaceAll("(if|while)","$1 "); + + try { + StringBuffer errorBuffer = new StringBuffer(); + ASTTree astTree = AST.parseString(code, "StatementSequence", errorBuffer); + + if (astTree != null) { + model.init((AST.StatementSequence)astTree, code); + } else { + setStatusText(Messages.getString("hoare","control.ParseCodeError")); + // the exception tells the view the parsing failed + throw new InvalidParameterException(); + } + } catch (RecognitionException e) { + setStatusText(e.getMessage()); + // the exception tells the view the parsing failed + throw new InvalidParameterException(); + } + } + + /** + * checks for a VerificationFormula if its parent must change its status because of its own status changes + * + * @param vfId + * vfId that changed its status and whose parents have to be checked + */ + public void checkVfParentStatus(int vfId){ + if( model.getVerificationFormula(vfId) == null ){ + return; + } + + if( model.getVerificationFormula(vfId).getParent() == null ){ + // wir sind am Wurzelknoten angelangt + if( model.getVerificationFormula(vfId).getStatus() == Status.RESULTOK ){ + model.notifyObservers(); + view.showProveFinished(); + } + return; + } + + + + VerificationFormula parent = model.getVerificationFormula(vfId).getParent(); + boolean selfOk = true; + Status state = Status.RESULTOK; + if( !parent.hasFilledPreAssertion() || !parent.hasFilledPostAssertion() || parent.getAppliedRule() == null || !parent.isCorrect() ) + selfOk = false; + if( parent.isImplication() && (parent.getStatus() == Status.RESULTWRONG || parent.getStatus() == Status.WAITING) ) + selfOk = false; + + if( !selfOk ){ + state = Status.RESULTWRONG; + } + else { + for( VerificationFormula childVf : parent.getChildren() ){ + if( childVf.getStatus() == Status.UNCHANGED || childVf.getStatus() == Status.RESULTWRONG || childVf.getStatus() == Status.WAITING ){ + state = Status.UNCHANGED; + } + } + + } + + if( ! parent.getStatus().equals(state) ){ + parent.setStatus(state); + checkVfParentStatus(parent.getId()); + } + return; + } + + /** + * shows a Message in View by setting the status text + * @param text + * the text to set + */ + public void setStatusText(String text){ + if( text == null ) + text = ""; + view.setStatusText(text); + } +} diff --git a/src/org/jalgo/module/hoare/control/Evaluation.java b/src/org/jalgo/module/hoare/control/Evaluation.java new file mode 100644 index 0000000..a7b802a --- /dev/null +++ b/src/org/jalgo/module/hoare/control/Evaluation.java @@ -0,0 +1,28 @@ +package org.jalgo.module.hoare.control; + +import org.jalgo.module.hoare.model.VerificationFormula; + +/** + * an interface for Evaluation. + * has only the needed functions for evaluation, stopping it and reporting things + * + * @author Johannes + */ +public interface Evaluation { + /** + * will stop an evaluation with the given id + * + * @param id + * this evaluation should be stopped + */ + public void killThread(int id); + + /** + * will start an evaluaton of the given VerificationFormula + * + * @param vf + * the VerificationFormula to evaluate + */ + public void evaluate(VerificationFormula vf); + +} diff --git a/src/org/jalgo/module/hoare/control/EvaluationThread.java b/src/org/jalgo/module/hoare/control/EvaluationThread.java new file mode 100644 index 0000000..2d7b615 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/EvaluationThread.java @@ -0,0 +1,218 @@ +package org.jalgo.module.hoare.control; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jalgo.main.util.Messages; +import org.lsmp.djep.xjep.XJep; +import org.nfunk.jep.Node; +import org.nfunk.jep.ParseException; +import org.jalgo.module.hoare.constants.ParserAccess; + +/** + * an Thread for evaluating the correctness of pre- and postAssertions. + * it reports errors and results through his father. + * + * @author Johannes, Uwe + */ +public class EvaluationThread extends Thread { + + private int myId; + private int maxEvalTime; + private int base; + private boolean run; + private JepEvaluator father; + private String leftSide; + private String rightSide; + + + private XJep evaluator; + + /** + * creates a new instance of EvaluationThread + * + * @param myId + * index of the node/VerificationFormula - also the ThreadId + * @param maxEvalTime + * maxEvalTime given in seconds + * @param base + * number of ciphers to test + * @param father + * father of the thread, will get results reported + * @param leftSide + * left side of the equation + * @param rightSide + * right side of the equation + */ + public EvaluationThread(int myId, int maxEvalTime, int base, JepEvaluator father, String leftSide, String rightSide){ + this.myId = myId; + this.maxEvalTime = maxEvalTime * 1000; + this.base = base; + this.father = father; + this.leftSide = leftSide; + this.rightSide = rightSide; + run = true; + + evaluator = ParserAccess.createParser(); + } + + + /** + * the main working function of the thread. + * evaluates the assertions an report any result or error to the father + */ + public void run(){ + int count = 0; + double max = 0.0; + double startTime = 0.0; + Node leftNode; + Node rightNode; + Set unbound = new HashSet(); + Map fixed = new HashMap(); + Random random = new Random(); + + + if (!(leftSide.matches(".*\\|\\|.*")) && !(rightSide.matches(".*\\|\\|.*"))) { + leftSide = prepareForXJep(leftSide, true); + rightSide = prepareForXJep(rightSide, false); + fixed = getFixed(leftSide); + + for (String s : fixed.keySet()) { + evaluator.addVariable(s, fixed.get(s)); + } + } + + + + try { + leftNode = evaluator.parse(leftSide); + rightNode = evaluator.parse(rightSide); + } catch (ParseException pe) { + father.report(myId, false, Messages.getString("hoare", "out.evalError") + pe.getErrorInfo()); + return; + } + + for (Object o : evaluator.getSymbolTable().keySet()) { + if (evaluator.getVarValue((String)o) == null + && !(leftSide.matches(".*(Sum|Product)\\([^,]*," + o + ",[^,]*,[^,]*\\).*")) + && !(leftSide.matches(".*(\\&|\\||\\()" + o + "=(Sum|Product).*")) + && !(rightSide.matches(".*(Sum|Product)\\([^,]*," + o + ",[^,]*,[^,]*\\).*"))) { + unbound.add(o); + } + } + + + max = Math.pow(base, unbound.size()); + startTime = System.currentTimeMillis(); + run = true; + + + while ((run) && (count < max)) { + + for (Object o : unbound){ + evaluator.setVarValue((String)o, (random.nextInt() % (base/2))); + } + + try { + if (evaluator.evaluate(leftNode).equals(1.0) + && evaluator.evaluate(rightNode).equals(0.0)) { + father.report(myId, false, Messages.getString("hoare", "out.evaluationWrong") + + "\n" + evaluator.getSymbolTable().toString()); + return; + } + } catch (ParseException pe){ + father.report(myId, false, Messages.getString("hoare", "out.evalError") + pe.getErrorInfo()); + return; + } + count++; + + if ((count % 100) == 0) { + if ((System.currentTimeMillis() - startTime) > maxEvalTime) { + break; + } + } + + }// while + + if (!run) { + return; + } + + father.report(myId, true, Messages.getString("hoare", "out.evaluationOK")); + } + + /** + * will stop the thread + */ + public void end(){ + run = false; + } + + /** + * Prepares the assertion for XJep. + * Equals were replaced by double equals except for variable=Sum|Product + * and variable=double value. + * + * @param assertion + * String of assertion to translate + * @return the reworked String representing the assertion + */ + private String prepareForXJep(String assertion, boolean prepareSum){ + + Pattern p1; + Matcher matcher; + + + assertion = assertion.replaceAll("(?=\\!])=(?!=)", "=="); + + + + if (prepareSum) { + p1 = Pattern.compile("((?:\\&|\\||\\A)(?:\\(*)([a-zA-Z][a-zA-Z]*\\d*))==((?:Sum|Product)\\([^,]*,[^,]*,[^,]*,[^\\)]*\\)[^\\&\\|]*)"); + + matcher = p1.matcher(assertion); + while (matcher.find()) { + assertion = assertion.replace(matcher.group(1) + "==" + matcher.group(3), + matcher.group(1) + "=" + matcher.group(3) + "==" + matcher.group(2)); + } + } + + + return assertion; + } + + /** + * Creates a Map with the fixed variables (variable=double value). + * + * @param assertion the String representing the assertion + * @return Map with the fixed variables and their values + */ + private Map getFixed(String assertion){ + + HashMap fixed = new HashMap(); + Pattern p2; + Matcher matcher; + + + p2 = Pattern.compile("((?:\\(|\\&|\\||\\A)([a-zA-Z][a-zA-Z]*\\d*\\b))==((\\d*(\\.\\d*)?)(?:\\)|\\||\\&|\\z))"); + + matcher = p2.matcher(assertion); + while (matcher.find()) { + try { + fixed.put(matcher.group(2), Double.valueOf(matcher.group(4))); + } catch (NumberFormatException nfe) { + // do not add as fixed Variable + // this Exception can't be raised + // because only proper Double values matches the regex + } + } + + return fixed; + } + +} diff --git a/src/org/jalgo/module/hoare/control/JepEvaluator.java b/src/org/jalgo/module/hoare/control/JepEvaluator.java new file mode 100644 index 0000000..8f08939 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/JepEvaluator.java @@ -0,0 +1,124 @@ +package org.jalgo.module.hoare.control; + +import java.util.Map; +import java.util.HashMap; + +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.model.VerificationFormula; + +/** + * implementation of the interface Evaluation for djep. + * manages all EvaluationThreads and forwards the messages send by them to the Controller + * + * @author Johannes + */ +public class JepEvaluator implements Evaluation { + + private int base = 50; + private int maxEvalTime = 15; + private Controller controller; + private Map threadTable = new HashMap(); + + /** + * creates a new instance of JepEvaluator + * + * @param base + * number of ciphers to test + * @param maxEvalTime + * maximum time an evaluation may last in seconds + * @param controller + * the Controller, that results and errors will be send to + */ + public JepEvaluator(int base, int maxEvalTime, Controller controller){ + this.base = base; + this.maxEvalTime = maxEvalTime; + this.controller = controller; + } + + /** + * will send results and errors to the Controller + * + * @param id + * index of the node/VerificationFormula that was evaluated + * @param result + * false for errors or evaluation failed + * @param message + * the message for the error or result + */ + public void report(int id, boolean result, String message){ + // just to be sure it's one of our threads ... + if( threadTable.containsKey(id) ){ + // forward message and result to controller + controller.report( id, result, message ); + + // thread should finish after this -> remove from threadTable + threadTable.remove(id); + } + } + + /** + * will stop an evaluation with the given id. + * this will call end() of the thread and remove it from the threadTable + * + * @param id + * this evaluation should be stopped + */ + public void killThread(int id){ + if( threadTable.containsKey(id) ){ + try { + threadTable.get(id).end(); + } catch( NullPointerException e ) { + // do nothing + } + threadTable.remove(id); + } + } + + /** + * will start an evaluaton of the given VerificationFormula + * + * @param vf + * the VerificationFormula to evaluate + */ + public void evaluate(VerificationFormula vf){ + if( vf == null ) + return; + + // check if this vf already gets evaluated -> kill this evaluation + if( threadTable.containsKey( vf.getId() ) ){ + killThread( vf.getId() ); + } + + //TODO: Pr�fen ob es korrekt ist ? sieht zu einfach aus + if (vf.isImplication()){ + //System.out.println(vf.getPreAssertion(TextStyle.SOURCE)+"=>"+vf.getPostAssertion(TextStyle.SOURCE)); + + EvaluationThread thread = new EvaluationThread(vf.getId(),maxEvalTime, + base,this, + vf.getPreAssertion(TextStyle.SOURCE), + vf.getPostAssertion(TextStyle.SOURCE)); + threadTable.put(vf.getId(),thread); + + thread.start(); + } + + +/* // create new thread + EvaluationThread thread; + if( vf.getParent().getAppliedRule() == Rule.STRONGPRE ){ + thread = new EvaluationThread( vf.getId(), maxEvalTime, base, this, vf.getParent().getPreAssertion(TextStyle.SOURCE), vf.getPreAssertion(TextStyle.SOURCE) ); + } + else if( vf.getParent().getAppliedRule() == Rule.WEAKPOST ){ + thread = new EvaluationThread( vf.getId(), maxEvalTime, base, this, vf.getPostAssertion(TextStyle.SOURCE), vf.getParent().getPostAssertion(TextStyle.SOURCE) ); + } + else { + return; + } + + // save id => thread for later killing + threadTable.put( vf.getId(), thread ); + + thread.start();*/ + } + +} diff --git a/src/org/jalgo/module/hoare/control/UndoableEdit.java b/src/org/jalgo/module/hoare/control/UndoableEdit.java new file mode 100644 index 0000000..2a79ab0 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/UndoableEdit.java @@ -0,0 +1,11 @@ +package org.jalgo.module.hoare.control; + +/** + * the interface used by UndoManager and Controller for all the edits, + * that needs to be undoable + * + * @author Johannes + */ +public interface UndoableEdit extends javax.swing.undo.UndoableEdit { + void apply(); + } \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/control/edits/ApplyRule.java b/src/org/jalgo/module/hoare/control/edits/ApplyRule.java new file mode 100644 index 0000000..6115dc1 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/ApplyRule.java @@ -0,0 +1,231 @@ +package org.jalgo.module.hoare.control.edits; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.InvalidParameterException; +import java.util.HashMap; +import java.util.Map; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.CannotRedoException; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.control.UndoableEdit; +import org.jalgo.module.hoare.control.Controller; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.VerificationFormula; + +/** + * a class implementing UndoableEdit which can apply any rule + * + * @author Johannes + */ +public class ApplyRule implements UndoableEdit { + + private Model model; + private Controller controller; + private int vfId; + private Rule rule; + private byte[] buffer; + private boolean undo = false; + private boolean redo = false; + + /** + * creates a new instance of ApplyRule + * + * @param model + * the model, the VerificationFormula belongs to + * @param vfId + * the ID of the VerificationFormula to apply the rule to + * @param rule + * Rule that should be applied + */ + public ApplyRule(Model model, int vfId, Rule rule, Controller controller){ + this.vfId = vfId; + this.model = model; + this.rule = rule; + this.controller = controller; + } + + /** + * applys the rule to the model, if possible + */ + public void apply() throws InvalidParameterException { + + if( model == null ) + throw new InvalidParameterException( Messages.getString("hoare", "out.ruleApplyError") ); + + if( model.getVerificationFormula(vfId) == null ) + throw new InvalidParameterException(Messages.getString("hoare", "out.noValidNode")); + + if( controller == null ) + throw new InvalidParameterException(Messages.getString("hoare", "out.ruleApplyError")); + + try { + if( !model.apply(vfId, rule) ){ + if( rule == Rule.ASSIGN ){ + model.getVerificationFormula(vfId).setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(vfId); + model.notifyObservers(); + } + throw new InvalidParameterException( Messages.getString("hoare", "out.ruleApplyError") ); + } + } catch( UnsupportedOperationException e ){ + throw new InvalidParameterException( e.getMessage() ); + } + + if( rule == Rule.ASSIGN ){ + model.getVerificationFormula(vfId).setStatus(Status.RESULTOK); + controller.checkVfParentStatus(vfId); + } + else { + controller.checkVfParentStatus(model.getVerificationFormula(vfId).getChildren().get(0).getId()); + } + + model.notifyObservers(); + undo = true; + redo = false; + } + + /** + * applys the rule to the model + */ + public void redo(){ + if( !redo ) + throw new CannotRedoException(); + + if( rule == Rule.STRONGPRE || rule == Rule.WEAKPOST ){ + // get old tree + try { + ByteArrayInputStream bais = new ByteArrayInputStream(buffer); + ObjectInputStream input = new ObjectInputStream(bais); + + int rootId = input.readInt(); + + Object tmp = input.readObject(); + if( !(tmp instanceof HashMap) ) + throw new IOException(); + Map formulas = (HashMap) tmp; + + input.close(); + bais.close(); + + model.init( formulas.get(rootId)); + model.setAllChanged(); + model.notifyObservers(); + } catch (IOException e){ + //e.printStackTrace(); + throw new CannotRedoException(); + } catch (ClassNotFoundException e){ + //e.printStackTrace(); + throw new CannotRedoException(); + } + undo = true; + redo = false; + } + else { + apply(); + } + } + + /** + * undoes the application of the rule + */ + public void undo(){ + if( !undo ) + throw new CannotUndoException(); + + if( rule == Rule.STRONGPRE || rule == Rule.WEAKPOST ){ + // save old tree + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream output = new ObjectOutputStream(baos); + + output.writeInt(model.getRoot().getId()); + output.writeObject(model.getFormulas()); + output.close(); + buffer = baos.toByteArray(); + baos.close(); + } catch( IOException e ){ + //e.printStackTrace(); + throw new CannotUndoException(); + } + } + + model.remove(vfId); + model.getVerificationFormula(vfId).setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(vfId); + + model.notifyObservers(); + undo = false; + redo = true; + } + + /** + * not needed, just to complete the interface + */ + public boolean canRedo(){ + return redo; + } + + /** + * not needed, just to complete the interface + */ + public boolean canUndo(){ + return undo; + } + + /** + * not needed, just to complete the interface + */ + public String getPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getRedoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getUndoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public boolean addEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + + /** + * not needed, just to complete the interface + */ + public void die(){ + + } + + /** + * not needed, just to complete the interface + */ + public boolean isSignificant(){ + return true; + } + + /** + * not needed, just to complete the interface + */ + public boolean replaceEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + +} diff --git a/src/org/jalgo/module/hoare/control/edits/AssertionEdit.java b/src/org/jalgo/module/hoare/control/edits/AssertionEdit.java new file mode 100644 index 0000000..fc23ab6 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/AssertionEdit.java @@ -0,0 +1,310 @@ +package org.jalgo.module.hoare.control.edits; + +import java.security.InvalidParameterException; +import java.util.SortedSet; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.control.Controller; +import org.jalgo.module.hoare.control.UndoableEdit; +import org.jalgo.module.hoare.control.Evaluation; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jalgo.module.hoare.model.Variable; + +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.CannotRedoException; + +import org.nfunk.jep.ParseException; + +/** + * and UndoableEdit that can edit pre- and postAssertion of an VerificationFormula + * + * @author Johannes + */ +public class AssertionEdit implements UndoableEdit { + + private Model model; + private Controller controller; + private int vfId; + private String preAssertion; + private String postAssertion; + private Evaluation evaluator; + private boolean undo = false; + private boolean redo = false; + + + /** + * creates a new instance of AssertionEdit + * + * @param vf + * the VerificationFormula the edit will be applied to + * @param preAssertion + * the maybe changed preAssertion of the VerificationFormula + * @param postAssertion + * the maybe changed postAssertion of the VerificationFormula + * @param evaluator + * the evaluator used by the Controller + * @param controller + * the Controler for checkVfParentStatus() + */ + public AssertionEdit(Model model, int vfId, String preAssertion, String postAssertion, Evaluation evaluator, Controller controller){ + this.model = model; + this.vfId = vfId; + this.preAssertion = preAssertion; + this.postAssertion= postAssertion; + this.evaluator = evaluator; + this.controller = controller; + } + + /** + * applys the edit to the specified VerificationFormula + */ + public void apply() throws InvalidParameterException { + if( model == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + if( preAssertion == null || postAssertion == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + if( model.getVerificationFormula(vfId) == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.noValidNode")); + if( evaluator == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + if( controller == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + + + String tempPre, tempPost; + VerificationFormula vf = model.getVerificationFormula(vfId); + + tempPre = vf.getPreAssertion(TextStyle.SOURCE); + tempPost = vf.getPostAssertion(TextStyle.SOURCE); + + if( !tempPre.equals(preAssertion) && vf.canEditPreAssertion() ){ + // edit preAssertion (changes Variable) + try { + vf.editPreAssertion(preAssertion); + } catch( Exception e ){ + throw new InvalidParameterException(e.getMessage()); + } + model.updateFormulas(); //Performs the Update of the Variable-List + + // search for Variable + SortedSet vars = model.getVariables(); + Variable var = null; + for( Variable tmpVar : vars){ + if( tmpVar.isPreAssertion() && tmpVar.getName().equals(vf.getPreAssertion(TextStyle.SHORT)) ){ + var = tmpVar; + break; + } + } + if( var == null ){ + // change it back + try { + vf.editPreAssertion(tempPre); + } catch( Exception e ){ + throw new InvalidParameterException(e.getMessage()); + } + model.updateFormulas(); //Performs the Update of the Variable-List + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + } + + // evaluate all VFs containing this Variable and update the state of the tree + for( VerificationFormula tmpVF : model.getFormulasByVariable(var.getName()) ){ + if( tmpVF.isRuleApplied() ){ // isVisible + tmpVF.setChanged(true); + if( tmpVF.verifiable() ){ + tmpVF.setStatus(Status.WAITING); + evaluator.evaluate(tmpVF); + } + else { + if( tmpVF.hasFilledPreAssertion() && tmpVF.hasFilledPostAssertion() && tmpVF.getAppliedRule() != null && tmpVF.isCorrect() ){ + if( tmpVF.getAppliedRule() == Rule.ASSIGN ){ + tmpVF.setStatus(Status.RESULTWRONG); + } + + if( tmpVF.hasChildren() && tmpVF.getChildren().get(0).isRuleApplied() ) + controller.checkVfParentStatus(tmpVF.getChildren().get(0).getId()); + else if(!tmpVF.hasChildren()) + controller.checkVfParentStatus(tmpVF.getId()); + } + else { + if( tmpVF.isImplication() ){ + tmpVF.setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(tmpVF.getId()); + } + if( tmpVF.getAppliedRule() == Rule.ITERATION ){ + tmpVF.setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(tmpVF.getId()); + if( !tmpVF.isCorrect() ) + controller.setStatusText(Messages.getString("hoare", "out.IterationChangedToWrong")); + } + } + } + } + } + + preAssertion = tempPre; + } + if( !tempPost.equals(postAssertion) && vf.canEditPostAssertion() ){ + // edit postAssertion (changes Variable) + try { + vf.editPostAssertion(postAssertion); + } catch( Exception e ){ + throw new InvalidParameterException(e.getMessage()); + } + model.updateFormulas(); //Performs the Update of the Variable-List + + // search for Variable + SortedSet vars = model.getVariables(); + Variable var = null; + for( Variable tmpVar : vars){ + if( !(tmpVar.isPreAssertion()) && tmpVar.getName().equals(vf.getPostAssertion(TextStyle.SHORT)) ){ + var = tmpVar; + break; + } + } + if( var == null ){ + // change it back + try { + vf.editPostAssertion(tempPost); + } catch( Exception e ){ + throw new InvalidParameterException(e.getMessage()); + } + model.updateFormulas(); //Performs the Update of the Variable-List + throw new InvalidParameterException(Messages.getString("hoare","out.EditAssertionFailed")); + } + + // evaluate all VFs containing this Variable which are WEAKPOST + for( VerificationFormula tmpVF : model.getFormulasByVariable(var.getName()) ){ + if( tmpVF.isRuleApplied() ){ // isVisible + tmpVF.setChanged(true); + if( tmpVF.verifiable() ){ + tmpVF.setStatus(Status.WAITING); + evaluator.evaluate(tmpVF); + } + else { + if( tmpVF.hasFilledPreAssertion() && tmpVF.hasFilledPostAssertion() && tmpVF.getAppliedRule() != null && tmpVF.isCorrect() ){ + if( tmpVF.getAppliedRule() == Rule.ASSIGN ){ + tmpVF.setStatus(Status.RESULTWRONG); + } + + if( tmpVF.hasChildren() && tmpVF.getChildren().get(0).isRuleApplied() ) + controller.checkVfParentStatus(tmpVF.getChildren().get(0).getId()); + else if(!tmpVF.hasChildren()) + controller.checkVfParentStatus(tmpVF.getId()); + } + else { + if( tmpVF.isImplication() ){ + tmpVF.setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(tmpVF.getId()); + } + if( tmpVF.getAppliedRule() == Rule.ITERATION ){ + tmpVF.setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(tmpVF.getId()); + if( !tmpVF.isCorrect() ) + controller.setStatusText(Messages.getString("hoare", "out.IterationChangedToWrong")); + } + } + } + } + } + + postAssertion = tempPost; + } + + model.notifyObservers(); + + if( undo == redo ){ + undo = true; + redo = false; + } + } + + /** + * redoes the edit + */ + public void redo(){ + if( !redo ) + throw new CannotRedoException(); + apply(); + undo = true; + redo = false; + } + + /** + * undoes the edit + */ + public void undo(){ + if( !undo ) + throw new CannotUndoException(); + apply(); + undo = false; + redo = true; + } + + /** + * not needed, just to complete the interface + */ + public boolean canRedo(){ + return redo; + } + + /** + * not needed, just to complete the interface + */ + public boolean canUndo(){ + return undo; + } + + /** + * not needed, just to complete the interface + */ + public String getPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getRedoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getUndoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public boolean addEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + + /** + * not needed, just to complete the interface + */ + public void die(){ + // do nothing + } + + /** + * not needed, just to complete the interface + */ + public boolean isSignificant(){ + return true; + } + + /** + * not needed, just to complete the interface + */ + public boolean replaceEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + +} diff --git a/src/org/jalgo/module/hoare/control/edits/CVS/Entries b/src/org/jalgo/module/hoare/control/edits/CVS/Entries new file mode 100644 index 0000000..0206c7b --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/CVS/Entries @@ -0,0 +1,4 @@ +/ApplyRule.java/1.1/Wed Aug 27 13:00:44 2008// +/AssertionEdit.java/1.2/Wed Aug 27 13:00:45 2008// +/DeleteNode.java/1.1/Wed Aug 27 13:00:40 2008// +/package-info.java/1.1/Wed Aug 27 13:00:41 2008// diff --git a/src/org/jalgo/module/hoare/control/edits/CVS/Repository b/src/org/jalgo/module/hoare/control/edits/CVS/Repository new file mode 100644 index 0000000..7996416 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/control/edits diff --git a/src/org/jalgo/module/hoare/control/edits/CVS/Root b/src/org/jalgo/module/hoare/control/edits/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/control/edits/DeleteNode.java b/src/org/jalgo/module/hoare/control/edits/DeleteNode.java new file mode 100644 index 0000000..fec3d80 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/DeleteNode.java @@ -0,0 +1,203 @@ +package org.jalgo.module.hoare.control.edits; + +import java.security.InvalidParameterException; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.Map; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.CannotRedoException; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.control.UndoableEdit; +import org.jalgo.module.hoare.control.Controller; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.VerificationFormula; + +/** + * an UndoableEdit that can delete a subtree of a node + * + * @author Johannes + */ +public class DeleteNode implements UndoableEdit { + + private Model model; + private Controller controller; + private int vfId; + private byte[] buffer; + private boolean undo = false; + private boolean redo = false; + + + /** + * creates a new instance of DeleteNode + * + * @param model + * the model, the VerificationFormula belongs to + * @param vfId + * the Id of the VerificationFormula + */ + public DeleteNode(Model model, int vfId, Controller controller){ + this.model = model; + this.vfId = vfId; + this.controller = controller; + } + + /** + * delete the node + */ + public void apply() throws InvalidParameterException{ + if( model == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.DeleteNodeFailed")); + if( model.getVerificationFormula(vfId) == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.noValidNode")); + if( controller == null ) + throw new InvalidParameterException(Messages.getString("hoare","out.DeleteNodeFailed")); + + // save old tree + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream output = new ObjectOutputStream(baos); + + output.writeInt(model.getRoot().getId()); + output.writeObject(model.getFormulas()); + output.close(); + buffer = baos.toByteArray(); + baos.close(); + } catch( IOException e ){ + throw new InvalidParameterException(Messages.getString("hoare","out.DeleteNodeFailed")); + } + + // make changes + model.remove(vfId); + + model.getVerificationFormula(vfId).setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(vfId); + + model.notifyObservers(); + + undo = true; + redo = false; + } + + /** + * delete the node again + */ + public void redo(){ + if( !redo ) + throw new CannotRedoException(); + + model.remove(vfId); + + model.getVerificationFormula(vfId).setStatus(Status.RESULTWRONG); + controller.checkVfParentStatus(vfId); + + model.notifyObservers(); + + undo = true; + redo = false; + } + + /** + * undelete the node. + * Warning: If the implementation of the Map of VerificationFormulas in Model changes, this method has to be changed, too. + */ + public void undo(){ + if( !undo ) + throw new CannotUndoException(); + + try { + ByteArrayInputStream bais = new ByteArrayInputStream(buffer); + ObjectInputStream input = new ObjectInputStream(bais); + + int rootId = input.readInt(); + Object tmp = input.readObject(); + if( !(tmp instanceof HashMap) ) + throw new IOException(); + Map formulas = (HashMap) tmp; + + input.close(); + bais.close(); + + model.init( formulas.get(rootId) ); + model.setAllChanged(); + model.notifyObservers(); + } catch (IOException e){ + e.printStackTrace(); + throw new CannotUndoException(); + } catch (ClassNotFoundException e){ + throw new CannotUndoException(); + } + + undo = false; + redo = true; + } + + /** + * not needed, just to complete the interface + */ + public boolean canRedo(){ + return redo; + } + + /** + * not needed, just to complete the interface + */ + public boolean canUndo(){ + return undo; + } + + /** + * not needed, just to complete the interface + */ + public String getPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getRedoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public String getUndoPresentationName(){ + return null; + } + + /** + * not needed, just to complete the interface + */ + public boolean addEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + + /** + * not needed, just to complete the interface + */ + public void die(){ + + } + + /** + * not needed, just to complete the interface + */ + public boolean isSignificant(){ + return true; + } + + /** + * not needed, just to complete the interface + */ + public boolean replaceEdit(javax.swing.undo.UndoableEdit arg0){ + return false; + } + +} diff --git a/src/org/jalgo/module/hoare/control/edits/package-info.java b/src/org/jalgo/module/hoare/control/edits/package-info.java new file mode 100644 index 0000000..9ffb9e3 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/edits/package-info.java @@ -0,0 +1,4 @@ +/** + * contains alle classes, that can be applied as undoable edits by the controller + */ +package org.jalgo.module.hoare.control.edits; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/control/package-info.java b/src/org/jalgo/module/hoare/control/package-info.java new file mode 100644 index 0000000..19b8e97 --- /dev/null +++ b/src/org/jalgo/module/hoare/control/package-info.java @@ -0,0 +1,6 @@ + +/** + * contains all classes used to control + * both {@link View} and {@link Model} + */ +package org.jalgo.module.hoare.control; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/de.properties b/src/org/jalgo/module/hoare/de.properties new file mode 100644 index 0000000..544fc43 --- /dev/null +++ b/src/org/jalgo/module/hoare/de.properties @@ -0,0 +1,102 @@ +Module_name=Hoare +Module_version=1.7 +Module_authors=Antje Lang, Johannes Kulik, Thomas Kühn, Tomas Karnagel, Uwe Pfeiffer +Module_description_1=Dieses Modul hilft beim Lernen und Verstehen von Beweisbäumen im Sinne des Hoare-Kalküls. +Module_description_2=Der Beweisbaum für ein Programm kann interaktiv entwickelt werden. +Module_license=GNU General Public License +Beamer_mode=Beamer-Modus + +ttt.openC0Program=C0-Program öffnen +ttt.redo=Einen Schritt wiederherstellen +ttt.undo=Einen Schritt rückgängig machen +ttt.reinit = Programm reinitialisieren +ttt.delNode=Teilbaum löschen +ttt.zoomIn=den Baum vergrößern +ttt.zoomOut=den Baum verkleinern +ttt.normalMouse=Auswahl von Zellen +ttt.toggleSplitter=Seitenleiste verstecken +ttt.resetZoom=Zoom zurücksetzen +ttt.applyFormulaChange=(Strg+Enter) + +out.evalError=Fehler bei der Auswertung: +out.noValidNode=Keinen zulässigen Knoten gewählt +out.ruleApplyError=Fehler bei Regelanwendung +out.IterationChangedToWrong=die Änderung hat eine Iterationsregel invalidiert +out.DeleteNodeFailed=Unterbaum konnte nicht gelöscht werden. +out.EditAssertionFailed=Die Bedingung konnte nicht editiert werden. +out.UndoImpossible=Undo nicht möglich +out.UndoError=Beim Undo ist ein Fehler aufgetreten. +out.RedoImpossible=Redo nicht möglich +out.RedoError=Beim Redo ist ein Fehler aufgetreten. +out.evaluationWrong=Auswertungs-Ergebnis: falsch +out.evaluationOK=Auswertungs-Ergebnis: richtig +out.loadError=Fehler beim Laden +out.saveError=Fehler beim Speichern +out.iterationCheckFailed=%s nicht von der Form %s \u2227 \u00AC \u03C0 + +allsuccessful=Herzlichen Glückwunsch. Der Beweis war erfolgreich. +wannaReinit=Eingaben löschen und Bildschrim neu laden? + +name.resetZoom=Zoom zurücksetzen +name.openC0Program=C0-Program öffnen +name.reparse=parst C0Program neu +name.toggleDesc=Details ein/aus +name.redo=Wiederherstellen +name.undo=Rückgängig +name.reinit=Programm neu starten +name.evalTree=Baum testen +name.delNode=Teilbaum löschen +name.eraseLog=Löschen +name.zoomIn=vergrößern +name.zoomOut=verkleinern +name.normalMouse=Auswahltool +name.toggleSplitter= +name.assign=Zuweisungsaxiom +name.comp=Block-Statement +name.sequence=Sequenz +name.alt1=If-Statement +name.alt2=If-Else +name.iter=Iteration +name.SV=Stärkere Vorbed. +name.SN=Schwächere Nachbed. +name.pre=Vorbedingung +name.post=Nachbedingung +name.source=C0-Quelltext +name.variables=Variablen +name.rules=Regeln + +rule.assign.desc=(ZA) +rule.comp.desc=(CR) +rule.sequence.desc=(SR) +rule.alt1.desc=(A1) +rule.alt2.desc=(A2) +rule.iter.desc=(IR) +rule.SV.desc=(SV) +rule.SN.desc=(SN) + +control.handleEvent.IdError=Diese Art Event brauch eine Id. +control.handleEvent.ParameterError=Nicht der richtige Parametertyp für dieses Event. +control.handleEvent.noSuchEvent=kein solches Event vorhanden +control.handleEvent.FileReadError=Fehler beim Lesen aus der Datei. +control.unknownRule=unbekannte Regel +control.ParseCodeError=Ein Fehler ist beim Parsen des Codes aufgetreten. + +view.zoomError=Zoom in diese Richtung nicht mehr möglich +view.cellSelectionError=keine Zelle ausgewählt +view.source.editButtonText=Bearbeiten +view.source.parseButtonText=Parsen +view.source.rereadButtonText=Wiederherstellen +view.source.editButtonTTT=anderes C0-Programm eingeben +view.source.parseButtonTTT=Parst das C0-Programm und erstellt die Wurzel des Beweisbaums. +view.source.rereadButtonTTT=Lädt wieder das zum aktuellen Baum zugehörige C0-Programm. Das eingegebene C0-Programm wird verworfen. +view.source.confirmParsingMessageTitle=Parsen bestätigen +view.source.confirmParsingMessage=Der aktuelle Beweisbaum geht beim Parsen verloren.\nWollen Sie den Quellcode trotzdem parsen? +view.parseError=Fehler beim Parsen +view.parseErrorFormulaSubstitution=(?) +view.changeFont=Schrift ändern +view.newFontName=neue Schriftart: +view.newFontSize=neue Schriftgröße: +view.editVariable=$Var bearbeiten +view.variables.selectedVariables=Variablen Vor- und Nachbedingung + +parserAccess.newParseException=Zusicherungen der Form a<b<c sind nicht gestattet. \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/en.properties b/src/org/jalgo/module/hoare/en.properties new file mode 100644 index 0000000..90a5008 --- /dev/null +++ b/src/org/jalgo/module/hoare/en.properties @@ -0,0 +1,103 @@ +Module_name=Hoare +Module_version=1.7 +Module_authors=Antje Lang, Johannes Kulik, Thomas Kühn, Tomas Karnagel, Uwe Pfeiffer +Module_description_1=A module for visualisation and training of the Hoare logic. +Module_description_2=The tree for a given programm can be interactivly developed. +Module_license=GNU General Public License +Beamer_mode=beamer-mode + +ttt.openC0Program=parse C0-program +ttt.redo=one step forward +ttt.undo=one step back +ttt.reinit = reinit program +ttt.delNode=delete the tree above the highlighted node +ttt.zoomIn=enlarge the tree +ttt.zoomOut=scaling down the tree +ttt.normalMouse=Mode for Selection of Cells +ttt.toggleSplitter=Hide sidebar +ttt.resetZoom=reset Zoom +ttt.applyFormulaChange=(Ctrl+Enter) + +out.evalError=evaluation error occured: +out.noValidNode=no valid node selected +out.ruleApplyError=error on ruleapply +out.IterationChangedToWrong=this edit invalidated an iteration rule +out.ApplyRuleFailed=Unable to apply that rule. +out.DeleteNodeFailed=Unable to delete the subtree. +out.EditAssertionFailed=Unable to edit assertion. +out.UndoImpossible=undo-operation impossible +out.UndoError=An error occured while trying to undo. +out.RedoImpossible=redo-operation impossible +out.RedoError=An error occured while trying to redo. +out.evaluationWrong=evaluation result: wrong +out.evaluationOK=evaluation result: ok +out.loadError=error on loading +out.saveError=error on saving +out.iterationCheckFailed=%s must have the form %s \u2227 \u00AC \u03C0 + +allsuccessful=You have been successful. +wannaReinit=Delete all inputs and reset the screen? + +name.resetZoom=reset Zoom +name.openC0Program=opens C0-Program +name.reparse=reparse C0Program +name.toggleDesc=toggle Description +name.redo=Redo +name.undo=Undo +name.reinit=reinit +name.evalTree=evaluate tree +name.delNode=delete the tree above the highlighted node +name.eraseLog=Clear +name.zoomIn=zoom in +name.zoomOut=zoom out +name.normalMouse=Selectiontool +name.toggleSplitter= +name.assign=assignment +name.comp=compound +name.sequence=sequence +name.alt1=if-statement +name.alt2=if-else +name.iter=iteration +name.SV=stronger precond. +name.SN=weaker postcond. +name.pre=precondition +name.post=postcondition +name.source=C0 source code +name.variables=Variables +name.rules=Rules + +rule.assign.desc=(AssR) +rule.comp.desc=(CR) +rule.sequence.desc=(SR) +rule.alt1.desc=(A1) +rule.alt2.desc=(A2) +rule.iter.desc=(IR) +rule.SV.desc=(SP) +rule.SN.desc=(WP) + +control.handleEvent.IdError=Need an Id for this type of Event +control.handleEvent.ParameterError=Not the correct parameter type for this Event +control.handleEvent.noSuchEvent=no such event +control.handleEvent.FileReadError=Error while reading from file. +control.unknownRule=unknown Rule +control.ParseCodeError=Unknown error occured while parsing the code. + +view.zoomError=cannot zoom anymore in this direction +view.cellSelectionError=no cell selected +view.source.editButtonText=Edit +view.source.parseButtonText=Parse +view.source.rereadButtonText=Reset +view.source.editButtonTTT=enter a different C0-program +view.source.parseButtonTTT=Parses the C0-program and creates the root of the proof tree. +view.source.rereadButtonTTT=Loads the C0-program belonging to the current tree. The entered C0-program will be lost. +view.source.confirmParsingMessageTitle=Confirm parsing +view.source.confirmParsingMessage=The current proof tree will be lost.\nDo you want to parse the source code anyway? +view.parseError=parse error +view.parseErrorFormulaSubstitution=(?) +view.changeFont=change font +view.newFontSize=new font size: +view.newFontName=new font: +view.editVariable=Edit $Var +view.variables.selectedVariables=Variables pre- and postcondition + +parserAccess.newParseException=Assertions like a<b<c aren't allowed. \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/model/AbstractAssertion.java b/src/org/jalgo/module/hoare/model/AbstractAssertion.java new file mode 100644 index 0000000..d28452f --- /dev/null +++ b/src/org/jalgo/module/hoare/model/AbstractAssertion.java @@ -0,0 +1,62 @@ +package org.jalgo.module.hoare.model; + +import java.io.Serializable; + +/** + * Represents an abstract class of an assertion + * + * @author Thomas + */ + +abstract class AbstractAssertion implements Serializable { + + /** + * To get the full C0 compatible String of this Assertion + * + * @see java.lang.Object#toString() + */ + public abstract String toString(); + + /** + * return the String with the correct Unicode Symbols of an + * either short or long Form of this Assertion + * + * @param full + * true if you want to get a long Form of this Assertion + * @return + * the String with the correct Unicode Symbols + */ + public abstract String toText(boolean full); + + /** + * return the original String.
          + * Note: You can insert an original String + * into every {@link VarAssertion} by calling + * {@link VarAssertion#setOriginal}. + * + * @return the original you set in a VarAssertion or + * the String you get by calling toString + */ + public String getOrginal(){ + return toString(); + } + + /** + * return true if this assertiontree includes only filled VarAssertions + * and normal assertions + * + * @return + * the possibility to verify this Assertion + */ + public abstract boolean verifiable(); + + /** + * Checks if the assertion is just an variable + * + * @return true if the Assertion is an VarAssertion + */ + public boolean isVariable() { + return false; + } + +} diff --git a/src/org/jalgo/module/hoare/model/AndAssertion.java b/src/org/jalgo/module/hoare/model/AndAssertion.java new file mode 100644 index 0000000..180919d --- /dev/null +++ b/src/org/jalgo/module/hoare/model/AndAssertion.java @@ -0,0 +1,60 @@ +package org.jalgo.module.hoare.model; + +/** + * Represents an And in the assertiontree. It must have two children assertion as operands. + * + * @author Thomas, Uwe + **/ +class AndAssertion extends AbstractAssertion { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = -7327027897881901603L; + /** + * the left side of the assertion tree under the and + */ + private AbstractAssertion left; + /** + * the right side of the assertion tree under the and + */ + private AbstractAssertion right; + + /** + * creates an AndAssertion with an left and right assertion tree + * + * @param left + * the left child assertion compared with And + * @param left + * the right child assertion compared with And + **/ + public AndAssertion(AbstractAssertion left,AbstractAssertion right) { + this.left=left; + this.right=right; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#verifiable() + */ + @Override + public boolean verifiable() { + return left.verifiable() && right.verifiable(); + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toString() + */ + @Override + public String toString() { + return "("+left.toString()+" && "+right.toString()+")"; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toText(boolean) + */ + @Override + public String toText(boolean full) { + return "("+left.toText(full) + " \u2227 " + right.toText(full) + ")"; + } + +} diff --git a/src/org/jalgo/module/hoare/model/AssignFormula.java b/src/org/jalgo/module/hoare/model/AssignFormula.java new file mode 100644 index 0000000..753fb8b --- /dev/null +++ b/src/org/jalgo/module/hoare/model/AssignFormula.java @@ -0,0 +1,133 @@ +package org.jalgo.module.hoare.model; + +import java.util.Vector; + +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.constants.ParserAccess; +import org.lsmp.djep.xjep.XJep; +import org.nfunk.jep.Node; + +/** + * Represents a single assignment. + * It is the leaf of the verification tree. + * + * @author Thomas, Uwe + * + */ + +public class AssignFormula extends VerificationFormula { + + private static final long serialVersionUID = 6878923401432559946L; + + /** + * Constructs a AssignFormula with the given beginning and end of the code + * and sets the parent and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + */ + AssignFormula(VerificationFormula parent, String source, int codeStart, int codeEnd){ + super(parent, source, codeStart,codeEnd); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return rule.equals(Rule.ASSIGN); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + String[] replace = new String[2]; + String pre; + String post; + String code; + + pre = parent.getPreAssertion(TextStyle.SOURCE).replaceAll("\\s", "").replaceAll(";", "").replaceAll("(?=!])=(?![=])", "=="); + post = parent.getPostAssertion(TextStyle.SOURCE).replaceAll("\\s", "").replaceAll(";", "").replaceAll("(?=!])=(?![=])", "=="); + code = parent.getCode(parent.code).replaceAll("\\s", "").replaceAll(";", ""); + replace = code.split("=", 2); + + XJep parser = ParserAccess.createParser(); + try { + Node preTop = ParserAccess.parse(pre);//parser.parse(pre); + Node postTop = ParserAccess.parse(post);//parser.parse(post); + Vector variables = new Vector(); + variables = (Vector)parser.getVarsInEquation(postTop, variables); + String[] variableNames = new String[variables.size()]; + Node[] variableNodes = new Node[variables.size()]; + for (int i=0; iVerificationFormula
          + * Note: That the Status can only be changed if the + * VerificationFormula is verifiable. + * + * @param status + * the {@link Status} to set + */ + @Override + public void setStatus(Status status) { + if (! this.status.equals(status)) { + setChanged(true); + this.status = status; + if (status == Status.RESULTWRONG) { + appliedRule = null; + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/model/CVS/Entries b/src/org/jalgo/module/hoare/model/CVS/Entries new file mode 100644 index 0000000..55bd98e --- /dev/null +++ b/src/org/jalgo/module/hoare/model/CVS/Entries @@ -0,0 +1,19 @@ +/AbstractAssertion.java/1.1/Wed Aug 27 13:01:38 2008// +/AndAssertion.java/1.2/Wed Aug 27 13:01:41 2008// +/AssignFormula.java/1.1/Wed Aug 27 13:01:39 2008// +/CompoundFormula.java/1.1/Wed Aug 27 13:01:40 2008// +/ConcreteAssertion.java/1.2/Wed Aug 27 13:01:41 2008// +/IfElseFormula.java/1.1/Wed Aug 27 13:01:45 2008// +/IfFormula.java/1.1/Wed Aug 27 13:01:40 2008// +/ImplicationFormula.java/1.1/Wed Aug 27 13:01:39 2008// +/IterationFormula.java/1.1/Wed Aug 27 13:01:39 2008// +/Model.java/1.1/Wed Aug 27 13:01:38 2008// +/NotAssertion.java/1.2/Wed Aug 27 13:01:38 2008// +/OrAssertion.java/1.2/Wed Aug 27 13:01:45 2008// +/StatSeqFormula.java/1.1/Wed Aug 27 13:01:46 2008// +/StrongPreFormula.java/1.1/Wed Aug 27 13:01:47 2008// +/VarAssertion.java/1.1/Wed Aug 27 13:01:42 2008// +/Variable.java/1.1/Wed Aug 27 13:01:43 2008// +/VerificationFormula.java/1.2/Wed Aug 27 13:01:41 2008// +/WeakPostFormula.java/1.1/Wed Aug 27 13:01:39 2008// +/package-info.java/1.1/Wed Aug 27 13:01:40 2008// diff --git a/src/org/jalgo/module/hoare/model/CVS/Repository b/src/org/jalgo/module/hoare/model/CVS/Repository new file mode 100644 index 0000000..40b9a8e --- /dev/null +++ b/src/org/jalgo/module/hoare/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/model diff --git a/src/org/jalgo/module/hoare/model/CVS/Root b/src/org/jalgo/module/hoare/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/model/CompoundFormula.java b/src/org/jalgo/module/hoare/model/CompoundFormula.java new file mode 100644 index 0000000..e6f2bfd --- /dev/null +++ b/src/org/jalgo/module/hoare/model/CompoundFormula.java @@ -0,0 +1,76 @@ +package org.jalgo.module.hoare.model; + + + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents a compound statement + * + * @author Thomas, Uwe + * + */ + +public class CompoundFormula extends VerificationFormula { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 5031680894960284107L; + + /** + * Constructs a CompoundFormula with the given beginning and end of the code + * and sets the parent and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + */ + CompoundFormula(VerificationFormula parent, String source, int codeStart, int codeEnd) { + super(parent, source, codeStart, codeEnd); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return rule.equals(Rule.COMPOUND); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + if (! parent.hasChildren()) { + return false; + } + VerificationFormula vf = parent.getChildren().get(0); + + if (vf.isRuleApplied()) { + return false; + } else { + parent.appliedRule = Rule.COMPOUND; + + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(parent.preAssertion); + vf.replacePostAssertion(parent.postAssertion); + + return true; + } + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return (full ? getCode(getCode()) :"{...}"); + } + +} diff --git a/src/org/jalgo/module/hoare/model/ConcreteAssertion.java b/src/org/jalgo/module/hoare/model/ConcreteAssertion.java new file mode 100644 index 0000000..2c6c51c --- /dev/null +++ b/src/org/jalgo/module/hoare/model/ConcreteAssertion.java @@ -0,0 +1,78 @@ +package org.jalgo.module.hoare.model; + +/** + * Represents a concrete term as the leaf of the assertion tree. + * Assertion strings my not contain any Not And or Or symbols. + * + * @author Thomas + * + */ +class ConcreteAssertion extends AbstractAssertion { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = -6773213821777206709L; + /** + * holds the concrete assertion as a string in c0 + */ + private String term; + /** + * holds the converted string with included Unicode symbols + */ + private String text; + /** + * holds the index of the PI + */ + private int index; + + /** + * creates an ConcreteAssertion with an C0 Assertion string. + * Every ConcreteAssertion gets his own Pi-identifier. + * + * @param assertion + * the concrete assertion string + * @param index + * the Number behind the Pi + */ + public ConcreteAssertion(String assertion,int index){ + this.index=index; + this.term=assertion; + this.text=new String(assertion); + + // some symbols will be replaced by Unicode symbols + text = text.replaceAll("==", "="); + text = text.replaceAll("<=", "\u2264"); + text = text.replaceAll(">=", "\u2265"); + text = text.replaceAll("<", "\u003C"); + text = text.replaceAll(">", "\u003E"); + text = text.replaceAll("sqrt", "\221A"); + text = text.replaceAll("Sum", "\u2211"); + text = text.replaceAll("Product", "\220F"); + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#includesVariable() + */ + @Override + public boolean verifiable() { + return true; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toString() + */ + @Override + public String toString() { + return "("+term+")"; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toText(boolean) + */ + @Override + public String toText(boolean full) { + return (full ? text : "\u03C0" + index); + } + +} diff --git a/src/org/jalgo/module/hoare/model/IfElseFormula.java b/src/org/jalgo/module/hoare/model/IfElseFormula.java new file mode 100644 index 0000000..641a5f1 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/IfElseFormula.java @@ -0,0 +1,96 @@ +package org.jalgo.module.hoare.model; + +import java.util.List; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents an If Else statement with an If statement (or statement sequence) + * and an Else statement (or statement sequence). + * + * @author Thomas, Uwe + * + */ + +public class IfElseFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = -4207471117336321005L; + /** + * holds the concrete assertion in the boolean expression in the if-else-statement + */ + private ConcreteAssertion boolExp; + + + + /** + * Constructs a IfElseFormula with the given beginning and end of the code + * and sets the parent, the boolean expression and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param pi1 the boolean Expression of the if-Statement + */ + IfElseFormula(VerificationFormula parent, String source, int codeStart, int codeEnd, + ConcreteAssertion pi1) { + super(parent, source, codeStart, codeEnd); + this.boolExp=pi1; + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return rule.equals(Rule.IFELSE); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + if (!parent.hasChildren()) { + return false; + } + List vfList = parent.getChildren(); + VerificationFormula vf = vfList.get(0); + + if (vf.isRuleApplied()) { + return false; + } else { + parent.appliedRule = Rule.IFELSE; + + /* left child */ + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(new AndAssertion(parent.preAssertion, + boolExp)); + vf.replacePostAssertion(parent.postAssertion); + + /* right child */ + vf = vfList.get(1); + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(new AndAssertion(parent.preAssertion, + new NotAssertion(boolExp))); + vf.replacePostAssertion(parent.postAssertion); + + return true; + } + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return (full ? getCode(getCode()) : "if ("+boolExp.toText(true)+")...else..."); + } + +} diff --git a/src/org/jalgo/module/hoare/model/IfFormula.java b/src/org/jalgo/module/hoare/model/IfFormula.java new file mode 100644 index 0000000..1c8187f --- /dev/null +++ b/src/org/jalgo/module/hoare/model/IfFormula.java @@ -0,0 +1,101 @@ +/** + + */ +package org.jalgo.module.hoare.model; + + + +import java.util.List; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents an If statement with only on statement (or statement sequence) + * + * @author Thomas, Uwe + * + */ + +public class IfFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 1852029170756056822L; + /** + * holds the concrete assertion in the boolean expression in the if-statement + */ + private ConcreteAssertion boolExp; + + + + /** + * Constructs a IfFormula with the given beginning and end of the code + * and sets the parent, the boolean expression and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param boolExp the boolean Expression of the if-Statement + */ + IfFormula(VerificationFormula parent, String source, int codeStart, + int codeEnd, ConcreteAssertion boolExp) { + super(parent, source, codeStart, codeEnd); + this.boolExp=boolExp; + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return rule.equals(Rule.IF); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + if (! parent.hasChildren()) { + return false; + } + + List vfList = parent.getChildren(); + VerificationFormula vf = vfList.get(0); + + if (vf.isRuleApplied()) { + return false; + } else { + parent.appliedRule = Rule.IF; + + /* left child */ + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(new AndAssertion(parent.preAssertion, + boolExp)); + vf.replacePostAssertion(parent.postAssertion); + + /* right child */ + vf = vfList.get(1); + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(new AndAssertion(parent.preAssertion, + new NotAssertion(boolExp))); + vf.replacePostAssertion(parent.postAssertion); + + return true; + } + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return (full ? getCode(getCode()) : "if ("+boolExp.toText(true)+")"); + } + +} diff --git a/src/org/jalgo/module/hoare/model/ImplicationFormula.java b/src/org/jalgo/module/hoare/model/ImplicationFormula.java new file mode 100644 index 0000000..573a24b --- /dev/null +++ b/src/org/jalgo/module/hoare/model/ImplicationFormula.java @@ -0,0 +1,127 @@ +package org.jalgo.module.hoare.model; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * This is the representation of the most discussed VerificationFormula + * in this project. It represents an implication considered to a + * {@link StrongPreFormula} or {@link WeakPostFormula}.
          + * This class should be created during createStrongPre and createWeakPost + * + * @author Thomas + * + */ +public class ImplicationFormula extends VerificationFormula { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 5126815578070064211L; + + /** + * This method creates a new instance of the most discussed + * {@link VerificationFormula} in this projekt. + * + * @param parent the parent node in the VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param preAssertion preAssertion of the ImplicationFormula + * @param postAssertion postAssertion of the ImplicationFormula + */ + public ImplicationFormula(VerificationFormula parent, int codeStart, int codeEnd, + AbstractAssertion preAssertion, AbstractAssertion postAssertion) { + super(parent, "", codeStart, codeEnd); + this.preAssertion=preAssertion; + this.postAssertion=postAssertion; + } + + /** + * This method returns false on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(org.jalgo.module.hoare.model.VerificationFormula) + */ + @Override + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + return false; + } + + /** + * This method returns false on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(org.jalgo.module.hoare.constants.Rule) + */ + @Override + boolean canApply(Rule rule) { + return false; + } + + /** + * This method returns null on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getAppliedRule() + */ + @Override + public Rule getAppliedRule() { + return null; + } + + /** + * This method returns "=>" on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return "=>"; + } + + /** + * This method returns false on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#createStrongPre(java.lang.String) + */ + @Override + boolean createStrongPre(String varName) { + return false; + } + + /** + * This method returns false on every call. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#createWeakPost(java.lang.String) + */ + @Override + boolean createWeakPost(String varName) { + return false; + } + + /** + * This method returns true if the pre assertion and + * the post assertion is verifiable.
          + * Note: An assertion is verifiable if every {@link VarAssertion} has an + * underlying assertion. + * + * @see org.jalgo.module.hoare.model.VerificationFormula#verifiable() + */ + @Override + public boolean verifiable() { + return preAssertion.verifiable() && postAssertion.verifiable(); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#isImplication() + */ + @Override + public boolean isImplication() { + return true; + } + + + + + + + +} diff --git a/src/org/jalgo/module/hoare/model/IterationFormula.java b/src/org/jalgo/module/hoare/model/IterationFormula.java new file mode 100644 index 0000000..53fee3f --- /dev/null +++ b/src/org/jalgo/module/hoare/model/IterationFormula.java @@ -0,0 +1,186 @@ +/** + * + */ +package org.jalgo.module.hoare.model; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.ParserAccess; +import org.jalgo.module.hoare.constants.Rule; +import org.nfunk.jep.ParseException; + +/** + * Represents the While statement with on statement (or statement sequence) + * + * @author Thomas, Uwe + * + */ + +public class IterationFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 3879791094677408935L; + /** + * holds the concrete assertion in the boolean expression in the while-statement + */ + private ConcreteAssertion boolExp; + + + + /** + * Constructs a IterationFormula with the given beginning and end of the code + * and sets the parent and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param boolExp the boolean Expression of the while-Statement + */ + IterationFormula(VerificationFormula parent, String source, int codeStart, + int codeEnd, ConcreteAssertion boolExp) { + super(parent, source, codeStart, codeEnd); + this.boolExp=boolExp; + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return rule.equals(Rule.ITERATION); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + if (! parent.hasChildren()) { + return false; + } + VerificationFormula vf = parent.getChildren().get(0); + + + if (vf.isRuleApplied()) { + return false; + } + + if (! check(parent)) { + throw new UnsupportedOperationException(String.format(Messages. + getString("hoare", "out.iterationCheckFailed"), + postAssertion.toText(false), + preAssertion.toText(false))); + } else { + parent.appliedRule = Rule.ITERATION; + + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(new AndAssertion(parent.preAssertion, + boolExp)); + vf.replacePostAssertion(parent.preAssertion); + return true; + } + } + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#check(VerificationFormula) + */ + protected boolean check(VerificationFormula formula) { + String pre; + String post; + String prePost; + String bool; + Pattern p; + Matcher m; + + + pre = formula.preAssertion.toString().replaceAll("(?\\!\\=])\\=(?![\\=])", "=="); + post = formula.postAssertion.toString().replaceAll("(?\\!\\=])\\=(?![\\=])", "=="); + try { + pre = ParserAccess.parseToString(pre).replaceAll("\\.0", ""); + post = ParserAccess.parseToString(post).replaceAll("\\.0", ""); + bool = ParserAccess.parseToString(boolExp.toString()).replaceAll("\\.0", ""); + } catch (ParseException pe){ + return false; + } + + + p = Pattern.compile("(.*)\\&\\&([^\\&]+)"); + m = p.matcher(post); + + + if (! m.find()) { + return false; + } + + + prePost = m.group(1); + return (prePost.equals(pre) && isEqual(bool, m.group(2))); + } + + /** + * isEqual is an internal method for checking whether neg equals NOT pos + * + * @param pos the positive assertion as a String + * @param neg the negative assertion to be checked as a String + * @return true if neg equals NOT pos + */ + private boolean isEqual(String pos, String neg) { + Pattern p; + Matcher m; + + + + if (("!(" + pos + ")").equals(neg) || ("!" + pos).equals(neg)) { + return true; + } + + + p = Pattern.compile("([^\\<\\>\\=\\!]+)(?:[\\<\\>\\=]\\=?|\\!\\=)([^\\<\\>\\=\\!]+)"); + m = p.matcher(pos); + if (! m.find()) { + return false; + } + + + if (pos.matches("([^\\<\\>\\=\\!]+)\\<([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + ">=" + m.group(2)).equals(neg) ? true : false); + } + + if (pos.matches("([^\\<\\>\\=\\!]+)\\>([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + "<=" + m.group(2)).equals(neg) ? true : false); + } + + if (pos.matches("([^\\<\\>\\=\\!]+)\\<\\=([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + ">" + m.group(2)).equals(neg) ? true : false); + } + + if (pos.matches("([^\\<\\>\\=\\!]+)\\>\\=([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + "<" + m.group(2)).equals(neg) ? true : false); + } + + if (pos.matches("([^\\<\\>\\=\\!]+)\\=\\=([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + "!=" + m.group(2)).equals(neg) ? true : false); + } + + if (pos.matches("([^\\<\\>\\=\\!]+)\\!\\=([^\\<\\>\\=\\!]+)")) { + return ((m.group(1) + "==" + m.group(2)).equals(neg) ? true : false); + } + + + return false; + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + public String getCode(boolean full) { + return (full ? getCode(getCode()) : "while (" + boolExp.toText(true)+")"); + } + +} diff --git a/src/org/jalgo/module/hoare/model/Model.java b/src/org/jalgo/module/hoare/model/Model.java new file mode 100644 index 0000000..d822a2b --- /dev/null +++ b/src/org/jalgo/module/hoare/model/Model.java @@ -0,0 +1,519 @@ +package org.jalgo.module.hoare.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.TextStyle; + +import c00.AST; + +/** + * This is the master control program of the hole data structure.
          + *
          + * To initialize a verification tree you have two possibilities
          + * 1) call the init-method to create a new verification tree + * from a parsed C0-source code
          + * 2) call the overloaded init-method to create + * a new verification tree from a given root-{@link VerificaitonFormula}
          + * To save an existing verification tree you have to perform two steps
          + * 1) collect all the {@link VerificationFormulas} with + * the getFormulas-method
          + * 2) get the index of the root-{@link VerificaitonFormula} by calling + * getRoot().getId()
          + * + * + * @author Thomas + */ +public class Model extends Observable { + + private VerificationFormula root; + private Map formulas; + private SortedSet variables; + private int varCount; + private int piCount; + + /** + * Creates a new instance of the Model. + */ + public Model() { + root=null; + formulas=new HashMap(); + variables=new TreeSet(); + + varCount=0; + piCount=0; + } + + /** + * Sets the root of the Verification tree to the given VerificationFormula + * Note: This method calls the method updateFormulas() to + * update the map of Formulas. So you do not have to call this method after + * using the setRoot-operation. + * + * @param vf the VerificationFormula to be set as root + */ + private void setRoot(VerificationFormula vf){ + if (vf!=null) { + root=vf; + updateFormulas(); + } + } + + /** + * Gives you the root of the Verification tree + * + * @return the root + */ + public VerificationFormula getRoot(){ + return root; + } + + /** + * Returns the {@link VerificationFormula} specified by the Id. + * Every {@link VerificationFormula} could have one or two children. + * + * @param id + * the Index of a {@link VerificationFormula} + * @return the selected {@link VerificationFormula} and + * null if no {@link VerificationFormula} was found + */ + public VerificationFormula getVerificationFormula(int id){ + VerificationFormula result=null; + + if (formulas!=null) { + result=formulas.get(new Integer(id)); + } + + return result; + } + + /** + * This method to performs a recursive collection + * of VerificationFormulas and there IDs. + * This routine is for internal use, and could + * cause a leak of performance if you use it to often. + * + */ + public void updateFormulas(){ + formulas.clear(); + variables.clear(); + varCount=0; + + if (root!=null) { + root.getFormulaMap(formulas); + Variable var; + SortedSet vars=new TreeSet(); + + for (VerificationFormula vf : formulas.values()) { + if (vf.canEditPreAssertion()){ + var=new Variable(vf.getId(), + vf.getPreAssertion(TextStyle.SHORT), + vf.getPreAssertion(TextStyle.FULL), + vf.getPreAssertion(TextStyle.EDITOR), + vf.getPreAssertion(TextStyle.SOURCE), + true); + if (vf.isRuleApplied()) { + variables.add(var); + } + vars.add(var); + } + + if (vf.canEditPostAssertion()) { + var=new Variable(vf.getId(), + vf.getPostAssertion(TextStyle.SHORT), + vf.getPostAssertion(TextStyle.FULL), + vf.getPostAssertion(TextStyle.EDITOR), + vf.getPostAssertion(TextStyle.SOURCE), + false); + if (vf.isRuleApplied()){ + variables.add(var); + } + vars.add(var); + } + } + Pattern p = Pattern.compile("([A-Za-z]*)([0-9]+)$"); + Matcher m = p.matcher(vars.last().getName()); + if (m.matches()) { + varCount=Integer.parseInt(m.group(2)); + } else { + varCount=vars.size(); + } + vars.clear(); + vars=null; + } + } + + /** + * Gives you a Map of all VerificationFormulas + * selected by their ID. + * + * @return the Map of ID and VerificationFormula + */ + public Map getFormulas(){ + return formulas; + } + + /** + * Gives you a Set of all variables which the user can edit. + * The {@link Variable}-Object knows the id of the VerificationFormula + * where the {@link VarAssertion} is placed, the name of the variable and + * the assertion text behind this variable. + * Note: That the set is sorted by the name of the variable. + * + * @return a {@link SortedSet} of variables + */ + public SortedSet getVariables(){ + return variables; + } + + /** + * Gives you the whole source code to get verified as String. + * If the Model was not initialized yet you will get an + * empty String + * + * @return the source code if the Model was initiated + */ + public String getSource(){ + return (root == null ? "" : root.getSource()); + } + + /** + * Applies a Rule to the {@link VerificationFormula} specified by the id parameter. + * Returns true if the Rule could be applied to this VerificationFormula. + * Expect that the Rules strong predecessor and weak successor could be + * applied everywhere in the verification tree. + * + * @param id + * the Index of the VerificationFormula + * @param rule + * the {@link Rule} which should be applied + * @return + * only true if the {@link Rule} has been applied + * successful + * @throws IllegalArgumentException + * if the given id does not belong to a + * {@link VerificationFormula} in the Model * + * + */ + public boolean apply(int id,Rule rule) throws IllegalArgumentException + { + boolean result=false; + VerificationFormula vf=getVerificationFormula(id); + if (vf==null){ + throw new IllegalArgumentException(Messages.getString("hoare", + "out.noValidNode")); + } + + if (rule.equals(Rule.STRONGPRE)) { + varCount++; + result=vf.createStrongPre("P"+varCount); + if (! result) varCount--; + } else { + if (rule.equals(Rule.WEAKPOST)) { + varCount++; + result=vf.createWeakPost("P"+varCount); + if (! result) varCount--; + } else { + if (vf.canApply(rule)) { + result=vf.applyNext(vf); + } + } + } + if (result) updateFormulas(); + return result; + } + + /** + * Removes all children of this {@link VerificationFormula}. + * This operation do not really delete the selected + * part of the verification tree, but sets all following + * VerificationFormulas as not visible.
          + * Note that strong predecessors and weak successors will be + * really removed from the verification tree. + * + * @param id + * of the selected {@link VerificationFormula} + * @return + * true if the {@link VerificationFormula} exists + */ + public boolean remove(int id) { + VerificationFormula vf=getVerificationFormula(id); + if (vf==null) return false; + vf.deleteChildren(); + updateFormulas(); + //Shows View that the whole tree has changed + getRoot().setChanged(true); + return true; + } + + + /** + * This method applies a given verification tree to the model. + * The verification tree will be build up by the given root. + * + * @param root + * the root of the verification tree + */ + public void init(VerificationFormula root){ + setRoot(root); + //Shows View that the whole tree has changed + root.setChanged(true); + VerificationFormula.setNextId(root); + } + + /** + * Builds a VF-data structure of an AST-Tree. + * Note: The given source code have to be a single line string. + * In other cases there will be Errors during the String selection! + * + * @param tree + * the AST-Tree + * @param source + * the associated sourcecode as a string + * @return the root VerificationFormula of the VF-data strucure + */ + public void init(AST.StatementSequence tree,String source) { + varCount=2; + piCount=0; + root=initTree(tree,null, source); + root.replacePreAssertion(new VarAssertion("P1")); + root.replacePostAssertion(new VarAssertion("P2")); + root.setApplied(); + root.setChanged(true); + updateFormulas(); + } + + /** + * Gives you the C0 conform source code of the given BoolExpression. + * + * @param bool + * a BoolExpression in an AST-tree + * @param source + * the source code which contains the BoolExpression + * @return the BoolExpression as C0 conform source code + */ + private String getBoolExpression(AST.BoolExpression bool, String source){ + return (bool.startColumn newChildren=new ArrayList(2); + VerificationFormula child=initTree(((AST.PairStmSeq) tree).stm,result,source); + if (child!=null){ + child.replacePostAssertion(variable); + newChildren.add(child); + } + child=initTree(((AST.PairStmSeq) tree).stmSeq,result,source); + if (child!=null){ + child.replacePreAssertion(variable); + newChildren.add(child); + } + result.setChildren(newChildren); + } + + } + return result; + } + + /** + * This method creates a part of the verification tree by + * recursive calling it self. + * Note: This is one of two overloaded methods to handle + * either StatementSequences or Statements in a dynamic way. + * + * @param tree + * a Statement in an AST-tree + * @param parent + * of the new created VerificationFormulas + * @return + * the root {@link VerificationFormula} created by this method + */ + private VerificationFormula initTree(AST.Statement tree, + VerificationFormula parent, String source) { + VerificationFormula result=null; + VerificationFormula child=null; + + if (tree instanceof AST.AssignStm){ + result=new AssignFormula(parent,source,tree.startColumn,tree.endColumn); + } else { + if (tree instanceof AST.PureIfStm) { + String boolExp=getBoolExpression(((AST.PureIfStm) tree).boolExp,source); + piCount++; + ConcreteAssertion pi=new ConcreteAssertion(boolExp,piCount); + result=new IfFormula(parent,source,tree.startColumn,tree.endColumn,pi); + + List newChildren=new ArrayList(2); + child=initTree(((AST.PureIfStm) tree).stm,result,source); + if (child!=null) { + newChildren.add(child); + } + child=new ImplicationFormula(result,tree.startColumn,tree.endColumn,null,null); + newChildren.add(child); + result.setChildren(newChildren); + } else { + if (tree instanceof AST.ElseIfStm) { + String boolExp=getBoolExpression(((AST.ElseIfStm) tree).boolExp,source); + piCount++; + ConcreteAssertion pi=new ConcreteAssertion(boolExp,piCount); + result=new IfElseFormula(parent,source,tree.startColumn,tree.endColumn,pi); + + List newChildren=new ArrayList(2); + child=initTree( ((AST.ElseIfStm) tree).stm1,result,source); + if (child!=null) { + newChildren.add(child); + } + + child=initTree( ((AST.ElseIfStm) tree).stm2,result,source); + if (child!=null) { + newChildren.add(child); + } + result.setChildren(newChildren); + } else { + if (tree instanceof AST.WhileStm) { + String boolExp = getBoolExpression(((AST.WhileStm) tree).boolExp,source); + piCount++; + ConcreteAssertion pi=new ConcreteAssertion(boolExp,piCount); + result=new IterationFormula(parent,source,tree.startColumn,tree.endColumn,pi); + + List newChildren=new ArrayList(2); + child=initTree( ((AST.WhileStm) tree).stm,result,source) ; + if (child!=null) { + newChildren.add(child); + } + result.setChildren(newChildren); + } else { + if (tree instanceof AST.CompStm) { + result=new CompoundFormula(parent,source,tree.startColumn,tree.endColumn); + + List newChildren=new ArrayList(2); + child=initTree(((AST.CompStm) tree).stmSeq,result,source); + // Declarations ignored! + if (child!=null) { + newChildren.add(child); + } + result.setChildren(newChildren); + } + } + } + } + } + return result; + } + + /** + * This methods notifies all observers which have been registered. + * Note: This method has been overridden to provide the + * notification of the observers without previously performing the + * setChanged-routine! + * + */ + @Override + public void notifyObservers(){ + setChanged(); + super.notifyObservers(); + setAllUnchanged(); + } + + /** + * This method removes the changed flags from all + * verification formulas in the verification tree. + */ + public void setAllUnchanged(){ + for (VerificationFormula vf: formulas.values()){ + vf.setChanged(false); + } + } + + /** + * This method sets all visible {@link VerificationFormula}s + * as changed.
          + * Note: Use this method after big changes in the verification tree! + */ + public void setAllChanged(){ + for (VerificationFormula vf: formulas.values()){ + if (vf.ruleApplied){ + vf.setChanged(true); + } + } + } + + /** + * Gives you a list of the visible {@link VerificationFormula}s + * that contains the {@link Variable} with the given name + * as pre or post assertion.
          + * Formulas are visible if {@link VerificationFormula#isRuleApplied()} + * returns true + * Note: That this method uses {@link String#indexOf(int)} to + * collect the VerificationFormulas and causes a leak of performance. + * + * @param name + * of the Variable to look for + * @return a list of {@link VerificationFormula}s which contain + * the given Variable + * @throws NullPointerException + * if the parameter name is null + */ + public List getFormulasByVariable(String name) + throws NullPointerException{ + + if (name==null) { + throw new NullPointerException("name must not be null"); + } + List result=new ArrayList(); + for (VerificationFormula vf : formulas.values()) { + if ((vf.getPreAssertion(TextStyle.SHORT).matches(".*"+name+"\\b.*")) + || (vf.getPostAssertion(TextStyle.SHORT).matches(".*"+name+"\\b.*"))){ + result.add(vf); + } + } + return result; + } + + /** + * Clear the verification represented by this Model.
          + * Note: You do not need to call clear before an + * init-Operation. + */ + public void clear(){ + root=null; + formulas.clear(); + variables.clear(); + } + +} diff --git a/src/org/jalgo/module/hoare/model/NotAssertion.java b/src/org/jalgo/module/hoare/model/NotAssertion.java new file mode 100644 index 0000000..5f45d99 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/NotAssertion.java @@ -0,0 +1,49 @@ +package org.jalgo.module.hoare.model; + +/** + * Represents an Not in the assertiontree. It could only have one child assertion as operand. + * + * @author Thomas + * + */ + +class NotAssertion extends AbstractAssertion { + + private static final long serialVersionUID = -4594430915140006774L; + private AbstractAssertion operand; + + /** + * creates an NotAssertion with one Assertion tree + * + * @param operand + * the child assertion to be negated + */ + public NotAssertion(AbstractAssertion operand) { + this.operand = operand; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#includesVariable() + */ + @Override + public boolean verifiable() { + return operand.verifiable(); + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toString() + */ + @Override + public String toString() { + return "!"+operand.toString(); + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toText(boolean) + */ + @Override + public String toText(boolean full) { + return "\u00ac(" + operand.toText(full)+")"; + } + +} diff --git a/src/org/jalgo/module/hoare/model/OrAssertion.java b/src/org/jalgo/module/hoare/model/OrAssertion.java new file mode 100644 index 0000000..1777df4 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/OrAssertion.java @@ -0,0 +1,60 @@ +package org.jalgo.module.hoare.model; + +/** + * Represents an Or in the assertiontree. It must have two children assertion as operands. + * + * @author Thomas + **/ +class OrAssertion extends AbstractAssertion { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = -4867430960518614L; + /** + * the left side of the assertion tree under the or + */ + private AbstractAssertion left; + /** + * the right side of the assertion tree under the or + */ + private AbstractAssertion right; + + /** + * creates an OrAssertion with an left and right Assertion tree + * + * @param left + * the left child assertion compared with Or + * @param left + * the right child assertion compared with Or + **/ + public OrAssertion(AbstractAssertion left,AbstractAssertion right) { + this.left=left; + this.right=right; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#verifiable() + */ + @Override + public boolean verifiable() { + return left.verifiable() && right.verifiable(); + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toString() + */ + @Override + public String toString() { + return "("+left.toString()+" || "+right.toString()+")"; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toText(boolean) + */ + @Override + public String toText(boolean full) { + return "("+left.toText(full) + " \u2228 " + right.toText(full)+")"; + } + +} diff --git a/src/org/jalgo/module/hoare/model/StatSeqFormula.java b/src/org/jalgo/module/hoare/model/StatSeqFormula.java new file mode 100644 index 0000000..97936fa --- /dev/null +++ b/src/org/jalgo/module/hoare/model/StatSeqFormula.java @@ -0,0 +1,82 @@ +package org.jalgo.module.hoare.model; + +import java.util.List; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents a statement sequence of two statements + * + * @author Thomas, Uwe + * + */ + +public class StatSeqFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 5144003586344912315L; + + /** + * Constructs a StatSeqFormula with the given beginning and end of the code + * and sets the parent and the source of + * the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + */ + public StatSeqFormula(VerificationFormula parent, String source, int codeStart, int codeEnd) { + super(parent, source, codeStart, codeEnd); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + public boolean canApply(Rule rule) { + return rule.equals(Rule.STATSEQ); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + if (! parent.hasChildren()) { + return false; + } + List vfList = parent.getChildren(); + VerificationFormula vf = vfList.get(0); + + if (vf.isRuleApplied()) { + return false; + } else { + parent.appliedRule = Rule.STATSEQ; + + /* left child */ + vf.setApplied(); + vf.setChanged(true); + vf.replacePreAssertion(parent.preAssertion); + + /* right child */ + vf = vfList.get(1); + vf.setApplied(); + vf.setChanged(true); + vf.replacePostAssertion(parent.postAssertion); + + return true; + } + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return (full ? getCode(getCode()) : "A1 A2"); + } + +} diff --git a/src/org/jalgo/module/hoare/model/StrongPreFormula.java b/src/org/jalgo/module/hoare/model/StrongPreFormula.java new file mode 100644 index 0000000..923b451 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/StrongPreFormula.java @@ -0,0 +1,73 @@ +package org.jalgo.module.hoare.model; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents a strong pre verification formula + * + * @author Thomas, Uwe + * + */ + +public class StrongPreFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 6793878960166641496L; + + /** + * Constructs a StrongPreFormula with the given beginning and end of the code + * and sets the parent, preAssertion, postAssertion and the source + * of the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param preAssertion preAssertion of the StrongPreFormula + * @param postAssertion postAssertion of the StrongPreFormula + */ + StrongPreFormula(VerificationFormula parent, String source, int codeStart, int codeEnd, + AbstractAssertion preAssertion, AbstractAssertion postAssertion) { + super(parent, source, codeStart, codeEnd); + this.preAssertion=preAssertion; + this.postAssertion=postAssertion; + this.setChanged(true); + this.setApplied(); + parent.appliedRule = Rule.STRONGPRE; + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return parent.canApply(rule); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + return this.parent.applyNext(parent); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#check(VerificationFormula) + */ + @Override + protected boolean check(VerificationFormula formula) { + return parent.check(formula); + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + public String getCode(boolean full) { + return parent.getCode(full); + } + + +} diff --git a/src/org/jalgo/module/hoare/model/VarAssertion.java b/src/org/jalgo/module/hoare/model/VarAssertion.java new file mode 100644 index 0000000..5148312 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/VarAssertion.java @@ -0,0 +1,132 @@ +package org.jalgo.module.hoare.model; + +/** + * Represents an variable assertion which could be edited by the User. + * It holds the name of the variable and the underlying Assertion + * + * @author Thomas + * + */ +class VarAssertion extends AbstractAssertion { + + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = 2976302686359687955L; + /** + * holds the name off this variable + */ + private String name; + /** + * holds the underlying assertion tree, by default null + */ + private AbstractAssertion child=null; + /** + * holds the original assertion String + */ + private String original; + + /** + * creates an VarAssertion without a underlying Assertiontree + * + * @param name + * the name of the variable + */ + public VarAssertion(String name) { + this.name=name; + this.child=null; + this.original=""; + } + + /** + * creates an VarAssertion with a underlying Assertiontree + * + * @param name + * the name of the variable + * @param child + * the child represents the underlying Assertiontree + */ + public VarAssertion(String name,AbstractAssertion child) { + this.name=name; + this.child=child; + this.original=""; + } + + /** + * Returns the name of the variable. + * + * @return the name + */ + public String getVariableName() { + return name; + } + + /** + * Sets the underlying assertiontree to the given assertiontree. + * If child is null the VarAssertion is set to be empty. + * + * @param child + * the root of the assertiontree + */ + public void setVariable(AbstractAssertion child) { + this.child=child; + } + + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#isVariable() + */ + public boolean isVariable() { + return true; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#verifiable() + */ + @Override + public boolean verifiable() { + return child!=null; + } + + /** + * @see org.jalgo.module.hoare.model.AbstractAssertion#toString() + */ + @Override + public String toString() { + return ((child == null) ? "" : child.toString()); + } + + /** + * If you want the full version of the assertion then + * the result becomes the full version of the underlying + * assertion tree. + * + * @see org.jalgo.module.hoare.model.AbstractAssertion#toText(boolean) + */ + public String toText(boolean full) { + return (full && (child != null)) ? child.toText(true) : name; + } + + /** + * This method sets the original String to the given parameter. + * Note: If the parameter is null the + * + * @param value + * the original assertion given + */ + public void setOriginal(String value){ + if (value!=null){ + this.original=value; + } + } + + /** + * + * @see org.jalgo.module.hoare.model.AbstractAssertion#getOrginal() + */ + @Override + public String getOrginal() { + return original; + } + +} diff --git a/src/org/jalgo/module/hoare/model/Variable.java b/src/org/jalgo/module/hoare/model/Variable.java new file mode 100644 index 0000000..5261d24 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/Variable.java @@ -0,0 +1,198 @@ +package org.jalgo.module.hoare.model; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jalgo.module.hoare.constants.TextStyle; + +/** + * Represents a Variable of the verification tree. + * This class implements methods to return information + * about the linked {@link VarAssertion} and the + * {@link VerificationFormula} where the Variable is placed. + * + * @author Thomas + * + */ +public class Variable implements Comparable { + + /** + * holds the id of the linked {@link VerificationFormula} which contains this variable + */ + private int id; + + /** + * holds the name of the variable + */ + private String name; + + /** + * holds the c0 compatible assertion under this variable + */ + private String source; + + /** + * holds the short form of the assertion under this variable + */ + private String text; + + /** + * flags if the variable is the preAssertion of the linked {@link VerificationFormula} + */ + private boolean isPreAssertion; + + /** + * holds the original assertion String + */ + private String original; + + /** + * Creates an instance of an Variable which represents a VarAssertion. + * + * @throws NullPointerException + * if one of the Parameter is null + * @param id + * of the VerificationFormula which contains the VarAssertion. + * @param name + * the name of the VarAssertion you get with + * {@link VarAssertion#getVariableName()} + * @param text + * the underlying assertion you get by calling + * {@link VarAssertion#toText(boolean)} with true + * @param original + * the originally entered String you get by calling + * {@link VarAssertion#getOriginal()} + * @param source + * the C0-conform underlying assertion you get by calling + * {@link VarAssertion#toString()} + * @param isPreAssertion + * should be true if the VarAssertion is a preAssertion + * of the {@link VerificationFormula} given by its id + * otherwise false + */ + public Variable(int id,String name,String text,String original, + String source,boolean isPreAssertion) throws NullPointerException{ + if ((name==null)||(text==null)||(source==null)){ + throw new NullPointerException(); + } + this.id=id; + this.name=name; + this.text=text; + this.original=original; + this.source=source; + this.isPreAssertion=isPreAssertion; + } + + + /** + * Gives you the ID of the VerificationFormula which + * contains the Variable + * + * @return an ID of the {@link VerificationFormula} + */ + public int getVerificaitonId(){ + return id; + } + + /** + * Gets the AssertionString under the Variable in + * the (@link TextStyle) you specify with the parameter. + * + * @param ts + * (@link TextStyle) tells the routine how + * the result should be formated + * @return the assertion under this Variable + */ + public String getAssertion(TextStyle ts) { + switch (ts) { + case SOURCE : return source; + case SHORT : return name; + case EDITOR : return original; + default : return text; + } + } + + /** + * Gives you the Name of the Variable. + * + * @return the Name of the Variable + */ + public String getName(){ + return name; + } + + + /** + * This method produces a natural order for Strings that + * match the following RegularExpression:
          + * ([A-Za-z]*)([0-9]+)$ + * + * @param argument + * the Variable to be compared. + * @return + * a negative integer, zero, or a positive integer as this Variable is less than, + * equal to, or greater than the specified Variable. + * + * @throws NullPointerException + * if the specified Variable is null + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(Variable argument) + throws NullPointerException{ + + if (argument==null) { + throw new NullPointerException("Given Variable is null and can not be compared!"); + } + Pattern p = Pattern.compile("([A-Za-z]*)([0-9]+)$"); + Matcher m1 = p.matcher(name); + Matcher m2 = p.matcher(argument.getName()); + if ((m1.matches()) && (m2.matches())) { + if (m1.group(1).compareTo(m2.group(1))==0) { + return (Integer.parseInt(m1.group(2))-Integer.parseInt(m2.group(2))); + } + } + return name.compareTo(argument.getName()); + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj){ + if (obj==null) { + return false; + } + + if (obj instanceof Variable) { + return ((Variable) obj).getName().equals(name); + } else { + return false; + } + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return name.hashCode(); + } + + /** + * Gives you the possibility to decide whether + * the Variable is a pre assertion or a post assertion + * of the Formula associated by the Id.
          + * Note: Check if the Variable is pre or post assertion + * before you call {@link VerificationFormula#editPreAssertion} + * or {@link VerificationFormula#editPreAssertion}. + * + * @return true if the Variable is the pre assertion + * of the associated formula
          + * false if the Variable is the post assertion + * of the associated formula + */ + public boolean isPreAssertion(){ + return isPreAssertion; + } + +} diff --git a/src/org/jalgo/module/hoare/model/VerificationFormula.java b/src/org/jalgo/module/hoare/model/VerificationFormula.java new file mode 100644 index 0000000..cc24bba --- /dev/null +++ b/src/org/jalgo/module/hoare/model/VerificationFormula.java @@ -0,0 +1,722 @@ +package org.jalgo.module.hoare.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jalgo.module.hoare.constants.CodeDimension; +import org.jalgo.module.hoare.constants.ParserAccess; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.constants.TextStyle; +import org.nfunk.jep.ASTFunNode; +import org.nfunk.jep.ASTStart; +import org.nfunk.jep.Node; +import org.nfunk.jep.ParseException; + +/** + * Represents a node of a verification tree. + * + * @author Uwe,Thomas + * + */ + +public abstract class VerificationFormula implements Serializable { + + protected int id; + private static int nextId = 0; + private String source; + protected Rule appliedRule; + protected boolean ruleApplied; + protected boolean changed; + protected Status status; + protected CodeDimension code; + protected VerificationFormula parent; + protected List children; + protected AbstractAssertion preAssertion; + protected AbstractAssertion postAssertion; + + /** + * Constructs a VerificationFormula with the given source code of the + * verification and the beginning and the end index of the part of the + * source code represented by this Formula.
          + * The preAssertion and postAssertion will be set to null. + * The attributes changed and ruleApplied will be set to false. + * + * @param parent + * the parent node in the VerificationFormula tree + * @param source + * the whole source code of this verification + * @param codeStart + * startIndex of the SourceCode + * @param codeEnd + * endIndex of the SourceCode + */ + VerificationFormula(VerificationFormula parent, String source, int codeStart, int codeEnd) { + children = new ArrayList(); + this.parent = parent; + this.changed = false; + this.ruleApplied = false; + this.status = Status.RESULTWRONG; + this.id = nextId++; + this.source = source; + code = new CodeDimension(); + code.start = codeStart; + code.end = codeEnd; + preAssertion = null; + postAssertion = null; + } + + /** + * Gets the source code of this VerificationFormula tree + * + * @return {@link String} which contains the source code + */ + String getSource() { + return source; + } + + /** + * Gets a code segment from the source code Note: This method is needed to show + * you a great example of the java class overloading to produce the + * getCode(getCode()) procedure call in the + * getCode(boolean) method. + * + * @param indices + * {@link CodeDimension} with the beginning and end of the code segment + * @return {@link String} representing the code segment + */ + protected String getCode(CodeDimension indices) { + return (indices.start < source.length() && indices.end < source.length()) + ? new String(source.substring(indices.start, indices.end + 1)) + : null; + } + + /** + * Gets the beginning and end of this code segment. + * + * @return CodeDimension containing startindex and endindex of the String + */ + public CodeDimension getCode() { + return code; + } + + /** + * Gives you the part of the source code which belongs to this rule. If + * parameter full is true the result will be the text segment in + * his full length. In the other case the result will be a simplified version, + * that represents the VerificationFormula + * + * @param full + * true will cause the result to be a full source code + * segment + * @return the source code in a version you decided by the parameter + * full + * + */ + public abstract String getCode(boolean full); + + /** + * Sets the new parent VerificationFormula. + * + * @param parent + * the new parent VerificationFormula + */ + protected void setParent(VerificationFormula parent) { + this.parent = parent; + } + + /** + * Gets the parent of this VerificationFormula. + * + * @return parent of the VerificationFormula + */ + public VerificationFormula getParent() { + return parent; + } + + /** + * Checks whether this VerificationFormula has children. + * + * @return true if this VerificationFormula has + * children + */ + public boolean hasChildren() { + return !children.isEmpty(); + } + + /** + * Gets the children as List, whether it has children or not. + * + * @return the {@link List} of children + */ + public List getChildren() { + return children; // this should never return null + } + + /** + * Sets the list of children to the given list of children. + * + * @param vfList + * a {@link List} containing the new children + */ + void setChildren(List vfList) { + this.children = new ArrayList(vfList); + } + + /** + * Gets the preAssertion of this VerificationFormula as String. + * Note: If no preAssertion was assigned to the Formula you get an empty + * string! + * + * @param ts kind of String you want to get back + * @return the preAssertion of this VerificationFormula + */ + public String getPreAssertion(TextStyle ts) { + if (preAssertion == null) return ""; + switch (ts) { + case SHORT: + return preAssertion.toText(false); + case SOURCE: + return preAssertion.toString(); + case EDITOR: + return preAssertion.getOrginal(); + default: + return preAssertion.toText(true); + } + } + + /** + * Gets the postAssertion of this VerificationFormula as String. + * Note: If no preAssertion was assigned to the Formula you get an empty + * string! + * + * @param ts + * kind of String you want to get back + * @return the postAssertion of this VerificationFormula + */ + public String getPostAssertion(TextStyle ts) { + if (postAssertion == null) return ""; + switch (ts) { + case SHORT: + return postAssertion.toText(false); + case SOURCE: + return postAssertion.toString(); + case EDITOR: + return postAssertion.getOrginal(); + default: + return postAssertion.toText(true); + } + } + + /** + * Gets the id. + * + * @return the id of this VerificationFormula + */ + public int getId() { + return id; + } + + /** + * Checks whether the Rule is already applied. + * + * @return true if the rule is already applied + */ + public boolean isRuleApplied() { + return ruleApplied; + } + + /** + * Sets this VerificationFormula applied. + */ + public void setApplied() { + ruleApplied = true; + } + + /** + * Returns the {@link Rule} that was Applied to this + * VerificationFormula. + * + * @return Rule that was Applied + */ + public Rule getAppliedRule() { + return appliedRule; + } + + /** + * Replaces the preAssertion by a new one. + * + * @param preAssertion + * the new preAssertion + */ + void replacePreAssertion(AbstractAssertion preAssertion) { + this.preAssertion = preAssertion; + setChanged(true); + } + + /** + * Replaces the postAssertion by a new one. + * + * @param postAssertion + * the new postAssertion + */ + void replacePostAssertion(AbstractAssertion postAssertion) { + this.postAssertion = postAssertion; + setChanged(true); + } + + /** + * Deletes all {@link StrongPreFormula} and {@link WeakPostFormula} and set all + * other VerificationFormulas invisible. That means that + * ruleApplied is set to false for all following + * VerificationFormulas. + */ + void deleteChildren() { + for (VerificationFormula vf : children) { + if (vf instanceof WeakPostFormula || vf instanceof StrongPreFormula) { + vf.deleteChildren(); + this.children = vf.getChildren(); + for (VerificationFormula ch : vf.getChildren()) { + ch.setParent(this); + } + } else { + vf.ruleApplied = false; + vf.deleteChildren(); + } + } + } + + /** + * This method builds an assertion tree from an {@link String}. + * The method uses XJep to parse the String into a tree of + * assertions.
          + * Note: This method returns null if the given + * assertion is null or an empty String + * + * @param assertion + * The {@link String} which should be transformed. + * @return the assertion tree as an {@link AbstractAssertion} or + * null if the assertion is empty + * @throws ParseException + * if the String can not be parsed by XJep + */ + private AbstractAssertion buildAssertion(String assertion) + throws ParseException { + + if ((assertion == null) || (assertion.length() == 0)) { + return null; + } else { + return build(ParserAccess.parse(assertion)); + } + } + + /** + * This method builds an assertion tree from an {@link Node}. + * The method goes recursive through the AST-tree by calling + * it self for each node.
          + * Note: This method returns null if the given + * tree is null + * + * @param tree + * The {@link Node} representing an AST-tree. + * @return the assertion tree as an {@link AbstractAssertion} or + * null if the tree is null + */ + private AbstractAssertion build(Node tree) { + // What to do when the Node is empty + if (tree==null) return null; + + if (tree instanceof ASTStart) { + return build(tree.jjtGetChild(0)); + } else { + if (tree instanceof ASTFunNode) { + String foo=((ASTFunNode) tree).getName(); + + if (foo.equals("&&")) { + //AndAssertion + return new AndAssertion( build(tree.jjtGetChild(0)), + build(tree.jjtGetChild(1)) ); + } else if (foo.equals("||")){ + //OrAssertion + return new OrAssertion( build(tree.jjtGetChild(0)), + build(tree.jjtGetChild(1)) ); + } else if (foo.equals("!")){ + //NotAssertion + return new NotAssertion(build(tree.jjtGetChild(0))); + } else { + //ConcreteAssertion + String code=ParserAccess.getString(tree).replaceAll("\\.0",""); + return new ConcreteAssertion(code,0); + } + } else { + //not a FunNode or a Start what to do now??? + //For Example Variables like (a) + //->Use this Section if you want to implement usage of + // Variables in an Assertion + String code=ParserAccess.getString(tree); + return new ConcreteAssertion(code,0); + } + } + } + + /** + * Checks if the PreAssertion is a Variable and can be edited. + * Note: Editing means that a User can define an underlying assertion to this + * Variable. + * + * @return true if the PreAssertion is a {@link VarAssertion} + */ + public boolean canEditPreAssertion() { + return (preAssertion != null ? preAssertion.isVariable() : false); + } + + /** + * Edits the PreAssertion of this VerificationFormula and sets + * the given {@link AbstractAssertion} as the underlying assertion to the + * PreAssertion. Note: This is only possible if the + * PreAssertion is a reference to an {@link VarAssertion}. + * + * @param assertion + * that should become the underlying assertion of the + * PreAssertion + * @return true if the editing was successful + * @throws ParseException + * if the String can not be parsed by XJep + * @throws UnsupportedOperationException + * if the PreAssertion has been frozen + */ + public boolean editPreAssertion(String assertion) + throws ParseException, UnsupportedOperationException { + + boolean result = false; + if ((canEditPreAssertion()) && (preAssertion instanceof VarAssertion)) { + VarAssertion variable=(VarAssertion) preAssertion; + variable.setVariable(buildAssertion(assertion)); + variable.setOriginal(assertion); + //status = Status.UNCHANGED; + setChanged(true); + result = true; + } + + return result; + } + + /** + * Checks if the PostAssertion is a Variable and can be edited. + * Note: Editing means that a User can define an underlying assertion to this + * Variable. + * + * @return true if the PostAssertion is a {@link VarAssertion} + */ + public boolean canEditPostAssertion() { + return (postAssertion != null ? postAssertion.isVariable() : false); + } + + /** + * Edits the PostAssertion of this VerificationFormula and sets + * the given {@link AbstractAssertion} as the underlying assertion to the + * POstAssertion. Note: This is only possible if the + * PostAssertion is a reference to an {@link VarAssertion}. + * + * @param assertion + * that should become the underlying assertion of the + * PostAssertion + * @return true if the editing was successful + * @throws ParseException + * if the String can not be parsed by XJep + * @throws UnsupportedOperationException + * if the PreAssertion has been frozen + */ + public boolean editPostAssertion(String assertion) + throws ParseException,UnsupportedOperationException { + + boolean result = false; + if ((canEditPostAssertion()) && (postAssertion instanceof VarAssertion)) { + VarAssertion variable=(VarAssertion) postAssertion; + variable.setVariable(buildAssertion(assertion)); + variable.setOriginal(assertion); + //status = Status.UNCHANGED; + setChanged(true); + result = true; + } + + return result; + } + + /** + * Creates a StrongPreFormula. + * + * @param varName + * the name of the created Variable (Px) + */ + boolean createStrongPre(String varName) { + for (VerificationFormula vf : children) { + if (vf.isRuleApplied()) { + return false; + } + } + + AbstractAssertion variable=new VarAssertion(varName); + VerificationFormula implication=new ImplicationFormula(this,code.start, code.end, + preAssertion,variable); + implication.setChanged(true); + implication.setApplied(); + VerificationFormula strongpre=new StrongPreFormula(this, source, code.start, + code.end,variable, + postAssertion); + // illegal object state + if (children.size() > 2) { + return false; + } + if (hasChildren()) { + for (VerificationFormula vf : children) { + vf.setParent(strongpre); + } + strongpre.setChildren(this.getChildren()); + children.clear(); + } + children.add(implication); + children.add(strongpre); + return true; + } + + /** + * Creates a WeakPostFormula. + * + * @param varName + * the name of the created Variable (Px) + */ + boolean createWeakPost(String varName) { + for (VerificationFormula vf : children) { + if (vf.isRuleApplied()) { + return false; + } + } + + AbstractAssertion variable=new VarAssertion(varName); + VerificationFormula weakpost=new WeakPostFormula(this, source, code.start, code.end, + preAssertion,variable); + VerificationFormula implication=new ImplicationFormula(this, code.start, code.end, variable, + postAssertion); + implication.setChanged(true); + implication.setApplied(); + + // illegal object state + if (children.size() > 2) { + return false; + } + if (hasChildren()) { + for (VerificationFormula vf : children) { + vf.setParent(weakpost); + } + weakpost.setChildren(this.getChildren()); + children.clear(); + } + children.add(weakpost); + children.add(implication); + return true; + } + + /** + * Applies the next Rule. + * + * @param vf + * the parent of the VerificationFormula to be created + * @return true if a VerificationFormula was + * created successfully + * @throws UnsupportedOperationException if something important failed + */ + abstract boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException; + + /** + * Checks whether the Rule can be applied to this + * VerificationFormula. + * + * @param rule + * the Rule to be applied + * @return true if the Rule can be applied to this + * VerificationFormula + */ + abstract boolean canApply(Rule rule); + + /** + * This Method performs a recursive collection of all the children and it self + * into a Map. This Map uses the Id of the VerificationFormula + * as Key. + * + * @param formulas + * reference of the concrete Map + */ + void getFormulaMap(Map formulas) { + for (VerificationFormula vf : children) { + vf.getFormulaMap(formulas); + } + formulas.put(id, this); + } + + /** + * Gives you the information whether this VerificationFormula + * was changed or not Note: That it is your opportunity to reset the Value. + * + * @return if the VerificationFormula has been changed + */ + public boolean hasChanged() { + return changed; + } + + /** + * Sets the value of isChanged to the given value + * + * @param changed + * the value that isChanged should have + */ + public void setChanged(boolean changed) { + this.changed = changed; + } + + /** + * This method provides the verifiable check for preAssertion. + * This check returns only true if all {@link VarAssertions} in + * the pre assertion tree have underlying assertions. + * + * @return true if the pre assertion can be verified + */ + public boolean hasFilledPreAssertion() { + return preAssertion.verifiable(); + } + + /** + * This method provides the verifiable check for postAssertion. + * This check returns only true if all {@link VarAssertions} in + * the post assertion tree have underlying assertions. + * + * @return true if the post assertion can be verified + */ + public boolean hasFilledPostAssertion() { + return postAssertion.verifiable(); + } + + /** + * This method provides the verifiable check of this Formula. + * Every Formula returns by default false and + * should be overridden by Subclasses which can be verified.
          + * Note: {@link StrongPreFormula},{@link WeakPostFormula} and + * {@link AssignFormula} override this method. + * + * @return false by default
          + * Subclasses sometimes implement there own check. + */ + public boolean verifiable() { + return false; + } + + /** + * Gives you the status of this VerificationFormula + * + * @return the current {@link Status} + */ + public Status getStatus() { + return status; + } + + /** + * This method performs a {@link Status} change of this + * VerificationFormula
          + * Note: That the Status can only be changed if the + * VerificationFormula is verifiable. + * + * @param status + * the {@link Status} to set + */ + public void setStatus(Status status) { + if (! this.status.equals(status)) { + setChanged(true); + this.status = status; + } + } + + /** + * Gives you true whether the Formula is an implication or + * false if not.
          + * Note: This method will be overridden by the {@link ImplicationFormula} to + * perform this task. + * + * @return true if the Formula is a {@link ImplicationFormula} + */ + public boolean isImplication(){ + return false; + } + + /** + * Gives by default true but in case of an + * {@link IterationFormula} it returns only true + * if the post assertion has the correct from.
          + *
          + * {P1} while(pi) {P2}
          + * P2 must have the form (P1 && !(pi)) + * + * @return true by default but is overridden by + * {@link IterationFormula} + */ + public boolean isCorrect(){ + return ((appliedRule == Rule.ITERATION) ? check(this) : true); + } + + /** + * Tests for weak post, strong pre and iteration formulas + * if the post assertion has the correct form: + * {P1} while(pi) {P2}
          + * P2 must have the form (P1 && !(pi)) + * + * @param formula the VerificationFormula to check + * @return + * true if post assertion consists of + * pre assertion AND NOT boolean expression + */ + protected boolean check(VerificationFormula formula) { + return true; + } + + /** + * Searches for the highest id in this VerificationFormula tree. + * + * @return the highest id in this VerificationFormula tree + */ + private int getHighestId() { + int result = this.id; + int help; + + for (VerificationFormula vf : getChildren()) { + help = vf.getHighestId(); + result = ((help > result) ? help : result); + } + + return result; + } + + /** + * Sets the nextId to the value which represents the highest id in the + * VerificationFormula tree increased by 1. + * + * @param root the root of the VerificationFormula tree + * @return true if nextId is now the highestID+1 of the + * VerificationFormula tree + */ + static boolean setNextId(VerificationFormula root) { + if (root == null) { + return false; + } + + if (root.parent == null) { + nextId = root.getHighestId()+1; + return true; + } else { + return false; + } + } + + +} diff --git a/src/org/jalgo/module/hoare/model/WeakPostFormula.java b/src/org/jalgo/module/hoare/model/WeakPostFormula.java new file mode 100644 index 0000000..0a8c06e --- /dev/null +++ b/src/org/jalgo/module/hoare/model/WeakPostFormula.java @@ -0,0 +1,74 @@ +package org.jalgo.module.hoare.model; + +import org.jalgo.module.hoare.constants.Rule; + +/** + * Represents a weak post verification formula + * + * @author Thomas, Uwe + * + */ + +public class WeakPostFormula extends VerificationFormula { + /** + * the serial Id of this Object + */ + private static final long serialVersionUID = -8042067274127804053L; + + /** + * Constructs a WeakPostFormula with the given beginning and end of the code + * and sets the parent, preAssertion, postAssertion and the source + * of the whole VerificationFormula tree. + * + * @param parent the parent node in the VerificationFormula tree + * @param source the source of the whole VerificationFormula tree + * @param codeStart startIndex of the SourceCode + * @param codeEnd endIndex of the SourceCode + * @param preAssertion preAssertion of the StrongPreFormula + * @param postAssertion postAssertion of the StrongPreFormula + */ + WeakPostFormula(VerificationFormula parent, String source, int codeStart, int codeEnd, + AbstractAssertion preAssertion, AbstractAssertion postAssertion) { + super(parent, source, codeStart, codeEnd); + this.preAssertion=preAssertion; + this.postAssertion=postAssertion; + this.setChanged(true); + this.setApplied(); + parent.appliedRule = Rule.WEAKPOST; + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#canApply(Rule) + */ + boolean canApply(Rule rule) { + return parent.canApply(rule); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#applyNext(VerificationFormula) + */ + boolean applyNext(VerificationFormula parent) + throws UnsupportedOperationException { + + return this.parent.applyNext(parent); + } + + /** + * @see org.jalgo.module.hoare.model.VerificationFormula#check(VerificationFormula) + */ + @Override + protected boolean check(VerificationFormula formula) { + return parent.check(formula); + } + + /** + * + * @see org.jalgo.module.hoare.model.VerificationFormula#getCode(boolean) + */ + @Override + public String getCode(boolean full) { + return parent.getCode(full); + } + + +} diff --git a/src/org/jalgo/module/hoare/model/package-info.java b/src/org/jalgo/module/hoare/model/package-info.java new file mode 100644 index 0000000..79303e8 --- /dev/null +++ b/src/org/jalgo/module/hoare/model/package-info.java @@ -0,0 +1,8 @@ +/** + * contains all the data objects of the hoare-module. + * The {@link Model} is the main class which handles most + * of the controlling.
          + * {@link VerificationFormula} represents all the data in the + * verification tree. * + */ +package org.jalgo.module.hoare.model; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/res.properties b/src/org/jalgo/module/hoare/res.properties new file mode 100644 index 0000000..f3e3f1a --- /dev/null +++ b/src/org/jalgo/module/hoare/res.properties @@ -0,0 +1,42 @@ +Module_logo=/hoare_pix/logo.gif +HelpSet_Name=/help/jhelp/hoare_help.hs + +icon.openC0Program=/hoare_pix/CNull.gif +icon.reinit=/hoare_pix/reinit.gif +icon.redo=/hoare_pix/redo.gif +icon.redo.gray=/hoare_pix/grayredo.gif +icon.undo=/hoare_pix/undo.gif +icon.undo.gray=/hoare_pix/grayundo.gif +icon.delNode=/hoare_pix/delnode.gif +icon.duck=/hoare_pix/duck.png +icon.toggleSplitter=/hoare_pix/toggleSplitter.gif +icon.resetZoom=/hoare_pix/resetZoom.gif +icon.zoomIn=/hoare_pix/zoomIn.gif +icon.zoomOut=/hoare_pix/zoomOut.gif +icon.normalMouse=/hoare_pix/normalMouse.gif + +icon.openC0Welcome0=/hoare_pix/openc0_welcome_0.gif +icon.openC0Welcome1=/hoare_pix/openc0_welcome_1.gif +icon.openC0WelcomeDesc_de=/hoare_pix/openc0_welcome_Desc_de.gif +icon.openC0WelcomeDesc_en=/hoare_pix/openc0_welcome_Desc_en.gif + +icon.newWelcome0=/hoare_pix/new_welcome_0.gif +icon.newWelcome1=/hoare_pix/new_welcome_1.gif +icon.newWelcomeDesc_de=/hoare_pix/new_welcome_Desc_de.gif +icon.newWelcomeDesc_en=/hoare_pix/new_welcome_Desc_en.gif + +icon.openWelcome0=/hoare_pix/open_welcome_0.gif +icon.openWelcome1=/hoare_pix/open_welcome_1.gif +icon.openWelcomeDesc_de=/hoare_pix/open_welcome_Desc_de.gif +icon.openWelcomeDesc_en=/hoare_pix/open_welcome_Desc_en.gif + +rule.assign=/hoare_pix/assign.gif +rule.comp=/hoare_pix/Block.gif +rule.sequence=/hoare_pix/Sequenz.gif +rule.alt1=/hoare_pix/if.gif +rule.alt2=/hoare_pix/ifelse.gif +rule.iter=/hoare_pix/while.gif +rule.SV=/hoare_pix/SV.gif +rule.SN=/hoare_pix/SN.gif + +fontFolder=/hoare_font/ \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/CVS/Entries b/src/org/jalgo/module/hoare/view/CVS/Entries new file mode 100644 index 0000000..29ab4d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/CVS/Entries @@ -0,0 +1,20 @@ +/JGraphRoundRectView.java/1.1/Wed Aug 27 13:00:53 2008// +/JToolButton.java/1.1/Wed Aug 27 13:00:53 2008// +/MyCell.java/1.1/Wed Aug 27 13:00:54 2008// +/MyCellViewFactory.java/1.1/Wed Aug 27 13:00:55 2008// +/MyEdge.java/1.1/Wed Aug 27 13:00:54 2008// +/PanelVertexRenderer.java/1.1/Wed Aug 27 13:00:56 2008// +/VertexPanelFactory.java/1.1/Wed Aug 27 13:00:52 2008// +/View.java/1.1/Wed Aug 27 13:00:52 2008// +/WSGraph.java/1.1/Wed Aug 27 13:00:53 2008// +/WSPart.java/1.1/Wed Aug 27 13:00:54 2008// +/WSRule.java/1.1/Wed Aug 27 13:00:57 2008// +/WSSource.java/1.1/Wed Aug 27 13:00:55 2008// +/WSVar.java/1.1/Wed Aug 27 13:00:56 2008// +/WelcomeScreen.java/1.1/Wed Aug 27 13:00:55 2008// +/WelcomeScreenButton.java/1.1/Wed Aug 27 13:00:54 2008// +/WorkScreen.java/1.1/Wed Aug 27 13:00:53 2008// +D/formula//// +/package-info.java/1.1/Wed Aug 27 13:00:56 2008// +D/toolbar//// +D/util//// diff --git a/src/org/jalgo/module/hoare/view/CVS/Repository b/src/org/jalgo/module/hoare/view/CVS/Repository new file mode 100644 index 0000000..d3ad301 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/view diff --git a/src/org/jalgo/module/hoare/view/CVS/Root b/src/org/jalgo/module/hoare/view/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/view/JGraphRoundRectView.java b/src/org/jalgo/module/hoare/view/JGraphRoundRectView.java new file mode 100644 index 0000000..9680662 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/JGraphRoundRectView.java @@ -0,0 +1,145 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BasicStroke; +import java.awt.Dimension; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Point2D; + +import org.jgraph.graph.CellViewRenderer; +import org.jgraph.graph.EdgeView; +import org.jgraph.graph.VertexView; + +/** + * Class to get a round cell + * @author Tomas + * + * also see: http://jsourcery.com/api/sourceforge/jgraph/5.9.2.1/com/jgraph/example/mycellview/ + */ +public class JGraphRoundRectView extends VertexView { + + private static final long serialVersionUID = 1L; + /** + * value which discripes the rounding of the cells (higher -> more round) + */ + private static int roundValue = 5; + public static transient CellViewRenderer normalRenderer = new PanelVertexRenderer(); + public static transient CellViewRenderer roundRectRenderer = new ActivityRenderer(); + + /** + * Constructor calls super() + */ + public JGraphRoundRectView() { + super(); + } + + /** + * Constructor calls super() with the given cell + * @param cell the Object + */ + public JGraphRoundRectView(Object cell) { + super(cell); + } + + /** + * Returns the intersection of the bounding rectangle and the straight line + * between the source and the specified point p. The specified point is + * expected not to intersect the bounds. Note: You must override this method + * if you use a different renderer. This is because this method relies on + * the VertexRenderer interface, which can not be safely assumed for + * subclassers. + */ + public Point2D getPerimeterPoint(EdgeView edge, Point2D source, Point2D p) { + if (getRenderer() instanceof PanelVertexRenderer) + return ((PanelVertexRenderer) getRenderer()).getPerimeterPoint(this, + source, p); + return super.getPerimeterPoint(edge, source, p); + } + + /** + * gets the Size of the Arc added by the roundValue + * @param width + * Cell Width + * @param height + * Cell Height + * @return + * Arcsize integer + */ + public static int getArcSize(int width, int height) { + int arcSize; + if (width <= height) { + arcSize = height / 5; + if (arcSize > (width / 2)) { + arcSize = width / 2; + } + } else { + arcSize = width / 5; + if (arcSize > (height / 2)) { + arcSize = height / 2; + } + } + return arcSize + roundValue; + } + + /** + * getter for CellViewRenderer + * @return CellViewRenderer + */ + public CellViewRenderer getRenderer() { + if (((MyCell)getCell()).isRounded()) { + return roundRectRenderer; + } + else { + return normalRenderer; + } + } + + public static class ActivityRenderer extends PanelVertexRenderer { + + private static final long serialVersionUID = -7089865114703122718L; + + /** + * overwridden getPreferredSize method to get the round cells + * @return Dimension + */ + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + d.width += d.height / 5; + return d; + } + + /** + * overwridden paint method to get the round cells + * @param Graphics + */ + public void paint(Graphics g) { + int b = borderWidth; + Graphics2D g2 = (Graphics2D)g; + Dimension d = getSize(); + boolean tmp = selected; + int roundRectArc = JGraphRoundRectView.getArcSize(d.width - b, d.height - b); + if (super.isOpaque()) { + g.setColor(super.getBackground()); + if (gradientColor != null && !preview) { + setOpaque(false); + g2.setPaint(new GradientPaint(0, 0, getBackground(), getWidth(), getHeight(), gradientColor, true)); + } + g.fillRoundRect(b / 2, b / 2, d.width - (int)(b * 1.5), d.height - (int)(b * 1.5), roundRectArc, roundRectArc); + } + try { + setBorder(null); + setOpaque(false); + selected = false; + super.paint(g); + } finally { + selected = tmp; + } + if (bordercolor != null) { + g.setColor(bordercolor); + g2.setStroke(new BasicStroke(b)); + g.drawRoundRect(b / 2, b / 2, d.width - (int)(b * 1.5), d.height - (int)(b * 1.5), roundRectArc, roundRectArc); + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/JToolButton.java b/src/org/jalgo/module/hoare/view/JToolButton.java new file mode 100644 index 0000000..b850490 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/JToolButton.java @@ -0,0 +1,110 @@ +package org.jalgo.module.hoare.view; + +import java.awt.Color; +import java.awt.SystemColor; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.border.BevelBorder; +import javax.swing.border.Border; +import javax.swing.border.EmptyBorder; + +/** + * This class defines a JButton, which is specialized for + * JToolbars. This means, that the standard JButton + * has a border, which is not appropriate for creating nice toolbars ;o) + * Furthermore the native look&feel doesn't support the rollover mechanism. + * + * @author Markus (year 2007) + * + * copied by tomas + */ +public class JToolButton extends JButton { + + private static final long serialVersionUID = 1764614541666747667L; + + private static Border oneLineRaisedBevelBorder = BorderFactory.createBevelBorder( + BevelBorder.RAISED, Color.white, SystemColor.control, Color.gray, + SystemColor.control); + + private static Border oneLineLoweredBevelBorder = BorderFactory.createBevelBorder( + BevelBorder.LOWERED, Color.white, SystemColor.control, Color.gray, + SystemColor.control); + + private static Border emptyBorder = new EmptyBorder(2, 2, 2, 2); + + private RolloverHandler rolloverHandler; + + /** + * Creates a new instance of JToolButton + * @param image icon that is shown on the button + * @param gui controller for the view + * @param tooltipText text for the tooltip + * @param actionCommand action that is performed when the button is clicked + */ + public JToolButton(ImageIcon image, final View gui,final String tooltipText, final AbstractAction actionCommand) { + + actionCommand.putValue(Action.SMALL_ICON, image); + setBorder(emptyBorder); + setAction(actionCommand); + setToolTipText(tooltipText); + addMouseListener(new MouseAdapter() { + public void mouseEntered(MouseEvent arg0) { + gui.setWelcomeMessage(tooltipText); + } + }); + rolloverHandler = new RolloverHandler(); + if (isEnabled()) + addMouseListener(rolloverHandler); + addPropertyChangeListener("enabled", new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + if ((Boolean) evt.getNewValue()) + addMouseListener(rolloverHandler); + else { + removeMouseListener(rolloverHandler); + setBorder(emptyBorder); + } + } + }); + } + + private class RolloverHandler extends MouseAdapter { + + private boolean mouseOver = false; + private boolean mouseDown = false; + + public void mouseExited(MouseEvent e) { + mouseOver = false; + setBorder(emptyBorder); + } + + public void mouseEntered(MouseEvent e) { + mouseOver = true; + if (mouseDown) + setBorder(oneLineLoweredBevelBorder); + else + setBorder(oneLineRaisedBevelBorder); + } + + public void mousePressed(MouseEvent e) { + mouseDown = true; + setBorder(oneLineLoweredBevelBorder); + } + + public void mouseReleased(MouseEvent e) { + mouseDown = false; + + if (mouseOver && isEnabled()) + setBorder(oneLineRaisedBevelBorder); + else + setBorder(emptyBorder); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/MyCell.java b/src/org/jalgo/module/hoare/view/MyCell.java new file mode 100644 index 0000000..8e8195a --- /dev/null +++ b/src/org/jalgo/module/hoare/view/MyCell.java @@ -0,0 +1,105 @@ +package org.jalgo.module.hoare.view; + +import org.jgraph.graph.DefaultGraphCell; + +/** + * This a DefaultGraphCell from JGraph package extended + * with an ID, a level in the graph and a position (left , right, middle) over the parent cell + * + * @author tomas + * + */ +public class MyCell extends DefaultGraphCell{ + private static final long serialVersionUID = 3982472968049935711L; + private int ID; + private int level; + private int pos; + private double ratio; + private boolean rounded; + + public static int setLeft(){return -1;} + public static int setRight(){return 1;} + public static int setMiddle(){return 0;} + + + /** + * here you can set name, ID, position, level, and rounded right in the constructor + * @param name + * @param ID + * @param pos + * @param level + * @param rounded + */ + public MyCell(String name, int ID, int pos, int level, boolean rounded){ + super(name); + this.ID = ID; + this.level = level; + this.pos = pos; + this.rounded = rounded; + } + /** + * getter for the Cell ID + * @return the iD + */ + public int getID() { + return ID; + } + + /** + * setter for the Cell ID + * @param id the iD to set + */ + public void setID(int id) { + ID = id; + } + /** + * getter for the Level the cell is supposed to be painted in the graph + * @return the level + */ + public int getLevel() { + return level; + } + /** + * setter for the Level the cell is supposed to be painted in the graph + * @param level the level to set + */ + public void setLevel(int level) { + this.level = level; + } + /** + * getter for the Position the cell should be in relation to the "parent cell", left of it = -1, middle = 0, right = 1 + * @return the position (1 or 0 or -1) + */ + public int getPos(){ return pos;} + /** + * getter for the Ratio the child cells are positioned with + * @return + */ + public double getRatio() { + return ratio; + } + /** + * setter for the Ratio the child cells are positioned with + * @param d + */ + public void setRatio(double d) { + this.ratio = d; + } + /** + * getter for isRounded feature to know if the cell is supposed to be painted round or not + * @return + */ + public boolean isRounded() { + return rounded; + } + /** + * setter for isRounded feature to know if the cell is supposed to be painted round or not + * @param rounded + */ + public void setRounded(boolean rounded) { + this.rounded = rounded; + } + + + +} diff --git a/src/org/jalgo/module/hoare/view/MyCellViewFactory.java b/src/org/jalgo/module/hoare/view/MyCellViewFactory.java new file mode 100644 index 0000000..bf7f0c3 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/MyCellViewFactory.java @@ -0,0 +1,31 @@ +package org.jalgo.module.hoare.view; + +import org.jgraph.graph.DefaultCellViewFactory; +import org.jgraph.graph.VertexView; + +/** + * Cell View Factory changed to return our JGraphRoundRectView to draw the cells + * + * @author Tomas + */ +public class MyCellViewFactory extends DefaultCellViewFactory { + + private static final long serialVersionUID = 1L; +/** + * overridden method to return our JGraphRoundRectView + * + * @param Object (Cell) + * DefaultGraphCell which should be painted + * @return VertexView + * VertexView (JGraphRoundRectView) for Jgraph to use + */ + protected VertexView createVertexView(Object v) { + + VertexView view = new JGraphRoundRectView(v); + view.setCell(v); + return view; + + } + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/MyEdge.java b/src/org/jalgo/module/hoare/view/MyEdge.java new file mode 100644 index 0000000..75165a5 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/MyEdge.java @@ -0,0 +1,60 @@ +package org.jalgo.module.hoare.view; + +import org.jgraph.graph.DefaultEdge; + +/** + * This a DefaultEdge from JGraph package extended + * with a parentCell and a sourceCell
          + *
          + * !! take care, source and parent cell of the MyEdge is used logically swapped in WSgraph for programming reasons + * + * @author Tomas + * + */ +public class MyEdge extends DefaultEdge{ + + private static final long serialVersionUID = 3649276324756278498L; + + private MyCell sourceCell, targetCell; + + /** + * this is the getter for the source cell + * !! take care, the source cell in this case is not the cell on the beginning of the arrow, + * it is the lower painted cell of the both cells involved in this arrow + * @return the sourceCell + */ + public MyCell getSourceCell() { + return sourceCell; + } + + /** + * this is the setter for the source cell + * !! take care, the source cell in this case is not the cell on the beginning of the arrow, + * it is the lower painted cell of the both cells involved in this arrow + * @param sourceCell the sourceCell to set + */ + public void setSourceCell(MyCell sourceCell) { + this.sourceCell = sourceCell; + } + + /** + * this is the getter for the target cell + * !! take care, the source cell in this case is not the cell at the end of the arrow, + * it is the higher painted cell of the both cells involved in this arrow + * @return the targetCell + */ + public MyCell getTargetCell() { + return targetCell; + } + + /** + * this is the setter for the target cell + * !! take care, the source cell in this case is not the cell at the end of the arrow, + * it is the higher painted cell of the both cells involved in this arrow + * @param targetCell the targetCell to set + */ + public void setTargetCell(MyCell targetCell) { + this.targetCell = targetCell; + } + +} diff --git a/src/org/jalgo/module/hoare/view/PanelVertexRenderer.java b/src/org/jalgo/module/hoare/view/PanelVertexRenderer.java new file mode 100644 index 0000000..8e7a173 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/PanelVertexRenderer.java @@ -0,0 +1,385 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.Stroke; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.io.Serializable; +import java.util.Map; + +import javax.swing.BorderFactory; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.UIManager; + +import org.jgraph.JGraph; +import org.jgraph.graph.CellView; +import org.jgraph.graph.CellViewRenderer; +import org.jgraph.graph.GraphConstants; +import org.jgraph.graph.VertexView; + +/** + * This renderer displays entries that implement the CellView interface and + * supports the following attributes. If the cell view is not a leaf, this + * object is only visible if it is selected. + *
        • GraphConstants.BOUNDS GraphConstants.ICON GraphConstants.FONT + * GraphConstants.OPAQUE GraphConstants.BORDER GraphConstants.BORDERCOLOR + * GraphConstants.LINEWIDTH GraphConstants.FOREGROUND GraphConstants.BACKGROUND + * GraphConstants.VERTICAL_ALIGNMENT GraphConstants.HORIZONTAL_ALIGNMENT + * GraphConstants.VERTICAL_TEXT_POSITION GraphConstants.HORIZONTAL_TEXT_POSITION + *
        • + * + * It is a modified VertexRenderer that inherits from JPanel instead of JLabel. + * + * @version 1.0 1/1/02 + * @author Gaudenz Alder, Antje Lang + */ +public class PanelVertexRenderer extends JPanel implements CellViewRenderer, + Serializable { + + private static final long serialVersionUID = 5326213962683876047L; + + /** Cache the current shape for drawing. */ + transient protected VertexView view; + + /** Cached hasFocus and selected value. */ + transient protected boolean hasFocus, selected, preview, childrenSelected; + + /** Cached default foreground and default background. */ + transient protected Color defaultForeground, defaultBackground, + bordercolor; + + /** Cached borderwidth. */ + transient protected int borderWidth; + + /** Cached value of the double buffered state */ + transient protected boolean isDoubleBuffered = false; + + transient protected Color gradientColor = null, gridColor = Color.black, + highlightColor = Color.black, lockedHandleColor = Color.black; + + /** + * Constructs a renderer that may be used to render vertices. + */ + public PanelVertexRenderer() { + defaultForeground = UIManager.getColor("Tree.textForeground"); + defaultBackground = UIManager.getColor("Tree.textBackground"); + setLayout(new BorderLayout()); + } + + /** + * Configure and return the renderer component based on the passed in cell. + * The value is typically set from messaging the graph with + * convertValueToString. We recommend you check the value's + * class and throw an illegal argument exception if it's not correct. + * + * @param graph + * the graph that that defines the rendering context. + * @param view + * the cell view that should be rendered. + * @param sel + * whether the object is selected. + * @param focus + * whether the object has the focus. + * @param preview + * whether we are drawing a preview. + * @return the component used to render the value. + */ + public Component getRendererComponent(JGraph graph, CellView view, + boolean sel, boolean focus, boolean preview) { + gridColor = graph.getGridColor(); + highlightColor = graph.getHighlightColor(); + lockedHandleColor = graph.getLockedHandleColor(); + isDoubleBuffered = graph.isDoubleBuffered(); + if (view instanceof VertexView) { + this.view = (VertexView) view; + setComponentOrientation(graph.getComponentOrientation()); + if (graph.getEditingCell() != view.getCell()) { + Object label = ((MyCell)view.getCell()).getUserObject();//graph.convertValueToString(view); + if (label != null) { + removeAll(); + if (label instanceof String) { + add(new JLabel((String)label)); + } + else if (label instanceof Component) { + add((Component)label); + } + } + else { + //removeAll(); + //setText(null); + } + } else { + //removeAll(); + //setText(null);+ + } + this.hasFocus = focus; + this.childrenSelected = graph.getSelectionModel() + .isChildrenSelected(view.getCell()); + this.selected = sel; + this.preview = preview; + if (this.view.isLeaf() + || GraphConstants.isGroupOpaque(view.getAllAttributes())) + installAttributes(view); + else + resetAttributes(); + return this; + } + return null; + } + + /** + * Hook for subclassers that is invoked when the installAttributes is not + * called to reset all attributes to the defaults.
          + * Subclassers must invoke the superclass implementation. + * + */ + protected void resetAttributes() { + //setText(null); + setBorder(null); + setOpaque(false); + setGradientColor(null); + //setIcon(null); + removeAll(); + } + + /** + * Install the attributes of specified cell in this renderer instance. This + * means, retrieve every published key from the cells hashtable and set + * global variables or superclass properties accordingly. + * + * @param view + * the cell view to retrieve the attribute values from. + */ + protected void installAttributes(CellView view) { + Map map = view.getAllAttributes(); + //setIcon(GraphConstants.getIcon(map)); + setOpaque(GraphConstants.isOpaque(map)); + setBorder(GraphConstants.getBorder(map)); + //setVerticalAlignment(GraphConstants.getVerticalAlignment(map)); + //setHorizontalAlignment(GraphConstants.getHorizontalAlignment(map)); + //setVerticalTextPosition(GraphConstants.getVerticalTextPosition(map)); + //setHorizontalTextPosition(GraphConstants.getHorizontalTextPosition(map)); + bordercolor = GraphConstants.getBorderColor(map); + borderWidth = Math.max(1, Math.round(GraphConstants.getLineWidth(map))); + if (getBorder() == null && bordercolor != null) + setBorder(BorderFactory.createLineBorder(bordercolor, borderWidth)); + Color foreground = GraphConstants.getForeground(map); + setForeground((foreground != null) ? foreground : defaultForeground); + Color gradientColor = GraphConstants.getGradientColor(map); + setGradientColor(gradientColor); + Color background = GraphConstants.getBackground(map); + setBackground((background != null) ? background : defaultBackground); + setFont(GraphConstants.getFont(map)); + } + + /** + * Paint the renderer. Overrides superclass paint to add specific painting. + */ + public void paint(Graphics g) { + try { + if (gradientColor != null && !preview && isOpaque()) { + setOpaque(false); + Graphics2D g2d = (Graphics2D) g; + g2d.setPaint(new GradientPaint(0, 0, getBackground(), + getWidth(), getHeight(), gradientColor, true)); + g2d.fillRect(0, 0, getWidth(), getHeight()); + } + setLocation(g.getClipBounds().getLocation()); + if (getComponentCount()>0) { + if (getComponent(0) instanceof VertexPanelFactory.VertexPanel) { + VertexPanelFactory.VertexPanel p = (VertexPanelFactory.VertexPanel)getComponent(0); + VertexPanelFactory.setBounds(p); + } + } + super.paint(g); + paintSelectionBorder(g); + } catch (IllegalArgumentException e) { + // JDK Bug: Zero length string passed to TextLayout constructor + } + } + + /** + * Provided for subclassers to paint a selection border. + */ + protected void paintSelectionBorder(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + Stroke previousStroke = g2.getStroke(); + g2.setStroke(GraphConstants.SELECTION_STROKE); + if (childrenSelected || selected) { + if (childrenSelected) + g.setColor(gridColor); + else if (hasFocus && selected) + g.setColor(lockedHandleColor); + else if (selected) + g.setColor(highlightColor); + Dimension d = getSize(); + g.drawRect(0, 0, d.width - 1, d.height - 1); + } + g2.setStroke(previousStroke); + } + + /** + * Returns the intersection of the bounding rectangle and the straight line + * between the source and the specified point p. The specified point is + * expected not to intersect the bounds. + */ + public Point2D getPerimeterPoint(VertexView view, Point2D source, Point2D p) { + Rectangle2D bounds = view.getBounds(); + double x = bounds.getX(); + double y = bounds.getY(); + double width = bounds.getWidth(); + double height = bounds.getHeight(); + double xCenter = x + width / 2; + double yCenter = y + height / 2; + double dx = p.getX() - xCenter; // Compute Angle + double dy = p.getY() - yCenter; + double alpha = Math.atan2(dy, dx); + double xout = 0, yout = 0; + double pi = Math.PI; + double pi2 = Math.PI / 2.0; + double beta = pi2 - alpha; + double t = Math.atan2(height, width); + if (alpha < -pi + t || alpha > pi - t) { // Left edge + xout = x; + yout = yCenter - width * Math.tan(alpha) / 2; + } else if (alpha < -t) { // Top Edge + yout = y; + xout = xCenter - height * Math.tan(beta) / 2; + } else if (alpha < t) { // Right Edge + xout = x + width; + yout = yCenter + width * Math.tan(alpha) / 2; + } else { // Bottom Edge + yout = y + height; + xout = xCenter + height * Math.tan(beta) / 2; + } + return new Point2D.Double(xout, yout); + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void validate() { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void revalidate() { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void repaint(long tm, int x, int y, int width, int height) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void repaint(Rectangle r) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + protected void firePropertyChange(String propertyName, Object oldValue, + Object newValue) { + // Strings get interned... + if (propertyName == "text") + super.firePropertyChange(propertyName, oldValue, newValue); + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, byte oldValue, + byte newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, char oldValue, + char newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, short oldValue, + short newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, int oldValue, + int newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, long oldValue, + long newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, float oldValue, + float newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, double oldValue, + double newValue) { + } + + /** + * Overridden for performance reasons. See the Implementation Note for more information. + */ + public void firePropertyChange(String propertyName, boolean oldValue, + boolean newValue) { + } + + /** + * Returns the gradientColor. + * @return the gradientColor. + */ + public Color getGradientColor() { + return gradientColor; + } + + /** + * Sets the gradientColor. + * @param gradientColor + * The gradientColor to set. + */ + public void setGradientColor(Color gradientColor) { + this.gradientColor = gradientColor; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/VertexPanelFactory.java b/src/org/jalgo/module/hoare/view/VertexPanelFactory.java new file mode 100644 index 0000000..98272f5 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/VertexPanelFactory.java @@ -0,0 +1,300 @@ +package org.jalgo.module.hoare.view; + +import java.awt.Component; +import java.awt.Font; +import java.awt.Graphics; + +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jalgo.module.hoare.view.formula.FormulaViewer; + +/** + * Provides panels for the vertices of the verification tree. + * + * @author Antje, Thomas + * + */ +public class VertexPanelFactory { + + /** + * The class is not supposed to be instanciated as there are only static methods. + * + */ + private VertexPanelFactory() { + } + + /** + * Returns a JPanel for the specified cell. + * @param gui the gui controller + * @param cell the cell the JPanel is for + * @param isSelected true if the cell is selected, otherwise false + * @param isDetailed true if the cell is expanded, otherwise false + * @return a JPanel for the specified cell + */ + public static JPanel getVertexPanel(View gui, MyCell cell, boolean isSelected, boolean isDetailed) { + if (isDetailed) { + return getDetailedVertexPanel(gui, cell, isSelected); + } + else { + return getCompactVertexPanel(gui, cell, isSelected); + } + } + + /** + * Returns a JPanel for the specified cell which is assumed not to be expanded. + * @param gui the gui controller + * @param cell the cell the JPanel is for + * @param isSelected true if the cell is selected, otherwise false + * @return a JPanel for the specified cell which is assumed not to be expanded. + */ + public static JPanel getCompactVertexPanel(View gui, MyCell cell, boolean isSelected) { + + int id = cell.getID(); + VerificationFormula vf = gui.getModel().getVerificationFormula(id); + if (cell==null) throw new NullPointerException("ups! cell is null."); + if (vf==null) throw new NullPointerException("ups! Formula is null."); + float fontSize = (float)gui.getWorkScreen().getGraph().getFont().getSize2D(); + Font assertionFont = gui.getMainFont().deriveFont(fontSize); + Font sourceCodeFont = gui.getSourceCodeFont().deriveFont(fontSize); + + JPanel p = new VertexPanel(false); + String preLabelString = vf.getPreAssertion(TextStyle.SHORT); + if (!vf.isImplication()) { + preLabelString = "{" + preLabelString + "} "; + } + JLabel preLabel = new JLabel(preLabelString); + preLabel.setFont(assertionFont.deriveFont(Font.BOLD)); + JLabel sourceLabel = new JLabel(vf.getCode(false)); + sourceLabel.setFont(sourceCodeFont.deriveFont(Font.ITALIC)); + String postLabelString = vf.getPostAssertion(TextStyle.SHORT); + if (!vf.isImplication()) { + postLabelString = " {" + postLabelString + "}"; + } + JLabel postLabel = new JLabel(postLabelString); + postLabel.setFont(assertionFont.deriveFont(Font.BOLD)); + + p.add(preLabel); + p.add(sourceLabel); + p.add(postLabel); + + setBounds(p); + + return p; + } + + /** + * Returns a JPanel for the specified cell which is assumed to be expanded. + * @param gui the gui controller + * @param cell the expanded cell the JPanel is for + * @param isSelected true if the cell is selected, otherwise false + * @return a JPanel for the specified cell which is assumed to be expanded. + */ + public static JPanel getDetailedVertexPanel(View gui, MyCell cell, boolean isSelected) { + int id = cell.getID(); + VerificationFormula vf = gui.getModel().getVerificationFormula(id); + float fontSize = (float)gui.getWorkScreen().getGraph().getFont().getSize2D(); + Font assertionFont = gui.getMainFont().deriveFont(fontSize); + Font sourceCodeFont = gui.getSourceCodeFont().deriveFont(fontSize); + + JPanel p = new VertexPanel(true); + // if there is still a (?) in the preAssertion do not draw + JLabel preFV=null; + if (vf.hasFilledPreAssertion()){ + FormulaViewer newFV = new FormulaViewer(vf.getPreAssertion(TextStyle.SOURCE), + assertionFont.deriveFont(Font.BOLD)); + if (!vf.isImplication()) { + newFV.setPreString("{"); + newFV.setPostString("}"); + } + newFV.setColor(WSVar.HIGHLIGHT_COLOR_PRE); + newFV.initSize(); + preFV = newFV; + }else{ + String preLabelString = vf.getPreAssertion(TextStyle.FULL); + if (!vf.isImplication()) { + preLabelString = "{" + preLabelString + "} "; + } + preFV = new JLabel(preLabelString); + preFV.setFont(assertionFont.deriveFont(Font.BOLD)); + preFV.setForeground(WSVar.HIGHLIGHT_COLOR_PRE); + } + + + JLabel sourceLabel = new JLabel(vf.getCode(true)); + sourceLabel.setFont(sourceCodeFont.deriveFont(Font.ITALIC)); + // if there is still a (?) in the postAssertion do not draw + JLabel postFV=null; + if (vf.hasFilledPostAssertion()){ + FormulaViewer newFV = new FormulaViewer(vf.getPostAssertion(TextStyle.SOURCE), + assertionFont.deriveFont(Font.BOLD)); + if (!vf.isImplication()) { + newFV.setPreString("{"); + newFV.setPostString("}"); + } + newFV.setColor(WSVar.HIGHLIGHT_COLOR_POST); + newFV.initSize(); + postFV=newFV; + }else{ + String postLabelString = vf.getPostAssertion(TextStyle.FULL); + if (!vf.isImplication()) { + postLabelString = "{" + postLabelString + "} "; + } + postFV = new JLabel(postLabelString); + postFV.setFont(assertionFont.deriveFont(Font.BOLD)); + postFV.setForeground(WSVar.HIGHLIGHT_COLOR_POST); + } + + p.add(preFV); + p.add(sourceLabel); + p.add(postFV); + + setBounds(p); + + return p; + } + + /** + * Arranges the components of the specified JPanel. + * It is assumed that the JPanel was generated by a method of this class, otherwise this method will probably not work. + * @param p the JPanel whose components will be arranged + */ + public static void setBounds(JPanel p) { + if (p instanceof VertexPanel) { + boolean detailed = ((VertexPanel)p).detailed; + int dist = 5; + int x = dist; + int y = dist; + int maxX = 0; + int maxY = 0; + if (detailed) { + for (int i=0; i<3; i++) { + Component c = p.getComponent(i); + int width = (int)Math.ceil(c.getPreferredSize().getWidth()); + int height = (int)Math.ceil(c.getPreferredSize().getHeight()); + // only the baseline width is computed, therefore extra width has to be added for overhanging letters in italic style + if ((c instanceof JLabel)&(c.getFont().isItalic())) { + width = width+(int)Math.ceil(c.getFontMetrics(c.getFont()).getAscent()/2); + } + c.setBounds(x, y, width, height); + y = y + height; + y = y + dist; + if (width>maxX) maxX = width; + } + maxX = maxX + 2*dist; + maxY = y; + for (int i=0; i<3; i++) { + Component c = p.getComponent(i); + c.setBounds((maxX-c.getWidth())/2, c.getY(), c.getWidth(), c.getHeight()); + } + } + else { + for (int i=0; i<3; i++) { + Component c = p.getComponent(i); + int width = (int)Math.ceil(c.getPreferredSize().getWidth()); + int height = (int)Math.ceil(c.getPreferredSize().getHeight()); + // only the baseline width is computed, therefore extra width has to be added for overhanging letters in italic style + if ((c instanceof JLabel)&(c.getFont().isItalic())) { + width = width+(int)Math.ceil(c.getFontMetrics(c.getFont()).getAscent()/2); + } + c.setBounds(x, y, width, height); + x = x + width; + x = x + dist; + if (height>maxY) maxY = height; + } + maxX = x; + maxY = maxY + 2*dist; + } + p.setSize(maxX, maxY); + p.setPreferredSize(p.getSize()); + p.setMinimumSize(p.getSize()); + p.setMaximumSize(p.getSize()); + } + } + + /** + * Returns the component displaying the pre assertion + * @param p the JPanel displaying the vertex + * @return the pre assertion component + */ + public static Component getPreAssertionComponent(JPanel p) { + return p.getComponent(0); + } + + /** + * Returns the component displaying the source code part + * @param p the JPanel displaying the vertex + * @return the source code part component + */ + public static Component getSourceCodePartComponent(JPanel p) { + return p.getComponent(1); + } + + /** + * Returns the component displaying the post assertion + * @param p the JPanel displaying the vertex + * @return the post assertion component + */ + public static Component getPostAssertionComponent(JPanel p) { + return p.getComponent(2); + } + + /** + * Changes the JPanel to displaying a selected vertex. + * @param p the JPanel displaying the vertex + */ + public static void setSelected(JPanel p) { + getPreAssertionComponent(p).setForeground(WSVar.HIGHLIGHT_COLOR_PRE); + getPostAssertionComponent(p).setForeground(WSVar.HIGHLIGHT_COLOR_POST); + } + + /** + * Changes the JPanel to displaying a vertex that is not selected. + * @param p the JPanel displaying the vertex + */ + public static void setNotSelected(JPanel p) { + getPreAssertionComponent(p).setForeground(WSVar.NO_HIGHLIGHT_COLOR); + getPostAssertionComponent(p).setForeground(WSVar.NO_HIGHLIGHT_COLOR); + } + + /** + * JPanel that remembers wether it shows a detailed or a compact view and that is not drawn itself (but its children are). + * + * @author antje + * + */ + protected static class VertexPanel extends JPanel { + private static final long serialVersionUID = 5581424971403601373L; + + /** + * If true the VertexPanel shows a detailed view, otherwise it shows a compact view. + */ + protected boolean detailed; + + /** + * Creates a new instance of VertexPanel. + * @param detailed must be true if the VertexPanel shows a detailed view, otherwise it must be false + */ + public VertexPanel(boolean detailed) { + this.detailed = detailed; + } + + /** + * The border of the panel is not drawn. + */ + protected void paintBorder(Graphics g) { + // do nothing + } + + /** + * The panel itself is not drawn. + */ + protected void paintComponent(Graphics g) { + // do nothing + } + + } + +} diff --git a/src/org/jalgo/module/hoare/view/View.java b/src/org/jalgo/module/hoare/view/View.java new file mode 100644 index 0000000..8ce5160 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/View.java @@ -0,0 +1,1170 @@ +package org.jalgo.module.hoare.view; + + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Font; +import java.awt.Image; +import java.awt.Point; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.io.File; +import java.net.URL; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.JToolBar; +import javax.swing.JToolBar.Separator; +import javax.swing.filechooser.FileFilter; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.hoare.ModuleConnector; +import org.jalgo.module.hoare.constants.Event; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.control.Controller; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.Variable; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jalgo.module.hoare.view.formula.ConcreteFormulaEditor; +import org.jalgo.module.hoare.view.formula.FormulaEditor; +import org.jalgo.module.hoare.view.formula.FormulaEditorObserver; +import org.jalgo.module.hoare.view.formula.FormulaViewer; +import org.jalgo.module.hoare.view.formula.Enten; +import org.jalgo.module.hoare.view.toolbar.BeamerMode; +import org.jalgo.module.hoare.view.toolbar.DelPart; +import org.jalgo.module.hoare.view.toolbar.LoadCNullProg; +import org.jalgo.module.hoare.view.toolbar.NormalMouse; +import org.jalgo.module.hoare.view.toolbar.ReInit; +import org.jalgo.module.hoare.view.toolbar.Redo; +import org.jalgo.module.hoare.view.toolbar.ResetZoom; +import org.jalgo.module.hoare.view.toolbar.ToggleSplitter; +import org.jalgo.module.hoare.view.toolbar.Undo; +import org.jalgo.module.hoare.view.toolbar.ZoomIn; +import org.jalgo.module.hoare.view.toolbar.ZoomOut; +import org.jgraph.graph.GraphConstants; + +/** + * + * This is the master class of the Graphical User Interface + * and the connection to contol and model + * @author tomas, Antje + * + */ + +public class View implements Observer, KeyListener{ + + /** + * font size if the beamer mode is activated + */ + protected static final int fontSizeBeamerMode = 19; + /** + * standard font size + */ + protected static final int fontSizeNormalMode = 14; + /** + * font size if the beamer mode is activated + */ + protected static final String mainFontFileName = "DejaVuSans.ttf"; + /** + * standard font size + */ + protected static final String sourceCodeFontFileName = "DejaVuSansMono.ttf"; + + /** + * Represents a zoom mode: + * NO - no zoom + * IN - zoom in + * OUT -zoom out + * @author Antje + * + */ + public enum ZoomMode { NO, IN, OUT } + + /** + * The screen that is shown on startup. + */ + private WelcomeScreen startScreen; + /** + * The screen that is shown when working with the modul, after the welcome screen. + */ + private WorkScreen workScreen; + /** + * Root component that is the container for all components of the gui. + */ + private JComponent rootComponent; + /** + * Tool bar of the gui. + */ + private JToolBar toolbar; + /** + * Connects the module with j-Algo. + */ + private ModuleConnector mc; + /** + * The current zoom mode. + */ + private ZoomMode zoomMode = ZoomMode.NO; + /** + * Label that displays the current error message. + */ + private JLabel errorLabel; + /** + * Controller. + */ + private Controller control; + /** + * Model for the gui. + */ + private Model model; + /** + * FormulaEditors that are currently open. + */ + private Map editors = new HashMap(); + /** + * Global font of the gui. + */ + private Font mainFont; + + /** + * Font for source code. + */ + private Font sourceCodeFont; + /** + * Listens to mouse events in WSGraph. + */ + private GraphListener graphMouseListener = new GraphListener(); + /** + * true for beamer mode (viewing options optimized for using a beamer), false for normal mode. + */ + private boolean isBeamerMode = false; + private Undo undo; + private Redo redo; + private JToolBar westToolbar; + + /** + * Creates a new instance of the view controller. + * @param c the connector with j-algo + */ + public View(ModuleConnector c) { + if( c == null ) + return; + mc=c; + rootComponent = JAlgoGUIConnector.getInstance().getModuleComponent(c); + toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar(c); + + rootComponent.removeAll(); + rootComponent.setLayout(new BorderLayout()); + try { + mainFont = Font.createFont(Font.TRUETYPE_FONT, new URL(Messages.getResourceURL("hoare", "fontFolder").toString()+mainFontFileName).openStream()); + } + catch (Exception e) { + e.printStackTrace(); + mainFont = rootComponent.getFont(); + } + try { + sourceCodeFont = Font.createFont(Font.TRUETYPE_FONT, new URL(Messages.getResourceURL("hoare", "fontFolder").toString()+sourceCodeFontFileName).openStream()); + } + catch (Exception e) { + e.printStackTrace(); + sourceCodeFont = mainFont; + } + try { + isBeamerMode = Settings.getBoolean("hoare", "isBeamerMode"); + } + catch (Exception e) { + e.printStackTrace(); + } + + this.installMenu(); + this.installToolbar(true); + } + + /** + * Model setter + * @param m + */ + public void setModel(Model m){ + model=m; + } + + /** + * Model getter + * @return the model + */ + public Model getModel(){ + return model; + } + + /** + * Control setter + * @param c controller + */ + public void setConroller(Controller c){ + control = c; + } + + /** + * Returns the controller. + * @return the controller + */ + private Controller getController() { + return control; + } + + /** + * installs the welcomescreen + */ + public void installWelcomeScreen() { + + if (startScreen == null) + startScreen = new WelcomeScreen(this); + + rootComponent.removeAll(); + rootComponent.add(startScreen); + startScreen.revalidate(); + } + + /** + * install workscreen will install the workscreen, + * this function is supposed to be used by controller only + * otherwise use init() + */ + public void installWorkScreen() { + installToolbar(false); + + if (workScreen == null) + workScreen = new WorkScreen(this); + + rootComponent.removeAll(); + rootComponent.add(workScreen); + + updateFont(); + setBeamer(isBeamerMode); + + workScreen.revalidate(); + } + + /** + * changes the error label in the toolbar and makes it red + * @param text + * labeltext + */ + public void setStatusText(String text){ + int textSize=14; + errorLabel.setForeground(Color.red); + errorLabel.setText("
          "+text+"
          "); + } + + /** + * sets the error label to an other "bleeched" color + */ + public void bleechStatusText(){ + errorLabel.setForeground(Color.decode("#a68067")); + } + + /** + * changes the zoom mode + * which changes the cursor to zoomIn, ZoomOut, or don't zoom + * + * you won't zoom if you use this function, use instead zoom(int Point) + * + * @param mode the new zoom mode + */ + public void setZoomMode(ZoomMode mode) { + zoomMode = mode; + workScreen.getGraph().setCursor(getMyCursor(mode)); + } + + /** + * the current zoom mode + * @return the corrent zoom mode + */ + public ZoomMode getZoomMode() { + return zoomMode; + } + + /** + * makes a new workscreen (not for reinit button to use) + */ + public void init() { + + installToolbar(false); + + workScreen = new WorkScreen(this); + rootComponent.removeAll(); + rootComponent.add(workScreen); + + updateFont(); + setBeamer(isBeamerMode); + + workScreen.revalidate(); + + } + + /** + * clears the workscreen by performing a reinit + */ + public void reinit(){ + //k�nnte Exception werfen + try{ + if (JOptionPane.showConfirmDialog(workScreen, Messages.getString("hoare", "wannaReinit"), Messages.getString("hoare","ttt.reinit"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { + getController().handleEvent(Event.REINIT); + } + } catch (Exception e){ + getController().handleEvent(Event.REINIT); + } + + } + + /** + * interface method to get updates from Model + * gives the Observable to the workscreen for further use + * @param o + * supposed to be the Model + * @param arg + * supposed to be null + */ + synchronized public void update(Observable o, Object arg) { + workScreen.update(model, arg); + } + + /** + * function to set up the beamer mode + * @param beamer if true the view is set to beamer mode, otherwise it's set to normal mode + */ + public void setBeamer(boolean beamer){ + isBeamerMode = beamer; + try { + Settings.setBoolean("hoare", "isBeamerMode", beamer); + } + catch (Exception e) { + e.printStackTrace(); + } + int fontSize = 14; + if (beamer){ + fontSize = fontSizeBeamerMode; + if (workScreen!=null) + workScreen.getGraph().setAbsolutZoomValueToMiddle(3); + } else { + fontSize = fontSizeNormalMode; + if (workScreen!=null) + workScreen.getGraph().setAbsolutZoomValueToMiddle(0); + } + setFontSize(fontSize); + + } + + /** + * installs the Toolbar with buttons and errorLabel + * if boolean initToolbar is true, the function will init the toolbar without buttons + * if it is false it will init the buttons (therefor the toolbar should be inited before) + * + * @param initToolbar + */ + public void installToolbar(boolean initToolbar) { + + if (initToolbar){ + toolbar.removeAll(); + + westToolbar = new JToolBar();; + westToolbar.setFloatable(false); + westToolbar.setRollover(true); + + errorLabel = new JLabel(""); + errorLabel.setForeground(Color.red); + + toolbar.setLayout(new BorderLayout()); + + toolbar.add(westToolbar, BorderLayout.WEST); + toolbar.add(errorLabel, BorderLayout.EAST); + + + + } else { + westToolbar.removeAll(); + + undo = new Undo(this); + redo = new Redo(this); + + ResetZoom rZ = new ResetZoom(this); + ReInit reInit = new ReInit(this); + LoadCNullProg loadCNullProg = new LoadCNullProg(this); + DelPart del = new DelPart(this); + ZoomIn in = new ZoomIn(this); + ZoomOut out = new ZoomOut(this); + NormalMouse nM = new NormalMouse(this); + ToggleSplitter tS= new ToggleSplitter(this); + + del.putValue(AbstractAction.NAME, ""); + reInit.putValue(AbstractAction.NAME, ""); + loadCNullProg.putValue(AbstractAction.NAME, ""); + undo.putValue(AbstractAction.NAME, ""); + redo.putValue(AbstractAction.NAME, ""); + in.putValue(AbstractAction.NAME, ""); + out.putValue(AbstractAction.NAME, ""); + nM.putValue(AbstractAction.NAME, ""); + rZ.putValue(AbstractAction.NAME, ""); + + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.undo")), this, Messages.getString("hoare", + "ttt.undo"), undo)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.redo")), this, Messages.getString("hoare", + "ttt.redo"), redo)); + + westToolbar.addSeparator(); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.reinit")), this, Messages.getString("hoare", + "ttt.reinit"), reInit)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.openC0Program")), this, Messages.getString( + "hoare", "ttt.openC0Program"), loadCNullProg)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.delNode")), this, Messages.getString( + "hoare", "ttt.delNode"), del)); + + westToolbar.addSeparator(); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.resetZoom")), this, Messages.getString("hoare", + "ttt.resetZoom"), rZ)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.zoomIn")), this, Messages.getString("hoare", + "ttt.zoomIn"), in)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.zoomOut")), this, Messages.getString("hoare", + "ttt.zoomOut"), out)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.normalMouse")), this, Messages.getString("hoare", + "ttt.normalMouse"),nM)); + + westToolbar.add(new JToolButton(new ImageIcon(Messages.getResourceURL( + "hoare", "icon.toggleSplitter")), this, Messages.getString("hoare", + "ttt.toggleSplitter"),tS)); + + + + + + } + + + } + + /** + * installs the Menu of the Hoare module + */ + public void installMenu() { + + JMenu menu = JAlgoGUIConnector.getInstance().getModuleMenu(mc); + menu.removeAll(); + menu.add(new ReInit(this)); + menu.add(new LoadCNullProg(this)); + menu.add(new Separator()); + menu.add(new Undo(this)); + menu.add(new Redo(this)); + menu.add(new Separator()); + BeamerMode beamerMode = new BeamerMode(this); + if (beamerMode.isAktiv() || isBeamerMode) { + beamerMode.setSelected(beamerMode.isAktiv() || isBeamerMode); + } + menu.add(beamerMode); + + } + + /** + * workscreen getter + * @return the workScreen + */ + public WorkScreen getWorkScreen() { + return workScreen; + } + + /** + * Message setter for welcome Screen (for the label in the welcome screen) + * @param s + */ + public void setWelcomeMessage(String s){ + JAlgoGUIConnector.getInstance().setStatusMessage(s); + + } + + /** + * calls handle Event in controller with the Event Redo + */ + public void redo(){ + getController().handleEvent(Event.REDO); + } + + /** + * calls handle Event in controller with the Event Undo + */ + public void undo(){ + getController().handleEvent(Event.UNDO); + } + + /** + * Shows the formula editor for a variable when the mouse is clicked or an action is performed. + * Can be used as MouseListener or ActionListener. + * @author Antje + * + */ + protected class EditVariableListener extends MouseAdapter implements ActionListener { + + private String variableName; + + /** + * Creates a new listener for the specified variable. + * @param variableName name of the variable that will be edited + */ + public EditVariableListener(String variableName) { + this.variableName = variableName; + } + + /** + * Creates a new listener for the specified variable. + * @param verificationFormulaID id of the VerificationFormula that uses the variable that will be edited + * @param isPreAssertion true if the variable is part of the pre assertion, false if it is part of the post assertion + */ + public EditVariableListener(int verificationFormulaID, boolean isPreAssertion) { + VerificationFormula vf = getModel().getVerificationFormula(verificationFormulaID); + variableName = getVariable(vf, isPreAssertion).getName(); + } + + public void mouseClicked(MouseEvent e) { + showFormulaEditor(variableName); + } + + public void actionPerformed(ActionEvent e) { + showFormulaEditor(variableName); + } + + } + + /** + * MouseListener and MouseWheelListener for WSGraph + * @author Tomas + * + */ + protected class GraphListener extends MouseAdapter implements MouseWheelListener { + + public void mouseClicked(MouseEvent e) { +// if (e.getClickCount()>2){ +// setStatusText("asdhfbvhsdbfjvhbfsjvbjlfsdbvlfsdbvbvlbfkljbydfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasdhfbvhsdbfjvhbfsjvbjlfsdbvlfsdbvbvlbfkljbydfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasdhfbvhsdbfjvhbfsjvbjlfsdbvlfsdbvbvlbfkljbydfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasdhfbvhsdbfjvhbfsjvbjlfsdbvlfsdbvbvlbfkljbydfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasdhfbvhsdbfjvhbfsjvbjlfsdbvlfsdbvbvlbfkljbydfffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +// } + + + if (getZoomMode()==ZoomMode.NO) { + MyCell cell = null; + try { + cell = (MyCell) workScreen.getGraph().getGraph().getFirstCellForLocation(e.getX(), e.getY()); + } catch (Exception Ex) {} + if (cell == null) { + workScreen.getGraph().setUnselected(); + } + else if (cell==workScreen.getGraph().getSelectedCell()) { + if (e.getButton()==MouseEvent.BUTTON1) { + + // Formular Editor �ffnen + if (cell==workScreen.getGraph().getOpened()) { + Rectangle2D rect = GraphConstants.getBounds(cell.getAttributes()); + double scale = workScreen.getGraph().getGraph().getScale(); + Rectangle2D rec = new Rectangle2D.Double(0, rect.getY()*scale, 0, rect.getHeight()*scale); + + double y = e.getY() - rec.getY(); + double third = rec.getHeight()/3; + + if ( y <= third){ + EditVariableListener evl = new EditVariableListener(workScreen.getGraph().getSelectedCell().getID(),true); + evl.actionPerformed(new ActionEvent( evl, 0 ,"Pre")); + + } else { + if (y>= (third*2)){ + EditVariableListener evl = new EditVariableListener(workScreen.getGraph().getSelectedCell().getID(),false); + evl.actionPerformed(new ActionEvent( evl, 0 ,"Post")); + + }} + } + // Zelle Selectieren oder Expanden + else { workScreen.getGraph().setSelected(cell);} + + + } + } + else { + + + workScreen.getGraph().setSelected(cell); + } + } + else { + if (e.getButton()==MouseEvent.BUTTON3){ + setZoomMode(ZoomMode.NO); + e.consume(); + } else { + + zoom(getZoomMode(), e.getPoint()); } + } + + } + + /** + * MouseWheel with Alt pressed as zoom + */ + public void mouseWheelMoved(MouseWheelEvent e) { + + if (e.isAltDown()){ + if (e.getWheelRotation()>0) { + zoom(ZoomMode.OUT, e.getPoint()); + } + if (e.getWheelRotation()<0) { + zoom(ZoomMode.IN, e.getPoint()); + } + } + } + + } + + /** + * Listener that generates popup menus for WSGraph. + * @author Tomas + * + */ + protected class CellPopupMenu extends MouseAdapter { + + public void mouseClicked(MouseEvent e) { + + if (e.getButton() == MouseEvent.BUTTON3 && workScreen.getGraph().getSelectedCell() != null && !e.isConsumed()){ + + String pre = getVariableForAssertion(model.getVerificationFormula(workScreen.getGraph().getSelectedCell().getID()).getPreAssertion(TextStyle.SHORT)).getName(); + String post= getVariableForAssertion(model.getVerificationFormula(workScreen.getGraph().getSelectedCell().getID()).getPostAssertion(TextStyle.SHORT)).getName(); + + + JPopupMenu popmen = new JPopupMenu(); + + popmen.add(new JLabel ("edit:")); + popmen.addSeparator(); + if (pre!=null){ + JMenuItem vor = new JMenuItem("{ "+pre+" }"); + vor.addActionListener(new EditVariableListener( + workScreen.getGraph().getSelectedCell().getID(), + true) + ); + popmen.add(vor); + } + if (post!=null && !post.equals(pre)) { + JMenuItem nach = new JMenuItem("{ "+post+" }"); + nach.addActionListener(new EditVariableListener( + workScreen.getGraph().getSelectedCell().getID(), + false) + ); + popmen.add(nach); + } + + popmen.show( e.getComponent(), e.getX(), e.getY() ); + } + + } + + } + + /** + * zooming function + * + * @param mode + * Zoommode + * @param point + * point to zoom to + */ + public void zoom (ZoomMode mode, Point2D point){ + switch(mode) { + case IN: + workScreen.getGraph().zoom(1, point); + break; + case OUT: + workScreen.getGraph().zoom(-1, point); + break; + } + } + + /** + * the Cursor changer for the zoom function + * the int value should be: -1 for zoomOut Cursor, 1 for zoomInCursor or 0 for default Cursor + * @param zoomMode + * ZoomMode (if zoom out or zoom in) + * @return Cursor + */ + public static Cursor getMyCursor(ZoomMode zoomMode) + { + Cursor defaultCursor = null; + if (zoomMode!=ZoomMode.NO){ + Toolkit toolkit = Toolkit.getDefaultToolkit(); + URL cursorUrl = null; + if (zoomMode==ZoomMode.OUT) {cursorUrl = Messages.getResourceURL("hoare", "icon.zoomOut");} + else {cursorUrl = Messages.getResourceURL("hoare", "icon.zoomIn");} + + Image cursorImage = new ImageIcon(cursorUrl).getImage(); + defaultCursor = toolkit.createCustomCursor(cursorImage, new Point(1, 1),"AA_Cursor"); + } else { + defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); + } + + return defaultCursor; + } + + /** + * ModuleConnector getter + * @return the modul connector + */ + public ModuleConnector getMC(){ + return mc; + } + + /** + * Applies the rule to the selected cell if possible. + * @param rule + * rule which should be applied + */ + public void applyRule(Rule rule) { + MyCell cell = workScreen.getGraph().getSelectedCell(); + if (!(cell==null)) { + int nodeID = workScreen.getGraph().getSelectedCell().getID(); + getController().handleEvent(Event.APPLYRULE, rule, nodeID); + } + else { + setStatusText(Messages.getString("hoare", "view.cellSelectionError")); + } + } + + /** + * Returns the variable with the specified name. + * @param name name of the variable + * @return variable specified by the name + */ + protected Variable getVariable(String name) { + for (Variable v : getModel().getVariables()) { + if (v.getName().equals(name)) { + return v; + } + } + return null; + } + + /** + * Returns the two variables belonging to the specified VerifictaionFormula. + * @param vf the VerificationFormula + * @return an array variables with variables[0] being the variable of the pre assertion and variables[1] being the variable of the post assertion of the specified VerificationFormula + */ + protected Variable[] getVariables(VerificationFormula vf) { + if (vf==null) return new Variable[2]; + + + Variable[] variables = new Variable[2]; + variables[0] = getVariableForAssertion(vf.getPreAssertion(TextStyle.SHORT)); + variables[1] = getVariableForAssertion(vf.getPostAssertion(TextStyle.SHORT)); + return variables; + } + + /** + * Returns the variable belonging to the pre or post assertion of the speicified VerificationFormula. + * @param vf the VerificationFormula + * @param isPreAssertion if true the variable of the pre assertion is returned, if false the variable of the post assertion is returned + * @return the variable belonging to the pre or post assertion of the speicified VerificationFormula. + */ + protected Variable getVariable(VerificationFormula vf, boolean isPreAssertion) { + if (isPreAssertion) { + return getVariables(vf)[0]; + } + else { + return getVariables(vf)[1]; + } + } + + /** + * Returns the variable that is contained in the specified assertion + * @param assertionShort assertion String in the form that contains the variable name. + * @return the variable of the assertion + */ + protected Variable getVariableForAssertion(String assertionShort) { + for (Variable v : getVariablesSortedByLength()) { + if (assertionShort.indexOf(v.getName())!=-1) { + return v; + } + } + return null; + } + + /** + * Sorts all variables by length. + * @return the sorted collection of variables. + */ + private Collection getVariablesSortedByLength() { + + class VariableLengthComparator implements Comparator { + + public int compare(Variable o1, Variable o2) { + return o1.getName().length()-o2.getName().length(); + } + + } + + List var = new ArrayList(getModel().getVariables()); + Collections.sort(var, Collections.reverseOrder(new VariableLengthComparator())); + return var; + } + + /** + * KeyListener for DELETE Treeparts + */ + public void keyPressed(KeyEvent e) { + if ((e.getKeyCode()==KeyEvent.VK_DELETE || e.getKeyCode()==KeyEvent.VK_BACK_SPACE)) { + deletePart(); + } + } + + /** + * deletes a part of the tree, used by Keyevents and the DeletePart button + */ + public void deletePart(){ + if (workScreen.getGraph().getSelectedCell()!=null) { + getController().handleEvent(Event.DELETENODE, workScreen.getGraph().getSelectedCell().getID()); + getWorkScreen().getVar().initVariablesView(); + } else { + errorLabel.setText(Messages.getString("hoare","out.DeleteNodeFailed")); + } + } + + /** + * Is called when a key is released. + * @param e the key event + */ + public void keyReleased(KeyEvent e) { + + } + + /** + * Is called when a key is typed. + * @param e the key event + */ + public void keyTyped(KeyEvent e) { + + } + + /** + * Shows the {@link ConcreteFormulaEditor} to edit the specified {@link Variable}. + * @param variableName the {@link Variable} that is edited + */ + public void showFormulaEditor(final String variableName) { + if (editors.containsKey(variableName)) { + editors.get(variableName).toFront(); + } + else { + final Variable v = getVariable(variableName); + FormulaEditorObserver observer = new FormulaEditorObserver() { + class WarteThread extends Thread { + boolean run = true; + long time; + FormulaEditor editor; + public WarteThread(long time){ + this.time = time; + this.start(); + } + public void run(){ + try { + sleep(time); + } catch(InterruptedException e){ + return; + } + if( editor == null ) + return; + Enten enten = new Enten(); + if( enten == null ) + return; + ((ConcreteFormulaEditor)editor).setFormulaPreview(enten); + + while( run ){ + enten.repaint(); + try { + Thread.sleep(50); + } catch(InterruptedException e){ + return; + } + } + } + public void setEditor(FormulaEditor editor){ + this.editor = editor; + } + public void end(){ + run = false; + } + } + WarteThread warteThread = new WarteThread(15*60000); + + public void applyFormulaChange(FormulaEditor editor) { + ConcreteFormulaEditor e = (ConcreteFormulaEditor)editor; + int id = v.getVerificaitonId(); + VerificationFormula vf = getModel().getVerificationFormula(id); + if (vf.getPreAssertion(TextStyle.SHORT).indexOf(v.getName())!=-1) { + getController().handleEvent(Event.EDITPREASSERTION, e.getFormula(), id); + } + else { + getController().handleEvent(Event.EDITPOSTASSERTION, e.getFormula(), id); + } + } + public void formulaChanged(FormulaEditor editor) { + // do nothing + } + public void formulaEditorClosed(FormulaEditor editor) { + warteThread.interrupt(); + warteThread.end(); + editors.remove(v.getName()); + workScreen.getRules().validate(); + } + public void receiveParseMessage(FormulaEditor editor, String message) { + if( message == null ){ + warteThread.setEditor(editor); + return; + } + if (message == FormulaEditor.MESSAGE_OKAY) { + editor.removeParseMessage(); + } + else if (message == FormulaEditor.MESSAGE_ERROR) { + editor.setParseMessage(Messages.getString("hoare", "view.parseError")); + } + else { + editor.setParseMessage(message); + } + } + }; + ConcreteFormulaEditor editor = new ConcreteFormulaEditor(v.getName(), v.getAssertion(TextStyle.EDITOR)); + observer.receiveParseMessage(editor, null); + editor.setFont(getMainFont()); + editor.addFormulaEditorObserver(observer); + + FormulaViewer viewer = new FormulaViewer(editor.getFont(), v.getName()); + editor.setFormulaPreview(viewer); + viewer.setFormulaEditor(editor); + editors.put(variableName, editor); + } + } + + /** + * Parses the speicified source code. + * To be used by other classes belonging to the view. + * @param sourceCode the source code as a string + */ + public void parseSourceCode(String sourceCode) { + getWorkScreen().getGraph().setUnselected(); + getWorkScreen().getSource().makeNotEditable(); + try { + getController().handleEvent(Event.PARSECODE, sourceCode); + } + catch (Exception e) { // parsing failed + getWorkScreen().getSource().makeEditable(); + } + } + + /** + * Parses the speicified source code. + * To be used by other classes belonging to the view. + * @param sourceCodeFile file that contains the source code + */ + public void parseSourceCode(File sourceCodeFile) { + getWorkScreen().getGraph().setUnselected(); + getWorkScreen().getSource().makeNotEditable(); + try { + getController().handleEvent(Event.PARSECODE, sourceCodeFile); + } + catch (Exception e) { // parsing failed + getWorkScreen().getSource().makeEditable(); + } + } + + /** + * Loads source code from a file that will be specified by the user. + */ + public void loadSourceCode() { + JFileChooser fc = new JFileChooser(System.getProperty("user.dir") + + System.getProperty("file.separator") + "examples" + + System.getProperty("file.separator") + "hoare"); + fc.setFileFilter(new FileFilter() { + + @Override + public boolean accept(File f) { + if (f.getName().endsWith("c")) + return true; + if (f.isDirectory()) + return true; + return false; + } + + @Override + public String getDescription() { + return "*.c"; + } + + }); + + if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { // parsing succeeded + parseSourceCode(fc.getSelectedFile()); + } + } + + /** + * Loads a previously saved verification tree from a file that will be specified by the user. + */ + public void openTree() { + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + } + + /** + * Changes the global font size for the gui. + * @param fontSize the new font size + */ + public void setFontSize(int fontSize) { + mainFont = mainFont.deriveFont((float)fontSize); + sourceCodeFont = sourceCodeFont.deriveFont((float)fontSize); + String settingsString; + if (isBeamerMode) { + settingsString = "fontSize.beamer"; + } + else { + settingsString = "fontSize.normal"; + } + try { + Settings.setString("hoare", settingsString, String.valueOf(fontSize)); + } + catch (Exception e) { + e.printStackTrace(); + } + updateFont(); + } + + /** + * Updates the font of all children. + * + */ + public void updateFont() { + if (workScreen!=null) { + workScreen.updateFont(); + } + for (ConcreteFormulaEditor e : editors.values()) { + e.setFont(mainFont); + } + } + + /** + * Returns the global font for the gui. + * @return the global font for the gui. + */ + public Font getMainFont() { + return mainFont; + } + + /** + * Returns the source code font for the gui. + * @return the source code font for the gui. + */ + public Font getSourceCodeFont() { + return sourceCodeFont; + } + /** + * getter for graphMouseListener + * @return the graphMouseListener + */ + public GraphListener getGraphMouseListener(){ + return graphMouseListener; + } + /** + * shows success dialog + */ + @SuppressWarnings("deprecation") + public void showProveFinished() { + JOptionPane pane = new JOptionPane(Messages.getString("hoare", "allsuccessful")); + JDialog dialog = pane.createDialog(workScreen, "Success"); + dialog.show(); + } + /** + * functions grays the undo button or makes it colorful again + * @param gray + */ + public void grayUndo(boolean gray){ + if (undo!= null){ + undo.grayButton(gray); + } + } + /** + * functions grays the redo button or makes it colorful again + * @param gray + */ + public void grayRedo(boolean gray){ + if (undo!= null){ + redo.grayButton(gray); + } + } + + /** + * This Method performs the splitter to toggle between + * the visible and the invisible State. + * Note: The state is by default visible! + */ + public void toggleSplitter(){ + if (workScreen!=null){ + workScreen.toggleSplitter(); + workScreen.getGraph().beautifier(); + } + } + /** + * this function will reset the graph to the initial zoom + * it will test if the beamermode is on and ajust zoom to this + */ + public void resetZoom(){ + if(isBeamerMode) { + this.getWorkScreen().getGraph().setAbsolutZoomValueToMiddle(3); + } else { + this.getWorkScreen().getGraph().setAbsolutZoomValueToMiddle(0); + } + this.setZoomMode(ZoomMode.NO); + } + + +} diff --git a/src/org/jalgo/module/hoare/view/WSGraph.java b/src/org/jalgo/module/hoare/view/WSGraph.java new file mode 100644 index 0000000..b9fc05e --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WSGraph.java @@ -0,0 +1,813 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Point; + +import java.awt.Color; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Rule; +import org.jalgo.module.hoare.constants.Status; +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.model.Model; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jgraph.JGraph; +import org.jgraph.graph.AttributeMap; +import org.jgraph.graph.DefaultGraphCell; +import org.jgraph.graph.DefaultGraphModel; +import org.jgraph.graph.DefaultPort; +import org.jgraph.graph.GraphConstants; +import org.jgraph.graph.GraphLayoutCache; + +/** + * This is the Panel which shows the Graph using JGraph. + * All changes to the graph have to be in this class. + * + * @author Tomas + * + */ +public class WSGraph extends JPanel implements Observer { + + private static Color selectionColor = new Color(0,165,255); + private static final long serialVersionUID = 5704113904547903732L; + private JGraph graph = new JGraph(new DefaultGraphModel()); + private double zoom = 0; + private MyCell selected; + private MyCell opened; + private HashMap openedPos = new HashMap(); + private final View gui; + private ArrayList neueZellen = new ArrayList (); + + /** + * Starting the JPanel containing the the Graph + * @param View + * the controlling View to save it + * + */ + public WSGraph(View gui){ + super(); + this.gui = gui; + this.setLayout(new BorderLayout()); + + graph.setCloneable(true); + graph.setInvokesStopCellEditing(true); + graph.setJumpToDefaultPort(true); + graph.setSelectionEnabled(false); + graph.setDisconnectable(false); + graph.setEditable(false); + graph.setAntiAliased(true); + graph.getGraphLayoutCache().setFactory(new MyCellViewFactory()); + graph.addKeyListener(gui); + graph.addMouseListener(gui.getGraphMouseListener()); + graph.addMouseWheelListener(gui.getGraphMouseListener()); + graph.addMouseListener(gui.new CellPopupMenu()); + graph.setBounds(this.getBounds()); + + this.add(graph); + this.add(new JScrollPane(graph)); + + +} + /** + * the cell maker, which makes a cell + * with an color gradient, an ID, a Text and the level and positioning flag + *
          + * the Width and Height of a Cell is set 0 because the autosize function of jgraph will size the cells + * + * @param name + * the Text to be shown in the cell + * @param ID + * the ID of the Verification Formula, which the cell is representing. + * also used to find a specific cell in a Cell Array + * @param bg + * the background Gradient color of the cell + * @param pos + * the position of the cell in relation to his parent cell (1,0,-1) + * @param level + * the level the cell should be shown in the graph (for example: the root cell gets Level 0, the children of root Level 1) + * @return MyCell + * the made cell, but not inserted in jgraph yet + */ + private MyCell createCell(String name, int ID, Color bg, int pos, int level, boolean rounded) { + return createCell(name, ID, 1, 1, bg, pos, level, rounded); + } + + /** + * the real cell maker, which makes a cell on a specific position, + * with an color gradient, an ID, a Text and the level and positioning flag + *
          + * the Width and Height of a Cell is set 0 because the autosize function of jgraph will size the cells + * + * @param name + * the Text to be shown in the cell + * @param ID + * the ID of the Verification Formula, which the cell is representing. + * also used to find a specific cell in a Cell Array + * @param x + * the X coordinate of the cells position + * @param y + * the Y coordinate of the cells position + * @param bg + * the background Gradient color of the cell + * @param pos + * the position of the cell in relation to his parent cell (1,0,-1) + * @param level + * the level the cell should be shown in the graph (for example: the root cell gets Level 0, the children of root Level 1) + * @return MyCell + * the made cell, but not inserted in jgraph yet + */ + private MyCell createCell(String name, int ID, int x, int y, Color bg, int pos, int level, boolean rounded) { + + MyCell cell = new MyCell(name, ID, pos, level, rounded); + cell.setUserObject(VertexPanelFactory.getVertexPanel(gui, cell, getSelectedCell()==cell, false)); + + GraphConstants.setBounds(cell.getAttributes(),new Rectangle2D.Double(x, y, 0, 0)); + + GraphConstants.setAutoSize(cell.getAttributes(), true); + GraphConstants.setSelectable(cell.getAttributes(),false); + GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createLineBorder(Color.black)); + GraphConstants.setBorderColor(cell.getAttributes(), Color.black); + if (bg != null) {GraphConstants.setGradientColor(cell.getAttributes(), bg); + GraphConstants.setOpaque(cell.getAttributes(), true); + } + + DefaultPort port = new DefaultPort(); + cell.add(port); + port.setParent(cell); + + + return cell; + } + + /** + * the Edgemaker, which gets two cells and the label name and retruns the cell. + * the Edges will have a link to the parent and the child cell saved inside the edge. + * + * @param label + * the Edge Label written in the middle of an edge (keep empty if you don't want a label) + * @param source + * the Source Cell (parent) of the type MyCell + * @param target + * the Target Cell (child) of the type MyCell + * @return MyEdge + * the made edge, but not inserted in jgraph yet + */ + private MyEdge createEdge(MyCell source, MyCell target){ + + // Richtung ist ge�ndert + + MyEdge edge= new MyEdge(); + // source - target gewechselt + edge.setSource(target.addPort()); + edge.setTarget(source.addPort()); + // �nderung ende + edge.setSourceCell(source); + edge.setTargetCell(target); + GraphConstants.setLineEnd(edge.getAttributes(), GraphConstants.ARROW_SIMPLE); + edge.setUserObject(getEdgeText(source,target,TextStyle.SHORT)); + + GraphConstants.setOffset(edge.getAttributes(), new Point2D.Double(20, 0)); + + return edge; + } + /** + * this function was is supposed to give the EdgeText for an edge with two Cells of the MyCell type. + * The text will be the rule which was used. + * + * The function also finds cells which should be not rounded in the view and changes the preferences of the cell. + * + * @param source + * @param target + * @param style + * @return + */ + private String getEdgeText(MyCell source, MyCell target, TextStyle ts){ + VerificationFormula ziel =gui.getModel().getVerificationFormula(target.getID()); + return getEdgeText( ziel.getParent(), ziel , ts); + + } + + /** + * this function was is supposed to give the EdgeText for an edge with two Verification formulars. + * The text will be the rule which was used. + * + * The function also finds cells which should be not rounded in the view and changes the preferences of the cell. + * + * @param source + * @param target + * @param style + * @return + */ + private String getEdgeText(VerificationFormula source, VerificationFormula target, TextStyle style){ + String label=""; + + if (source!= null && target!= null){ + Rule rule = source.getAppliedRule(); + label = translateRule(rule); + } + + return label; + + } + + /** + * zooming the graph with e^(value/5) as function + * + * @param value + * zooming value is supposed to be 1 or -1 + * @param p + * point to which it should zoom + * @return true + * returns the success of the operation + */ + public boolean zoom(double value, Point2D p){ + this.zoom = zoom + (value/5); + double newScale = Math.exp(zoom); + + if ((newScale>=20 && value > 0) || (newScale<=0.2 && value < 0)) { + gui.setStatusText(Messages.getString("hoare", "view.zoomError")); + this.zoom = zoom - (value/5); + return false; + } else { + gui.setStatusText(""); + graph.setScale(newScale, p); + } + return true; + + } + + /** + * getter for Jgraph + * @return JGraph + */ + public JGraph getGraph(){ + return graph; + } + + /** + * function to select a cell, change the border color and notify the variable and source screen + * @param cell + * cell which should be selected + */ + public void setSelected(MyCell cell){ + if (selected != cell){ + if (selected != null) {setUnselected(); } + contractCell(); + selected=cell; + GraphConstants.setBorderColor(cell.getAttributes(), selectionColor); + GraphConstants.setBorder(cell.getAttributes(), BorderFactory.createLineBorder(selectionColor,1)); + + graph.getGraphLayoutCache().editCell(cell, cell.getAttributes()); + VertexPanelFactory.setSelected((JPanel)cell.getUserObject()); + gui.getWorkScreen().getVar().newCellSelected(cell); + gui.getWorkScreen().getSource().newCellSelected(cell); + } else { + expandCell(cell); + } + beautifier(); + } + + /** + * the selected Cell getter + * @return + */ + public MyCell getSelectedCell(){ + return selected; + } + + /** + * function to deselect a cell and reset all properies (border color, ...), + * notifies the variable and source screen + */ + public void setUnselected(){ + if (selected != null){ + GraphConstants.setBorder(selected.getAttributes(), BorderFactory.createLineBorder(Color.black)); + GraphConstants.setBorderColor(selected.getAttributes(), Color.black); + graph.getGraphLayoutCache().editCell(selected, selected.getAttributes()); + contractCell(); + VertexPanelFactory.setNotSelected((JPanel)selected.getUserObject()); + selected = null; + gui.getWorkScreen().getSource().cellsUnselected(); + gui.getWorkScreen().getVar().cellsUnselected(); + } + } + + /** + * function to bring cell in an order on the screen. + *
          + * function is used everytime when something was changed on the graph.
          + * it works is this order:
          + * 1. finding out how many levels there are and which one the root cell is (Level = 0)
          + * 2. getting maximum Width using the getMaxWidth function
          + * 3. painting the cells
          + */ + protected void beautifier(){ + + int minLevelHeight = 100, levelCount=0; + MyCell root = null; + Object[] cells = graph.getGraphLayoutCache().getCells(false, true, false, false); + + for (Object obj : cells) { + MyCell cell = (MyCell)obj; + levelCount = Math.max(cell.getLevel(), levelCount); + if (cell.getLevel() == 0) { root = cell;} + } + + if (root!= null){ + levelCount++; + int height = Math.max(this.getHeight(), minLevelHeight*(levelCount+1)); + double maxWidth= getMaxWidth(root)+30; + graph.getGraphLayoutCache().edit(setCellBounds(root, 0, Math.max(this.getWidth(), maxWidth), height, Math.round(height/(levelCount+1)),null)); + } + + } + + /** + * this function is used by the beautifier to get max Width
          + * you can give the root Cell and it will call itself in depth first (left - right - self) to get the width of the children, + * set a ratio, sum the Width and return the max(width of the cell or sum of width of the children) + * @param cell + * MyCell which should be the root + * @return + * the Max Width needed to paint the cell with all the children (without a cell overlaying an other) + */ + private double getMaxWidth(MyCell cell){ + + Object[] edges = DefaultGraphModel.getEdges(graph.getModel(), cell, true); + + switch(edges.length) { + case 1: + return Math.max(GraphConstants.getBounds(cell.getAttributes()).getWidth(), getMaxWidth(((MyEdge)edges[0]).getTargetCell())); + case 2: + double width1 = 0, width2 =0; + if (((MyEdge)edges[0]).getTargetCell().getPos() > 0){ + width1 = getMaxWidth(((MyEdge)edges[0]).getTargetCell()); + width2 = getMaxWidth(((MyEdge)edges[1]).getTargetCell()); + } else { + width2 = getMaxWidth(((MyEdge)edges[0]).getTargetCell()); + width1 = getMaxWidth(((MyEdge)edges[1]).getTargetCell()); + } + cell.setRatio(Math.round(100/((width1+width2)/width2))); + return Math.max(GraphConstants.getBounds(cell.getAttributes()).getWidth(), width1+width2); + } + return GraphConstants.getBounds(cell.getAttributes()).getWidth(); + } + + /** + * this function is used by the beautifier to paint the cells,
          + * it paints the cell in the middle of the (from-to) region, uses the ratio to divide the area and calls itself with the children Cells + * @param cell + * MyCell which should be the root + * @param from + * Point on the X axis where the area for this cell starts + * @param to + * Point on the X axis where the area for this cell ends + * @param height + * the height of the whole cell painting area + * @param levelHeight + * the level height ( area between the cells in Y Axis) + * @return + * a Map with all the changes on the Graph !!! the content of the map has to be given to Jgraph after calling this method, + * this method doesn't change the cell position in the graph directly - it just write the changes in the Map + */ + private Map setCellBounds(MyCell cell, double from, double to, int height, int levelHeight, Map special){ + HashMap nested = new HashMap(); + + long minusX = Math.round(GraphConstants.getBounds(cell.getAttributes()).getWidth()/2); + long minusY = Math.round(GraphConstants.getBounds(cell.getAttributes()).getHeight()/2); + + if (special==null){ + GraphConstants.setBounds(cell.getAttributes(), new Rectangle2D.Double((from + Math.round((to-from)/2))-minusX, (height-(levelHeight*(cell.getLevel()+1)))-minusY,0,0)); + } + nested.put(cell, cell.getAttributes()); + + + Object[] edges = DefaultGraphModel.getEdges(graph.getModel(), cell, true); + switch(edges.length) { + case 1: + nested.putAll(setCellBounds(((MyEdge)edges[0]).getTargetCell(), from, to, height, levelHeight, null)); + case 2: + int mitte = (int) Math.round(from + ((to-from)*cell.getRatio()/100)); + + HashMap specialNeu = null; + + for (Object edge : edges){ + MyCell zelle = ((MyEdge)edge).getTargetCell(); + if (zelle.getPos() == -1) nested.putAll(setCellBounds(zelle, from, mitte , height, levelHeight, specialNeu)); + if (zelle.getPos() == 1) nested.putAll(setCellBounds(zelle, mitte ,to, height, levelHeight, specialNeu)); + } + + default: break; + } + + + + return nested; + } + + /** + * paints the graph new (supposed to be called when the root VerificationFormula was changed) + * @param root + * VerificationFormula root + */ + private void paintNew(VerificationFormula root) { + + graph.setGraphLayoutCache(new GraphLayoutCache()); + graph.getGraphLayoutCache().setFactory(new MyCellViewFactory()); + if (root.isRuleApplied()){ + graph.getGraphLayoutCache().insert(cellPaint(root, 0, MyCell.setMiddle()).toArray()); + + MyCell se = selected; + MyCell ex = opened; + + setUnselected(); + + if (se != null) { + MyCell cell = getCell(se.getID()); + if (cell != null){ + setSelected(cell); + + if (ex != null && ex.equals(se)) setSelected(cell); + } + } + + } + } + + /** + * support function of paintNew(VerificationFormula) for recursive calls to paint the cells + * @param vf + * VerificationFormula on which the cell is based + * @param Level + * the Level the cell should be painted (root = 0, children of root =1, their children =2,...) + * @param seite + * the Position relative to the parent cell (-1 = left, 0 = middle , 1 = right) + * @return + * ArrayList of Cells which should be inserted in the graph (this function doesn't insert them into the graph) + */ + private ArrayList cellPaint(VerificationFormula vf, int Level, int seite){ + ArrayList list = new ArrayList(); + MyCell cell = createCell(getCellText(vf, false), vf.getId(), getNeededColor(vf), seite, Level, !vf.isImplication()); + list.add(cell); + + if (vf.hasChildren()){ + if (vf.getChildren().size()>1) { + if (vf.getChildren().get(0).isRuleApplied()){ + List a = cellPaint(vf.getChildren().get(0), Level+1, MyCell.setLeft()); + list.addAll(a); + list.add(createEdge(cell,(MyCell) a.get(0))); + + } + if (vf.getChildren().get(1).isRuleApplied()){ + List b = cellPaint(vf.getChildren().get(1), Level+1, MyCell.setRight()); + list.addAll(b); + list.add(createEdge(cell,(MyCell) b.get(0))); + + } + } else { + if (vf.getChildren().get(0).isRuleApplied()){ + List c = cellPaint(vf.getChildren().get(0), Level+1, MyCell.setMiddle()); + list.addAll(c); + list.add(createEdge( cell,(MyCell) c.get(0))); + + } + } + } + + return list; + } + + /** + * shows a cell in big with detailed information, might call the beautifier if the big cell moves out of the left border of the screen + * @param cell + * the cell which should be expanded + */ + public void expandCell(MyCell cell){ + + if (opened == null){ + opened=cell; + double openedH2 = GraphConstants.getBounds(opened.getAttributes()).getHeight()/2; + double openedW2 = GraphConstants.getBounds(opened.getAttributes()).getWidth()/2; + opened.setUserObject(VertexPanelFactory.getVertexPanel(gui, cell, (cell==getSelectedCell()), true)); + graph.getGraphLayoutCache().editCell(opened, opened.getAttributes()); + + openedPos.put("altX", GraphConstants.getBounds(opened.getAttributes()).getX()); + openedPos.put("neuX", (openedPos.get("altX"))-(GraphConstants.getBounds(opened.getAttributes()).getWidth()/2)+openedW2); + openedPos.put("altY", GraphConstants.getBounds(opened.getAttributes()).getY()); + openedPos.put("neuY", ((openedPos.get("altY"))-GraphConstants.getBounds(opened.getAttributes()).getHeight()/2)+openedH2); + + GraphConstants.setBounds(opened.getAttributes(), new Rectangle2D.Double(openedPos.get("neuX"),openedPos.get("neuY"), 0, 0)); + graph.getGraphLayoutCache().editCell(opened, opened.getAttributes()); + + + + beautifier(); + } + + } + + /** + * shows the graph in "normal-mode" if the cell was expanded before + * if the beautifier was used in expanding a Cell this function will use the beautifier as well + */ + public void contractCell(){ + + if (opened != null){ + VerificationFormula vf = gui.getModel().getVerificationFormula(opened.getID()); + opened.setUserObject(VertexPanelFactory.getVertexPanel(gui, opened, opened==getSelectedCell(), false)); + double x =openedPos.get("altX")+(GraphConstants.getBounds(opened.getAttributes()).getX()-openedPos.get("neuX")); + double y =openedPos.get("altY")+(GraphConstants.getBounds(opened.getAttributes()).getY()-openedPos.get("neuY")); + GraphConstants.setBounds(opened.getAttributes(), new Rectangle2D.Double(x,y, 0, 0)); + graph.getGraphLayoutCache().editCell(opened, opened.getAttributes()); + beautifier(); + openedPos.clear(); + Object[] edges = DefaultGraphModel.getEdges(graph.getModel(), opened, false); + if (edges.length>0) { + ((MyEdge)edges[0]).setUserObject(getEdgeText(vf.getParent(),vf, TextStyle.SHORT)); + graph.getGraphLayoutCache().editCell(((MyEdge)edges[0]), ((MyEdge)edges[0]).getAttributes()); + } + opened = null; + } + + } + + /** + * return the color, the VerificationFormula is supposed to be + * @param vf + * VerificationFormula that color we want to have + * @return + * Color of the VerificationFormula + */ + private Color getNeededColor(VerificationFormula vf){ + if (vf.getStatus() == Status.WAITING) {return Color.YELLOW;} + if (vf.getStatus() == Status.RESULTOK) {return Color.GREEN;} + if (vf.getStatus() == Status.RESULTWRONG) {return new Color(255,112,64);} + return Color.LIGHT_GRAY; + } + + /** + * returns the name of the differnet Rules how it is supposed to be shown + * @param rule + * the Enum rule we wnt to show + * @return + * String with the rule name (in english or german) + */ + private String translateRule(Rule rule){ + if (rule == null) return ""; + + switch(rule){ + case ASSIGN: return Messages.getString("hoare","rule.assign.desc"); + case IF: return Messages.getString("hoare","rule.alt1.desc"); + case IFELSE: return Messages.getString("hoare","rule.alt2.desc"); + case COMPOUND: return Messages.getString("hoare","rule.comp.desc"); + case STATSEQ: return Messages.getString("hoare","rule.sequence.desc"); + case ITERATION: return Messages.getString("hoare","rule.iter.desc"); + case STRONGPRE: return Messages.getString("hoare","rule.SV.desc"); + case WEAKPOST: return Messages.getString("hoare","rule.SN.desc"); + default: return ""; + } + + } + + /** + * finds the cell to an ID or returns null if Cell not found + * @param ID + * int ID we want to find (most times the ID of a VerificationFormula) + * @return + * MyCell with the ID or null + */ + private MyCell getCell(int ID){ + MyCell zelle = null; + Object[] cells = graph.getGraphLayoutCache().getCells(false, true, false, false); + + for (Object cell : cells){ + if (((MyCell)cell).getID() == ID) { zelle = (MyCell)cell; break;} + } + return zelle; + } + + /** + * changes cells properties or builds a List of cells which should be paint + * @param verificationFormula + * VerificationFormula which was changed + */ + private void changeCell(VerificationFormula vf) { + MyCell cell = getCell(vf.getId()); + if (cell != null){ + cell.setUserObject(VertexPanelFactory.getVertexPanel(gui, cell, cell==getSelectedCell(), cell==opened));//getCellText(vf, false)); + GraphConstants.setGradientColor(cell.getAttributes(), getNeededColor(vf)); + graph.getGraphLayoutCache().editCell(cell, cell.getAttributes()); + } else { + if (vf.isRuleApplied()){ + neueZellen.add(vf); + } + } + } + + /** + * paints new cells of the base of the List made in changeCell + * so, just call this function if you called changeCell(VerificationFormula ) before + */ + private void makeNewCells(){ + + ArrayList neu = new ArrayList(); + + while (!neueZellen.isEmpty()) { + + VerificationFormula vf= neueZellen.get(0); + VerificationFormula root= vf.getParent(); + if (root==null) throw new NullPointerException("root should not be null"); + MyCell rootCell = getCell(root.getId()); + if (rootCell==null) throw new NullPointerException("rootCell should not be null"); + + int position= 0; + if (root.getChildren().size()<2) {position = MyCell.setMiddle();} + else { + if (root.getChildren().get(0).equals(vf)) { + position = MyCell.setLeft(); + } else { + position = MyCell.setRight(); + } + } + MyCell cell = createCell( getCellText(vf, false), vf.getId(), getNeededColor(vf), position, rootCell.getLevel()+1, !vf.isImplication()); + neu.add(cell); + neu.add(createEdge(rootCell, cell)); + + neueZellen.remove(0); + } + if (!neu.isEmpty()){ + graph.getGraphLayoutCache().insert(neu.toArray()); + if (gui.getModel().getVerificationFormula(((MyCell) neu.get(0)).getID()).isImplication() && neu.size() > 2) { + setSelected((MyCell) neu.get(2)); + } else { setSelected((MyCell) neu.get(0)); } + } + neueZellen.clear(); + } + + /** + * gives a String which is supposed to be shown in the Cell of this VerificationFormula + * the boolean full discripes if the text should be in short or full mode + * @param vf + * VerificationFormula we want to show in the cell + * @param full + * true means the full text , false means the short form of the text + * @return + * String with the text to put into the cell User Object + */ + private String getCellText(VerificationFormula vf, boolean full){ + if (vf==null) throw new NullPointerException("Formula is null!"); + String userObject=""; + String resultPre=""; + String resultPost=""; + String format; + TextStyle style; + if (full){ + format="
          %s"+ + " {%s}
          %s
          {%s} %s
          "; + style=TextStyle.FULL; + }else{ + format="
          %s"+ + " {%s} %s {%s} %s
          "; + style=TextStyle.SHORT; + } + if (vf.getParent()!=null){ + Rule rule=vf.getParent().getAppliedRule(); + + if (Rule.IF.equals(rule)){ + if (full) { + resultPost="("+vf.getPreAssertion(style)+ + ") => "+vf.getParent().getPostAssertion(style)+")"; + resultPost=resultPost.replace("<", "<").replace(">", ">").replace("\u2227 ", "\u2227 \u00ac("); + resultPost="
          "+resultPost;} + else{ + resultPost="("+vf.getPreAssertion(style)+ + " => "+vf.getParent().getPostAssertion(style)+")"; + resultPost=resultPost.replace("<", "<").replace(">", ">"); + resultPost=resultPost.replace("\u03C0", "\u00ac\u03C0");} + + + } + + } + + String pre=vf.getPreAssertion(style); + pre=pre.replace("<", "<").replace(">", ">"); + String post=vf.getPostAssertion(style); + post=post.replace("<", "<").replace(">", ">"); + String source=vf.getCode(full); + source=source.replace("<", "<").replace(">", ">"); + userObject=String.format(format,resultPre,pre,source,post,resultPost); + return userObject; + + } + + /** + * function that gets information from View if something changed in the Model
          + * it splits the event : if root was changed then paintnew else change cells and make new Cells + */ + public void update(Observable o, Object arg) { + + VerificationFormula root = ((Model)o).getRoot(); + + if (root != null){ + + if (root.hasChanged()) { + paintNew(root); + } else { + ArrayList changes = getChanges(root); + for (VerificationFormula vf : changes){ + changeCell(vf); + } + makeNewCells(); + } + + beautifier(); + } else { + graph.setGraphLayoutCache(new GraphLayoutCache()); + graph.getGraphLayoutCache().setFactory(new MyCellViewFactory()); + this.setUnselected(); + } + + } + + /** + * function to get a list of changed VerificationFormula + * @param root + * the root VerificationFormula + * @return + * ArrayList of VerificationFormulas which been changed + */ + private ArrayList getChanges(VerificationFormula test){ + ArrayList changes = new ArrayList(); + if (test.getChildren()!=null){ + for (VerificationFormula a : test.getChildren()){ + changes.addAll(getChanges(a)); + } + } + if (test.hasChanged()&&test.isRuleApplied()) {changes.add(test);} + return changes; + } + + /** + * empty function, the graph is not supposed to get changed font + */ + public void updateFont() { + } + + /** + * with this function you can set the absolute zoom value "SCALE" of the jgraph + * as point it uses the middle of the graphArea + * @param newValue + */ + public void setAbsolutZoomValueToMiddle(double newValue){ + Point p = new Point(this.getWidth()/2, this.getHeight()/2); + + this.zoom = 0 + (newValue/5); + graph.setScale(Math.exp(zoom), p); + + } + + /** + * returns the actional font used in the graph + */ + public Font getFont() { + if (graph!=null) { + return graph.getFont(); + } + else { + return super.getFont(); + } + } + + /** + * getter for the expanded Cell + * @return + */ + public MyCell getOpened() { + return opened; + } + + /** + * setter for the expanded Cell but doesn't expand a cell itself, for this case you should use expandCell(MyCell) + * @param opened + */ + public void setOpened(MyCell opened) { + this.opened = opened; + } + + + +} diff --git a/src/org/jalgo/module/hoare/view/WSPart.java b/src/org/jalgo/module/hoare/view/WSPart.java new file mode 100644 index 0000000..9021923 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WSPart.java @@ -0,0 +1,149 @@ +package org.jalgo.module.hoare.view; + +import java.awt.Dimension; +import java.net.URL; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * Abstract super class of parts of the gui. + * It provides some useful functions. + * + * @author Antje + */ +public abstract class WSPart extends JPanel implements Observer { + + /** + * ID for getting settings and external strings. + */ + protected final String ID; + /** + * JLabel displaying the title + */ + protected final JLabel title; + + /** + * Creates a new instance of WSPart. + * @param id for getting settings and external strings. + */ + public WSPart(String id) { + ID = id; + title = new JLabel(Messages.getString("hoare", "name."+ID)); + title.setMinimumSize(new Dimension(0,0)); + } + + /** + * Updates the gui. + * This method is called when there is a change in the Model. + * @param o + * supposed to be the Model. + * @param arg + * supposed to be null. + */ + public void update(Observable o, Object arg) { + + } + + /** + * Returns the setting specified by the key. + * The actual key used is "view." + ID + key. + * @param key the string that identifies the setting. + * @return the setting as a string. + */ + protected String getSettingsString(String key) { + if (ID!=null) { + String value = ""; + try { + value = Settings.getString("hoare", "view."+ID+"."+key); + } + catch (Exception e) { + e.printStackTrace(); + } + return value; + } + return null; + } + + /** + * Sets the setting specified by the key to the specified value. + * @param key the string that identifies the setting. + * @param value the new value for the setting. + */ + protected void setSettingsString(String key, String value) { + if (ID!=null) { + try { + Settings.setString("hoare", "view."+ID+"."+key, value); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** + * Returns the setting specified by the key. + * The actual key used is "view." + ID + key. + * @param key the string that identifies the setting. + * @return the setting as a boolean. + */ + protected boolean getSettingsBoolean(String key) { + if (ID!=null) { + boolean value = false; + try { + value = Settings.getBoolean("hoare", "view."+ID+"."+key); + } catch (Exception e) { + e.printStackTrace(); + } + return value; + } + return false; + } + + /** + * Sets the setting specified by the key to the specified value. + * @param key the string that identifies the setting. + * @param value the new value for the setting. + */ + protected void setSettingsBoolean(String key, boolean value) { + if (ID!=null) { + try { + Settings.setBoolean("hoare", "view."+ID+"."+key, value); + } + catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** + * Returns the message specified by the key. + * The actual key used is "view." + ID + key. + * @param key the string that identifies the message. + * @return the message. + */ + protected String getMessage(String key) { + if (ID!=null) { + return Messages.getString("hoare", "view."+ID+"."+key); + } + return null; + } + + /** + * Returns the url specified by the key. + * The actual key used is "view." + ID + key. + * @param key the string that identifies the message. + * @return the url. + */ + protected URL getURL(String key) { + if (ID!=null) { + return Messages.getResourceURL("hoare", "view."+ID+"."+key); + } + return null; + } + +} diff --git a/src/org/jalgo/module/hoare/view/WSRule.java b/src/org/jalgo/module/hoare/view/WSRule.java new file mode 100644 index 0000000..5d6a73c --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WSRule.java @@ -0,0 +1,279 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.Font; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.Collection; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JViewport; +import javax.swing.Popup; +import javax.swing.PopupFactory; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.Rule; + +/** + * This is the Panel which shows the Rules you can use. + * + * @author Antje + * + */ +public class WSRule extends WSPart { + private static final long serialVersionUID = 1L; + + /** + * The gui controller. + */ + protected final View gui; + /** + * Collection of the rule views. + */ + protected Collection ruleViews = new ArrayList(); + + /** + * Creates a new instance of WSRule. + * @param gui the gui controller + */ + public WSRule(View gui){ + super("rules"); + this.gui = gui; + + setLayout(new BorderLayout()); + + Container rulesView = new JPanel(); + rulesView.setLayout(new GridLayout(8,1)); + ruleViews.add(new RuleView(Rule.ASSIGN, + Messages.getString("hoare", "name.assign"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.assign"))))); + ruleViews.add(new RuleView(Rule.COMPOUND, + Messages.getString("hoare", "name.comp"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.comp"))))); + ruleViews.add(new RuleView(Rule.IF, + Messages.getString("hoare", "name.alt1"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.alt1"))))); + ruleViews.add(new RuleView(Rule.IFELSE, + Messages.getString("hoare", "name.alt2"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.alt2"))))); + ruleViews.add(new RuleView(Rule.ITERATION, + Messages.getString("hoare", "name.iter"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.iter"))))); + ruleViews.add(new RuleView(Rule.STATSEQ, + Messages.getString("hoare", "name.sequence"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.sequence"))))); + ruleViews.add(new RuleView(Rule.STRONGPRE, + Messages.getString("hoare", "name.SV"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.SV"))))); + ruleViews.add(new RuleView(Rule.WEAKPOST, + Messages.getString("hoare", "name.SN"), + new JLabel(new ImageIcon(Messages.getResourceURL("hoare", "rule.SN"))))); + for (RuleView ruleView : ruleViews) { + rulesView.add(ruleView); + } + + JScrollPane scrollPane = new JScrollPane(); + JViewport viewp = new JViewport(); + viewp.setView(rulesView); + scrollPane.setViewport(viewp); + + add(title, BorderLayout.NORTH); + add(scrollPane, BorderLayout.CENTER); + + } + + /** + * Shows a single rule. + * @author Antje + * + */ + protected class RuleView extends JPanel { + + private static final long serialVersionUID = -8641308951811997611L; + + private RuleButton button; + + /** + * Creates a new instance of RuleView. + * @param rule rule that can be applied by this RuleView + * @param text description of the rule + */ + public RuleView(Rule rule, String text) { + init(text, new RuleButton(rule, text)); + } + + /** + * Creates a new instance of RuleView. + * @param rule rule that can be applied by this RuleView + * @param text description of the rule + * @param popup a more detailed preview of the rule + */ + public RuleView(Rule rule, String text, Component popup) { + init(text, new RuleButton(rule, text, popup)); + } + + /** + * Inits the RuleView. + * @param name description of the rule + * @param button applies the rule on click + */ + protected void init(String name, RuleButton button) { + this.button = button; + setLayout(new BorderLayout()); + add(button); + setText(name); + setFont(); + } + + /** + * Returns the text that describes the rule. + * @return the text that describes the rule + */ + public String getText() { + return button.getText(); + } + + /** + * Sets the text that describes the rule. + * @param name text that describes the rule + */ + public void setText(String name) { + button.setText(name); + } + + /** + * Sets the font to the global font of the gui. + * + */ + public void setFont() { + Font f = gui.getMainFont(); + button.setFont(f); + } + + } + + /** + * Button that applies a rule on click. + * @author Antje + * + */ + protected class RuleButton extends JButton { + + private static final long serialVersionUID = 7776645518236062545L; + + /** + * Rule that will be applied on click. + */ + protected final Rule rule; + /** + * The instance itself + */ + private final RuleButton ruleButtonMirror = this; + /** + * Factory for creating the popup with the rule preview + */ + private final PopupFactory popups; + /** + * Popup with a detailed preview of the rule. + */ + protected Popup popup; + /** + * Container for the rule preview + * This container together with its content will be shown in the popup. + */ + private Container popupContainer = new JPanel(new BorderLayout()); + + /** + * Creates a new button that can be used to apply the specified rule. + * @param ruleToApply rule that will be applied on click + */ + protected RuleButton(Rule ruleToApply) { + this.rule = ruleToApply; + + popups = new PopupFactory(); + + addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + gui.applyRule(rule); + } + }); + + addMouseListener(new MouseAdapter() { + public void mouseEntered(MouseEvent e) { + int posX = getPopupPosX((int)Math.round(ruleButtonMirror.getLocationOnScreen().getX())+e.getX()); + int posY = getPopupPosY((int)Math.round(ruleButtonMirror.getLocationOnScreen().getY())+e.getY()); + popup = popups.getPopup(ruleButtonMirror, popupContainer, posX, posY); + popup.show(); + } + public void mouseExited(MouseEvent e) { + popup.hide(); + } + }); + + } + + /** + * Creates a new button that can be used to apply the specified rule. + * @param rule rule that will be applied on click + * @param text short description of the rule + */ + public RuleButton(Rule rule, String text) { + this(rule); + setText(text); + } + + /** + * Creates a new button that can be used to apply the specified rule. + * @param rule rule that will be applied on click + * @param text short description of the rule + * @param popup detailed preview of the rule + */ + public RuleButton(Rule rule, String text, Component popup) { + this(rule, text); + popupContainer.add(popup); + } + + /** + * Returns the popup position on the screen in x direction. + * @param mousePosX the current mouse position in x direction + * @return the popup position on the screen in x direction + */ + private int getPopupPosX(int mousePosX) { + return mousePosX-(int)popupContainer.getPreferredSize().getWidth()-5; + } + + /** + * Returns the popup position on the screen in y direction. + * @param mousePosY the current mouse position in y direction + * @return the popup position on the screen in y direction + */ + private int getPopupPosY(int mousePosY) { + return mousePosY+5; + } + + } + + /** + * Sets the font to the global font of the gui. + * + */ + public void updateFont() { + title.setFont(gui.getMainFont().deriveFont(Font.BOLD)); + if (ruleViews!=null) { + for (RuleView ruleView : ruleViews) { + ruleView.setFont(); + } + } + } + +} diff --git a/src/org/jalgo/module/hoare/view/WSSource.java b/src/org/jalgo/module/hoare/view/WSSource.java new file mode 100644 index 0000000..bc95589 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WSSource.java @@ -0,0 +1,374 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Arrays; +import java.util.Observable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.JViewport; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Highlighter.HighlightPainter; + +import org.jalgo.module.hoare.constants.CodeDimension; +import org.jalgo.module.hoare.view.util.VariableSizeButton; + +/** + * This is the Panel which shows the c0 Programm. + * + * @author Antje + * + */ +public class WSSource extends WSPart { + private static final long serialVersionUID = -629213617627596386L; + + /** + * The newline symbol (either \n or \n\r) + */ + protected static final String NEW_LINE = System.getProperty("line.separator"); + + /** + * The gui controller. + */ + protected final View gui; + /** + * JScrollPane in which the scrollContainer is displayed. + */ + protected JScrollPane scrollPane; + /** + * The source code container. + */ + protected Container scrollContainer = new JPanel(); + /** + * JTextPane where the source code is shown and can be edited. + */ + protected JTextPane sourcePane; + /** + * Highlights the source code belonging to the selected cell in the sourcePane. + */ + protected HighlightPainter highlightPainter; + /** + * JButton for making the source code editable. + */ + protected JButton editButton; + /** + * JButton for parsing the source code. + */ + protected JButton parseButton; + /** + * JButton for setting the source code to the current source code from the model. + */ + protected JButton rereadButton; + /** + * JPanel for the parseButton and the rereadButton. + */ + protected JPanel buttonPanel; + /** + * true if the source code is editable, otherwise false. + */ + protected boolean editable = false; + + /** + * Creates a new instance of WSSource. + * @param gui the gui controller + */ + public WSSource(final View gui){ + super("source"); + this.gui = gui; + + this.setLayout(new BorderLayout()); + + sourcePane = new JTextPane(); + + highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY); + + editButton = new VariableSizeButton(0.2); + editButton.setText(getMessage("editButtonText")); + editButton.setToolTipText(getMessage("editButtonTTT")); + editButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + makeEditable(); + } + }); + + parseButton = new VariableSizeButton(0.2); + parseButton.setText(getMessage("parseButtonText")); + parseButton.setToolTipText(getMessage("parseButtonTTT")); + parseButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + if ((gui.getModel().getSource()==null)||(gui.getModel().getSource().equals(""))) { + gui.parseSourceCode(sourcePane.getText()); + } + else { + int choice = JOptionPane.showConfirmDialog(gui.getWorkScreen(), getMessage("confirmParsingMessage"), getMessage("confirmParsingMessageTitle"), JOptionPane.OK_CANCEL_OPTION); + if (choice==JOptionPane.OK_OPTION) { + makeNotEditable(); + gui.parseSourceCode(sourcePane.getText()); + } + } + } + }); + + rereadButton = new VariableSizeButton(0.2); + rereadButton.setText(getMessage("rereadButtonText")); + rereadButton.setToolTipText(getMessage("rereadButtonTTT")); + rereadButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + readSourceCode(); + } + }); + + buttonPanel = new JPanel(new BorderLayout()); + + scrollContainer.setLayout(new BorderLayout()); + scrollContainer.add(sourcePane, BorderLayout.CENTER); + + scrollPane = new JScrollPane(); + JViewport viewp = new JViewport(); + viewp.setView(scrollContainer); + scrollPane.setViewport(viewp); + + add(title, BorderLayout.NORTH); + add(scrollPane, BorderLayout.CENTER); + add(buttonPanel, BorderLayout.SOUTH); + + makeEditable(); + } + + /** + * Allows parsing. + * This includes showing the parseButton. + */ + protected void makeEditable() { + editable = true; + unhighlightSourceCode(); + sourcePane.setFocusable(true); + buttonPanel.removeAll(); + buttonPanel.add(parseButton, BorderLayout.NORTH); + buttonPanel.add(rereadButton, BorderLayout.SOUTH); + validate(); + } + + /** + * Disables parsing. + * This includes removing the parseButton. + */ + protected void makeNotEditable() { + editable = false; + sourcePane.setFocusable(false); + buttonPanel.removeAll(); + buttonPanel.add(editButton, BorderLayout.CENTER); + validate(); + } + + /** + * Sets the source code that is displayed to the new value + * @param sourceCode new source code to display + */ + public void setSourceCode(String sourceCode) { + sourcePane.setText(prepareSource(sourceCode)); + if (sourcePane.getText().equals("")) { + makeEditable(); + } else { + makeNotEditable(); + } + } + + /** + * Sets the source code that is displayed to the source code of the model + */ + public void readSourceCode() { + if (gui==null) return; + + String sourceCode = ""; + if (gui.getModel()!=null){ + sourceCode=gui.getModel().getSource(); + } + setSourceCode(sourceCode); + if ( (gui.getWorkScreen()!=null) && + (gui.getWorkScreen().getGraph().getSelectedCell()!=null) ) { + highlightSourceCode(gui.getWorkScreen().getGraph().getSelectedCell().getID()); + } + + } + + /** + * Returns the source code that is displayed at the moment + * @return the source code that is displayed at the moment + */ + public String getSourceCode() { + return extractSourceCode(sourcePane.getText()); + } + + /** + * Highlights the code belonging to the selected cell. + * Is called when a new cell is selected. + * @param cell the cell that has been selected + */ + public void newCellSelected(MyCell cell) { + highlightSourceCode(cell.getID()); + } + + /** + * Is called when all cells have been unselected. + */ + public void cellsUnselected() { + unhighlightSourceCode(); + } + + /** + * Highlights the code belonging to the specified verification formula. + * @param verificationFormulaID id of the verification formula + */ + public void highlightSourceCode(int verificationFormulaID) { + if (!editable) { + CodeDimension d = gui.getModel().getVerificationFormula(verificationFormulaID).getCode(); + int start = getNewCodePos(d.start); + int end = getNewCodePos(d.end)+1; + //"+1" because the position of the last letter is given, not the position after the last + sourcePane.getHighlighter().removeAllHighlights(); + try { + sourcePane.getHighlighter().addHighlight(start, end, highlightPainter); + } + catch (BadLocationException e) { + e.printStackTrace(); + } + } + } + + /** + * Unhighlights all source code. + */ + public void unhighlightSourceCode() { + sourcePane.getHighlighter().removeAllHighlights(); + } + + /** + * This method produces a {@link String} with the given number + * of space symbols.
          + * Note: If the parameter is less or equal zero the method return + * an empty String. + * @param i number of the space symbols to produce + * @return a new {@link String} filled with i space symbols + */ + private String praefix(int i){ + if (i>0){ + char[] result=new char[i]; + Arrays.fill(result,' '); + return new String(result); + } else { + return ""; + } + } + + /** + * Prepares the source code for displaying it. + * This includes adding line separators and indents to the source. + * @param source the source code to prepare + * @return the prepared source code + */ + protected String prepareSource(String source){ + //RegEx Style + String result=source; + result=result.replaceAll("[{]",NEW_LINE+"{"+NEW_LINE); + result=result.replaceAll("[;]",";"+NEW_LINE); + result=result.replaceAll("[}]","}"+NEW_LINE); + String[] temp=result.split(NEW_LINE); + result=""; + int indent=0; + for (int i=0;itrue
          until update(o, arg) is called for the first time, then false
          + * In the first update the source code should be read if none was entered yet, + * no matter if it is editable or not. This is necessary in case the model has + * been initialized in the mean time. + */ + private boolean firstUpdate = true; + + public void update(Observable o, Object arg) { + if (firstUpdate&&editable) { + if (getSourceCode().equals("")) { + readSourceCode(); + } + } + else if (!editable) { + readSourceCode(); + } + } + + /** + * Sets the font to the global font of the gui. + */ + public void updateFont() { + title.setFont(gui.getMainFont().deriveFont(Font.BOLD)); + sourcePane.setFont(gui.getSourceCodeFont()); + editButton.setFont(gui.getMainFont()); + parseButton.setFont(gui.getMainFont()); + rereadButton.setFont(gui.getMainFont()); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/WSVar.java b/src/org/jalgo/module/hoare/view/WSVar.java new file mode 100644 index 0000000..0ca38a1 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WSVar.java @@ -0,0 +1,451 @@ +package org.jalgo.module.hoare.view; + + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.HashMap; +import java.util.Map; +import java.util.Observable; + +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; + +import org.jalgo.module.hoare.constants.TextStyle; +import org.jalgo.module.hoare.model.Variable; +import org.jalgo.module.hoare.model.VerificationFormula; +import org.jalgo.module.hoare.view.formula.FormulaViewer; + +/** + * This is the Panel which shows the Variables. + * + * @author Antje + * + */ +public class WSVar extends WSPart { + + private static final long serialVersionUID = 1L; + + /** + * Color in which the pre asssertion of the selected verification formula is highlighted. + */ + protected static final Color HIGHLIGHT_COLOR_PRE = new Color(0, 128, 0); + /** + * Color in which the post assertion of the selected verification formula is highlighted. + */ + protected static final Color HIGHLIGHT_COLOR_POST = new Color(128, 0, 0); + /** + * Color in which the post assertion of the selected verification formula is highlighted. + */ + protected static final Color NO_HIGHLIGHT_COLOR = (new JLabel()).getForeground(); + + /** + * The instance itself. + */ + private WSVar mirror = this; + /** + * The gui controller. + */ + protected final View gui; + /** + * Container for the variableViews. + */ + private final Container variablesView; + /** + * Container for the variableViews showing the variables for the pre- and the postcondition of the selected node. + */ + private final Container selectedVariablesView; + /** + * Container for the selectedVariablesView. + */ + private final Container selectedPanel; + /** + * Map of the variable names to their VariableView. + */ + private Map variableViews = new HashMap(); + + /** + * Creates a new instance of WSVar. + * @param gui the gui controller + */ + public WSVar(View gui){ + super("variables"); + this.gui = gui; + + setLayout(new BorderLayout()); + + variablesView = new JPanel(null); + + selectedVariablesView = new JPanel(new GridLayout(2, 1)); + + class SelectedVariablesPanel extends JPanel { + + private static final long serialVersionUID = -1444312757194614155L; + + public SelectedVariablesPanel() { + super(new BorderLayout()); + } + + public void setFont(Font f) { + super.setFont(f); + if (selectedPanel!=null) { + int width = 1; + int height = 1; + for (int i=0; i0) { + height = (int)getComponent(0).getPreferredSize().getHeight(); + } + FormulaViewer dummy = new FormulaViewer(f); + dummy.initSize(); + setPreferredSize(new Dimension(width, height+dummy.getHeight()*2)); + setMaximumSize(getPreferredSize()); + } + } + + } + + selectedPanel = new SelectedVariablesPanel(); + JLabel selectedTitle = new JLabel(getMessage("selectedVariables")); + selectedTitle.setMinimumSize(title.getMinimumSize()); + selectedPanel.add(selectedTitle, BorderLayout.NORTH); + selectedPanel.add(selectedVariablesView, BorderLayout.SOUTH); + + add(title, BorderLayout.NORTH); + add(new JScrollPane(variablesView), BorderLayout.CENTER); + add(selectedPanel, BorderLayout.SOUTH); + } + + /** + * Highlights the variables belonging to the selected cell. + * Is called when a new cell is celected. + * @param cell the cell that has been selected + */ + public void newCellSelected(MyCell cell) { + initVariablesView(); + validate(); + repaint(); + } + + /** + * Unhighlights all variables. + * Is called when all cells have been unselected. + */ + public void cellsUnselected() { + initVariablesView(); + validate(); + repaint(); + } + + /** + * Shows one variable. + * @author antje + * + */ + protected class VariableView extends JPanel { + + /** + * serial Id need to make JPanel serializable + */ + private static final long serialVersionUID = 8680750215447522047L; + + /** + * Name of the variable that is shown. + */ + protected String name; + /** + * Shows the current value of the variable. + */ + protected Component content; + /** + * Listener for showing the appropriate FormulaEditor. + */ + private FormulaEditorShower formulaEditorShower = new FormulaEditorShower(); + /** + * true if the variable is highlighted, otherwise false. + */ + protected boolean highlighted = false; + + /** + * Creates a new view for the specified variable + * @param variableName name of the variable to display + * @param content value that always shows the content of the variable + */ + public VariableView(String variableName, Component content) { + this.content = content; + setVariableName(variableName); + setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + GridBagConstraints contentConstraints = new GridBagConstraints(1, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, c.insets, c.ipadx, c.ipady); + add(content, contentConstraints); + GridBagConstraints extraLabelConstraints = new GridBagConstraints(2, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, c.insets, c.ipadx, c.ipady); + add(new JLabel(), extraLabelConstraints); + content.addMouseListener(gui.new EditVariableListener(getVariableName())); + + setFont(); + + if (content instanceof FormulaViewer) { + ((FormulaViewer)content).initSize(); + setPreferredSize(content.getPreferredSize()); + setSize(getPreferredSize()); + } + } + + /** + * Returns the name of the variable the view is for. + * @return the name of the variable the view is for + */ + public String getVariableName() { + return name; + } + + /** + * Changes the name of the variable the view is for + * @param name new variable name + */ + protected void setVariableName(String name) { + this.name = name; + formulaEditorShower.setVariableName(this.name); + } + + /** + * Returns the component that displays the value of the variable. + * @return the component that displays the value of the variable + */ + public Component getContent() { + return content; + } + + /** + * Changes the component that displays the value of the variable. + * @param content new component that displays the value of the variable + */ + public void setContent(Component content) { + this.content = content; + } + + /** + * MouseListener that shows a FormulaEditor for the variable on a click event. + * @author antje + * + */ + private class FormulaEditorShower extends MouseAdapter { + private String variableName = ""; + /** + * Sets the name of the variable for the FormulaEditor. + * @param variableName + */ + public void setVariableName(String variableName) { + this.variableName = variableName; + } + public void mouseClicked(MouseEvent e) { + gui.showFormulaEditor(variableName); + } + } + + /** + * Highlights the VariableView as a pre assertion. + * + */ + public void highlightPre() { + highlight(HIGHLIGHT_COLOR_PRE); + } + + /** + * Highlights the VariableView as a post assertion. + * + */ + public void highlightPost() { + highlight(HIGHLIGHT_COLOR_POST); + } + + /** + * Highligths the VariableView with the specified color. + * @param color the highlight color + */ + public void highlight(Color color) { + highlighted = true; + setColor(color); + } + + /** + * Changes the color of the VariableView. + * @param color the new color + */ + public void setColor (Color color) { + if (content instanceof FormulaViewer) { + ((FormulaViewer)content).setColor(color); + } + else if (content instanceof JLabel) { + ((JLabel)content).setForeground(color); + } + } + + /** + * Unhighlights the VariableView. + * + */ + public void unhighlight() { + if (highlighted) { + setColor(getParent().getBackground()); + } + } + + /** + * Sets the font to the global font of the gui. + * + */ + public void setFont() { + Font f = gui.getMainFont(); + content.setFont(f); + } + + } + + public void update(Observable o, Object arg) { + initVariablesView(); + validate(); + repaint(); + } + + /** + * Removes all VariableViews. + * + */ + protected void clearVariablesView() { + variablesView.removeAll(); + variableViews.clear(); + } + + /** + * Shows the current variables of the model. + * Highlights the variables of the selected cell. + */ + protected void initVariablesView() { + //show all variables + clearVariablesView(); + for (Variable v : gui.getModel().getVariables()) { + initVariableView(v); + } + if (variableViews.size()>0) { + variablesView.setPreferredSize(new Dimension((int)variablesView.getPreferredSize().getWidth(), variableViews.size()*variablesView.getComponent(0).getHeight())); + } + highlightSelectedVariables(); + setVariablesViewPreferredSize(); + initSelectedVariablesView(); + } + + /** + * Creates a new VariableView for the specified variable + * @param v variable for the VariableView + */ + protected void initVariableView(Variable v) { + VariableView variableView = createVariableView(v); + variableView.setBounds(0, variableViews.size()*(int)variableView.getPreferredSize().getHeight(), (int)variableView.getPreferredSize().getWidth(), (int)variableView.getPreferredSize().getHeight()); + variableViews.put(v.getName(), variableView); + variablesView.add(variableView); + } + + /** + * Creates a new VariableView for the specified variable. + * @param v the variable + * @return the VariableView + */ + protected VariableView createVariableView(Variable v) { + Component content = new FormulaViewer(v.getAssertion(TextStyle.EDITOR), mirror.getFont(), v.getName()); + return new VariableView(v.getName(), content); + } + + /** + * Calculates and sets the preferred size of the variableView. + * + */ + protected void setVariablesViewPreferredSize() { + if (variableViews.size()>0) { + int width = 0; + for (VariableView v : variableViews.values()) { + width = Math.max(width, v.getWidth()); + } + variablesView.setPreferredSize(new Dimension(width, variablesView.getComponent(0).getHeight()*variableViews.size())); + } + } + + /** + * Shows the the varibles belonging to the pre- and postcondition of the selected cell (if any) and highlights them. + */ + protected void initSelectedVariablesView() { + if (gui.getWorkScreen().getGraph().getSelectedCell()!=null) { + selectedVariablesView.removeAll(); + + int id = gui.getWorkScreen().getGraph().getSelectedCell().getID(); + VerificationFormula vf = gui.getModel().getVerificationFormula(id); + Variable[] variables = gui.getVariables(vf); + if (variables[0]!=null) { + VariableView selectedPreVariableView = createVariableView(variables[0]); + selectedPreVariableView.highlightPre(); + selectedVariablesView.add(selectedPreVariableView); + } + if (variables[1]!=null) { + VariableView selectedPostVariableView = createVariableView(variables[1]); + selectedPostVariableView.highlightPost(); + selectedVariablesView.add(selectedPostVariableView); + } + } + else { + selectedVariablesView.removeAll(); + } + selectedPanel.setFont(gui.getMainFont()); + } + + /** + * Unhighlights all variables. + * + */ + protected void unhighlightAllVariables() { + for (VariableView v : variableViews.values()) { + v.unhighlight(); + } + } + + /** + * Highlights the variables of the selected cell. + * + */ + protected void highlightSelectedVariables() { + unhighlightAllVariables(); + MyCell selectedCell = gui.getWorkScreen().getGraph().getSelectedCell(); + if (selectedCell!=null) { + VerificationFormula vf = gui.getModel().getVerificationFormula(selectedCell.getID()); + Variable[] variables = gui.getVariables(vf); + if (!(variables[0]==null)) { + variableViews.get(variables[0].getName()).highlightPre(); + } + if (!(variables[1]==null)) { + variableViews.get(variables[1].getName()).highlightPost(); + } + } + } + + /** + * Sets the font to the global font of the gui. + * + */ + public void updateFont() { + title.setFont(gui.getMainFont().deriveFont(Font.BOLD)); + initVariablesView(); + validate(); + repaint(); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/WelcomeScreen.java b/src/org/jalgo/module/hoare/view/WelcomeScreen.java new file mode 100644 index 0000000..973e1bf --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WelcomeScreen.java @@ -0,0 +1,168 @@ +package org.jalgo.module.hoare.view; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * The Welcome Screen + * + * @author Tomas + * most things used from older Hoare version + * + *the welcomescreen is it's own mouseListener for the mouseover events + */ +public class WelcomeScreen extends JPanel implements MouseListener{ + + private static final long serialVersionUID = 1L; + public final static Color WELCOME_BACKGROUND = new Color(192, 32, 00); + private JLabel descriptionLabel; + private WelcomeScreenButton loadC0, newC0, loadTree; + + /** + * Costructor opens the JPanel + * @param View gui + */ + + public WelcomeScreen(final View gui) { + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + String lang = Settings.getString("main", "Language"); + + if (!lang.equals("de")) + lang = "en"; + ActionListener l = new ActionListener() { + public void actionPerformed(ActionEvent e) { + gui.init(); + if (e.getActionCommand().equals("openC0")) { + gui.loadSourceCode(); + } + else if (e.getActionCommand().equals("newC0")) {} + else if (e.getActionCommand().equals("openTree")) { + gui.openTree(); + } + + } + }; + loadC0 = new WelcomeScreenButton( new ImageIcon(Messages.getResourceURL("hoare", "icon.openC0Welcome0")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.openC0Welcome1")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.openC0WelcomeDesc_" + lang)), + "openC0", l, this); + + newC0 = new WelcomeScreenButton( new ImageIcon(Messages.getResourceURL("hoare", "icon.newWelcome0")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.newWelcome1")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.newWelcomeDesc_" + lang)), + "newC0", l, this); + + loadTree = new WelcomeScreenButton( new ImageIcon(Messages.getResourceURL("hoare", "icon.openWelcome0")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.openWelcome1")), + new ImageIcon(Messages.getResourceURL("hoare", "icon.openWelcomeDesc_" + lang)), + "openTree", l, this); + + descriptionLabel = new JLabel(); + descriptionLabel.setText(" "); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(WELCOME_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(loadC0); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(newC0); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(loadTree); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + } + +/** + * sets the description label + * @param Icon desc + */ + public void setDescription(Icon desc) { + descriptionLabel.setIcon(desc); + descriptionLabel.updateUI(); + } + +/* // aus altem Hoare, bis jetzt noch nicht gebraucht! + + public void setButtonsEnabled(boolean b) { + loadC0.setEnabled(b); + newC0.setEnabled(b); + if (!b) + setDescription(null); + } +*/ + /** + * paint function to set background + */ + protected void paintComponent(Graphics g) { + g.setColor(WELCOME_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + } + + /** + * empty, not needed + */ + public void mouseClicked(MouseEvent e) {} + + /** + * Causes the event source button to be displayed as seleced and to show the + * description string from the screen. + */ + public void mouseEntered(MouseEvent e) { + if (e.getSource() instanceof WelcomeScreenButton) { + WelcomeScreenButton source = (WelcomeScreenButton) e.getSource(); + if (!source.isEnabled()) + return; + source.setSelected(true); + setDescription(source.getDescription()); + } + } + + /** + * Causes the event source button to be displayed normally and to remove the + * description string from the screen. + */ + public void mouseExited(MouseEvent e) { + if (e.getSource() instanceof WelcomeScreenButton) { + ((WelcomeScreenButton) e.getSource()).setSelected(false); + setDescription(null); + } + } + + + /** + * empty, not needed + */ + public void mousePressed(MouseEvent e) { + // TODO Auto-generated method stub + + } + /** + * empty, not needed + */ + public void mouseReleased(MouseEvent e) { + // TODO Auto-generated method stub + + } +} diff --git a/src/org/jalgo/module/hoare/view/WelcomeScreenButton.java b/src/org/jalgo/module/hoare/view/WelcomeScreenButton.java new file mode 100644 index 0000000..29aa83d --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WelcomeScreenButton.java @@ -0,0 +1,69 @@ +package org.jalgo.module.hoare.view; + +import java.awt.Dimension; +import java.awt.event.ActionListener; +import java.awt.event.MouseListener; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +/** + * This is a JToggleButton to use on the welcomescreen. + * + * @author Tomas + * + */ +public class WelcomeScreenButton extends JToggleButton { + private static final long serialVersionUID = 1L; + + private final ImageIcon desc; + + /** + * @param ImageIcon defaulIcon + * Standard Icon + * @param ImageIcon rolloverIcon + * rollover Itcon + * @param ImageIcon description + * Description + * @param String actionCommand + * ActionComand + * @param ActionListener action + * ActionListener + * @param MouseListener mouse + * MouseListner + */ + public WelcomeScreenButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + ImageIcon description, String actionCommand, + ActionListener action, MouseListener mouse) { + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + desc = description; + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension(getIcon().getIconWidth(), getIcon() + .getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(mouse); + } + + /** + * returning the Icon + * + * @return ImageIcon + */ + + public ImageIcon getDescription() { + return desc; + } +} diff --git a/src/org/jalgo/module/hoare/view/WorkScreen.java b/src/org/jalgo/module/hoare/view/WorkScreen.java new file mode 100644 index 0000000..bad47c8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/WorkScreen.java @@ -0,0 +1,298 @@ +package org.jalgo.module.hoare.view; + +import java.awt.BorderLayout; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.Observable; +import java.util.Observer; + +import javax.swing.JPanel; +import javax.swing.JSplitPane; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Settings; +import org.jalgo.module.hoare.view.util.SplitPaneWithWorkingDividerLocationSetter; + +/** + * This is the master Panel of the workscreen which keeps the smaller Panels within. + * It also edits the size relations between the Panels. + * + * @author Tomas, Antje, Johannes + * + */ +public class WorkScreen extends JPanel implements Observer { + private static final long serialVersionUID = 1L; + + /** + * The gui controller. + */ + protected final View gui; + /** + * Shows all rules. + */ + private WSRule rules; + /** + * Shows the verification tree. + */ + private WSGraph graph; + /** + * Shows the source code. + */ + private WSSource source; + /** + * Shows a list of all variables. + */ + private WSVar var; + /** + * Seperates the graph from the rules, the source and the var. + */ + private JSplitPane mainSplitter, rightUpndownSplitter, rightLeftRightSplitter; + private boolean init = true; + /** + * Represents the visibility of the mainSplitter + */ + private boolean isVisible = true; + /** + * saves the relation of the mainSplitter + */ + private double mainRelation = 0.8; + + /** + * opens the JPanel + * @param gui + */ + public WorkScreen(View gui) { + super(); + this.gui = gui; + + this.rules = new WSRule(gui); + this.graph = new WSGraph(gui); + this.source = new WSSource(gui); + this.var = new WSVar(gui); + + this.setLayout(new BorderLayout()); + + rightLeftRightSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, rules, source); + rightUpndownSplitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, rightLeftRightSplitter, var); + + // width of splitter-line + rightLeftRightSplitter.setDividerSize(3); + rightUpndownSplitter.setDividerSize(3); + + // position of splitter-line + int leftRightLocation = 240; + int upndownLocation = 195; + try { + leftRightLocation = Integer.valueOf(Settings.getString("hoare", "workScreen.rightLeftRightSplitterLocation")); + } + catch (Exception e) { + e.printStackTrace(); + } + try { + upndownLocation = Integer.valueOf(Settings.getString("hoare", "workScreen.rightUpndownSplitterLocation")); + } + catch (Exception e) { + e.printStackTrace(); + } + rightUpndownSplitter.setDividerLocation(upndownLocation); + rightLeftRightSplitter.setDividerLocation(leftRightLocation); + + rightLeftRightSplitter.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange (PropertyChangeEvent changeEvent) { + if (changeEvent.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { + int location = rightLeftRightSplitter.getDividerLocation(); + try { + Settings.setString("hoare", "workScreen.rightLeftRightSplitterLocation", String.valueOf(location)); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + + rightUpndownSplitter.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange (PropertyChangeEvent changeEvent) { + if (changeEvent.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { + int location = rightUpndownSplitter.getDividerLocation(); + try { + Settings.setString("hoare", "workScreen.rightUpndownSplitterLocation", String.valueOf(location)); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + + + + mainSplitter = new SplitPaneWithWorkingDividerLocationSetter(JSplitPane.HORIZONTAL_SPLIT, this.graph, rightUpndownSplitter); + + mainSplitter.setDividerSize(3); + + this.add(mainSplitter); + + + double relation = 0.8; + try { + relation = Double.valueOf(Settings.getString("hoare", "workScreen.mainSplitterRelation"));//0.8; + } + catch (Exception e) { + e.printStackTrace(); + } + + mainSplitter.setDividerLocation(relation); + mainSplitter.setResizeWeight(relation); + + int graphweite = (int)Math.round(JAlgoGUIConnector.getInstance().getModuleComponent(gui.getMC()).getSize().getWidth()*(relation-0.1)); + int graphhoehe = (int)Math.round(JAlgoGUIConnector.getInstance().getModuleComponent(gui.getMC()).getSize().getHeight()); + graph.setSize(graphweite, graphhoehe); + + mainSplitter.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange (PropertyChangeEvent changeEvent) { + if (changeEvent.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { + double relation = (Double.valueOf(mainSplitter.getDividerLocation()))/(mainSplitter.getWidth()-mainSplitter.getDividerSize()); + try { + if (isVisible){ + //Sets this property only if the Splitter is visible + Settings.setString("hoare", "workScreen.mainSplitterRelation", String.valueOf(relation)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + + init = false; + } + + /** + * Rules Screen Getter + * @return the rules + */ + public WSRule getRules() { + return rules; + } + + /** + * Rules Screen Setter + * @param rules the rules to set + */ + public void setRules(WSRule rules) { + this.rules = rules; + } + + /** + * Graph Screen Getter + * @return the graph + */ + public WSGraph getGraph() { + return graph; + } + + /** + * Graph Screen Setter + * @param graph + */ + public void setGraph(WSGraph graph) { + this.graph = graph; + } + + /** + * Source Screen Getter + * @return the source + */ + public WSSource getSource() { + return source; + } + + /** + * Source Screen Setter + * @param source + */ + public void setSource(WSSource source) { + this.source = source; + } + + /** + * Variable Screen Getter + * @return the var + */ + public WSVar getVar() { + return var; + } + + /** + * Variable Screen Setter + * @param var + */ + public void setVar(WSVar var) { + this.var = var; + } + /** + * update method to give events from view to Screens below (Variable, Source, Graph, Rules Screen) + */ + public void update(Observable o, Object arg) { + try { + getRules().update(o, arg); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + try { + getSource().update(o, arg); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + try { + getVar().update(o, arg); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + try { + getGraph().update(o, arg); + } + catch (RuntimeException e) { + e.printStackTrace(); + } + } + + /** + * Updates the font in the Screens below (Variable, Source, Graph, Rules Screen). + */ + public void updateFont() { + if (!init) { + getSource().updateFont(); + getVar().updateFont(); + getRules().updateFont(); + getGraph().updateFont(); + } + } + + /** + * This Method changes the visibility of the + * Rules, Source and Variable view by toggling + * between visible and invisible.
          + * Note: This Method saves the old position + * of the Splitter and resets this position. + */ + public void toggleSplitter(){ + isVisible=!isVisible; + rightUpndownSplitter.setVisible(isVisible); + if (isVisible){ + mainSplitter.setDividerLocation(mainRelation); + mainSplitter.setResizeWeight(mainRelation); + } else { + mainRelation=(Double.valueOf(mainSplitter.getDividerLocation()))/(mainSplitter.getWidth()-mainSplitter.getDividerSize()); + mainSplitter.setDividerLocation(0); + } + //UpdateBorderLayout + this.validate(); + } + +} + + + diff --git a/src/org/jalgo/module/hoare/view/formula/CVS/Entries b/src/org/jalgo/module/hoare/view/formula/CVS/Entries new file mode 100644 index 0000000..c7f5677 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/CVS/Entries @@ -0,0 +1,7 @@ +/ConcreteFormulaEditor.java/1.1/Wed Aug 27 13:02:55 2008// +/Enten.java/1.1/Wed Aug 27 13:02:55 2008// +/FormulaEditor.java/1.1/Wed Aug 27 13:02:54 2008// +/FormulaEditorObserver.java/1.1/Wed Aug 27 13:02:53 2008// +/FormulaViewer.java/1.1/Wed Aug 27 13:02:54 2008// +/Symbols.java/1.1/Wed Aug 27 13:02:54 2008// +/package-info.java/1.1/Wed Aug 27 13:02:53 2008// diff --git a/src/org/jalgo/module/hoare/view/formula/CVS/Repository b/src/org/jalgo/module/hoare/view/formula/CVS/Repository new file mode 100644 index 0000000..0ad9bf4 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/view/formula diff --git a/src/org/jalgo/module/hoare/view/formula/CVS/Root b/src/org/jalgo/module/hoare/view/formula/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.java b/src/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.java new file mode 100644 index 0000000..8b3a3fb --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/ConcreteFormulaEditor.java @@ -0,0 +1,593 @@ +package org.jalgo.module.hoare.view.formula; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextPane; +import javax.swing.border.LineBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; + +/** + * Concrete editor for formulas. + * @author Antje + * + */ +public class ConcreteFormulaEditor extends JFrame implements FormulaEditor { + + private static final long serialVersionUID = 7986457509356594920L; + + /** + * Array of all special characters needed in formulas. + */ + protected static final String[] SYMBOLS = { + Symbols.SYMBOL_AND, + Symbols.SYMBOL_OR, + Symbols.SYMBOL_NOT, + Symbols.SYMBOL_SUM, + Symbols.SYMBOL_PROD, + Symbols.SYMBOL_ABS+"x"+Symbols.SYMBOL_ABS, + Symbols.SYMBOL_LN, + Symbols.SYMBOL_EXP, + "x^y", + Symbols.SYMBOL_SQRT, + "()" + }; + + /** + * Background color of the formula preview if there is a parse error for the formula. + */ + protected static final Color ERROR_COLOR = new Color(255, 150, 150); + /** + * Map that specifies for each entry of SYMBOLS which string should be inserted into the editor before the selected text. + */ + private static final Map SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT = new HashMap(); + /** + * Map that specifies for each entry of SYMBOLS which string should be inserted into the editor after the selected text. + */ + private static final Map SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT = new HashMap(); + /** + * Map that specifies for each entry of SYMBOLS if the selected text should be added between SYMBOL_REPLACEMENTS_REVERSE_BEFORE_TEXT and SYMBOL_REPLACEMENT_REVERSE_AFTER_TEXT. + */ + private static final Map SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT = new HashMap(); + /** + * Map that specifies for each entry of SYMBOLS if the selected text should be added, but there is none there, the default text will be added instead. + */ + private static final Map SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT = new HashMap(); + + static { + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_AND, "&&"); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_OR, "||"); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_NOT, "!"); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_SUM, "Sum("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_PROD, "Product("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_ABS+"x"+Symbols.SYMBOL_ABS, "abs("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_LN, "ln("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_EXP, "exp("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put("x^y", "^"); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put(Symbols.SYMBOL_SQRT, "sqrt("); + SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.put("()", "("); + + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_AND, ""); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_OR, ""); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_NOT, ""); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_SUM, ", var, start, end)"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_PROD, ", var, start, end)"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_ABS+"x"+Symbols.SYMBOL_ABS, ")"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_LN, ")"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_EXP, ")"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put("x^y", ""); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put(Symbols.SYMBOL_SQRT, ")"); + SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.put("()", ")"); + + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_AND, false); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_OR, false); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_NOT, false); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_SUM, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_PROD, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_ABS+"x"+Symbols.SYMBOL_ABS, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_LN, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_EXP, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put("x^y", false); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put(Symbols.SYMBOL_SQRT, true); + SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.put("()", true); + + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_AND, ""); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_OR, ""); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_NOT, ""); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_SUM, "expr"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_PROD, "expr"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_ABS+"x"+Symbols.SYMBOL_ABS, "x"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_LN, "x"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_EXP, "x"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put("x^y", ""); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put(Symbols.SYMBOL_SQRT, "x"); + SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.put("()", ""); + } + + /** + * Collection of observers observing the editor. + */ + protected final Collection formulaEditorObservers = new ArrayList(); + /** + * Name of the variable that is edited. + */ + protected final String variableName; + /** + * Value of the variable. + */ + protected String formula; + /** + * Panel for the symbol buttons. + */ + protected final JPanel buttonPanel; + /** + * Text field for editing the value of the variable + */ + protected final JTextPane textField; + /** + * Container in which the preview of the value is shown. + */ + protected Container previewContainer = new JPanel(new BorderLayout()); + /** + * Label that shows parse error messages. + */ + protected JLabel errorLabel = new JLabel(); + /** + * Button to apply the change of the value of the variable. + */ + protected JButton applyButton; + /** + * The instance of ConcreteFormulaEditor itself. + */ + private final ConcreteFormulaEditor mirror = this; + + /** + * Creates a new editor for the variable with the specified name and the specified formula as initial value for the variable + * @param variableName name of the variable + * @param initialFormula initial value of the variable + */ + public ConcreteFormulaEditor(String variableName, String initialFormula) { + super(); + this.variableName = variableName; + String title = Messages.getString("hoare", "view.editVariable"); + title = title.replaceAll("[$]Var", this.variableName); + setTitle(title); + this.setAlwaysOnTop(true); + getContentPane().setLayout(new BorderLayout()); + + JPanel mainPanel = new JPanel(new BorderLayout()); + getContentPane().add(mainPanel); + + // symbol button bar + buttonPanel = new JPanel(); + buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); + for (int i=0;iConcreteFormulaEditor
          is closed. + */ + private void close() { + try { + if (getState()==JFrame.MAXIMIZED_BOTH) { + Settings.setBoolean("hoare", "formulaEditor.maximized", true); + } + else { + Settings.setBoolean("hoare", "formulaEditor.maximized", false); + Point loc = getLocationOnScreen(); + Settings.setString("hoare", "formulaEditor.left", String.valueOf(loc.x)); + Settings.setString("hoare", "formulaEditor.top", String.valueOf(loc.y)); + Settings.setString("hoare", "formulaEditor.width", String.valueOf(getWidth())); + Settings.setString("hoare", "formulaEditor.height", String.valueOf(getHeight())); + } + } + catch (Exception e) { + e.printStackTrace(); + } + notifyFormulaEditorObserversClose(); + } + + /** + * Returns the name of the variable that is edited. + * @return the name of the varialbe that is edited. + */ + public String getVariableName() { + return variableName; + } + + /** + * Returns the current value of the variable. + * @return the current value of the variable + */ + public String getFormula() { + return getExternalString(formula); + } + + /** + * Sets the value of the variable to the specified String. + * @param formula the new value of the variable. + */ + public void setFormula(String formula) { + this.formula = getInternalString(formula); + textField.setText(this.formula); + if (FormulaViewer.isParsable(getFormula())) { + applyButton.setEnabled(true); + } + else { + applyButton.setEnabled(false); + } + } + + /** + * Change the component the displays the preview of the current value of the variable. + * @param preview new component for displaying the preview of the current value of the variable + */ + public void setFormulaPreview(Component preview) { + previewContainer.removeAll(); + previewContainer.add(preview, BorderLayout.CENTER); + validate(); + } + + /** + * Button that can be used to insert special characters into the formula. + * @author Antje + * + */ + protected class SymbolButton extends JButton { + + private static final long serialVersionUID = -5734541550815247050L; + + /** + * Creates a new button for inserting special characters into the formula. + * @param symbol special character that will be inserted + */ + public SymbolButton(final String symbol) { + setText(symbol); + addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + addTextAtCaret(SYMBOL_REPLACEMENTS_REVERSE_IN_FRONT_OF_SELECTED_TEXT.get(symbol), SYMBOL_REPLACEMENTS_REVERSE_AFTER_SELECTED_TEXT.get(symbol), SYMBOL_REPLACEMENTS_REVERSE_ADD_SELECTED_TEXT.get(symbol), SYMBOL_REPLACEMENTS_REVERSE_DEFAULT_TEXT.get(symbol)); + textField.grabFocus(); + } + }); + } + + } + + /** + * Sets the font for this formula editor. + * @param font the desired Font for this formula editor + */ + public void setFont(Font f) { + super.setFont(f); + textField.setFont(f); + applyButton.setFont(f); + for (Component c : buttonPanel.getComponents()) { + c.setFont(f); + } + for (int i=0; i(formulaEditorObservers)) { + observer.formulaChanged(this); + } + } + + /** + * Notifies all observers that the change of the value of the variable is supposed to be applied. + * + */ + protected void notifyFormulaEditorObserversApply() { + for (FormulaEditorObserver observer : new ArrayList(formulaEditorObservers)) { + observer.applyFormulaChange(this); + } + } + + /** + * Notifies all observers that the editor is closed. + * + */ + protected void notifyFormulaEditorObserversClose() { + for (FormulaEditorObserver observer : new ArrayList(formulaEditorObservers)) { + observer.formulaEditorClosed(this); + } + } + + /** + * Notifies all observers that the variable value has been parsed. + * The message may be one of the constant messages specified in FormulaEditor. + * @param message String that describes wether there was an error. + */ + protected void notifyFormulaEditorObserversParseMessage(String message) { + for (FormulaEditorObserver observer : new ArrayList(formulaEditorObservers)) { + observer.receiveParseMessage(this, message); + } + } + + public void receiveParseMessage(String message) { + notifyFormulaEditorObserversParseMessage(message); + } + + public void removeParseMessage() { + Color normalColor = getBackground(); + previewContainer.setBackground(normalColor); + for (int i=0; itrue the selected text is added between beforeText and afterText, otherwise the selected text is deleted + * @param defalutText is used as selected text for inserting if no text is selected and addSelectedText is true + */ + protected void addTextAtCaret(String frontText, String backText, boolean addSelectedText, String defaultText) { + String selectedText = textField.getSelectedText(); + String text = frontText; + if (addSelectedText) { + if (selectedText!=null) { + text = text + selectedText; + } + else { + text = text + defaultText; + } + } + text = text + backText; + int caret = deleteSelected(); + String formula = this.formula; + formula = formula.substring(0, caret)+ + text+ + formula.substring(caret); + setFormula(formula); + // if the selected text should be added inside, but there is none there, select the standard text, as the user is likely to delete it immediately + if (addSelectedText & (selectedText==null)) { + caret = caret + frontText.length(); + textField.setSelectionStart(caret); + caret = caret + defaultText.length(); + textField.setSelectionEnd(caret); + } + // if there can't be added text, simply put the cursor at the end + else { + caret = caret + text.length(); + textField.setCaretPosition(caret); + } + notifyFormulaEditorObserversChange(); + } + + /** + * Deletes the selected text in the text field. + * @return the new position of the caret + */ + protected int deleteSelected() { + String formula = this.formula; + int caret = textField.getCaretPosition(); + int selStart = textField.getSelectionStart(); + int selEnd = textField.getSelectionEnd(); + if (selStart!=selEnd) { + formula = formula.substring(0, selStart)+ + formula.substring(selEnd, formula.length()); + setFormula(formula); + return selStart; + } + return caret; + } + + /** + * Expressions that are replaced + */ + private static final String[] REPLACE_REGEX = { + "==", + "<=", + ">=", + "!=", + "=", + Symbols.SYMBOL_LE, + Symbols.SYMBOL_GE, + Symbols.SYMBOL_NOT + }; + + /** + * Replacements for expressions in REPLACE_REGEX + */ + private static final String[] REPLACE_WITH = { + "**only use = not ==**", + Symbols.SYMBOL_LE, + Symbols.SYMBOL_GE, + Symbols.SYMBOL_NOT, + "==", + "<=", + ">=", + "!=" + }; + + /** + * Returns another representation of the specified formula in the format other classes see it. + * Replaces substrings with the matching REPLACE_REGEX with REPLACE_WITH. + * @param formula original String + * @return the String representation of the formula as other classes see it. + */ + private static String getExternalString(String str) { + String newStr = str; + for (int i=0;i Xs; + private static final long serialVersionUID = -1; + + public Enten(){ + try { + entenImage = ImageIO.read(Messages.getResourceURL("hoare","icon.duck")); + } catch(IOException e){ + return; + } + Xs = new ArrayList(); + Xs.add(Integer.valueOf(-entenImage.getWidth(null))); + } + + public void paint(Graphics g){ + if( entenImage == null ) + return; + + int i = 0; + for( int x : Xs ){ + g.drawImage(entenImage, entenImage.getWidth(null)+x, 0, 0, entenImage.getHeight(null), 0, 0, entenImage.getWidth(null)+x, entenImage.getHeight(null), null); + x++; + Xs.set(i, x); + i++; + } + if( Xs.get(Xs.size()-1) >= (entenImage.getWidth(null)/2) ){ + Xs.add(-entenImage.getWidth(null)-(((Double)(Math.random()*1000)).intValue()%40)); + } + if( Xs.get(0)-entenImage.getWidth(null) > g.getClipBounds().width ){ + Xs.remove(0); + } + ((Graphics2D) g).setPaint(new GradientPaint(0,g.getClipBounds().height-(g.getClipBounds().height - entenImage.getHeight(null)), new Color(0.5f, 0.5f, 1f), 0, g.getClipBounds().height, Color.BLUE)); + ((Graphics2D) g).fillRect(0, g.getClipBounds().height-(g.getClipBounds().height - entenImage.getHeight(null) + 3), g.getClipBounds().width, g.getClipBounds().height); + } +} diff --git a/src/org/jalgo/module/hoare/view/formula/FormulaEditor.java b/src/org/jalgo/module/hoare/view/formula/FormulaEditor.java new file mode 100644 index 0000000..45b0c49 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/FormulaEditor.java @@ -0,0 +1,56 @@ +package org.jalgo.module.hoare.view.formula; + +/** + * Editor for formulas. + * @author Antje + * + */ +public interface FormulaEditor { + + /** + * Standard parse message: No error occured while parsing. + */ + static final String MESSAGE_OKAY = "okay"; + /** + * Standard parse message: An error occured while parsing. + */ + static final String MESSAGE_ERROR = "error"; + + /** + * Returns the current formula. + * @return the current formula + */ + String getFormula(); + + /** + * Accepts a message from the parser. + * The message received may be one of the standard messages MESSAGE_OKAY and MESSAGE_ERROR. + * @param message the message from the parser. + */ + void receiveParseMessage(String message); + + /** + * Displays the specified message + * @param message the parse message to display. + */ + void setParseMessage(String message); + + /** + * Removes the display of the parse message if any is displayed. + * + */ + void removeParseMessage(); + + /** + * Adds a FormulaEditorObserver. + * @param observer new observer of the FormulaEditor + */ + void addFormulaEditorObserver(FormulaEditorObserver observer); + + /** + * Removes a FormulaEditorObserver. + * @param observer the FormulaEditorObserver to be removed + */ + void removeFormulaEditorObserver(FormulaEditorObserver observer); + +} diff --git a/src/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.java b/src/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.java new file mode 100644 index 0000000..1c2a1f1 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/FormulaEditorObserver.java @@ -0,0 +1,35 @@ +package org.jalgo.module.hoare.view.formula; + +/** + * Observer for FormulaEditors. + * @author Antje + * + */ +public interface FormulaEditorObserver { + + /** + * Is called when the formula is changed. + * @param editor FormulaEditor where the change happened. + */ + void formulaChanged(FormulaEditor editor); + + /** + * Is called when the FormulaEditor receives a parse message from the parser. + * @param editor the FormulaEditor that received the parse message + * @param message the parse message that is received. + */ + void receiveParseMessage(FormulaEditor editor, String message); + + /** + * Is called when a change of the formula should be applied. + * @param editor the FormulaEditor that requested the application. + */ + void applyFormulaChange(FormulaEditor editor); + + /** + * Is called when a FormulaEditor is closed. + * @param editor the FormulaEditor that is closed. + */ + void formulaEditorClosed(FormulaEditor editor); + +} diff --git a/src/org/jalgo/module/hoare/view/formula/FormulaViewer.java b/src/org/jalgo/module/hoare/view/formula/FormulaViewer.java new file mode 100644 index 0000000..4d441a5 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/FormulaViewer.java @@ -0,0 +1,1348 @@ +package org.jalgo.module.hoare.view.formula; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; + +import javax.swing.JLabel; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.constants.ParserAccess; +import org.nfunk.jep.ASTConstant; +import org.nfunk.jep.ASTFunNode; +import org.nfunk.jep.ASTStart; +import org.nfunk.jep.ASTVarNode; +import org.nfunk.jep.Node; +import org.nfunk.jep.Operator; +import org.nfunk.jep.OperatorSet; +import org.nfunk.jep.ParseException; + +/** + * Renders formulas and displays them in a JPanel. + * @author Antje + * + */ +public class FormulaViewer extends JLabel { + private static final long serialVersionUID = -3573478356628706956L; + + /** + * Possible positions for text. + * SUPER means superscript, + * NORMAL means normal script, + * and SUB means subscript. + * @author Antje + * + */ + protected enum YPos { + /** + * higher than super script (e.g. over a sum or product symbol) + */ + SUPERSUPER, + /** + * super script + */ + SUPER, + /** + * normal script + */ + NORMAL, + /** + * sub script + */ + SUB, + /** + * lower than sub script (e.g. under a sum or product symbol) + */ + SUBSUB, + /** + * lowest possible position (used to determine the height of the component) + */ + MAX + } + + /** + * Set of all operators. + */ + protected static final OperatorSet operatorSet = new OperatorSet(); + /** + * String for an opening bracket. + */ + protected static final String BRACKET_OPEN = "("; + /** + * String for a closing bracket. + */ + protected static final String BRACKET_CLOSE = ")"; + /** + * Array of all possible unary operators. + */ + protected static final String[] UNARY_OPERATORS = { + operatorSet.getNot().getName(), + operatorSet.getUMinus().getName() + }; + /** + * Array of all possible binary operators. + */ + protected static final String[] BINARY_OPERATORS = { + operatorSet.getAssign().getName(), + operatorSet.getEQ().getName(), + operatorSet.getNE().getName(), + operatorSet.getGT().getName(), + operatorSet.getGE().getName(), + operatorSet.getLT().getName(), + operatorSet.getLE().getName(), + operatorSet.getAdd().getName(), + operatorSet.getSubtract().getName(), + operatorSet.getMultiply().getName(), + operatorSet.getDivide().getName(), + operatorSet.getMod().getName(), + operatorSet.getPower().getName(), + operatorSet.getAnd().getName(), + operatorSet.getOr().getName() + }; + /** + * Array of all possible binary operators that don't require brackets. + */ + protected static final String[] BINARY_OPERATORS_WITHOUT_BRACKETS = { + operatorSet.getAnd().getName(), + operatorSet.getAssign().getName(), + operatorSet.getEQ().getName(), + operatorSet.getNE().getName(), + operatorSet.getGT().getName(), + operatorSet.getGE().getName(), + operatorSet.getLT().getName(), + operatorSet.getLE().getName() + }; + /** + * Array of all possible unary functions. + */ + protected static final String[] UNARY_FUNCTIONS = { + "abs", + "ln", + "exp", + "sqrt" + }; + /** + * Array containing the functions sum and product. + */ + protected static final String[] SUM_OR_PROD = { + "Sum", + "Product" + }; + /** + * Priority order for all operators and functions (starting with the highest priority). + */ + protected static final String[] PRIORITY = { + operatorSet.getPower().getName(), + "sqrt", + operatorSet.getDivide().getName(), + operatorSet.getMultiply().getName(), + operatorSet.getMod().getName(), + "Product", + operatorSet.getSubtract().getName(), + operatorSet.getAdd().getName(), + "Sum", + operatorSet.getUMinus().getName(), + "ln", + "abs", + operatorSet.getLT().getName(), + operatorSet.getLE().getName(), + operatorSet.getGT().getName(), + operatorSet.getGE().getName(), + operatorSet.getEQ().getName(), + operatorSet.getAssign().getName(), + operatorSet.getNE().getName(), + operatorSet.getNot().getName(), + operatorSet.getAnd().getName(), + operatorSet.getOr().getName() + }; + /** + * List of all binary operators that are not assciative + */ + protected static final String[] NOT_ASSOCIATIVE = { + operatorSet.getPower().getName(), + operatorSet.getDivide().getName(), + operatorSet.getSubtract().getName(), + }; + + /** + * Graphics where the formula is displayed. + */ + protected Graphics2D g; + /** + * Image of the Graphics of the last display of the formula. + */ + protected Image img; + /** + * Top node of the parsed formula. + */ + private Node top; + /** + * FormulaEditor the FormulaViewer belongs to + * null if it belongs to no FormulaEditor. + */ + protected FormulaEditor editor = null; + /** + * formula that is displayed. + */ + protected String formula; + /** + * x position in g where the last writing on YPos.NORMAL ended. + */ + private double currentPosX = 0; + /** + * x position where the last writing on YPos.SUB ended relative to currentPosX. + */ + private double currentRelSuperSuperPosX = 0; + /** + * x position where the last writing on YPos.SUPER ended relative to currentPosX. + */ + private double currentRelSubSubPosX = 0; + /** + * Distance of the super script from the upper border, relative to the size. + */ + private double yPosSuperFactor = 0; + /** + * Distance of the normal script from the super script, relative to the size. + */ + private double yPosNormalFactor = 0.02; + /** + * Distance of the sub script from the normal script, relative to the size. + */ + private double yPosSubFactor = 0.02; + /** + * super super script font size = fontSize * sizeSuperSuperFactor + */ + private double sizeSuperSuperFactor = 0.75; + /** + * super script font size = fontSize * sizeSuperFactor + */ + private double sizeSuperFactor = 0.75; + /** + * sub script font size = fontSize * sizeSubFactor + */ + private double sizeSubFactor = 0.75; + /** + * sub sub script font size = fontSize * sizeSubSubFactor + */ + private double sizeSubSubFactor = 0.75; + /** + * Color of the font. + */ + private Color color = Color.BLACK; + /** + * Font size of the font in normal script. + */ + private int fontSize = 12; + /** + * true if the formula changed since the last rendering, otherwise false. + * After intialization and after the setting of the FormulaEditor it is always false. + * It is only used for knowing when to draw the PARSE_ERROR_SUBSTITUTION_TEXT. + */ + protected boolean changed = false; + /** + * If true something is drawn, otherwise not. + * This is used to calculate the length of a string without actually drawing it. + */ + private boolean enableDrawing = true; + /** + * Name of the variable that is displayed. + */ + protected String variableName; + /** + * true if the instance is still initializing, otherwise it's false. + */ + protected boolean init = true; + /** + * Text that is shown instead of the variable value, if there was a parse error for the value on initialization or setting of the FormulaEditor. + */ + public static final String PARSE_ERROR_SUBSTITUTION_TEXT; + /** + * If true the PARSE_ERROR_SUBSTITUTION_TEXT will be drawn, otherwise the formula will be drawn. + */ + protected boolean drawParseErrorSubstitutionText = false; + /** + * String that is written in front of the Formula + */ + protected String preString = ""; + /** + * String that is written behind the Formula + */ + protected String postString = ""; + + static { + String temp = ""; + try { + temp = Messages.getString("hoare", "view.parseErrorFormulaSubstitution"); + } + catch (Exception e) { + e.printStackTrace(); + } + PARSE_ERROR_SUBSTITUTION_TEXT = temp; + } + /** + * Creates a new FormulaViewer displaying the empty String. + * + */ + public FormulaViewer() { + this(""); + } + + /** + * Creates a new FormulaViewer displaying the specified formula. + * @param formula initial formula to display + */ + public FormulaViewer(String formula) { + setFormula(formula); + changed = false; + parse(); + setFontSize(20); + init = false; + } + + /** + * Creates a new FormulaViewer displaying the specified formula with the specified variable name. + * @param formula initial formula to display + * @param variableName name of the variable that is displayed + */ + public FormulaViewer(String formula, String variableName) { + this(formula); + setVariableName(variableName); + } + + /** + * Creates a new FormulaViewer with the specified font displaying the empty string. + * @param font font the FormulaViewer will use to render the formula + */ + public FormulaViewer(Font font) { + this(); + setFont(font); + } + + /** + * Creates a new FormulaViewer with the specified font displaying the specified formula + * @param formula initial formula to display + * @param font font the FormulaViewer will use to render the formula + */ + public FormulaViewer(String formula, Font font) { + this(formula); + setFont(font); + } + + /** + * Creates a new FormulaViewer displaying the specified formula with the specified variable name. + * @param font font the FormulaViewer will use to render the formula + * @param variableName name of the variable that is displayed + */ + public FormulaViewer(Font font, String variableName) { + this (font); + setVariableName(variableName); + } + + /** + * Creates a new FormulaViewer displaying the specified formula with the specified variable name. + * @param formula initial formula to display + * @param font font the FormulaViewer will use to render the formula + * @param variableName name of the variable that is displayed + */ + public FormulaViewer(String formula, Font font, String variableName) { + this (formula, font); + setVariableName(variableName); + } + + /** + * Sets the FormulaEditor to the specified one. + * @param editor the new FormulaEditor + */ + public void setFormulaEditor(FormulaEditor editor) { + this.editor = editor; + setFormula(editor.getFormula()); + drawParseErrorSubstitutionText = false; + init = true; + parse(); + init = false; + editor.addFormulaEditorObserver(new FormulaEditorObserver() { + + public void applyFormulaChange(FormulaEditor editor) { + // do nothing + } + + public void formulaChanged(FormulaEditor editor) { + setFormula(editor.getFormula()); + parse(); + repaint(); + } + + public void formulaEditorClosed(FormulaEditor editor) { + // do nothing + } + + public void receiveParseMessage(FormulaEditor editor, String message) { + // do nothing + } + + }); + changed = false; + } + + /** + * Sets the String that is written in front of the Formula to the specified value + * @param preString String that is written in front of the Formula + */ + public void setPreString(String preString) { + this.preString = preString; + } + + /** + * Sets the String that is written behind the Formula to the specified value + * @param postString String that is written behind the Formula + */ + public void setPostString(String postString) { + this.postString = postString; + } + + /** + * Parses the current formula. + * + */ + protected void parse() { + if (formula.equals("")) { + top = null; + if (editor!=null) { + editor.receiveParseMessage(FormulaEditor.MESSAGE_OKAY); + } + } + else { + try { + top = ParserAccess.parse(formula); + if (editor!=null) { + editor.receiveParseMessage(FormulaEditor.MESSAGE_OKAY); + } + } + catch (ParseException e) { + handleParseException(); + } + catch (Exception e) { + handleParseException(); + } + catch (Error e) { + handleParseException(); + } + } + } + + /** + * Parses the current formula. + * + */ + protected static boolean isParsable(String formula) { + if (formula.equals("")) { + return true; + } + try { + ParserAccess.parse(formula); + return true; + } + catch (ParseException e) { + return false; + } + catch (Exception e) { + return false; + } + catch (Error e) { + return false; + } + } + + /** + * Is called if an exception occurs while parsing. + */ + protected void handleParseException() { + if (editor!=null) { + editor.receiveParseMessage(FormulaEditor.MESSAGE_ERROR); + } + if (init) { + drawParseErrorSubstitutionText = true; + } + } + + /** + * Paints the formula on the JPanel. + */ + protected void paintComponent(Graphics g) { + this.g = (Graphics2D)g; + super.paintComponent(this.g); + // make the text borders smooth + this.g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + this.g.setColor(color); + // set the Font of the Graph2D to the super font + this.g.setFont(super.getFont()); + // start drawing from the very left + currentPosX = 0; + // draw the preString + drawString(preString, YPos.NORMAL); + // draw the variable name if there is any + if (getVariableName()!=null) { + drawString(getVariableName(), YPos.NORMAL); + drawString(" := ", YPos.NORMAL); + } + // draw the formula + if (drawParseErrorSubstitutionText) { + if (changed) { + drawParseErrorSubstitutionText = false; + } + else { + drawString(PARSE_ERROR_SUBSTITUTION_TEXT, YPos.NORMAL); + } + } + else if (top==null) { + // draw nothing + } + else { + drawNode(top, YPos.NORMAL, false); + } + // draw the postString + drawString(postString, YPos.NORMAL); + // set the width to the new length of the formula + fitSize(); + changed = false; + } + + /** + * Draws the node + * @param node the node to draw + * @param yPos the position where the node will be drawn + * @param allowBrackets if false no bracktes will be drawn, otherwise they may be drawn, depending of the kind of node + * @return the width that is needed to draw the node + */ + protected double drawNode(Node node, YPos yPos, boolean drawBrackets) { + double result = 0; + if (node instanceof ASTStart) { + result = drawNode(node.jjtGetChild(0), yPos, false); + } + else if (node instanceof ASTConstant) { + result = drawString(getConstantString((ASTConstant)node), yPos); + } + else if (node instanceof ASTVarNode) { + result = drawVariable((ASTVarNode)node, yPos); + } + else if (node instanceof ASTFunNode) { + ASTFunNode f = (ASTFunNode)node; + if (isUnaryOperator(f.getName())) { + result = drawUnaryOperation(f, yPos, drawBrackets); + } + else if (isBinaryOperator(f.getName())) { + result = drawBinaryOperation(f, yPos, drawBrackets); + } + else if (isUnaryFunction(f.getName())) { + result = drawUnaryFunction(f, yPos, drawBrackets); + } + else if (isSumOrProd(f.getName())) { + result = drawSumOrProd(f, yPos, drawBrackets); + } + } + return result; + } + + /** + * Draws a variable. + * @param v the variable node + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawVariable(ASTVarNode v, YPos yPos) { + return drawString(getVarString(v), yPos); + } + + /** + * Draws a unary operation + * @param f the node with the operation its parameter + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawUnaryOperation(ASTFunNode f, YPos yPos, boolean drawBrackets) { + if (f.getName().equals(operatorSet.getNot())) { + drawBrackets = false; + } + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, yPos); + } + length = length + drawString(getOperatorString(f.getOperator()), yPos); + length = length + drawNode(f.jjtGetChild(0), yPos, areBracketsNecessary(f, 0)); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, yPos); + } + return length; + } + + /** + * Draws a binary operation + * @param f the node with the operation its parameters + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawBinaryOperation(ASTFunNode f, YPos yPos, boolean drawBrackets) { + if (f.getOperator().getName().equals(operatorSet.getPower().getName())&(yPos==YPos.NORMAL)) { + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, YPos.NORMAL); + } + length = length + drawNode(f.jjtGetChild(0), YPos.NORMAL, areBracketsNecessary(f, 0)); + length = length + drawNode(f.jjtGetChild(1), YPos.SUPER, false); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, YPos.NORMAL); + } + return length; + } + if (f.getOperator().getName().equals(operatorSet.getSubtract().getName())) { + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, yPos); + } + boolean drawBracketsFirstChild = areBracketsNecessary(f, 0); + Node firstChild = f.jjtGetChild(0); + if (firstChild instanceof ASTFunNode) { + if (((ASTFunNode)firstChild).getName().equals(operatorSet.getAdd().getName())) { + drawBracketsFirstChild = false; + } + } + length = length + drawNode(f.jjtGetChild(0), yPos, drawBracketsFirstChild); + length = length + drawString(getOperatorString(f.getOperator()), yPos); + length = length + drawNode(f.jjtGetChild(1), yPos, areBracketsNecessary(f, 1)); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, yPos); + } + return length; + } + if (f.getOperator().getName().equals(operatorSet.getDivide().getName())) { + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, yPos); + } + boolean drawBracketsFirstChild = areBracketsNecessary(f, 0); + Node firstChild = f.jjtGetChild(0); + if (firstChild instanceof ASTFunNode) { + if (((ASTFunNode)firstChild).getName().equals(operatorSet.getMultiply().getName())) { + drawBracketsFirstChild = false; + } + } + length = length + drawNode(f.jjtGetChild(0), yPos, drawBracketsFirstChild); + length = length + drawString(getOperatorString(f.getOperator()), yPos); + length = length + drawNode(f.jjtGetChild(1), yPos, areBracketsNecessary(f, 1)); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, yPos); + } + return length; + } + else if (isBinaryOperatorWithoutBrackets(f.getName())||(!drawBrackets)) { + return drawBinaryOperationWithoutBrackets(f, yPos); + } + else { + return drawBinaryOperationWithBrackets(f, yPos); + } + } + + /** + * Draws a binary operation with brackets + * @param f the node with the operation its parameters + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawBinaryOperationWithBrackets(ASTFunNode f, YPos yPos) { + double length = 0; + length = length + drawString(BRACKET_OPEN, yPos); + length = length + drawBinaryOperationWithoutBrackets(f, yPos); + length = length + drawString(BRACKET_CLOSE, yPos); + return length; + } + + /** + * Draws a binary operation without brackets + * @param f the node with the operation its parameters + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawBinaryOperationWithoutBrackets(ASTFunNode f, YPos yPos) { + double length = 0; + length = length + drawNode(f.jjtGetChild(0), yPos, areBracketsNecessary(f, 0)); + length = length + drawString(getOperatorString(f.getOperator()), yPos); + length = length + drawNode(f.jjtGetChild(1), yPos, areBracketsNecessary(f, 1)); + return length; + } + + /** + * Draws a unary function + * @param f the node with the function its parameter + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawUnaryFunction(ASTFunNode f, YPos yPos, boolean drawBrackets) { + if (f.getName().equals("abs")) { + double length = 0; + length = length + drawString("|", yPos); + length = length + drawNode(f.jjtGetChild(0), yPos, false); + length = length + drawString("|", yPos); + return length; + } + else if (f.getName().equals("sqrt")) { + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, yPos); + } + length = length + drawString(getFunctionString(f.getName()), yPos); + length = length + drawNode(f.jjtGetChild(0), yPos, areBracketsNecessary(f, 0)); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, yPos); + } + return length; + } + else if (f.getName().equals("exp")&(yPos==YPos.NORMAL)) { + double length = 0; + if (drawBrackets) { + length = length + drawString(BRACKET_OPEN, YPos.NORMAL); + } + length = length + drawString("e", YPos.NORMAL); + length = length + drawNode(f.jjtGetChild(0), YPos.SUPER, false); + if (drawBrackets) { + length = length + drawString(BRACKET_CLOSE, YPos.NORMAL); + } + return length; + } + else { + double length = 0; + length = length + drawString(getFunctionString(f.getName()), yPos); + length = length + drawString(BRACKET_OPEN, yPos); + length = length + drawNode(f.jjtGetChild(0), yPos, false); + length = length + drawString(BRACKET_CLOSE, yPos); + return length; + } + } + + /** + * Draws a sum or a product function + * @param f the node with the function its parameters + * @param yPos the position where the node will be drawn + * @return the width that is needed to draw the node + */ + protected double drawSumOrProd(ASTFunNode f, YPos yPos, boolean drawBrackets) { + double result = 0; + // draw opening bracket for the sum if necessary + if (drawBrackets&&(yPos==YPos.NORMAL)) { + drawString(BRACKET_OPEN, YPos.NORMAL); + } + // draw nice sum if in normal position + if (yPos==YPos.NORMAL) { + //save starting position + double startPosX = currentPosX; + //disable drawing + enableDrawing = false; + + double superLength = 0; + double normalLength = 0; + double subLength = 0; + //calculate the length of the subscript + currentRelSubSubPosX = 0; + subLength = subLength + drawNode(f.jjtGetChild(1), YPos.SUBSUB, false); + currentRelSubSubPosX = subLength; + subLength = subLength + drawString(getOperatorString(operatorSet.getAssign()), YPos.SUBSUB); + currentRelSubSubPosX = subLength; + subLength = subLength + drawNode(f.jjtGetChild(2), YPos.SUBSUB, false); + //calculate the length of the superscript + currentRelSuperSuperPosX = 0; + superLength = superLength + drawNode(f.jjtGetChild(3), YPos.SUPERSUPER, false); + //calculate the length of the sum symbol + normalLength = normalLength + drawString(getFunctionString(f.getName()), YPos.NORMAL); + + //reset the starting position to the original one (has been changed during the calculation of the length of the sum symbol) + currentPosX = startPosX; + //enable drawing + enableDrawing = true; + + //calculate the maximum width needed + double maxLength = Math.max(superLength, Math.max(normalLength, subLength)); + + //draw the subscript in the center of the maximum width + double length = (maxLength-subLength)/2.0; + currentRelSubSubPosX = length; + length = length + drawNode(f.jjtGetChild(1), YPos.SUBSUB, false); + currentRelSubSubPosX = length; + length = length + drawString(getOperatorString(operatorSet.getAssign()), YPos.SUBSUB); + currentRelSubSubPosX = length; + length = length + drawNode(f.jjtGetChild(2), YPos.SUBSUB, false); + currentRelSubSubPosX = 0; + //draw the superscript in the center of the maximum width + length = (maxLength-superLength)/2.0; + currentRelSuperSuperPosX = length; + length = length + drawNode(f.jjtGetChild(3), YPos.SUPERSUPER, false); + currentRelSuperSuperPosX = 0; + //draw the sum symbol in the center of the maximum width + length = (maxLength-normalLength)/2.0; + currentPosX = startPosX + length; + length = length + drawString(getFunctionString(f.getName()), YPos.NORMAL); + //adjust the x position and continue drawing the rest + currentPosX = startPosX + maxLength; + length = 0; + length = length + drawNode(f.jjtGetChild(0), YPos.NORMAL, areBracketsNecessary(f, 0)); + + result = length+maxLength; + } + // draw sum as normal function if not in normal position + else { + double length = 0; + length = length + drawString(getFunctionString(f.getName())+BRACKET_OPEN, yPos); + length = length + drawNode(f.jjtGetChild(0), yPos, false); + length = length + drawString(", ", yPos); + length = length + drawNode(f.jjtGetChild(1), yPos, false); + length = length + drawString(", ", yPos); + length = length + drawNode(f.jjtGetChild(2), yPos, false); + length = length + drawString(", ", yPos); + length = length + drawNode(f.jjtGetChild(3), yPos, false); + length = length + drawString(BRACKET_CLOSE, yPos); + result = length; + } + // draw opening bracket for the sum if necessary + if (drawBrackets&&(yPos==YPos.NORMAL)) { + drawString(BRACKET_CLOSE, YPos.NORMAL); + } + return result; + } + + /** + * Draws the String on the Graphics g. + * @param str the String to be drawn + * @param yPos the postion where the String will be drawn + * @return the width that is needed to draw the String + */ + private double drawString(String str, YPos yPos) { + double length = 0; + switch (yPos) { + case SUPERSUPER: + length = drawString(str, currentPosX+currentRelSuperSuperPosX, getBaseLineYPos(YPos.SUPERSUPER), getFontSize(YPos.SUPERSUPER)); + currentRelSuperSuperPosX = currentRelSuperSuperPosX + length; + break; + case SUPER: + length = drawString(str, currentPosX, getBaseLineYPos(YPos.SUPER), getFontSize(YPos.SUPER)); + currentPosX = currentPosX + length; + break; + case NORMAL: + length = drawString(str, currentPosX, getBaseLineYPos(YPos.NORMAL), getFontSize(YPos.NORMAL)); + currentPosX = currentPosX + length; + break; + case SUB: + length = drawString(str, currentPosX, getBaseLineYPos(YPos.SUB), getFontSize(YPos.SUB)); + currentPosX = currentPosX + length; + break; + case SUBSUB: + length = drawString(str, currentPosX+currentRelSubSubPosX, getBaseLineYPos(YPos.SUBSUB), getFontSize(YPos.SUBSUB)); + currentRelSubSubPosX = currentRelSubSubPosX + length; + break; + } + return length; + } + + /** + * Draws the String on the Graphics g. + * @param str the String to be drawn. + * @param x x position of the baseline + * @param y y position of the baseline + * @param fontSize font size for the font + * @return the width that is needed to draw the String + */ + private double drawString(String str, double x, double y, int fontSize) { + g.setFont(g.getFont().deriveFont((float)fontSize)); + if (enableDrawing) { + g.drawString(str, (int)Math.round(x), (int)Math.round(y)); + } + return g.getFontMetrics().getStringBounds(str, g).getWidth(); + } + + /** + * Returns the String that should be drawn for the specified constant. + * @param c the constant node + * @return the String that should be drawn + */ + protected String getConstantString(ASTConstant c) { + String str = c.getValue().toString(); + if (str.endsWith(".0")) { + str = str.substring(0, str.length()-".0".length()); + } + return str; + } + + /** + * Returns the String that should be drawn for the specified variable. + * @param v the variable node + * @return the String that should be drawn + */ + protected String getVarString(ASTVarNode v) { + return v.getName(); + } + + /** + * Returns the String that should be drawn for the specified operator. + * @param op the operator node + * @return the String that should be drawn + */ + protected String getOperatorString(Operator op) { + String name = op.getName(); + if (name.equals(operatorSet.getGE().getName())) { + return Symbols.SYMBOL_GE; + } + if (name.equals(operatorSet.getLE().getName())) { + return Symbols.SYMBOL_LE; + } + if (name.equals(operatorSet.getAnd().getName())) { + return Symbols.SYMBOL_AND; + } + if (name.equals(operatorSet.getOr().getName())) { + return Symbols.SYMBOL_OR; + } + if (name.equals(operatorSet.getNot().getName())) { + return Symbols.SYMBOL_NOT; + } + if (name.equals(operatorSet.getNE().getName())) { + return Symbols.SYMBOL_NE; + } + if (name.equals(operatorSet.getEQ().getName())) { + return operatorSet.getAssign().getName(); + } + return op.getSymbol(); + } + + /** + * Returns the String that should be drawn for the specified function. + * @param function the function name + * @return the String that should be drawn + */ + protected String getFunctionString(String function) { + if (function.equals("Sum")) { + return Symbols.SYMBOL_SUM; + } + else if (function.equals("Product")) { + return Symbols.SYMBOL_PROD; + } + else if (function.equals("sqrt")) { + return Symbols.SYMBOL_SQRT; + } + else { + return function; + } + } + + /** + * Checks if the specified operator is unary. + * @param operatorName name of the operator + * @return true if the operator is unary, otherwise false + */ + protected boolean isUnaryOperator(String operatorName) { + for (int i=0;itrue if the operator is binary, otherwise false + */ + protected boolean isBinaryOperator(String operatorName) { + for (int i=0;itrue if the operator is binary and should be displayed without brackets, otherwise false + */ + protected boolean isBinaryOperatorWithoutBrackets(String operatorName) { + for (int i=0;itrue if the function is unary, otherwise false + */ + protected boolean isUnaryFunction(String functionName) { + for (int i=0;itrue if the function is the sum or the product function, otherwise false + */ + protected boolean isSumOrProd(String functionName) { + for (int i=0;i parentPriority) { + return true; + } + else if (childPriority < parentPriority) { + return false; + } + else { + if (getIndex(NOT_ASSOCIATIVE, parentName)!=-1) { + if (parentName.equals(operatorSet.getPower().getName())) { + if (childNodeIndex==0) { + return true; + } + } + else if (childNodeIndex>0) { + return true; + } + } + return false; + } + } + else { + return false; + } + } + + /** + * Returns the index of str in the array strs. + * @param strs the array of String + * @param str the String + * @return the index of str in strs, -1 if str is not contained in strs + */ + private int getIndex(String[] strs, String str) { + for (int i=0; iString as the name of the formula. + * @param name name of the formula + */ + public void setVariableName(String name) { + variableName = name; + } + + /** + * Returns the String that is shown as the name of the formula. + * @return the String that is shown as the name of the formula + */ + public String getVariableName() { + return variableName; + } + + /** + * No name will be shown for the formula. + * + */ + public void removeVariableName() { + variableName = null; + } + + /** + * Sets the font size for normal script to the new size. + * @param fontSize the new font size + */ + public void setFontSize(int fontSize) { + this.fontSize = fontSize; + yPosInitialized = false; + fitSize(); + } + + /** + * Returns the current font size for normal script. + * @return the current font size for normal script + */ + public int getFontSize() { + return getFontSize(YPos.NORMAL); + } + + /** + * Fits the size of the FormulaViewer to the current font size. + * + */ + public void fitSize() { + int height = getBaseLineYPos(YPos.MAX); + int width = (int)Math.ceil(currentPosX); + if (width==0) { + width = 1; + } + Dimension d = new Dimension(width, height); + setSize(d); + setMinimumSize(d); + setMaximumSize(d); + setPreferredSize(d); + } + + /** + * Returns the font size for the specified position. + * @param yPos the position of the text + * @return the font size for the position + */ + protected int getFontSize(YPos yPos) { + switch (yPos) { + case SUPERSUPER: + return (int)Math.round(fontSize*sizeSuperSuperFactor); + case SUPER: + return (int)Math.round(fontSize*sizeSuperFactor); + case NORMAL: + return fontSize; + case SUB: + return (int)Math.round(fontSize*sizeSubFactor); + case SUBSUB: + return (int)Math.round(fontSize*sizeSubSubFactor); + default: + return 0; + } + } + + /** + * true if the y positions of the different script types have been calculated for the current font size, otherwise false. + */ + private boolean yPosInitialized = false; + /** + * Highest possible y position of supersuperscript + */ + private double posSuperSuperTop; + /** + * Base line position of supersuperscript + */ + private double posSuperSuperBase; + /** + * Lowest possible y position of supersuperscript + */ + private double posSuperSuperBottom; + /** + * Highest possible y position of superscript + */ + private double posSuperTop; + /** + * Base line position of superscript + */ + private double posSuperBase; + /** + * Lowest possible y position of superscript + */ + private double posSuperBottom; + /** + * Highest possible y position of normal script + */ + private double posNormalTop; + /** + * Base line position of normal script + */ + private double posNormalBase; + /** + * Lowest possible y position of normal script + */ + private double posNormalBottom; + /** + * Highest possible y position of subscript + */ + private double posSubTop; + /** + * Base line position of subscript + */ + private double posSubBase; + /** + * Lowest possible y position of subscript + */ + private double posSubBottom; + /** + * Highest possible y position of subsubscript + */ + private double posSubSubTop; + /** + * Base line position of subsubscript + */ + private double posSubSubBase; + /** + * Lowest possible y position of subsubscript + */ + private double posSubSubBottom; + /** + * Maximal y position, which is equal to the height of the component + */ + private double posMax; + + /** + * Returns the y position of the base line for text on the specified position + * @param yPos the position of the text + * @return the y position of the base line + */ + protected int getBaseLineYPos(YPos yPos) { + double pos = 0; + + if (g!=null) { + + if (!yPosInitialized) { + initYPos(); + } + + switch(yPos) { + case SUPERSUPER: + return (int)Math.round(posSuperSuperBase); + case SUPER: + return (int)Math.round(posSuperBase); + case NORMAL: + return (int)Math.round(posNormalBase); + case SUB: + return (int)Math.round(posSubBase); + case SUBSUB: + return (int)Math.round(posSubSubBase); + case MAX: + return (int)Math.round(posMax); + } + + } + else { + pos = 1; + } + return (int)Math.ceil(pos); + } + + /** + * Calculates the y position for all script types for the current font size, if the Graphics of the component have been initialized already + */ + private void initYPos() { + if (g!=null) { + g.setFont(g.getFont().deriveFont((float)getFontSize(YPos.SUPERSUPER))); + int ascSuperSuper = g.getFontMetrics().getAscent(); + int descSuperSuper = g.getFontMetrics().getDescent(); + g.setFont(g.getFont().deriveFont((float)getFontSize(YPos.SUPER))); + int ascSuper = g.getFontMetrics().getAscent(); + int descSuper = g.getFontMetrics().getDescent(); + g.setFont(g.getFont().deriveFont((float)getFontSize(YPos.NORMAL))); + int ascNormal = g.getFontMetrics().getAscent(); + int descNormal = g.getFontMetrics().getDescent(); + g.setFont(g.getFont().deriveFont((float)getFontSize(YPos.SUB))); + int ascSub = g.getFontMetrics().getAscent(); + int descSub = g.getFontMetrics().getDescent(); + g.setFont(g.getFont().deriveFont((float)getFontSize(YPos.SUBSUB))); + int ascSubSub = g.getFontMetrics().getAscent(); + int descSubSub = g.getFontMetrics().getDescent(); + + posSuperSuperTop = yPosSuperFactor*fontSize; + posSuperSuperBase = posSuperSuperTop + ascSuperSuper; + posSuperSuperBottom = posSuperSuperBase + descSuperSuper; + posNormalTop = posSuperSuperBottom + yPosNormalFactor*fontSize; + posNormalBase = posNormalTop + ascNormal; + posNormalBottom = posNormalBase + descNormal; + posSubSubTop = posNormalBottom + yPosSubFactor*fontSize; + posSubSubBase = posSubSubTop + ascSubSub; + posSubSubBottom = posSubSubBase + descSubSub; + posMax = posSubSubBottom; + posSuperBase = posNormalBase - fontSize + getFontSize(YPos.SUPER)*0.75; + posSuperTop = posSuperBase - ascSuper; + posSuperBottom = posSuperBase + descSuper; + posSubBase = posNormalBase + getFontSize(YPos.SUB)*0.5; + posSubTop = posSubBase - ascSub; + posSubBottom = posSubBase + descSub; + + yPosInitialized = true; + } + else { + yPosInitialized = false; + } + } + + /** + * Changes the color of the font. + * @param c the new color + */ + public void setColor(Color c) { + color = c; + repaint(); + } + + /** + * Sets the font for this formula viewer. + * @param font the desired Font for this formula viewer + */ + public void setFont(Font font) { + super.setFont(font); + setFontSize(font.getSize()); + } + + /** + * Calculates and sets size, minimum size, maximum size and preferred size even if it's not drawn yet. + * + */ + public void initSize() { + GraphicsConfiguration gfxConf = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(); + BufferedImage img = gfxConf.createCompatibleImage(1, 1); + Graphics2D g = img.createGraphics(); + print(g); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/formula/Symbols.java b/src/org/jalgo/module/hoare/view/formula/Symbols.java new file mode 100644 index 0000000..ae06243 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/Symbols.java @@ -0,0 +1,68 @@ +package org.jalgo.module.hoare.view.formula; + +/** + * Symbols for displaying formulas. + * @author antje + * + */ + +public class Symbols { + + /** + * Symbol for "and". + */ + public static final String SYMBOL_AND = "\u2227"; + /** + * Symbol for "or". + */ + public static final String SYMBOL_OR = "\u2228"; + /** + * Symbol for "not". + */ + public static final String SYMBOL_NOT = "\u00AC"; + /** + * Symbol for "sum". + */ + public static final String SYMBOL_SUM = "\u2211"; + /** + * Symbol for "product". + */ + public static final String SYMBOL_PROD = "\u220F"; + /** + * Symbol for "abs". + */ + public static final String SYMBOL_ABS = "|"; + /** + * Symbol for "ln". + */ + public static final String SYMBOL_LN = "ln"; + /** + * Symbol for "exp". + */ + public static final String SYMBOL_EXP = "exp"; + //public static final String SYMBOL_SQUARE = "\u00B2"; + /** + * Symbol for "square root". + */ + public static final String SYMBOL_SQRT = "\u221A"; + /** + * Symbol for "less or equal". + */ + public static final String SYMBOL_LE = "\u2264"; + /** + * Symbol for "greater or equal". + */ + public static final String SYMBOL_GE = "\u2265"; + /** + * Symbol for "not equal". + */ + public static final String SYMBOL_NE = "\u2260"; + + /** + * No instanciation allowed. + * + */ + private Symbols() { + } + +} diff --git a/src/org/jalgo/module/hoare/view/formula/package-info.java b/src/org/jalgo/module/hoare/view/formula/package-info.java new file mode 100644 index 0000000..f50551b --- /dev/null +++ b/src/org/jalgo/module/hoare/view/formula/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains classes for displaying and editing formulas. + */ +package org.jalgo.module.hoare.view.formula; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/package-info.java b/src/org/jalgo/module/hoare/view/package-info.java new file mode 100644 index 0000000..0fab019 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/package-info.java @@ -0,0 +1,5 @@ +/** + * This package contains all Classes necessary for + * the graphical user interface of the hoare-module + */ +package org.jalgo.module.hoare.view; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/BeamerMode.java b/src/org/jalgo/module/hoare/view/toolbar/BeamerMode.java new file mode 100644 index 0000000..c2778bb --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/BeamerMode.java @@ -0,0 +1,78 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashSet; +import java.util.Set; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The class BeamerMode defines a checkbox menuitem for + * switching between beamer mode and pc mode.
          + * Here a special design is implemented, in order that this setting + * takes global effect for all open instances of the Hoare module.
          + * + * @author Thomas + */ +public class BeamerMode extends JCheckBoxMenuItem implements ActionListener { + private static final long serialVersionUID = 5523818288828234644L; + + private static boolean isAktiv=false; + + private static Set beamerModes=new HashSet(); + + private View view; + + /** + * Creates a new BeamerModeAction which provides the + * isAktiv state with all views who have an instance + * of this action. + * + * @param view the {@link View} which includes this action + */ + public BeamerMode(View view) { + super(Messages.getString("hoare", "Beamer_mode"), new ImageIcon( + Messages.getResourceURL("main", "Icon.Beamer_mode")), false); + this.view=view; + //isAktiv=aktiv;//????? + this.setSelected(isAktiv); + addActionListener(this); + beamerModes.add(this); + } + + /** + * Performs the action for all views which have created an instance. + */ + public void actionPerformed(ActionEvent e) { + isAktiv=this.isSelected(); + for (BeamerMode bm : beamerModes){ + bm.setSelected(isAktiv); + bm.changeView(); + } + } + + /** + * Performs the call of the setBeamer-method of the + * assigned {@link View} + */ + private void changeView(){ + if (view!=null){ + view.setBeamer(isAktiv); + } + } + + /** + * Returns the state of the BeamerMode + * + * @return true if the BeamerMode is aktiv + */ + public boolean isAktiv(){ + return isAktiv; + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/CVS/Entries b/src/org/jalgo/module/hoare/view/toolbar/CVS/Entries new file mode 100644 index 0000000..03476ae --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/CVS/Entries @@ -0,0 +1,12 @@ +/BeamerMode.java/1.1/Wed Aug 27 13:02:22 2008// +/DelPart.java/1.1/Wed Aug 27 13:02:20 2008// +/LoadCNullProg.java/1.1/Wed Aug 27 13:02:22 2008// +/NormalMouse.java/1.1/Wed Aug 27 13:02:20 2008// +/ReInit.java/1.1/Wed Aug 27 13:02:19 2008// +/Redo.java/1.1/Wed Aug 27 13:02:19 2008// +/ResetZoom.java/1.1/Wed Aug 27 13:02:22 2008// +/ToggleSplitter.java/1.1/Wed Aug 27 13:02:20 2008// +/Undo.java/1.1/Wed Aug 27 13:02:21 2008// +/ZoomIn.java/1.1/Wed Aug 27 13:02:21 2008// +/ZoomOut.java/1.1/Wed Aug 27 13:02:23 2008// +/package-info.java/1.1/Wed Aug 27 13:02:19 2008// diff --git a/src/org/jalgo/module/hoare/view/toolbar/CVS/Repository b/src/org/jalgo/module/hoare/view/toolbar/CVS/Repository new file mode 100644 index 0000000..81e2416 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/view/toolbar diff --git a/src/org/jalgo/module/hoare/view/toolbar/CVS/Root b/src/org/jalgo/module/hoare/view/toolbar/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/view/toolbar/DelPart.java b/src/org/jalgo/module/hoare/view/toolbar/DelPart.java new file mode 100644 index 0000000..fbbc52f --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/DelPart.java @@ -0,0 +1,41 @@ +package org.jalgo.module.hoare.view.toolbar; +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * Deletes a partial tree (the tree above the selectet cell) + * + * @author:Tomas + */ +public class DelPart extends AbstractAction{ + + private static final long serialVersionUID = 1L; + + private View gui; +/** + * sets up the button + * @param gui + */ + public DelPart(View gui) { + + this.gui = gui; + + this.putValue(NAME, Messages.getString("hoare", "name.delNode")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.delNode"))); + + } +/** + * tells the view if button was pressed (deletePart()) + */ + public void actionPerformed(ActionEvent e) { + gui.deletePart(); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.java b/src/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.java new file mode 100644 index 0000000..aa184ea --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/LoadCNullProg.java @@ -0,0 +1,39 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * loads C0-Program from .c-file + * + * @author:Tomas + */ +public class LoadCNullProg extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private View gui; + /** + * sets up the button + * @param gui + */ + public LoadCNullProg(View gui) { + this.gui = gui; + + this.putValue(NAME, Messages.getString("hoare", "name.openC0Program")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.openC0Program"))); + } + /** + * tells the view if button was pressed (loadSourceCode()) + */ + public void actionPerformed(ActionEvent arg0) { + gui.loadSourceCode(); + } + +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/NormalMouse.java b/src/org/jalgo/module/hoare/view/toolbar/NormalMouse.java new file mode 100644 index 0000000..9cd3975 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/NormalMouse.java @@ -0,0 +1,37 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The set too normal mouse + * + * @author: Tomas + */ +public class NormalMouse extends AbstractAction{ + + private static final long serialVersionUID = 1L; + private View gui; + /** + * sets up the button + * @param gui + */ + public NormalMouse(View gui){ + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.normalMouse")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.normalMouse"))); + } + /** + * tells the view if button was pressed (setZoomMode(View.ZoomMode.NO)) + */ + public void actionPerformed(ActionEvent arg0) { + gui.setZoomMode(View.ZoomMode.NO); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/ReInit.java b/src/org/jalgo/module/hoare/view/toolbar/ReInit.java new file mode 100644 index 0000000..0ed8f8f --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/ReInit.java @@ -0,0 +1,41 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The reinit-action + * + * @author: Tomas + * + */ +public class ReInit extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private View gui; + /** + * sets up the button + * @param gui + */ + public ReInit(View gui) { + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.reinit")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.reinit"))); + + } + /** + * tells the view if button was pressed (reinit()) + */ + public void actionPerformed(ActionEvent arg0) { + gui.reinit(); + } + +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/Redo.java b/src/org/jalgo/module/hoare/view/toolbar/Redo.java new file mode 100644 index 0000000..bf2475b --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/Redo.java @@ -0,0 +1,54 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The redo-action + * + * @author: Tomas + * + */ +public class Redo extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private View gui; + /** + * sets up the button + * @param gui + */ + public Redo(View g) { + gui = g; + this.putValue(NAME, Messages.getString("hoare", "name.redo")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.redo"))); + + } + /** + * tells the view if button was pressed (redo()) + * and calls the update function on View with (null, null) + */ + public void actionPerformed(ActionEvent arg0) { + gui.redo(); + gui.update(null, null); + } + /** + * replaces the button with a gray copy or reverse + * @param gray + */ + public void grayButton(boolean gray){ + if (gray){ + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL("hoare", "icon.redo.gray"))); + } else { + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL("hoare", "icon.redo"))); + } + + } + +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/ResetZoom.java b/src/org/jalgo/module/hoare/view/toolbar/ResetZoom.java new file mode 100644 index 0000000..33f4524 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/ResetZoom.java @@ -0,0 +1,38 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The reset zoom to initial -action + * + * @author: Tomas + * + */ +public class ResetZoom extends AbstractAction{ + + private static final long serialVersionUID = 1L; + private View gui; + /** + * sets up the button + * @param gui + */ + public ResetZoom(View gui){ + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.resetZoom")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.resetZoom"))); + } + /** + * tells the view if button was pressed (resetZoom()) + */ + public void actionPerformed(ActionEvent arg0) { + gui.resetZoom(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.java b/src/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.java new file mode 100644 index 0000000..d4d864b --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/ToggleSplitter.java @@ -0,0 +1,37 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +public class ToggleSplitter extends AbstractAction{ + /** + * The toggle splitter-action + * + * @author: Tomas + * + */ + private static final long serialVersionUID = 1L; + private View gui; + /** + * sets up the button + * @param gui + */ + public ToggleSplitter(View gui){ + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.toggleSplitter")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.toggleSplitter"))); + } + /** + * tells the view if button was pressed (toggleSplitter()) + */ + public void actionPerformed(ActionEvent arg0) { + gui.toggleSplitter(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/toolbar/Undo.java b/src/org/jalgo/module/hoare/view/toolbar/Undo.java new file mode 100644 index 0000000..b02bb93 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/Undo.java @@ -0,0 +1,53 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The undo-action + * + * @author: Tomas + */ +public class Undo extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private View gui; + /** + * sets up the button + * @param gui + */ + public Undo(View g) { + gui = g; + this.putValue(NAME, Messages.getString("hoare", "name.undo")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.undo"))); + } + /** + * tells the view if button was pressed (undo()) + * and calls the update function on View with (null, null) + */ + public void actionPerformed(ActionEvent arg0) { + gui.undo(); + gui.update(null, null); + + } + /** + * replaces the button with a gray copy or reverse + * @param gray + */ + public void grayButton(boolean gray){ + if (gray){ + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL("hoare", "icon.undo.gray"))); + } else { + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL("hoare", "icon.undo"))); + } + + } + +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/ZoomIn.java b/src/org/jalgo/module/hoare/view/toolbar/ZoomIn.java new file mode 100644 index 0000000..532806d --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/ZoomIn.java @@ -0,0 +1,37 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * The zoom in-action + * + * @author: Tomas + */ +public class ZoomIn extends AbstractAction{ + + private static final long serialVersionUID = 1L; + private View gui; + /** + * sets up the button + * @param gui + */ + public ZoomIn(View gui){ + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.zoomIn")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.zoomIn"))); + } + /** + * tells the view if button was pressed (setZoomMode(View.ZoomMode.IN)) + */ + public void actionPerformed(ActionEvent arg0) { + gui.setZoomMode(View.ZoomMode.IN); + } +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/ZoomOut.java b/src/org/jalgo/module/hoare/view/toolbar/ZoomOut.java new file mode 100644 index 0000000..b63d3db --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/ZoomOut.java @@ -0,0 +1,36 @@ +package org.jalgo.module.hoare.view.toolbar; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.hoare.view.View; + +/** + * the zoom Out button + * @author: Tomas + */ +public class ZoomOut extends AbstractAction{ + + private static final long serialVersionUID = 1L; + private View gui; + /** + * sets up the button + * @param gui + */ + public ZoomOut(View gui){ + + this.gui = gui; + this.putValue(NAME, Messages.getString("hoare", "name.zoomOut")); + this.putValue(AbstractAction.SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "hoare", "icon.zoomOut"))); + } + /** + * tells the view if button was pressed (setZoomMode(View.ZoomMode.OUT)) + */ + public void actionPerformed(ActionEvent arg0) { + gui.setZoomMode(View.ZoomMode.OUT); + } +} diff --git a/src/org/jalgo/module/hoare/view/toolbar/package-info.java b/src/org/jalgo/module/hoare/view/toolbar/package-info.java new file mode 100644 index 0000000..5c725f4 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/toolbar/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains actions for the toolbar buttons. + */ +package org.jalgo.module.hoare.view.toolbar; \ No newline at end of file diff --git a/src/org/jalgo/module/hoare/view/util/CVS/Entries b/src/org/jalgo/module/hoare/view/util/CVS/Entries new file mode 100644 index 0000000..37947f0 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/CVS/Entries @@ -0,0 +1,3 @@ +/SplitPaneWithWorkingDividerLocationSetter.java/1.1/Wed Aug 27 13:03:04 2008// +/VariableSizeButton.java/1.1/Wed Aug 27 13:03:03 2008// +/package-info.java/1.1/Wed Aug 27 13:03:03 2008// diff --git a/src/org/jalgo/module/hoare/view/util/CVS/Repository b/src/org/jalgo/module/hoare/view/util/CVS/Repository new file mode 100644 index 0000000..d0a3ab1 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/hoare/view/util diff --git a/src/org/jalgo/module/hoare/view/util/CVS/Root b/src/org/jalgo/module/hoare/view/util/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.java b/src/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.java new file mode 100644 index 0000000..fe471a7 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/SplitPaneWithWorkingDividerLocationSetter.java @@ -0,0 +1,81 @@ +package org.jalgo.module.hoare.view.util; + +import java.awt.Graphics; + +import javax.swing.JSplitPane; + +//The method setDividerLocation(double) doesn't work as expected, if the component isn't painted yet +//so this changed class is nesseccary. +/** + * JSplitPane that allows changing the divider position during the initialization + * @author unknown + */ + +public class SplitPaneWithWorkingDividerLocationSetter extends JSplitPane { + + private static final long serialVersionUID = -2815748405860579477L; + + private boolean isPainted = false; + private boolean hasProportionalLocation = false; + private boolean hasDividerLocation = false; + private double proportionalLocation; + private int dividerLocation; + + /** + * Returns a new JSplitPane with the specified orientation and with the specified components that does not do continuous redrawing. + * @param orientation an int specifying the horizontal or vertical orientation + * @param leftOrTop a boolean, true for the components to redraw continuously as the divider changes position, false to wait until the divider position stops changing to redraw + * @param rightOrBottom the Component that will appear on the left of a horizontally-split pane, or at the top of a vertically-split pane. + */ + public SplitPaneWithWorkingDividerLocationSetter(int orientation, java.awt.Component leftOrTop, java.awt.Component rightOrBottom) { + super(orientation, leftOrTop, rightOrBottom); + } + + /** + * Sets the divider location as a percentage of the JSplitPane's size. + * @param proportionalLocation a double-precision floating point value that specifies a percentage, from zero (top/left) to 1.0 (bottom/right) + */ + public void setDividerLocation(double proportionalLocation) { + if (!isPainted) { + hasProportionalLocation = true; + this.proportionalLocation = proportionalLocation; + } + else + super.setDividerLocation(proportionalLocation); + } + + /** + * Sets the location of the divider. This is passed off to the look and feel implementation. + * @param dividerLocation an int specifying a UI-specific value (typically a pixel count) + */ + public void setDividerLocation(int dividerLocation) { + if (!isPainted) { + hasDividerLocation = true; + this.dividerLocation = dividerLocation; + } + else + super.setDividerLocation(dividerLocation); + } + + /** + * Paints this component.
          + *
          + * This method is called when the contents of the component should be painted; such as when the component is first being shown or is damaged and in need of repair.
          + * The clip rectangle in the Graphics parameter is set to the area which needs to be painted. Subclasses of Component that override this method need not call super.paint(g).
          + *
          + * For performance reasons, Components with zero width or height aren't considered to need painting when they are first shown, and also aren't considered to need repair. + * + * @param g the graphics context to use for painting + */ + public void paint(Graphics g) { + if (!isPainted) { + if (hasProportionalLocation) + super.setDividerLocation(proportionalLocation); + if (hasDividerLocation) + super.setDividerLocation(dividerLocation); + isPainted = true; + } + super.paint(g); + } + +} diff --git a/src/org/jalgo/module/hoare/view/util/VariableSizeButton.java b/src/org/jalgo/module/hoare/view/util/VariableSizeButton.java new file mode 100644 index 0000000..83d33f2 --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/VariableSizeButton.java @@ -0,0 +1,41 @@ +package org.jalgo.module.hoare.view.util; + +import java.awt.Dimension; +import java.awt.Font; + +import javax.swing.JButton; + +/** + * Button that changes its preferred and minimum size when the font size is changed. + * @author Antje + * + */ +public class VariableSizeButton extends JButton { + + private static final long serialVersionUID = -6440409413153586489L; + + /** + * Relative distance between the text and the border in y direction: height = font size * (1+2*borderWidthFactor) + */ + private double borderWidthFactor = 0.2; + + /** + * Creates a new button that changes its preferred and minimum size when the font size is changed. + * @param borderWidthFactor relative distance between the text and the border in y direction: height = font size * (1+2*borderWidthFactor) + */ + public VariableSizeButton(final double borderWidthFactor) { + this.borderWidthFactor = borderWidthFactor; + } + + /** + * Sets the font for this button. + * @param font the desired Font for this button + */ + public void setFont(Font f) { + super.setFont(f); + Dimension d = new Dimension(getWidth(), (int)Math.round(f.getSize()*(1+borderWidthFactor*2))); + this.setPreferredSize(d); + this.setMinimumSize(d); + } + +} diff --git a/src/org/jalgo/module/hoare/view/util/package-info.java b/src/org/jalgo/module/hoare/view/util/package-info.java new file mode 100644 index 0000000..11ec44c --- /dev/null +++ b/src/org/jalgo/module/hoare/view/util/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains useful classes for the view. + */ +package org.jalgo.module.hoare.view.util; \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/.emptyDir b/src/org/jalgo/module/kmp/.emptyDir new file mode 100644 index 0000000..96d2928 --- /dev/null +++ b/src/org/jalgo/module/kmp/.emptyDir @@ -0,0 +1 @@ +This file was generated by Together to prevent this folder from being deleted during synchronization with the CVS repositiory. Please do not delete this file. \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/CVS/Entries b/src/org/jalgo/module/kmp/CVS/Entries new file mode 100644 index 0000000..a8381e6 --- /dev/null +++ b/src/org/jalgo/module/kmp/CVS/Entries @@ -0,0 +1,10 @@ +/.emptyDir/1.1/Fri Jun 30 14:35:17 2006/-kb/ +/Constants.java/1.2/Thu Jan 31 20:15:12 2008// +/Controller.java/1.1/Fri Jun 30 14:35:17 2006// +/ModuleConnector.java/1.2/Thu Jan 31 20:15:12 2008// +/ModuleInfo.java/1.2/Thu Jan 31 20:15:12 2008// +D/algorithm//// +/de.properties/1.1/Fri Jun 30 14:35:17 2006// +/en.properties/1.1/Fri Jun 30 14:35:17 2006// +D/gui//// +/res.properties/1.1/Fri Jun 30 14:35:17 2006// diff --git a/src/org/jalgo/module/kmp/CVS/Repository b/src/org/jalgo/module/kmp/CVS/Repository new file mode 100644 index 0000000..218c48f --- /dev/null +++ b/src/org/jalgo/module/kmp/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp diff --git a/src/org/jalgo/module/kmp/CVS/Root b/src/org/jalgo/module/kmp/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/Constants.java b/src/org/jalgo/module/kmp/Constants.java new file mode 100644 index 0000000..445acb7 --- /dev/null +++ b/src/org/jalgo/module/kmp/Constants.java @@ -0,0 +1,68 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.05.2005 */ +package org.jalgo.module.kmp; + +/** + * The interface Constants is a collection of several constant + * values used in the core implementation of the KMP module. + * + * @author Danilo Lisske + */ +public interface Constants { + + /*----------------------------valid key range----------------------------*/ + /** The minimum integer value a key can have. */ + public static final int MAX_PAT_LENGTH = 10; + /** The size of the alphabet for the random pattern. */ + public static final int ALPHABET_SIZE = 10; + /** The length of the random generated searchtext. */ + public static final int RANDOM_SEARCHTEXT_LENGTH = 30; + /** The newline-character depending on the operating system. */ + public static final String SEPARATOR = System.getProperty("line.separator"); + /** The file seperator depending on the Operating System. */ + public static final String FILE_SEPARATOR = System.getProperty("file.separator"); + /** The code of phase one (build shiftingtable). */ + public static final String CODE_PHASE_ONE = "Tabelle[0] = -1;" + SEPARATOR + + "VglInd = 0;" + SEPARATOR + + "for (PatPos = 1; PatPos <= PatternLength - 1; PatPos = PatPos + 1) {" + SEPARATOR + + " if (Pattern[PatPos] == Pattern[VglInd])" + SEPARATOR + + " Tabelle[PatPos] = Tabelle[VglInd];" + SEPARATOR + + " else Tabelle[PatPos] = VglInd;" + SEPARATOR + + " while ((VglInd >= 0) && (Pattern[PatPos] != Pattern[VglInd]))" + SEPARATOR + + " VglInd = Tabelle[VglInd];" + SEPARATOR + + " VglInd = VglInd + 1;" + SEPARATOR + + "}"; + /** The code of phase two (find pattern). */ + public static final String CODE_PHASE_TWO = "TextPos = 0; PatternPos = 0;" + SEPARATOR + + "while ((PatternPos < Patternlength) && (TextPos < TextLength)) {" + SEPARATOR + + " while ((PatternPos >=0 ) && (Text[TextPos] != Pattern[PatternPos]))" + SEPARATOR + + " PatternPos = Tabelle[PatternPos];" + SEPARATOR + + " TextPos = TextPos + 1;" + SEPARATOR + + " PatternPos = PatternPos + 1;" + SEPARATOR + + "}" + SEPARATOR + + "if (PatternPos == Patternlength)" + SEPARATOR + + " printf(\"Pattern was found at position : %d\", TextPos - Patternlength);" + SEPARATOR + + "else printf(\"Pattern was not found\");"; +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/Controller.java b/src/org/jalgo/module/kmp/Controller.java new file mode 100644 index 0000000..42e36b8 --- /dev/null +++ b/src/org/jalgo/module/kmp/Controller.java @@ -0,0 +1,284 @@ +package org.jalgo.module.kmp; + +import org.jalgo.module.kmp.algorithm.History; +import org.jalgo.module.kmp.algorithm.Pattern; +import org.jalgo.module.kmp.algorithm.StepFactory; +import org.jalgo.module.kmp.algorithm.Step; +import org.jalgo.module.kmp.algorithm.phaseone.P1Step; +import org.jalgo.module.kmp.algorithm.phasetwo.P2Step; + +import java.io.ObjectOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * The class Controller is an important connection between the + * GUI an the working algorithm.
          + * It provides several functions like: to start a new algorithm, to check if the + * working algorithm is ready and to get the results of the active algorithm. + * + * @author Danilo Lisske + */ +public class Controller implements Constants { + private Pattern pattern; + private String searchtext; + private History history; + private StepFactory stepfactory; + private int phase; + private boolean isload; + + /** + * The constructor of the controller. It creates the StepFactory + * and initialises some variables. + * + * @param p the pattern + * @param s the searchtext + * @param h the history + */ + public Controller(Pattern p, String s, History h) { + pattern = p; + searchtext = s; + history = h; + stepfactory = new StepFactory(); + phase = 0; + isload = false; + } + + /** + * The method is called when a j-Algo-KMP-module file has to be loaded. + * + * @param p the pattern + * @param s the searchtext + * @param h the history + * @return nothing (0) + */ + public int loadData(String p, String s, History h) { + pattern.setPattern(p); + searchtext = s; + history = h; + isload = true; + Step step = null; + if (history.getAktStepNo() == -1) step = history.getNextStep(); + else step = history.getCurrentStep(); + if (step instanceof P1Step) return 1; + if (step instanceof P2Step) return 2; + return 0; + } + + /** + * The method is called when a user wants to save his actual session. + * + * @param out the output stream + */ + public void saveData(ByteArrayOutputStream out) { + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeObject(pattern.getPattern()); + objOut.writeObject(searchtext); + objOut.writeObject(history); + objOut.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + } + + /** + * The method starts the phase one by setting the phase-variable to 1. + * + */ + public void startPhaseOne() { + phase = 1; + } + + /** + * The method initialises the phase one by initialising the StepFactory. + * + */ + public void initPhaseOne() { + phase = 1; + if (!isload) stepfactory.startPhaseOne(pattern,history); + } + + /** + * The method is called when loading a session or expanding the pattern in phase one. + * + */ + public void restorePhaseOne() { + phase = 1; + int oldstepno = history.getAktStepNo(); + initPhaseOne(); + if (oldstepno == -1) oldstepno++; + history.setAktStepNo(oldstepno - 1); + } + + /** + * The method starts the phase two by setting the phase-variable to 2. + * + */ + public void startPhaseTwo() { + phase = 2; + } + + /** + * The method initialises the phase two by initialising the StepFactory. + * + */ + public void initPhaseTwo() { + phase = 2; + if (!isload) stepfactory.startPhaseTwo(pattern,searchtext,history); + } + + /** + * The method is called when loading a session or expanding the pattern in phase two. + * + */ + public void restorePhaseTwo() { + phase = 2; + int oldstepno = history.getAktStepNo(); + initPhaseTwo(); + history.setAktStepNo(oldstepno - 1); + } + + /** + * The method is called if a session was loaded. + * + * @param value if the actual session was loaded + */ + public void setLoad(boolean value) { + isload = value; + } + + /** + * The method is called to get the pattern. + * + * @return the pattern + */ + public Pattern getPattern() { + return pattern; + } + + /** + * The method is called to check if the pattern is set. + * + * @return if the pattern is set + */ + public boolean isPatternSet() { + return pattern.isPatternSet(); + } + + /** + * The method is called to check if the pattern is expandable. + * + * @return if the pattern is expandable + */ + public boolean isPatternExpandable() { + return pattern.isPatternExpandable(); + } + + /** + * The method is called to get the searchtext. + * + * @return the searchtext + */ + public String getSearchText() { + return searchtext; + } + + /** + * The method is called to check if the searchtext is set. + * + * @return if the searchtext is set + */ + public boolean isSearchTextSet() { + return !(searchtext.equals("") || searchtext == null); + } + + /** + * The method is called to set the searchtext. + * + * @param s the searchtext + */ + public void setSearchText(String s) { + searchtext = s; + } + + /** + * The method is called to check in which phase the user is. + * + * @return the actual phase + */ + public int getPhase() { + return phase; + } + + /** + * The method is called when the next step should be performed. + * + * @return the next step + */ + public Step doNextStep() { + Step nextstep = history.getNextStep(); + return nextstep; + } + + /** + * The method is called when the next big step should be performed. + * + * @return the next big step + */ + public Step doNextBigStep() { + Step nextbigstep = history.getNextBigStep(); + return nextbigstep; + } + + /** + * The method is called when the algorithm should be finished. + * + * @return the end step + */ + public Step doEndStep() { + Step endstep = history.getEndStep(); + return endstep; + } + + /** + * The method is called when the previous step should be performed. + * + * @return the previous step + */ + public Step doPreviousStep() { + Step previousstep = history.getPreviousStep(); + return previousstep; + } + + /** + * The method is called when the previous big step should be performed. + * + * @return the previous big step + */ + public Step doPreviousBigStep() { + Step previousbigstep = history.getPreviousBigStep(); + return previousbigstep; + } + + /** + * The method is called when the algorithm should be rewinded. + * + * @return the start step + */ + public Step doStartStep() { + Step startstep = history.getStartStep(); + return startstep; + } + + /** + * The method is called to clear all sensible data. + * + */ + public void clearData() { + pattern.setPattern(""); + history.clear(); + searchtext = ""; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/ModuleConnector.java b/src/org/jalgo/module/kmp/ModuleConnector.java new file mode 100644 index 0000000..21e7753 --- /dev/null +++ b/src/org/jalgo/module/kmp/ModuleConnector.java @@ -0,0 +1,99 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.04.2005 */ +package org.jalgo.module.kmp; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.Controller; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.algorithm.History; +import org.jalgo.module.kmp.algorithm.Pattern; + +/** + * This class provides the bridge between the main program and the current + * instance of the KMP module. It handles the references of several objects and + * provides some methods used in the main program. + * + * @author Danilo Lisske + */ +public class ModuleConnector +extends AbstractModuleConnector { + private Controller controller; + private GUIController gui; + + public void init() { + controller = new Controller(new Pattern(), new String(), new History()); + gui = new GUIController(this, controller); + } + + public void run() { + gui.installWelcomeScreen(); + } + + public void setDataFromFile(ByteArrayInputStream data) { + try { + ObjectInputStream in = new ObjectInputStream(data); + String pattern = (String)in.readObject(); + String searchtext = (String)in.readObject(); + History history = (History)in.readObject(); + int phase = controller.loadData(pattern, searchtext, history); + if (phase == 1) { + gui.installPhaseOneScreen(); + gui.restorePhaseOne(); + } + else if (phase == 2) { + gui.installPhaseTwoScreen(); + gui.restorePhaseTwo(); + } + else gui.installWelcomeScreen(); + } + catch (IOException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "kmp", "ModuleConnector.No_valid_KMP_file")); + } + catch (ClassNotFoundException ex) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "kmp", "ModuleConnector.Loading_error") + + System.getProperty("line.separator") + + Messages.getString("kmp", "ModuleConnector.File_damaged")); + } + } + + public ByteArrayOutputStream getDataForFile() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + controller.saveData(out); + return out; + } + + public void print() { +// printing is currently not supported + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/ModuleInfo.java b/src/org/jalgo/module/kmp/ModuleInfo.java new file mode 100644 index 0000000..1340cd5 --- /dev/null +++ b/src/org/jalgo/module/kmp/ModuleInfo.java @@ -0,0 +1,120 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.04.2005 */ +package org.jalgo.module.kmp; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +/** + * This class represents some information about the KMP module. + * + * @author Danilo Lißke + */ +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getName() + */ + public String getName() { + return Messages.getString("kmp", "Module_name"); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getVersion() + */ + public String getVersion() { + return Messages.getString("kmp", "Module_version"); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getAuthor() + */ + public String getAuthor() { + return Messages.getString("kmp", "Module_authors"); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getDescription() + */ + public String getDescription() { + return Messages.getString("kmp", "Module_description_1") + + System.getProperty("line.separator") + + Messages.getString("kmp", "Module_description_2"); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getLogo() + */ + public URL getLogoURL() { + return Messages.getResourceURL("kmp", "Module_logo"); + } + + /* + * (non-Javadoc) + * + * @see org.jalgo.main.IModuleInfo#getLicense() + */ + public String getLicense() { + return Messages.getString("kmp", "Module_license"); + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("kmp","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/CVS/Entries b/src/org/jalgo/module/kmp/algorithm/CVS/Entries new file mode 100644 index 0000000..ea15f72 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/CVS/Entries @@ -0,0 +1,8 @@ +/ExampleFileFilter.java/1.1/Fri Jun 30 14:35:19 2006// +/History.java/1.1/Fri Jun 30 14:35:19 2006// +/KMPHighlighter.java/1.1/Fri Jun 30 14:35:19 2006// +/Pattern.java/1.1/Fri Jun 30 14:35:19 2006// +/Step.java/1.1/Fri Jun 30 14:35:19 2006// +/StepFactory.java/1.1/Fri Jun 30 14:35:19 2006// +D/phaseone//// +D/phasetwo//// diff --git a/src/org/jalgo/module/kmp/algorithm/CVS/Repository b/src/org/jalgo/module/kmp/algorithm/CVS/Repository new file mode 100644 index 0000000..e2cdbd1 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/algorithm diff --git a/src/org/jalgo/module/kmp/algorithm/CVS/Root b/src/org/jalgo/module/kmp/algorithm/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/algorithm/ExampleFileFilter.java b/src/org/jalgo/module/kmp/algorithm/ExampleFileFilter.java new file mode 100644 index 0000000..53571c3 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/ExampleFileFilter.java @@ -0,0 +1,269 @@ +/* + * @(#)ExampleFileFilter.java 1.16 04/07/26 + * + * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * -Redistribution of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * -Redistribution in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING + * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") + * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE + * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST + * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, + * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY + * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, + * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed, licensed or intended + * for use in the design, construction, operation or maintenance of any + * nuclear facility. + */ + +/* + * @(#)ExampleFileFilter.java 1.16 04/07/26 + */ +package org.jalgo.module.kmp.algorithm; + +import java.io.File; +import java.util.Hashtable; +import java.util.Enumeration; +import javax.swing.filechooser.FileFilter; + +/** + * A convenience implementation of FileFilter that filters out + * all files except for those type extensions that it knows about. + * + * Extensions are of the type ".foo", which is typically found on + * Windows and Unix boxes, but not on Macinthosh. Case is ignored. + * + * Example - create a new filter that filerts out all files + * but gif and jpg image files: + * + * JFileChooser chooser = new JFileChooser(); + * ExampleFileFilter filter = new ExampleFileFilter( + * new String{"gif", "jpg"}, "JPEG & GIF Images") + * chooser.addChoosableFileFilter(filter); + * chooser.showOpenDialog(this); + * + * @version 1.16 07/26/04 + * @author Jeff Dinkins, redesign by Danilo Lisske + */ +public class ExampleFileFilter extends FileFilter { + private Hashtable filters = null; + private String description = null; + private String fullDescription = null; + private boolean useExtensionsInDescription = true; + + /** + * Creates a file filter. If no filters are added, then all + * files are accepted. + * + * @see #addExtension + */ + public ExampleFileFilter() { + this.filters = new Hashtable(); + } + + /** + * Creates a file filter that accepts files with the given extension. + * Example: new ExampleFileFilter("jpg"); + * + * @see #addExtension + * @param extension the extension + */ + public ExampleFileFilter(String extension) { + this(extension,null); + } + + /** + * Creates a file filter that accepts the given file type. + * Example: new ExampleFileFilter("jpg", "JPEG Image Images"); + * + * Note that the "." before the extension is not needed. If + * provided, it will be ignored. + * + * @see #addExtension + * @param extension the extension + * @param description the description + */ + public ExampleFileFilter(String extension, String description) { + this(); + if(extension!=null) addExtension(extension); + if(description!=null) setDescription(description); + } + + /** + * Creates a file filter from the given string array. + * Example: new ExampleFileFilter(String {"gif", "jpg"}); + * + * Note that the "." before the extension is not needed adn + * will be ignored. + * + * @see #addExtension + * @param filters the filters + */ + public ExampleFileFilter(String[] filters) { + this(filters, null); + } + + /** + * Creates a file filter from the given string array and description. + * Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images"); + * + * Note that the "." before the extension is not needed and will be ignored. + * + * @see #addExtension + * @param filters the filters + * @param description the description + */ + public ExampleFileFilter(String[] filters, String description) { + this(); + for (int i = 0; i < filters.length; i++) { + // add filters one by one + addExtension(filters[i]); + } + if (description != null) setDescription(description); + } + + /** + * Return true if this file should be shown in the directory pane, + * false if it shouldn't. + * + * Files that begin with "." are ignored. + * + * @see #getExtension + */ + public boolean accept(File f) { + if(f != null) { + if(f.isDirectory()) { + return true; + } + String extension = getExtension(f); + if(extension != null && filters.get(getExtension(f)) != null) { + return true; + }; + } + return false; + } + + /** + * Return the extension portion of the file's name . + * + * @see #getExtension + * @see FileFilter#accept + * @param f the file + * @return the extension + */ + public String getExtension(File f) { + if(f != null) { + String filename = f.getName(); + int i = filename.lastIndexOf('.'); + if(i>0 && iHistory includes all Steps which are necessary + * for the current algorithm session. + * + * @author Danilo Lisske, Nadine Grabow + */ +public class History implements Serializable { + private static final long serialVersionUID = 5319401850744447321L; + + private List history; + private int aktstepno; + + /** + * The constructor of the History. + * + */ + public History() { + history = new LinkedList(); + aktstepno = -1; + } + + /** + * Returns the actual step number. + * + * @return the actual step number + */ + public int getAktStepNo() { + return aktstepno; + } + + /** + * Sets the actual step number. + * + * @param newaktstepno the new actual step number + */ + public void setAktStepNo(int newaktstepno) { + aktstepno = newaktstepno; + } + + /** + * Returns the size of the history. + * + * @return the size of the history + */ + public int getGesStepNo() { + return history.size() - 1; + } + + /** + * Adds a given Step to the History. + * + * @param step the step + */ + public void addStep(Step step) { + history.add(step); + } + + /** + * Returns the current Step. + * + * @return the current Step + */ + public Step getCurrentStep() { + return history.get(aktstepno); + } + + /** + * Returns the next Step. + * + * @return the next Step + */ + public Step getNextStep() { + if (aktstepno < getGesStepNo()) return history.get(++aktstepno); + else return null; + } + + /** + * Returns the next big Step. + * + * @return the next big Step + */ + public Step getNextBigStep() { + if (aktstepno < getGesStepNo()) { + Step step = history.get(++aktstepno); + while((step instanceof P1SmallStep || step instanceof P2SmallStep) + && (aktstepno < getGesStepNo())) step = history.get(++aktstepno); + return step; + } + else return null; + } + + /** + * Returns the end Step. + * + * @return the end Step + */ + public Step getEndStep() { + if (getGesStepNo() > 0) { + aktstepno = getGesStepNo(); + return history.get(getGesStepNo()); + } + else return null; + } + + /** + * Returns the previous Step. + * + * @return the previous Step + */ + public Step getPreviousStep() { + if (aktstepno > 0) return history.get(--aktstepno); + else return null; + } + + /** + * Returns the previous big Step. + * + * @return the previous big Step + */ + public Step getPreviousBigStep() { + if (aktstepno > 0) { + Step step = history.get(--aktstepno); + while((step instanceof P1SmallStep || step instanceof P2SmallStep) + && (aktstepno > 0)) step = history.get(--aktstepno); + return step; + } + else return null; + } + + /** + * Returns the start Step. + * + * @return the start Step + */ + public Step getStartStep() { + if (getGesStepNo() > 0) { + aktstepno = 0; + return history.get(0); + } + else return null; + } + + /** + * Clears the History. + * + */ + public void clear() { + aktstepno = -1; + history.clear(); + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(aktstepno); + out.writeObject(history); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + aktstepno = in.readInt(); + history = (List)in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/KMPHighlighter.java b/src/org/jalgo/module/kmp/algorithm/KMPHighlighter.java new file mode 100644 index 0000000..2728e82 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/KMPHighlighter.java @@ -0,0 +1,72 @@ +package org.jalgo.module.kmp.algorithm; + +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Highlighter; +import java.awt.Color; +import java.io.Serializable; +import java.io.IOException; + +/** + * The highlighters for the InfoTabbedPanel. + * + * @author Danilo Lisske, Sebastian Patschorke + */ +public class KMPHighlighter implements Serializable { + private static final long serialVersionUID = 4582211301082985368L; + + private int startpos; + private int endpos; + private Color hlpcolor; + + /** + * The constructor if the KMPHighlighter. + * + * @param start the start position + * @param end the end position + * @param color the color of the highlight + */ + public KMPHighlighter(int start, int end, Color color) { + startpos = start; + endpos = end; + hlpcolor = color; + } + + /** + * Returns the start position. + * + * @return the start position + */ + public int getStartPos() { + return startpos; + } + + /** + * Returns the end position. + * + * @return the end position + */ + public int getEndPos() { + return endpos; + } + + /** + * Returns the Highlighter.HighlightPainter of this highlight. + * + * @return the Highlighter.HighlightPainter + */ + public Highlighter.HighlightPainter getHightlightPainter() { + return new DefaultHighlighter.DefaultHighlightPainter(hlpcolor); + } + + private void writeObject(java.io.ObjectOutputStream out) throws IOException { + out.writeInt(startpos); + out.writeInt(endpos); + out.writeObject(hlpcolor); + } + + private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { + startpos = in.readInt(); + endpos = in.readInt(); + hlpcolor = (Color)in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/Pattern.java b/src/org/jalgo/module/kmp/algorithm/Pattern.java new file mode 100644 index 0000000..d4ee9d0 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/Pattern.java @@ -0,0 +1,184 @@ +package org.jalgo.module.kmp.algorithm; + +import org.jalgo.module.kmp.Constants; +import java.util.LinkedList; + +/** + * The Pattern for the algorithm. + * + * @author Danilo Lisske + */ +public class Pattern { + private String pattern; + private int[] shiftingtable; + private boolean ispatternset = false; + private boolean isexpandable = true; + private LinkedList cycletable; + + /** + * Sets the Pattern. + * + * @param pattern the pattern + */ + public void setPattern(String pattern) { + if(!(pattern == "" || pattern == null)) { + if(pattern.length() <= Constants.MAX_PAT_LENGTH) { + this.pattern = pattern; + ispatternset = true; + buildShiftingTable(); + buildCycleTable(); + if(pattern.length() == Constants.MAX_PAT_LENGTH) isexpandable = false; + else isexpandable = true; + } + } + else ispatternset = false; + } + + /** + * Returns the pattern as a Pattern object. + * + * @return the Pattern + */ + public String getPattern() { + return pattern; + } + + /** + * Checks if the pattern is already set. + * + * @return if the pattern is set + */ + public boolean isPatternSet() { + return ispatternset; + } + + /** + * Checks if the pattern is expandable. + * + * @return if the pattern is expandable + */ + public boolean isPatternExpandable() { + return isexpandable; + } + + /** + * Returns the Character at the specified position. + * + * @param index the position + * @return the character + */ + public char getCharAt(int index) { + return pattern.charAt(index); + } + + /** + * Returns the shiftingtable entry at the specified position. + * + * @param index the position + * @return the shiftingtable entry + */ + public int getTblEntryAt(int index) { + return shiftingtable[index]; + } + + /** + * Sets the shiftingtable entry at the specified position to the + * specified value. + * + * @param index the position + * @param value the value + */ + public void setTblEntryAt(int index, int value) { + shiftingtable[index] = value; + } + + private void buildShiftingTable() { + shiftingtable = new int[pattern.length()]; + shiftingtable[0] = -1; + int vglind = 0; + + for (int patpos = 1; patpos < pattern.length(); patpos++) + { + if (pattern.charAt(patpos) == pattern.charAt(vglind)) + shiftingtable[patpos] = shiftingtable[vglind]; + else shiftingtable[patpos] = vglind; + + while ((vglind >= 0) && (pattern.charAt(patpos) != pattern.charAt(vglind))) + vglind = shiftingtable[vglind]; + vglind++; + } + } + + private void buildCycleTable() { + cycletable = new LinkedList(); + int[] cycledepthtable = new int[pattern.length()]; + int[] workdata; + int vglind = 0; + int workpos = 0; + int i; + + for (int patpos = 1; patpos < pattern.length(); patpos++){ + vglind = 0; + if (pattern.charAt(0) == pattern.charAt(patpos)){ + workpos = patpos; + while( (workpos < pattern.length()) && (pattern.charAt(vglind) == pattern.charAt(workpos))) { + cycledepthtable[workpos]++; + workpos++; vglind++; + } + } + } + + cycletable.clear(); + workdata = new int[1]; workdata[0] = 0; + cycletable.add(0, workdata); + for (int patpos = 1; patpos < pattern.length(); patpos++){ + workdata = new int[(cycledepthtable[patpos])+1]; + for (i=0; i<(cycledepthtable[patpos])+1;i++) + workdata[i] = 0; + cycletable.add(patpos, workdata); + } + + for (int patpos = 1; patpos < pattern.length(); patpos++){ + vglind = 0; + if (pattern.charAt(0) == pattern.charAt(patpos)){ + workpos = patpos; + while((workpos < pattern.length()) && (pattern.charAt(vglind) == pattern.charAt(workpos))) { + workdata = (int[]) cycletable.get(workpos); + i=0; + while (workdata[i] != 0) i++; + workdata[i] = patpos; + cycletable.set(workpos, workdata); + workpos++; vglind++; + } + } + } + } + + /** + * Returns an intarray with the cycle data. + * + * @param index + * @return an intarray with the cycle data + */ + public int[] getCycleDataAt(int index) { + int[] work = new int[((int[])cycletable.get(index)).length -1]; + System.arraycopy((int[])cycletable.get(index), 0, work, 0, ((int[])cycletable.get(index)).length -1); + return work; + } + + public String toString() { + String shifttable = ""; + String cycletable = ""; + for (int i = 0; i < shiftingtable.length; i++) { + shifttable += shiftingtable[i]; + } + for (int j = 0; j < pattern.length(); j++) { + cycletable += "["; + for (int i = 0; i < (getCycleDataAt(j)).length; i++) { + cycletable += (int) ((int[]) (getCycleDataAt(j)))[i] + ","; + } + cycletable += "] "; + } + return "Pattern = " + pattern + "\nVerschiebeTabelle = " + shifttable + "\nZyklenInfo = " + cycletable; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/Step.java b/src/org/jalgo/module/kmp/algorithm/Step.java new file mode 100644 index 0000000..2ed2d8f --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/Step.java @@ -0,0 +1,32 @@ +package org.jalgo.module.kmp.algorithm; + +import java.io.Serializable; +import java.util.List; + +/** + * This class is the interface of all Stepclasses + * + * @author Danilo Lisske + */ +public interface Step extends Serializable { + /** + * Returns the pattern position. + * + * @return the pattern position + */ + public int getPatPos(); + + /** + * Returns a descriptionstring, who is specialy for each Stepclass with its parameters + * + * @return the descriptiontext + */ + public String getDescriptionText(); + + /** + * Returns a list of Highlightinformations, which is specialy for each stepclass with its parameters + * + * @return a List of KMPHighlighter + */ + public List getKMPHighlighter(); +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/StepFactory.java b/src/org/jalgo/module/kmp/algorithm/StepFactory.java new file mode 100644 index 0000000..3ea9a00 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/StepFactory.java @@ -0,0 +1,256 @@ +package org.jalgo.module.kmp.algorithm; + +import org.jalgo.module.kmp.algorithm.phaseone.*; +import org.jalgo.module.kmp.algorithm.phasetwo.*; + +/** + * This class implements a factory for producing the steps which represent parts + * of the original KMP algorithm + * + * @author Elisa Böhl, Matthias Neubert + */ +public class StepFactory { + private Pattern pattern; + + private String searchtext; + + private History history; + + /** + * This method is for phase one (production of the shifting table). It fills + * the History with steps which represent parts of the original KMP + * algorithm by adding steps produced by performNextStepP1() + * + * @param startstep the startstep + */ + private void fillHistoryP1(Step startstep) { + Step aktstep = performNextStepP1(startstep); + while (aktstep != null) { + history.addStep(aktstep); + aktstep = performNextStepP1(aktstep); + } + } + + /** + * This procedure starts the algorithm Phase 2 (Patternsearching in a text) + * and fills the history with steps, which represent the algorithmstates + * + * @param startstep the startstep + */ + private void fillHistoryP2(Step startstep) { + Step aktstep = performNextStepP2(startstep); + while (aktstep != null) { + history.addStep(aktstep); + aktstep = performNextStepP2(aktstep); + } + } + + /** + * This method initializes phase one. Called by the controller. + * At first it clears the history and then creates the first step + * (P1InitStep) with PatPos and VglInd set zero. After adding this firststep + * to the history fillHistoryP1() is called by using P1InitStep as a + * root-step + * + * @param p the actual Pattern + * @param h the History + */ + public void startPhaseOne(Pattern p, History h) { + pattern = p; + history = h; + history.clear(); + Step startstep = new P1InitStep(0, 0); // patpos==0 is interpreted as: + // make PatPos arrow invisble + history.addStep(startstep); + fillHistoryP1(startstep); + } + + /** + * This procedure starts with all needed objects to calculate the list of + * algorithmsates (called History) for Phase 2 (Pattermsearch in a Text). it + * sets the values, initializes the History and fills it with steps + * + * @param p the Pattern + * @param s the searchtext + * @param h the History + */ + public void startPhaseTwo(Pattern p, String s, History h) { + pattern = p; + searchtext = s; + history = h; + history.clear(); + Step startstep = new P2InitStep(0, 0); + history.addStep(startstep); + fillHistoryP2(startstep); + } + + /** + * This method produces -based on the actual step- a new step corrensponding + * to the original KMP algorithm. (steps represent parts or statements of + * the original C - sourcecode) + * + * @param step the actual Step + * + * @return Step the next Step + */ + private Step performNextStepP1(Step step) { + + if (step instanceof P1InitStep) + return new P1BeginForStep(1, 0, false); + + if (step instanceof P1BeginForStep) { + if (pattern.getPattern().length() == 1) return null; + + if (!((P1BeginForStep) step).isLastForStep()) { + + if (pattern.getPattern().charAt(step.getPatPos()) != pattern + .getPattern().charAt( + ((P1BeginForStep) step).getVglInd())) + return new P1IfFalseStep(step.getPatPos(), + ((P1BeginForStep) step).getVglInd(), pattern + .getPattern().charAt(step.getPatPos()), + pattern.getPattern().charAt( + ((P1BeginForStep) step).getVglInd())); + + else + return new P1IfTrueStep(step.getPatPos(), + ((P1BeginForStep) step).getVglInd(), pattern + .getPattern().charAt(step.getPatPos()), + pattern.getPattern().charAt( + ((P1BeginForStep) step).getVglInd())); + } + + else return null; + } + + if (step instanceof P1IfFalseStep) + if ((((P1IfFalseStep) step).getVglInd() >= 0) + && (pattern.getPattern().charAt(step.getPatPos()) != pattern + .getPattern().charAt( + ((P1IfFalseStep) step).getVglInd()))) + return new P1WhileStep(step.getPatPos(), pattern + .getTblEntryAt(((P1IfFalseStep) step).getVglInd()), + false, 0, ((P1IfFalseStep) step).getVglInd()); + + if (step instanceof P1IfTrueStep) + return new P1EndForStep(step.getPatPos(), ((P1IfTrueStep) step) + .getVglInd() + 1); + + if (step instanceof P1WhileStep) { + if (!((P1WhileStep) step).isLastWhileStep()) { + if ((((P1WhileStep) step).getVglInd() >= 0) + && (pattern.getPattern().charAt(step.getPatPos()) != pattern + .getPattern().charAt( + ((P1WhileStep) step).getVglInd()))) + return new P1WhileStep(step.getPatPos(), pattern + .getTblEntryAt(((P1WhileStep) step).getVglInd()), + false, 0, ((P1WhileStep) step).getVglInd()); + + if (((P1WhileStep) step).getVglInd() < 0) + return new P1WhileStep(step.getPatPos(), + ((P1WhileStep) step).getVglInd(), true, 1, + ((P1WhileStep) step).getVglInd()); + + if (pattern.getPattern().charAt(step.getPatPos()) == pattern + .getPattern().charAt(((P1WhileStep) step).getVglInd())) + return new P1WhileStep(step.getPatPos(), + ((P1WhileStep) step).getVglInd(), true, 2, + ((P1WhileStep) step).getVglInd()); + } + + else return new P1EndForStep(step.getPatPos(), ((P1WhileStep) step) + .getVglInd() + 1); + } + + if (step instanceof P1EndForStep) { + if (step.getPatPos() == (pattern.getPattern().length() - 1)) + return new P1BeginForStep(step.getPatPos() + 1, + ((P1EndForStep) step).getVglInd(), true); + + else return new P1BeginForStep(step.getPatPos() + 1, + ((P1EndForStep) step).getVglInd(), false); + } + + return null; + + } + + /** + * this function returns the fallowing P2step of a given P2step. if the + * given step is the last step who can be created, it will be returned null + * + * @param step the old Step + * + * @return the new Step + */ + private Step performNextStepP2(Step step) { + if (step instanceof P2InitStep) { + if ((step.getPatPos() >= (pattern.getPattern()).length()) + || (((P2InitStep) step).getTextPos() >= searchtext.length())) + return new P2OuterWhileStep(step.getPatPos(), + ((P2InitStep) step).getTextPos(), true); + else return new P2OuterWhileStep(step.getPatPos(), + ((P2InitStep) step).getTextPos(), false); + } + + if (step instanceof P2OuterWhileStep) { + if (((P2OuterWhileStep) step).isLastWhileStep()) { + if (step.getPatPos() >= (pattern.getPattern()).length()) + return new P2EndStep(step.getPatPos(), + ((P2OuterWhileStep) step).getTextPos(), true); + else return new P2EndStep(step.getPatPos(), + ((P2OuterWhileStep) step).getTextPos(), false); + } + else if ((step.getPatPos() >= 0) + && ((pattern.getPattern()).charAt(step.getPatPos()) != searchtext + .charAt(((P2OuterWhileStep) step).getTextPos()))) { + int tableEntry = pattern.getTblEntryAt(step.getPatPos()); + int tp = ((P2OuterWhileStep) step).getTextPos(); + return new P2InnerWhileStep(tableEntry, tp, false, step + .getPatPos() + - tableEntry, (pattern.getPattern()).length()); + + } + else { + int tp = ((P2OuterWhileStep) step).getTextPos(); + return new P2InnerWhileStep(step.getPatPos(), tp, true, 0, + (pattern.getPattern()).length()); + } + } + + if (step instanceof P2InnerWhileStep) { + if (((P2InnerWhileStep) step).isLastWhileStep()) + return new P2InnerSetStep(step.getPatPos() + 1, + ((P2InnerWhileStep) step).getTextPos() + 1); + else if ((step.getPatPos() >= 0) + && ((pattern.getPattern()).charAt(step.getPatPos()) != searchtext + .charAt(((P2InnerWhileStep) step).getTextPos()))) { + int tableEntry = pattern.getTblEntryAt(step.getPatPos()); + int tp = ((P2InnerWhileStep) step).getTextPos(); + return new P2InnerWhileStep(tableEntry, tp, false, step + .getPatPos() + - tableEntry, (pattern.getPattern()).length()); + } + else { + int tp = ((P2InnerWhileStep) step).getTextPos(); + return new P2InnerWhileStep(step.getPatPos(), tp, true, 0, + (pattern.getPattern()).length()); + } + } + + if (step instanceof P2InnerSetStep) { + if ((step.getPatPos() >= (pattern.getPattern()).length()) + || (((P2InnerSetStep) step).getTextPos() >= searchtext + .length())) + return new P2OuterWhileStep(step.getPatPos(), + ((P2InnerSetStep) step).getTextPos(), true); + + else return new P2OuterWhileStep(step.getPatPos(), + ((P2InnerSetStep) step).getTextPos(), false); + } + + if (step instanceof P2EndStep) return null; + + return null; + } +} diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Entries b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Entries new file mode 100644 index 0000000..b30f354 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Entries @@ -0,0 +1,9 @@ +/P1BeginForStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1BigStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1EndForStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1IfFalseStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1IfTrueStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1InitStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1SmallStep.java/1.1/Fri Jun 30 14:35:15 2006// +/P1Step.java/1.1/Fri Jun 30 14:35:15 2006// +/P1WhileStep.java/1.1/Fri Jun 30 14:35:15 2006// diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Repository b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Repository new file mode 100644 index 0000000..8ee4a54 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/algorithm/phaseone diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Root b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.java new file mode 100644 index 0000000..7fa7e4e --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1BeginForStep.java @@ -0,0 +1,101 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the P1BeginForStep. It marks the + * position in KMP original sourcecode when the if condition in the FOR loop + * evaluated. + * + * @author Matthias Neubert + */ +public class P1BeginForStep extends P1BigStep { + private static final long serialVersionUID = -8505363387847297109L; + + private boolean lastforstep; + + /** + * The constructor. + * + * @param pp the pattern position + * @param vi the compare index + * @param lf if this is the last for step + */ + public P1BeginForStep(int pp, int vi, boolean lf) { + patpos = pp; + vglind = vi; + lastforstep = lf; + } + + /** + * Returns status of beeing the last P1BeginForStep or not for this step + * + * @return bool is true if this is the last P1BeginForStep + */ + public Boolean isLastForStep() { + return lastforstep; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (!lastforstep) { + if (lang.equals("de")) + return "Rücke nun den P-Zeiger um eins nach rechts. " + + "Aktuell: PatPos=" + patpos + + ". Das Ende des Pattern ist noch nicht erreicht."; + else + return "The for loop is not over, increase the patternposition."; + } else { + if (lang.equals("de")) + return "Das Ende des Pattern ist nun erreicht." + + Constants.SEPARATOR + + "Die Verschiebetabelle ist fertig!"; + else + return "The for loop is over, this is the end of the algorithm."; + } + } + + public List getKMPHighlighter() { + if (!lastforstep) { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(34, 45, GUIConstants.HIGHLIGHT_COLOR)); + liste.add(new KMPHighlighter(46, 74, GUIConstants.TRUE_COLOR)); + liste.add(new KMPHighlighter(75, 94, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } else { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(34, 45, GUIConstants.HIGHLIGHT_COLOR)); + liste.add(new KMPHighlighter(46, 74, GUIConstants.FALSE_COLOR)); + liste.add(new KMPHighlighter(75, 94, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeBoolean(lastforstep); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + lastforstep = in.readBoolean(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.java new file mode 100644 index 0000000..4d33f7f --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1BigStep.java @@ -0,0 +1,60 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.ObjectInputStream; +import java.util.List; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; + +/** + * This abstract class implements the interface P1Step partially Only + * P1BeginForStep is an big step.(P1BigStep) This marks the P1BeginForStep as an + * big step like a flag but this solution is more potent to control movement on + * the history. + * + * @author Matthias Neubert + */ +public abstract class P1BigStep implements P1Step { + /** The pattern position. */ + public int patpos; + /** The compare index. */ + public int vglind; + /** The descriptiontext. */ + public String descriptiontext; + /** The list filled with KMPHighlighter. */ + public List kmphighlights; + + /** + * Returns the actual value of the pattern position (PatPos) of this step. + * + * @return value of pattern position of this step + */ + public int getPatPos() { + return patpos; + } + + /** + * Returns the actual value of the comparing position (Vergleichsindex) of + * this step. + * + * @return value of comparing position (Vergleichsindex) of this step + */ + public int getVglInd() { + return vglind; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.java new file mode 100644 index 0000000..9a6a776 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1EndForStep.java @@ -0,0 +1,45 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the P1EndForStep. + * + * @author Matthias Neubert + */ +public class P1EndForStep extends P1SmallStep { + private static final long serialVersionUID = -4149353033472562689L; + + /** + * The constructor. + * + * @param pp the pattern position + * @param vi the compare index + */ + public P1EndForStep(int pp, int vi) { + patpos = pp; + vglind = vi; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (lang.equals("de")) + return "Rücke den V-Zeiger um eins nach rechts. " + + "Aktuell: Vergleichsindex=" + vglind + "."; + + else + return "End of for loop."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(324, 344, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.java new file mode 100644 index 0000000..c33938b --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfFalseStep.java @@ -0,0 +1,86 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the P1IfFalseStep. It marks the + * position in KMP original sourcecode when the if condition in the FOR loop is + * not fullfilled so the two letters are different. + * + * @author Matthias Neubert + */ +public class P1IfFalseStep extends P1SmallStep { + private static final long serialVersionUID = 7621445479791563738L; + + char myV; + + char myP; + + /** + * Constructor method (differs from P1SmallStep). + * + * @param pp Pattern position (PatPos) + * @param vi compare index (VglInd) + * @param p character at postion of PatPos + * @param v character at position if VglInd + */ + public P1IfFalseStep(int pp, int vi, char p, char v) { + patpos = pp; + vglind = vi; + myP = p; + myV = v; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (lang.equals("de")) + return "Vergleiche die Buchstaben an den Stellen V und P: " + + Constants.SEPARATOR + + "'" + + myV + + "' ungleich '" + + myP + + "'." + + " Deshalb schreibe den Indexwert von Stelle V in den Tabelleneintrag an Stelle P." + + " Beachte den Tabelleneintrag an der Stelle V." + + " Auf diese Position wird der V-Zeiger im nächsten Schritt verschoben"; + else + return "The if-condition is false."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(106, 140, GUIConstants.FALSE_COLOR)); + liste.add(new KMPHighlighter(194, 219, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeChar(myP); + out.writeChar(myV); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + myP = in.readChar(); + myV = in.readChar(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.java new file mode 100644 index 0000000..0a33bf7 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1IfTrueStep.java @@ -0,0 +1,80 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the P1IfTrueStep. It marks the position + * in KMP original sourcecode when the if condition in the FOR loop is + * fullfilled so the two letters are equal. + * + * @author Matthias Neubert + */ +public class P1IfTrueStep extends P1SmallStep { + private static final long serialVersionUID = -215559000398454503L; + + char myV; + char myP; + + /** + * Constructor method (differs from P1SmallStep). + * + * @param pp Pattern position (PatPos) + * @param vi compare index (VglInd) + * @param p character at postion of PatPos + * @param v character at position if VglInd + */ + public P1IfTrueStep(int pp, int vi, char p, char v) { + patpos = pp; + vglind = vi; + myP = p; + myV = v; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (lang.equals("de")) + return "Vergleiche die Buchstaben an den Stellen V und P: " + + Constants.SEPARATOR + "'" + myP + "' gleich '" + myV + + "'." + Constants.SEPARATOR + + "Deshalb schreibe den Tabelleneintrag von Stelle V in " + + "den Tabelleneintrag an Stelle P."; + else + return "The if-condition is true."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(106, 140, GUIConstants.TRUE_COLOR)); + liste.add(new KMPHighlighter(150, 184, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeChar(myP); + out.writeChar(myV); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + myP = in.readChar(); + myV = in.readChar(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.java new file mode 100644 index 0000000..35771a8 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1InitStep.java @@ -0,0 +1,51 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the initial step of phase one. It marks the start of + * the shifting table build process It is allway created with patpos==0 and + * vglind==0 KMP usually initializes with patpos==-1 but for some reason we had + * to select 0 and interpret it to patpos arrow is invisible. + * + * @author Matthias Neubert + */ +public class P1InitStep extends P1SmallStep { + private static final long serialVersionUID = -5512637554518269829L; + + /** + * The constructor. + * + * @param pp the pattern position + * @param vi the compare index + */ + public P1InitStep(int pp, int vi) { + patpos = pp; + vglind = vi; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (lang.equals("de")) + return "Initialisierung: Der Verschiebetabelleneintrag an der Stelle 0 wird auf -1 gesetzt. " + + "Der Vergleichsindex wird auf 0 gesetzt."; + else + return "Initialisation: The shifting table entry at position 0 is set to -1. " + + "The compare index is set to 0." + + Constants.SEPARATOR + + "Meaning: the algorithm starts."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(0, 29, GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } +} diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.java new file mode 100644 index 0000000..251ca6c --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1SmallStep.java @@ -0,0 +1,60 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; + +import org.jalgo.module.kmp.algorithm.KMPHighlighter; + +/** + * This abstract class implements the interface P1Step partially Every concrete + * step exept the P1BeginForStep is an small step.(P1SmallStep) This is useful + * to differ between a normal "next"-clic and a "fast next"-clic. + * + * @author Matthias Neubert + */ +public abstract class P1SmallStep implements P1Step { + /** The pattern position. */ + public int patpos; + /** The compare index. */ + public int vglind; + /** The descriptiontext. */ + public String descriptiontext; + /** The List filled with KMPHighlighter. */ + public List kmphighlights; + + /** + * Returns the actual value of the pattern position (PatPos) of this step. + * + * @return value of pattern position of this step + */ + public int getPatPos() { + return patpos; + } + + /** + * Returns the actual value of the comparing position (Vergleichsindex) of + * this step. + * + * @return value of comparing position (Vergleichsindex) of this step + */ + public int getVglInd() { + return vglind; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1Step.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1Step.java new file mode 100644 index 0000000..d41b0ab --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1Step.java @@ -0,0 +1,18 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import org.jalgo.module.kmp.algorithm.Step; + +/** + * This class is the interface of all stepsclasses in phase one + * + * @author Matthias Neubert + */ +public interface P1Step extends Step { + + /** + * Returns the compare index. + * + * @return the compare index + */ + public int getVglInd(); +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.java b/src/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.java new file mode 100644 index 0000000..743cd48 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phaseone/P1WhileStep.java @@ -0,0 +1,149 @@ +package org.jalgo.module.kmp.algorithm.phaseone; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class implements the P1WhileStep. It marks the position in KMP original + * sourcecode when the while head is getting evaluated and possibliy the while + * body is executed. + * + * @author Matthias Neubert + */ +public class P1WhileStep extends P1SmallStep { + private static final long serialVersionUID = 2635832786142045084L; + + private boolean lastwhilestep; + private int condition; + private int myOldVglInd; + + /** + * Constructor method (differs from P1SmallStep). + * + * @param pp Pattern position (PatPos) + * @param vi compare index (VglInd) + * @param lw boolean is true when this is the last P1WhileStep in this FOR + * loop pass + * @param cond int which tells what condtion was the reason for escaping from + * or keeping in the while loop cond is 0 if the conditions are + * fullfilled, 1 if VglInd < 0 and 2 if the characters are equal + * @param oldVglind the old VglInd + */ + public P1WhileStep(int pp, int vi, boolean lw, int cond, int oldVglind) { + patpos = pp; + vglind = vi; + lastwhilestep = lw; + condition = cond; + myOldVglInd = oldVglind; + + } + + /** + * Returns the occured condition in the head of the while loop. + * + * @return int which tells what condtion was the reason for escaping from or + * keeping in the while loop cond is 0 if the conditions are + * fullfilled, 1 if VglInd < 0 and 2 if the characters are equal + */ + public int getCond() { + return condition; + } + + /** + * Returns status of beeing the last P1WhileStep or notfor this step. + * + * @return bool is true if this is the last P1WhileStep + */ + public boolean isLastWhileStep() { + return lastwhilestep; + } + + /** + * Returns the VlgInd of the step on which the production of this step is + * based on. This is used to mark the usage of former entries in the + * shiftingtable with a colour. + * + * @return int which is the former vglind + */ + public int getOldVglind() { + return myOldVglInd; + } + + public String getDescriptionText() { + String lang = Settings.getString("main", "Language"); + if (!lastwhilestep) { + if (lang.equals("de")) + return "1. Prüfe, ob der V-Zeiger den Anfang des Pattern noch nicht überschritten hat." + // + Constants.SEPARATOR + + " 2. Prüfe, ob der Buchstabe an Stelle V ungleich dem an Stelle P ist." + + Constants.SEPARATOR + + "Beide Bedingungen waren eben erfüllt. " + + "Deshalb wurde V-Zeiger auf den Indexwert, der bei ihm eben in der " + + "Verschiebetabelle stand, verschoben. (Also auf " + + vglind + + ")" + + " Wiederhole dies, bis eine der beiden Bedingungen nicht erfüllt wird."; + else + return "Whilestep, not the last one."; + } else { + if (lang.equals("de")) { + if (condition == 1) + return "Die 1. Bedingung (der while-Schleife) wurde nicht erfüllt." + + Constants.SEPARATOR + + "Der V-Zeiger hat den Anfang des Pattern überschritten." + + " Der Schleifenkörper wird nicht durchlaufen."; + if (condition == 2) + return "Die 2. Bedingung (der while-Schleife) wurde nicht erfüllt." + + Constants.SEPARATOR + + "Ein zu P gleicher Buchstabe wurde gefunden! Der Schleifenkörper wird nicht durchlaufen."; + } else { + if (condition == 1) + return "Whilestep, the last one_reason 1."; + if (condition == 2) + return "Whilestep, the last one_reason 2."; + } + } + return ""; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + if (!lastwhilestep) { + liste.add(new KMPHighlighter(231, 284, GUIConstants.TRUE_COLOR)); + liste + .add(new KMPHighlighter(293, 320, + GUIConstants.HIGHLIGHT_COLOR)); + } else + liste.add(new KMPHighlighter(231, 284, GUIConstants.FALSE_COLOR)); + return liste; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(vglind); + out.writeBoolean(lastwhilestep); + out.writeInt(condition); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException { + patpos = in.readInt(); + vglind = in.readInt(); + lastwhilestep = in.readBoolean(); + condition = in.readInt(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Entries b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Entries new file mode 100644 index 0000000..3d8c37f --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Entries @@ -0,0 +1,8 @@ +/P2BigStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2EndStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2InitStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2InnerSetStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2InnerWhileStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2OuterWhileStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2SmallStep.java/1.1/Fri Jun 30 14:35:16 2006// +/P2Step.java/1.1/Fri Jun 30 14:35:16 2006// diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Repository b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Repository new file mode 100644 index 0000000..622de4a --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/algorithm/phasetwo diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Root b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.java new file mode 100644 index 0000000..9b92c0e --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2BigStep.java @@ -0,0 +1,47 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; + +import org.jalgo.module.kmp.algorithm.KMPHighlighter; + +/** + * This class specifies an abstract algorithmstate. + * All classes, which implements this class, represent a Marker at the Stephistory. + * + * @author Danilo Lisske, Elisa Böhl + */ +public abstract class P2BigStep implements P2Step { + /** The pattern position. */ + public int patpos; + /** The text position. */ + public int textpos; + /** The descriptiontext. */ + public String descriptiontext; + /** The list filled with KMPHighlighter. */ + public List kmphighlights; + + public int getPatPos() { + return patpos; + } + + public int getTextPos() { + return textpos; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(textpos); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + patpos = in.readInt(); + textpos = in.readInt(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.java new file mode 100644 index 0000000..19e4e70 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2EndStep.java @@ -0,0 +1,94 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class specifies the concrete algorithmstate end of algorithm. + * + * @author Danilo Lisske, Elisa Böhl + */ +public class P2EndStep extends P2SmallStep { + private static final long serialVersionUID = -5517573495563514487L; + + private boolean found; + + /** + * The constructor. + * + * @param pp the pattern position + * @param tp the text position + * @param f if the pattern was found + */ + public P2EndStep(int pp, int tp, boolean f) { + patpos = pp; + textpos = tp; + found = f; + } + + /** + * Returns a boolean var, which descripes, if the Pattern was discovered (true). + * + * @return if the pattern was found + */ + public boolean isPatternFound() { + return found; + } + + public String getDescriptionText() { + String lang = Settings.getString("main","Language"); + if (found) { + if (lang.equals("de")) + return "PatternPos ist größer als die Länge des Patterns. " + + "Das wurde Pattern gefunden an Textposition " + + (textpos - patpos) + "."; + else + return "PatternPos is greater in number then the length of the pattern." + + " So the Pattern was found at Textposition " + (textpos - patpos) + "."; + } + else { + if (lang.equals("de")) + return "Nur die Textlänge wurde überschritten, " + + "das Pattern wurde nicht gefunden."; + else + return "The length of the text was exceeded." + "So the Pattern was not found."; + } + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + if (found) { + liste.add(new KMPHighlighter(274,301,GUIConstants.TRUE_COLOR)); + liste.add(new KMPHighlighter(307,376,GUIConstants.HIGHLIGHT_COLOR)); + } + else { + liste.add(new KMPHighlighter(274,301,GUIConstants.FALSE_COLOR)); + liste.add(new KMPHighlighter(382,415,GUIConstants.HIGHLIGHT_COLOR)); + } + return liste; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(textpos); + out.writeBoolean(found); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + patpos = in.readInt(); + textpos = in.readInt(); + found = in.readBoolean(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.java new file mode 100644 index 0000000..eb0e9ae --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InitStep.java @@ -0,0 +1,48 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class specifies the concrete algorithmstate initialisation of algorithm. + * + * @author Danilo Lisske, Elisa Böhl + */ +public class P2InitStep extends P2SmallStep { + private static final long serialVersionUID = 4453507936499153868L; + + /** + * The constructor. + * + * @param pp the pattern position + * @param tp the text position + */ + public P2InitStep(int pp, int tp) { + patpos = pp; + textpos = tp; + } + + public String getDescriptionText() { + String lang = Settings.getString("main","Language"); + if (lang.equals("de")) + return "Initialisierung: PatternPos und TextPos werden auf 0 gesetzt." + + " Das Sichtfenster (stellt PatternPos und TextPos grafisch dar) " + + "wird an den Anfang von Text und Pattern gesetzt. Sichtfensterposition " + + "(TextPos, PatPos) = (0, 0)"; + else + return "Initialisation: PatternPos and TextPos are set to 0." + + " The window, which represents PatternPos and TextPos graphically, " + + "is set to the beginning of text and Pattern."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(0,29,GUIConstants.HIGHLIGHT_COLOR)); + return liste; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.java new file mode 100644 index 0000000..46251af --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerSetStep.java @@ -0,0 +1,46 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class specifies the concrete algorithmstate increment of the intern values. + * + * @author Danilo Lisske, Elisa Böhl + */ +public class P2InnerSetStep extends P2BigStep { + private static final long serialVersionUID = -7963450147338716845L; + + /** + * The constructor. + * + * @param pp the pattern position + * @param tp the text position + */ + public P2InnerSetStep(int pp, int tp) { + patpos = pp; + textpos = tp; + } + + public String getDescriptionText() { + String lang = Settings.getString("main","Language"); + if (lang.equals("de")) + return "Das Sichtfenster wurde nach rechts auf die Position (" + + textpos + ", " + patpos + ") verschoben."; + else + return "The window was shifted left to position (" + + textpos + ", " + patpos + ")."; + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + liste.add(new KMPHighlighter(211,234,GUIConstants.HIGHLIGHT_COLOR)); //set: inc(patpos); + liste.add(new KMPHighlighter(238,267,GUIConstants.HIGHLIGHT_COLOR)); //set: inc(textpos); + return liste; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.java new file mode 100644 index 0000000..98b2b46 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2InnerWhileStep.java @@ -0,0 +1,163 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class specifies the concrete algorithmstate test and patternshifting. + * + * @author Danilo Lisske, Elisa Böhl + */ +public class P2InnerWhileStep extends P2SmallStep { + private static final long serialVersionUID = -2917571422573814032L; + + private boolean lastwhilestep; + private int jumpdistance; + private int patternlength; + + /** + * The constructor. + * + * @param pp the pattern position + * @param tp the text position + * @param lw if this is the last while step + * @param jd the jump distance + * @param pl the pattern length + */ + public P2InnerWhileStep(int pp, int tp, boolean lw, int jd, int pl) { + patpos = pp; + textpos = tp; + lastwhilestep = lw; + jumpdistance = jd; + patternlength = pl; + } + + public String getDescriptionText() { + String lang = Settings.getString("main","Language"); + if (lastwhilestep) { + if (patpos < 0) { + if (lang.equals("de")) + return "Das Sichtfenster steht vor dem Pattern, es kann nichts verglichen werden."; + else + return "The condition of the while loop PatternPos >= 0 is not true." + Constants.SEPARATOR + + " So the window is ahead of the pattern, there is nothing to be compared."; + } else { + if (lang.equals("de")) + return "Die Zeichen im Sichtfenster sind identisch. Pattern und Textausschnitt sind " + + "eventuell gleich, es müssen mehr Stellen verglichen werden."; + else + return "here the characters in the window are equal. The pattern is not moved " + + "because more positions have to be compared."; + } + } + else { + int ersatz = patpos; + if (ersatz<0) ersatz = 0; + if (lang.equals("de")){ + String intro = "Die while-Bedingung ist erfüllt. " + + "Das Pattern wurde auf PatPos " + patpos + " (" ; + String distance = jumpdistance+" Positionen nach rechts) verschoben. "; + if (jumpdistance == 1) distance = "eine Position nach rechts) verschoben. "; + String expl = "Die Zeichen waren bis an Patternposition " + (jumpdistance + patpos) + + " gleich, daher ist die nächste Gleichheit erst mit PatPos = " + + patpos + " möglich (Anwenden der in Phase eins ermittelten Daten). "; + + + if (patpos + jumpdistance < 1) + expl = "Keine Gleichheit zwischen Pattern und Suchtext, " + + "daher wird der Patternanfang an TextPos+1 gelegt. "; + + + if (jumpdistance + ersatz -1 < 1) + expl = expl + "Eingesparte Vergleiche = 0."; + else + expl = expl + "Eingesparte Vergleiche >= " + (jumpdistance + ersatz - 1) + "."; + return intro + distance + expl; + + } + else { + String intro = "The Pattern was shifted right at PatPos " + patpos + " (by " ; + String distance = jumpdistance+" positions). "; + if (jumpdistance == 1) distance = "one position). "; + String expl = "Up to Patternposition " + (jumpdistance + patpos) + + " the characters were equal, so it is known that the next equality is possible at PatPos = " + + patpos + ". This information can be derived from the structure of the pattern solely, " + + "And that is, what the first stage does. There was/were economized "; + if (jumpdistance + ersatz -1 == 1) + expl = expl + "at least one comparison in contrast to the naive search."; + else + if (jumpdistance + ersatz -1 <= 1) + expl = expl + "no comparisons in contrast to the naive search."; + else + expl = expl + "at least " + (jumpdistance + ersatz - 1) + " comparisons in contrast to the naive search"; + + + if (patpos + jumpdistance < 1) + expl = "As there was no equality between pattern and searchtext, " + + "the pattern was shifted along the text to its beginning. " + + "There were economized no comparisons in contrast to the naive search " + + "because the calculated table could not be used successfully."; + + return intro + distance + expl; + } + } + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + if (lastwhilestep) + liste.add(new KMPHighlighter(105,164,GUIConstants.FALSE_COLOR)); //while-header + else { + liste.add(new KMPHighlighter(105,164,GUIConstants.TRUE_COLOR)); // while-header + liste.add(new KMPHighlighter(173,207,GUIConstants.HIGHLIGHT_COLOR)); //true-case + } + return liste; + } + + /** + * Returns a boolean value, which indicates, if the loop of the innerwhileloop is false (then the value is true). + * + * @return if this is the last while step + */ + public boolean isLastWhileStep(){ + return lastwhilestep; + } + + /** + * Returns the distance, which have to be shiftet at this step. + * + * @return the jumpdistance + */ + public int getJumpDistance() { + return jumpdistance; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(textpos); + out.writeBoolean(lastwhilestep); + out.writeInt(jumpdistance); + out.writeInt(patternlength); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + patpos = in.readInt(); + textpos = in.readInt(); + lastwhilestep = in.readBoolean(); + jumpdistance = in.readInt(); + patternlength = in.readInt(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.java new file mode 100644 index 0000000..f16407f --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2OuterWhileStep.java @@ -0,0 +1,88 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This class specifies the concrete algorithmstate test of algorithm end. + * + * @author Danilo Lisske, Elisa Böhl + */ +public class P2OuterWhileStep extends P2SmallStep { + private static final long serialVersionUID = -2597475389206219552L; + + private boolean lastwhilestep; + + /** + * The constructor. + * + * @param pp the pattern position + * @param tp the text position + * @param lw if this is the last outer while step + */ + public P2OuterWhileStep(int pp, int tp, boolean lw) { + patpos = pp; + textpos = tp; + lastwhilestep = lw; + } + + public String getDescriptionText() { + String lang = Settings.getString("main","Language"); + if (lastwhilestep) { + if (lang.equals("de")) + return "Es gibt hier nichts mehr zu Vergleichen. " + + "Es muss noch festgestellt werden, warum der Algorithmus beendet wurde."; + else + return "There is nothing left to be compared. " + + "Now it has to be determined, why the algorithm was aborted."; + } + else { + if (lang.equals("de")) + return "Text- oder Patternlänge wurden nicht überschritten, " + + "vergleiche einfach weiter."; + else + return "Text- or Patternlength were not exceeded, " + + "compare next signs."; + } + } + + public List getKMPHighlighter() { + List liste; + liste = new LinkedList(); + if (lastwhilestep) liste.add(new KMPHighlighter(36,90,GUIConstants.FALSE_COLOR)); //while-header + else liste.add(new KMPHighlighter(36,90,GUIConstants.TRUE_COLOR)); //while-header + return liste; + } + + /** + * Returns a boolean value, which indicates, if the loop of the innerwhileloop is false (then the value is true). + * + * @return if this is the last outer while step + */ + public boolean isLastWhileStep() { + return lastwhilestep; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(textpos); + out.writeBoolean(lastwhilestep); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + patpos = in.readInt(); + textpos = in.readInt(); + lastwhilestep = in.readBoolean(); + descriptiontext = (String) in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.java new file mode 100644 index 0000000..dc7fb29 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2SmallStep.java @@ -0,0 +1,48 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; + +import org.jalgo.module.kmp.algorithm.KMPHighlighter; + +/** + *This class specifies an abstract algorithmstate. + *All classes, which implements this class, represents a normal state of the algorithm. + * + * @author Danilo Lisske, Elisa Böhl + */ + +public abstract class P2SmallStep implements P2Step { + /** The pattern position. */ + public int patpos; + /** The text position. */ + public int textpos; + /** The descriptiontext. */ + public String descriptiontext; + /** The list filled with KMPHighlighter. */ + public List kmphighlights; + + public int getPatPos() { + return patpos; + } + + public int getTextPos() { + return textpos; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(patpos); + out.writeInt(textpos); + out.writeObject(getDescriptionText()); + out.writeObject(getKMPHighlighter()); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + patpos = in.readInt(); + textpos = in.readInt(); + descriptiontext = (String)in.readObject(); + kmphighlights = (List) in.readObject(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.java b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.java new file mode 100644 index 0000000..f7cdfe5 --- /dev/null +++ b/src/org/jalgo/module/kmp/algorithm/phasetwo/P2Step.java @@ -0,0 +1,19 @@ +package org.jalgo.module.kmp.algorithm.phasetwo; + +import org.jalgo.module.kmp.algorithm.Step; + +/** + * This class is the interface for all stepclasses from phase 2. + * + * @author Danilo Lisske, Elisa Böhl + */ +public interface P2Step extends Step { + + /** + * Returns the text position. + * + * @return the text position + */ + public int getTextPos(); + +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/de.properties b/src/org/jalgo/module/kmp/de.properties new file mode 100644 index 0000000..853de0c --- /dev/null +++ b/src/org/jalgo/module/kmp/de.properties @@ -0,0 +1,120 @@ +Module_name=KMP - Knuth Morris Pratt +Module_version=1.0 +Module_authors=Danilo Lißke, Sebastian Patschorke, Elisa Böhl, Nadine Grabow, Matthias Neubert +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt den Suchalgorithmus von Knuth Morris Pratt. +Module_description_2=Es werden die Algorithmen Verschiebetabelle generieren und Anwendung auf den Suchtext visualisiert. Dabei können die Algorithmen interaktiv gesteuert werden. + +ModuleConnector.No_valid_KMP_file=Keine gültige KMP-Datei. +ModuleConnector.Loading_error=Fehler beim Laden der Datei. +ModuleConnector.File_damaged=Die Datei ist möglicherweise beschädigt. + +Screen.Slider_ttt=Veränderung der Anzeigegrössen. + +ShowPanel.Head_textposition=TextIndex +ShowPanel.Head_text=Text +ShowPanel.Head_pattern=Pattern +ShowPanel.Head_table=Tabelle +ShowPanel.Head_index=Index +ShowPanel.Head_cycles=Zyklen + +InputPanel.Label_extension=Erweiterung +InputPanel.Label_pattern=Pattern +InputPanel.Label_searchtext=Suchtext +InputPanel.Label_result_true=Pattern gefunden! +InputPanel.Label_result_false=Pattern nicht gefunden! +InputPanel.Label_result_ttt=Das Ergebnis der Suche. +InputPanel.TextField_pattern_ttt=Geben Sie hier Ihr Pattern ein. +InputPanel.TextField_addpattern_ttt=Geben Sie hier Ihre Erweiterung zum Pattern ein. +InputPanel.CheckBox_cycle=Zyklen +InputPanel.CheckBox_cycle_ttt=Sollen die Zyklen des Patterns angezeigt werden? +InputPanel.Button_goon=Weiter in Phase 2 +InputPanel.Button_goon_ttt=Das aktuelle Pattern in Phase 2 anwenden. +InputPanel.Button_set=Setzen +InputPanel.Button_set_ttt=Setzt das eingegebene Pattern. +InputPanel.Button_random=Zufall +InputPanel.Button_random_ttt=Generieren Sie sich ein Zufallspattern. +InputPanel.Button_addpattern=Hinzufügen +InputPanel.Button_addpattern_ttt=Fügt die Erweiterung an das bestehende Pattern an. +InputPanel.Button_loadst=Eingeben +InputPanel.Button_loadst_ttt=Laden, eingeben oder bearbeiten Sie den Suchtext. +InputPanel.Button_generst=Generieren +InputPanel.Button_generst_ttt=Generiert einen Suchtext anhand des Patterns. + +Abort=Algorithmus abbrechen +Abort_tooltip=Bricht den laufenden Algorithmus ab +Back=Schritt zurück +Back_tooltip=Macht den letzten Schritt im aktuellen Algorithmus rückgängig +FastBack=Blockschritt zurück +FastBack_tooltip=Macht den letzen grösseren Schritt im aktuellen Algorithmus rückgängig +Forward=Nächster Schritt +Forward_tooltip=Führt den nächsten Schritt im aktuellen Algorithmus aus +FastForward=Nächster Blockschritt +FastForward_tooltip=Führt den nächsten grösseren Schritt im aktuellen Algorithmus aus +Finish=Algorithmus beenden +Finish_tooltip=Durchläuft den Algorithmus bis zum Ende + +Show_welcome_screen=Willkommensbildschirm anzeigen +Show_welcome_screen_tooltip=Öffnet den Willkommensbildschirm +Beamer_mode=Beamer-Modus +Wish_to_discard=Möchten Sie Ihre Änderungen verwerfen? + +LED.Title=Lernbeispiele Laden +LED.RB_Title=Pattern +LED.LB_Title=Suchtext +LED.Button_apply=Laden +LED.Button_cancel=Abbrechen +LED.Example_pattern_0=sinn +LED.Example_searchtext_0=dasisteinsinnlosertext +LED.Example_description_0=Dieses Beispiel zeigt die simpelste Form des Patterns: Es existieren keine Zyklen. +LED.Example_pattern_1=essen +LED.Example_searchtext_1=esHatNurDagesessenUndZugeschaut. +LED.Example_description_1=In diesem Beispiel existiert genau ein Zyklus im Pattern. +LED.Example_pattern_2=gigant +LED.Example_searchtext_2=grgigigalaginggigantisch +LED.Example_description_2=In dieser Vorlage gibt es mehrere Zyklen. +LED.Example_pattern_3=abacaabcab +LED.Example_searchtext_3=abacaabacababacaabcabacaabcac +LED.Example_description_3=Auch hier gibt es mehrere Zyklen. Versuchen Sie einmal, selbst alle zu finden. +LED.Example_pattern_4=bbabbac +LED.Example_searchtext_4=bbbabcabbcaabbabbbabbacbbacbacb +LED.Example_description_4=Das Beispielpattern enthält recht viele Zyklen. Das besondere an diesen ist, dass Zyklen in Zyklen vokommen. +LED.Example_pattern_5=erereerr +LED.Example_searchtext_5=erererereererrerereerrerrreer +LED.Example_description_5=Das Pattern enthält mehrere Zyklen. Das besondere an diesen ist, dass Zyklen in Zyklen entstehen und gemeinsam enden. +LED.Example_pattern_6=nennen +LED.Example_searchtext_6=enenneenenenenneenenennenenneenene +LED.Example_description_6=Auch im Wort nennen gibt es mehrere Zyklen, die zum Teil ineinander verschachtelt sind. +LED.Example_pattern_7=babcababc +LED.Example_searchtext_7=bacbaababcabcbabcababcababcabababac +LED.Example_description_7=In diesem Beispielpattern existieren auch wieder Zyklen in Zyklen nur diesmal sind sie ineinander geschachtelt. +LED.Example_pattern_8=xxfxxfxxd +LED.Example_searchtext_8=xxfxxfxxfxxffxxfxxxxfxxfxffxfxxxffxx +LED.Example_description_8=Dieses Beispiel enthält viele Zyklen, ist jedoch im Suchtext nicht vorhanden. +LED.Example_pattern_9=abaababaab +LED.Example_searchtext_9=abaabababaabaabbaababaababaab +LED.Example_description_9=Umso weniger Zeichen in Text und Pattern verwendet werden, desto mehr "passiert" + +RPD.Title=Zufallsgenerierung +RPD.Label_alphabet=Kardinalität des Alphabets +RPD.Label_pattern=Länge des Patterns +RPD.Button_apply=Anwenden +RPD.Button_cancel=Abbrechen + +STLD.Title=Suchtext erstellen +STLD.Label_searchtext=Suchtext +STLD.Button_load=Laden +STLD.Button_apply=Anwenden +STLD.Button_cancel=Abbrechen + +ITP.Tab_codeanddesc=Code und Protokoll +ITP.Tab_codeonly=Code +ITP.Tab_desconly=Protokoll +ITP.Tab_codeandst=Code und Suchtext +ITP.Tab_descandst=Protokoll und Suchtext +ITP.Label_code=Code +ITP.Label_desc=Protokoll +ITP.Label_searchtext=Suchtext +ITP.TextPane_code_ttt=Zeigt den aktuell abzuarbeitenden Code an. +ITP.TextPane_desc_ttt=Zeigt das Protokoll der Algorithmenschritte an. +ITP.TextPane_st_ttt=Zeigt den Suchtext an. \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/en.properties b/src/org/jalgo/module/kmp/en.properties new file mode 100644 index 0000000..2e6c46e --- /dev/null +++ b/src/org/jalgo/module/kmp/en.properties @@ -0,0 +1,120 @@ +Module_name=KMP - Knuth Morris Pratt +Module_version=1.0 +Module_authors=Danilo Lißke, Sebastian Patschorke, Elisa Böhl, Nadine Grabow, Matthias Neubert +Module_license=GNU General Public License +Module_description_1=This module is about the search-algorithm from Knuth Morris Pratt. +Module_description_2=The algorithms to be visualized are: generating the shifting table and use to the search text. The algorithms can be controlled interactively. + +ModuleConnector.No_valid_KMP_file=No valid KMP - file. +ModuleConnector.Loading_error=Error while loading the file. +ModuleConnector.File_damaged=Maybe the file is damaged. + +Screen.Slider_ttt=Change the view size. + +ShowPanel.Head_textposition=TextIndex +ShowPanel.Head_text=Text +ShowPanel.Head_pattern=Pattern +ShowPanel.Head_table=Table +ShowPanel.Head_index=Index +ShowPanel.Head_cycles=Cycles + +InputPanel.Label_extension=Extension +InputPanel.Label_pattern=Pattern +InputPanel.Label_searchtext=Searchtext +InputPanel.Label_result_true=Pattern was found! +InputPanel.Label_result_false=Pattern was not found! +InputPanel.Label_result_ttt=The result of the search. +InputPanel.TextField_pattern_ttt=Enter your pattern here. +InputPanel.TextField_addpattern_ttt=Enter your extension to the pattern here. +InputPanel.CheckBox_cycle=Cycles +InputPanel.CheckBox_cycle_ttt=Should the cycles been shown? +InputPanel.Button_goon=Go on in phase 2 +InputPanel.Button_goon_ttt=Use the actual pattern in phase 2. +InputPanel.Button_set=Set +InputPanel.Button_set_ttt=Sets the given pattern. +InputPanel.Button_random=Random +InputPanel.Button_random_ttt=Generates a random pattern. +InputPanel.Button_addpattern=Add +InputPanel.Button_addpattern_ttt=Adds the extension to the given pattern. +InputPanel.Button_loadst=Enter +InputPanel.Button_loadst_ttt=Load, edit or type in a searchtext. +InputPanel.Button_generst=Generate +InputPanel.Button_generst_ttt=Generates a searchtext from the given pattern. + +Abort=Abort algorithm +Abort_tooltip=Aborts the currently running algorithm +Back=Undo +Back_tooltip=Undoes the last step in current algorithm +FastBack=Undo block step +FastBack_tooltip=Undoes the last block step in current algorithm +Forward=Next step +Forward_tooltip=Performs the next step in current algorithm +FastForward=Next block step +FastForward_tooltip=Performs the next block step in current algorithm +Finish=Finish algorithm +Finish_tooltip=Runs the algorithm until it ends + +Show_welcome_screen=Show welcome screen +Show_welcome_screen_tooltip=Shows the welcome screen +Beamer_mode=Beamer-Mode +Wish_to_discard=Do you wish to discard your changes? + +LED.Title=Load learnexamples +LED.RB_Title=Pattern +LED.LB_Title=Searchtext +LED.Button_apply=Load +LED.Button_cancel=Cancel +LED.Example_pattern_0=tasen +LED.Example_searchtext_0=thisisnotasensefulltext +LED.Example_description_0=This example shows the simplest of all Pattern: there is no cycle inside. +LED.Example_pattern_1=eye +LED.Example_searchtext_1=eneyyeeepopeye +LED.Example_description_1=In this Example exist exactly one cycle. +LED.Example_pattern_2=gigant +LED.Example_searchtext_2=grgigigalaginggigantgiaga +LED.Example_description_2=In this Pattern exists some cycles. +LED.Example_pattern_3=abacaabcab +LED.Example_searchtext_3=abacaabacababacaabcabacaabcac +LED.Example_description_3=In this example exists more cycles. +LED.Example_pattern_4=bbabbac +LED.Example_searchtext_4=bbbabcabbcaabbabbbabbacbbacbacb +LED.Example_description_4=This Pattern has got many cycles. The distinction is, that cycles are in cycles. +LED.Example_pattern_5=erereerr +LED.Example_searchtext_5=erererereererrerereerrerrreer +LED.Example_description_5=The Examplepattern has got some Cycles. The distinction here is, that cycles begin in cycles, they end together. +LED.Example_pattern_6=nennen +LED.Example_searchtext_6=enenneenenenenneenenennenenneenene +LED.Example_description_6=Also real words can have some cycles (nennen is a german word and means denominate) +LED.Example_pattern_7=babcababc +LED.Example_searchtext_7=bacbaababcabcbabcababcababcabababac +LED.Example_description_7=In this example are some cycles again, but these are in a structire like a box in a box. +LED.Example_pattern_8=xxfxxfxxd +LED.Example_searchtext_8=xxfxxfxxfxxffxxfxxxxfxxfxffxfxxxffxx +LED.Example_description_8=This Pattern has got many Cycles but it doesn't exist in the searchtext. +LED.Example_pattern_9=abaababaab +LED.Example_searchtext_9=abaabababaabaabbaababaababaab +LED.Example_description_9=If you use few signs, you got more actions. + +RPD.Title=Random Generation +RPD.Label_alphabet=Size of the alphabet +RPD.Label_pattern=Length of the patterns +RPD.Button_apply=Apply +RPD.Button_cancel=Cancel + +STLD.Title=Create Searchtext +STLD.Label_searchtext=Searchtext +STLD.Button_load=Load +STLD.Button_apply=Apply +STLD.Button_cancel=Cancel + +ITP.Tab_codeanddesc=Code and description +ITP.Tab_codeonly=Code +ITP.Tab_desconly=Description +ITP.Tab_codeandst=Code and searchtext +ITP.Tab_descandst=Description und searchtext +ITP.Label_code=Code +ITP.Label_desc=Description +ITP.Label_searchtext=Searchtext +ITP.TextPane_code_ttt=Shows the actual code. +ITP.TextPane_desc_ttt=Shows the protocol of the algorithm steps. +ITP.TextPane_st_ttt=Shows the searchtext. \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/CVS/Entries b/src/org/jalgo/module/kmp/gui/CVS/Entries new file mode 100644 index 0000000..2ed27b5 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/CVS/Entries @@ -0,0 +1,4 @@ +/GUIConstants.java/1.2/Thu Jan 31 20:15:10 2008// +/GUIController.java/1.2/Tue Feb 12 16:22:24 2008// +D/component//// +D/event//// diff --git a/src/org/jalgo/module/kmp/gui/CVS/Repository b/src/org/jalgo/module/kmp/gui/CVS/Repository new file mode 100644 index 0000000..d0e1e4e --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/gui diff --git a/src/org/jalgo/module/kmp/gui/CVS/Root b/src/org/jalgo/module/kmp/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/gui/GUIConstants.java b/src/org/jalgo/module/kmp/gui/GUIConstants.java new file mode 100644 index 0000000..584619c --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/GUIConstants.java @@ -0,0 +1,122 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.05.2005 */ +package org.jalgo.module.kmp.gui; + +import java.awt.Color; +import java.awt.Font; + +import org.jalgo.module.kmp.Constants; + +/** + * The interface Constants is a collection of several constant values, + * used in the GUI implementation of the KMP module. + * + * @author Danilo Lisske + */ +public interface GUIConstants +extends Constants { + + /*------------------------------colors----------------------------*/ + /** The background color in the welcome screen. */ + public final static Color WELCOME_SCREEN_BACKGROUND = new Color(51, 102, 153); + /** The font color in the welcome screen. */ + public final static Color WELCOME_SCREEN_FOREGROUND = new Color(254, 215, 0); + /** The color of the VglInd-pointer in the table visualisation phase one. */ + public final static Color VGLIND_POINTER_COLOR = Color.WHITE; + /** The color of the PatPos-pointer in the table visualisation phase one. */ + public final static Color PATPOS_POINTER_COLOR = Color.BLACK; + /** The color of the visualisation arrow over the table in phase one. */ + public final static Color ARROW_COLOR = Color.BLACK; + /** The color of the view window in phase two. */ + public final static Color VIEW_WINDOW_COLOR = Color.MAGENTA; + /** The color of the box border in phase one for highlight a cell. */ + public final static Color BOX_COLOR = Color.BLACK; + /** The color of the table heads. */ + public final static Color HEAD_COLOR = Color.YELLOW; + /** The color of the text in the "goon" button in phase one. */ + public static final Color MOVE_ON_TO_PHASE_TWO = Color.RED; + /** The color of the highlighted searchtext. */ + public static final Color SEARCHTEXT_HIGHLIGHT = Color.YELLOW; + /** The color of all true things. */ + public static final Color TRUE_COLOR = new Color(125, 255, 160); + /** The color of all false things. */ + public static final Color FALSE_COLOR = new Color(255, 160, 160); + /** The color for highlightning. */ + public static final Color HIGHLIGHT_COLOR = new Color(120, 200, 255); + + /*------------------------------fonts-----------------------------*/ + /** The font used in the welcome screen. */ + public static final Font WELCOME_SCREEN_FONT = + new Font("SansSerif", Font.PLAIN, 16); + /** The font used in the ShowPanels. Only monospaced fonts are supported. */ + public static final Font SHOW_PANEL_FONT = + new Font( "Monospaced", Font.BOLD, 18 ); + /** The font for the code in the InfoTabbedPanel. */ + public static final Font CODE_FONT = + new Font("SansSerif", Font.PLAIN, 11); + /** The font for the searchtext in the InfoTabbedPanel. */ + public static final Font SEARCHTEXT_FONT = + new Font("SansSerif", Font.PLAIN, 11); + /** The font for the screens. */ + public static final Font SCREEN_FONT = + new Font("SansSerif", Font.PLAIN, 12); + /** The font for the screens. */ + public static final Font RESULT_FONT = + new Font("SansSerif", Font.BOLD, 16); + + /*------------------------------ShowPanels-------------------------*/ + /** Indicates the horizontal position of the table in phase one.*/ + public static final int P1_X_OFFSET = 20; + /** Indicates the vertical position of the table in phase one.*/ + public static final int P1_Y_OFFSET = 30; + /** Indicates indirectly as a factor in compersisation to the letter width + * the minimal cell width of the table in phase one.*/ + public static final float P1_MIN_CELL_WIDTH = 2; + /** Indicates indirectly as a factor in compersisation to the letter width + * the maximal cell width of the table in phase one.*/ + public static final float P1_MAX_CELL_WIDTH = 7; + /** Indicates the number of (direct) shown cycles. */ + public static final int MAX_SHOW_CYCLES = 4; + /** Indicates the horizontal position of the table in phase two. */ + public static final int P2_X_OFFSET = 20; + /** Indicates the vertical position of the table in phase two. */ + public static final int P2_Y_OFFSET = 20; + /** Indicates the minimal cell width of the table in phase 2. */ + public static final int P2_MIN_CELL_WIDTH = 50; + /** Indicates the maximal cell width of the table in phase 2. */ + public static final int P2_MAX_CELL_WIDTH = 60; + /** Indicates the maximum number of text cells befor and after the pattern in phase 2. */ + public static final int P2_PREFERED_CELL_OFFSET = 2; + /** Indicates the minimal period time (in ms) of an animation partstep in phase 2. */ + public static final int MIN_PERIOD_TIME = 5; + /** Indicates the maximal period time (in ms) of an animation partstep in phase 2. */ + public static final int MAX_PERIOD_TIME = 100; + /** Indicates the length (in px) of the animation acceleration(s) in phase 2. */ + public static final int ACC_LENGTH = 20; + + /*------------------------------BeamerMode------------------------*/ + /** The scalefactor of the beamer mode. */ + public final static double SCALEFACTOR = 1.5; + /** The heigth difference of the show panel with or without cycles. */ + public static final int CYCLE_TAB_SIZE = 56; + /** The divider location of the beamer mode. */ + public static final int DIVIDER_LOCATION = 310; +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/GUIController.java b/src/org/jalgo/module/kmp/gui/GUIController.java new file mode 100644 index 0000000..79b82b5 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/GUIController.java @@ -0,0 +1,836 @@ +package org.jalgo.module.kmp.gui; + +import java.awt.BorderLayout; +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.Random; +import java.util.List; +import java.util.LinkedList; + +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JMenu; +import javax.swing.JPanel; +import javax.swing.JToolBar; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.Icon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.kmp.gui.component.WelcomeScreen; +import org.jalgo.module.kmp.gui.component.PhaseOneScreen; +import org.jalgo.module.kmp.gui.component.PhaseTwoScreen; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.Controller; +import org.jalgo.module.kmp.ModuleConnector; +import org.jalgo.module.kmp.algorithm.ExampleFileFilter; +import org.jalgo.module.kmp.algorithm.Step; +import org.jalgo.module.kmp.gui.event.AbortAction; +import org.jalgo.module.kmp.gui.event.BeamerModeAction; +import org.jalgo.module.kmp.gui.event.FastBackwardAction; +import org.jalgo.module.kmp.gui.event.BackwardAction; +import org.jalgo.module.kmp.gui.event.ForwardAction; +import org.jalgo.module.kmp.gui.event.FastForwardAction; +import org.jalgo.module.kmp.gui.event.FinishAction; +import org.jalgo.module.kmp.gui.event.WelcomeAction; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.module.kmp.algorithm.phasetwo.P2Step; +import org.jalgo.module.kmp.algorithm.phaseone.P1BeginForStep; +import org.jalgo.module.kmp.algorithm.phasetwo.P2EndStep; +import org.jalgo.module.kmp.algorithm.phaseone.P1InitStep; +import org.jalgo.module.kmp.algorithm.phasetwo.P2InitStep; + +/** + * The class GUIController is the main class of the GUI of the + * KMP module. It initializes the layout of the different parts, offers methods + * to set the state of buttons etc., to show several dialogs and messages, and + * causes GUI-components to update when necessary. + * + * @author Danilo Lisske + */ +public class GUIController implements GUIConstants { + private ModuleConnector modconn; + private Controller controller; + + private WelcomeScreen welcomeScreen; + private PhaseOneScreen phaseonescreen; + private PhaseTwoScreen phasetwoscreen; + + private AbstractAction abortAction; + private JToolbarButton btabort; + private AbstractAction fastBackwardAction; + private JToolbarButton btfastback; + private AbstractAction backwardAction; + private JToolbarButton btback; + private AbstractAction forwardAction; + private JToolbarButton btforward; + private AbstractAction fastForwardAction; + private JToolbarButton btfastforward; + private AbstractAction finishAction; + private JToolbarButton btfinish; + private WelcomeAction welcomeAction; + + private JPanel contentPane; + private boolean beamermode; + + /** + * Constructs the GUIController instance for the current KMP + * module instance.
          + * Initializes all layout components, especially the toolbar and the menu. + * Installs an AWT-Frame on the panel provided by the main program, so that + * GUI of the KMP module can be created on Swing base. + * + * @param m the ModuleConnector of the KMP module + * @param c the Controller of the KMP module + */ + public GUIController(ModuleConnector m, Controller c) { + controller = c; + modconn = m; + beamermode = false; + + JComponent rootPane = JAlgoGUIConnector.getInstance().getModuleComponent(modconn); + rootPane.setLayout(new BorderLayout()); + contentPane = new JPanel(); + rootPane.add(contentPane, BorderLayout.CENTER); + + installToolbar(); + installMenu(); + + welcomeScreen = new WelcomeScreen(this); + phaseonescreen = new PhaseOneScreen(this); + phasetwoscreen = new PhaseTwoScreen(this); + } + + /** + * Sets up the toolbar. + * + */ + private void installToolbar() { + JToolBar toolBar = JAlgoGUIConnector.getInstance().getModuleToolbar(modconn); + welcomeAction = new WelcomeAction(this); + JToolbarButton btwelcome = new JToolbarButton( + (Icon)welcomeAction.getValue(Action.SMALL_ICON),null,null); + btwelcome.setAction(welcomeAction); + btwelcome.setText(""); + btwelcome.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btwelcome); + toolBar.addSeparator(); + abortAction = new AbortAction(this); + btabort = new JToolbarButton( + (Icon)abortAction.getValue(Action.SMALL_ICON),null, null); + btabort.setAction(abortAction); + btabort.setText(""); + btabort.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btabort); + fastBackwardAction = new FastBackwardAction(this); + btfastback = new JToolbarButton( + (Icon)fastBackwardAction.getValue(Action.SMALL_ICON),null, null); + btfastback.setAction(fastBackwardAction); + btfastback.setText(""); + btfastback.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btfastback); + backwardAction = new BackwardAction(this); + btback = new JToolbarButton( + (Icon)backwardAction.getValue(Action.SMALL_ICON),null, null); + btback.setAction(backwardAction); + btback.setText(""); + btback.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btback); + forwardAction = new ForwardAction(this); + btforward = new JToolbarButton( + (Icon)forwardAction.getValue(Action.SMALL_ICON),null, null); + btforward.setAction(forwardAction); + btforward.setText(""); + btforward.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btforward); + fastForwardAction = new FastForwardAction(this); + btfastforward = new JToolbarButton( + (Icon)fastForwardAction.getValue(Action.SMALL_ICON),null, null); + btfastforward.setAction(fastForwardAction); + btfastforward.setText(""); + btfastforward.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btfastforward); + finishAction = new FinishAction(this); + btfinish = new JToolbarButton( + (Icon)finishAction.getValue(Action.SMALL_ICON),null, null); + btfinish.setAction(finishAction); + btfinish.setText(""); + btfinish.addMouseListener(StatusLineUpdater.getInstance()); + toolBar.add(btfinish); + } + + /** + * Sets up the menu. + * + */ + private void installMenu() { + JMenu menu = JAlgoGUIConnector.getInstance().getModuleMenu(modconn); + menu.add(welcomeAction); + menu.addSeparator(); + menu.add(abortAction); + menu.add(backwardAction); + menu.add(fastBackwardAction); + menu.add(forwardAction); + menu.add(fastForwardAction); + menu.add(finishAction); + menu.addSeparator(); + BeamerModeAction beamerAction = BeamerModeAction.getInstance(this); + menu.add(beamerAction); + } + + /** + * Installs the welcomescreen to the main panel. + * + */ + public void installWelcomeScreen() { + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(welcomeScreen, BorderLayout.CENTER); + modconn.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + setAllControlButton(false); + controller.clearData(); + contentPane.updateUI(); + contentPane.validate(); + } + + /** + * Installs the phaseonescreen to the main panel. + * + */ + public void installPhaseOneScreen() { + controller.startPhaseOne(); + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(phaseonescreen, BorderLayout.CENTER); + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + setAllControlButton(false); + phaseonescreen.infotabbedPane.setCode(Constants.CODE_PHASE_ONE); + phaseonescreen.infotabbedPane.setDescription("",false); + phaseonescreen.phaseoneinputPane.setPatternEnabled(false); + phaseonescreen.phaseoneinputPane.setAddPatternEnabled(false); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(false); + if(controller.isPatternSet()) { + phaseonescreen.phaseoneinputPane.setTfPatternText(controller.getPattern().getPattern()); + initPhaseOne(); + } + else { + phaseonescreen.phaseoneinputPane.setTfPatternText(""); + phaseonescreen.phaseoneinputPane.setTfAddPatternText(""); + phaseonescreen.phaseoneshowPane.setPattern(null); + } + + contentPane.updateUI(); + contentPane.validate(); + } + + /** + * The method is called to initialise the phase one. + * + */ + public void initPhaseOne() { + phaseonescreen.phaseoneinputPane.setTfAddPatternText(""); + phaseonescreen.phaseoneinputPane.setPatternEnabled(false); + phaseonescreen.phaseoneinputPane.setAddPatternEnabled(false); + phaseonescreen.phaseoneshowPane.setPattern(controller.getPattern()); + phaseonescreen.phaseoneshowPane.update((Step)null); + phaseonescreen.infotabbedPane.setDescription("",false); + setForwardControlButton(true); + controller.initPhaseOne(); + + phaseonescreen.updateUI(); + } + + /** + * The method is called when loading a session or expanding the pattern in phase one. + * + */ + public void restorePhaseOne() { + if (controller.isPatternSet()) { + controller.getPattern().setPattern(phaseonescreen.phaseoneinputPane.getTfPatternText()); + controller.restorePhaseOne(); + phaseonescreen.phaseoneshowPane.setPattern(controller.getPattern()); + phaseonescreen.infotabbedPane.setDescription("",false); + doNextStep(); + phaseonescreen.updateUI(); + } + } + + /** + * Install the phasetwoscreen to the main panel. + * + */ + public void installPhaseTwoScreen() { + if (controller.getPhase() == 1) + phasetwoscreen.setScaleFactor(phaseonescreen.getScaleFactor()); + controller.startPhaseTwo(); + if (beamermode) doBeamerMode(true); + contentPane.removeAll(); + contentPane.setLayout(new BorderLayout()); + contentPane.add(phasetwoscreen, BorderLayout.CENTER); + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + setAllControlButton(false); + phasetwoscreen.infotabbedPane.setCode(Constants.CODE_PHASE_TWO); + phasetwoscreen.infotabbedPane.setDescription("",false); + phasetwoscreen.phasetwoinputPane.setPatternEnabled(false); + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false, false); + phasetwoscreen.phasetwoinputPane.setGenerateSearchTextEnabled(controller.isPatternSet()); + if (controller.isSearchTextSet()) { + phasetwoscreen.infotabbedPane.setSearchText(controller.getSearchText()); + phasetwoscreen.phasetwoshowPane.setSearchText(controller.getSearchText()); + } + else { + phasetwoscreen.phasetwoshowPane.setSearchText(null); + } + if (controller.isPatternSet()) { + phasetwoscreen.phasetwoinputPane.setTfPatternText(controller.getPattern().getPattern()); + phasetwoscreen.phasetwoshowPane.setPattern(controller.getPattern()); + } + else { + phasetwoscreen.phasetwoinputPane.setTfPatternText(""); + phasetwoscreen.phasetwoshowPane.setPattern(null); + } + if (controller.isPatternSet() && controller.isSearchTextSet()) initPhaseTwo(); + scaleScreen(phaseonescreen.getScaleFactor() * 0.1); + contentPane.updateUI(); + contentPane.validate(); + } + + /** + * The method is called to initialise the phase two. + * + */ + public void initPhaseTwo() { + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false,false); + if(controller.isPatternSet() && controller.isSearchTextSet()) { + phasetwoscreen.phasetwoshowPane.setPattern(controller.getPattern()); + phasetwoscreen.phasetwoshowPane.setSearchText(controller.getSearchText()); + phasetwoscreen.phasetwoshowPane.update((Step)null,false); + controller.initPhaseTwo(); + setForwardControlButton(true); + phasetwoscreen.updateUI(); + } + if(controller.isPatternSet()) { + phasetwoscreen.phasetwoinputPane.setGenerateSearchTextEnabled(true); + phasetwoscreen.phasetwoshowPane.setPattern(controller.getPattern()); + phasetwoscreen.updateUI(); + } + if(controller.isSearchTextSet()) { + phasetwoscreen.phasetwoshowPane.setSearchText(controller.getSearchText()); + phasetwoscreen.infotabbedPane.setSearchText(controller.getSearchText()); + phasetwoscreen.updateUI(); + } + phasetwoscreen.infotabbedPane.setDescription("",false); + } + + /** + * The method is called when loading a session in phase two. + * + */ + public void restorePhaseTwo() { + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false,false); + if(controller.isPatternSet() && controller.isSearchTextSet()) { + controller.getPattern().setPattern(phasetwoscreen.phasetwoinputPane.getTfPatternText()); + phasetwoscreen.infotabbedPane.setSearchText(controller.getSearchText()); + phasetwoscreen.infotabbedPane.setDescription("",false); + controller.restorePhaseTwo(); + phasetwoscreen.phasetwoshowPane.setPattern(controller.getPattern()); + phasetwoscreen.phasetwoshowPane.setSearchText(controller.getSearchText()); + doNextStep(); + phasetwoscreen.updateUI(); + } + } + + /** + * The method is called to set the pattern. + * + */ + public void setPattern() { + controller.setLoad(false); + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + if (controller.getPhase() == 1) { + controller.getPattern().setPattern(phaseonescreen.phaseoneinputPane.getTfPatternText()); + initPhaseOne(); + } + if (controller.getPhase() == 2) { + controller.getPattern().setPattern(phasetwoscreen.phasetwoinputPane.getTfPatternText()); + phasetwoscreen.phasetwoinputPane.setGenerateSearchTextEnabled(true); + initPhaseTwo(); + } + } + + /** + * The method is called to get the searchtext. + * + * @return the searchtext + */ + public String getSearchText() { + return controller.getSearchText(); + } + + /** + * The method is called to set the searchext. + * + * @param searchtext the searchtext + */ + public void setSearchText(String searchtext) { + if(searchtext.equals("") || searchtext == null) phasetwoscreen.phasetwoshowPane.setSearchText(""); + controller.setLoad(false); + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + controller.setSearchText(searchtext); + phasetwoscreen.infotabbedPane.setSearchText(controller.getSearchText()); + if(controller.getPhase() == 2) initPhaseTwo(); + } + + /** + * Creates a random pattern by a number of characters and a length. + * + * @param alphabet the size of the alphabet + * @param length the length of the random generated pattern + */ + public void createRandomPattern(int alphabet, int length) { + String newpattern = ""; + Random rand = new Random(); + for(int i = 0; i < length; i++) { + newpattern += (char)(rand.nextInt(alphabet) + 97); + } + if(controller.getPhase() == 1) { + phaseonescreen.phaseoneinputPane.setTfPatternText(newpattern); + setPattern(); + } + if(controller.getPhase() == 2) { + phasetwoscreen.phasetwoinputPane.setTfPatternText(newpattern); + setPattern(); + } + } + + /** + * Creates a random searchtext. + * + */ + public void createRandomSearchText() { + String searchtext = ""; + List charset = new LinkedList(); + for(int i = 0; i < controller.getPattern().getPattern().length(); i++) + charset.add(controller.getPattern().getPattern().charAt(i)); + Random rand = new Random(); + int patposinst = rand.nextInt(Constants.RANDOM_SEARCHTEXT_LENGTH - controller.getPattern().getPattern().length()) + 1; + for(int i = 0; i < Constants.RANDOM_SEARCHTEXT_LENGTH; i++) { + if(i == patposinst) { + searchtext += controller.getPattern().getPattern(); + i += controller.getPattern().getPattern().length() - 1; + } + else searchtext += charset.get(rand.nextInt(charset.size())); + } + setSearchText(searchtext); + } + + /** + * The method is called when the next step should be performed. + * + */ + public void doNextStep() { + Step nextstep = controller.doNextStep(); + if (nextstep == null) setForwardControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setAllControlButton(true); + if (controller.getPhase() == 1) { + if (nextstep instanceof P1BeginForStep) { + if (((P1BeginForStep)nextstep).isLastForStep()) { + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(true); + setForwardControlButton(false); + } + } + phaseonescreen.phaseoneshowPane.update(nextstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(nextstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(nextstep.getDescriptionText(),true); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + if (nextstep instanceof P2EndStep) { + setForwardControlButton(false); + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(true,((P2EndStep)nextstep).isPatternFound()); + } + phasetwoscreen.phasetwoshowPane.update(nextstep,true); + phasetwoscreen.infotabbedPane.setKMPHighlighter(nextstep.getKMPHighlighter()); + int start = ((P2Step)nextstep).getTextPos() - nextstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(nextstep.getDescriptionText(),true); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called when the next big step should be performed. + * + */ + public void doNextBigStep() { + Step nextbigstep = controller.doNextBigStep(); + if (nextbigstep == null) setForwardControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setAllControlButton(true); + if (controller.getPhase() == 1) { + if (nextbigstep instanceof P1BeginForStep) { + if (((P1BeginForStep)nextbigstep).isLastForStep()) { + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(true); + setForwardControlButton(false); + } + } + phaseonescreen.phaseoneshowPane.update(nextbigstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(nextbigstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(nextbigstep.getDescriptionText(),true); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + if (nextbigstep instanceof P2EndStep) { + setForwardControlButton(false); + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(true,((P2EndStep)nextbigstep).isPatternFound()); + } + phasetwoscreen.phasetwoshowPane.update(nextbigstep,true); + phasetwoscreen.infotabbedPane.setKMPHighlighter(nextbigstep.getKMPHighlighter()); + int start = ((P2Step)nextbigstep).getTextPos() - nextbigstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(nextbigstep.getDescriptionText(),true); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called when the algorithm should be finished. + * + */ + public void doEndStep() { + Step endstep = controller.doEndStep(); + if (endstep == null) setAllControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setBackControlButton(true); + setForwardControlButton(false); + if (controller.getPhase() == 1) { + phaseonescreen.phaseoneshowPane.update(endstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(endstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(endstep.getDescriptionText(),true); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(true); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(true,((P2EndStep)endstep).isPatternFound()); + phasetwoscreen.phasetwoshowPane.update(endstep,true); + phasetwoscreen.infotabbedPane.setKMPHighlighter(endstep.getKMPHighlighter()); + int start = ((P2Step)endstep).getTextPos() - endstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(endstep.getDescriptionText(),true); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called when the previous step should be performed. + * + */ + public void doPreviousStep() { + Step previousstep = controller.doPreviousStep(); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(false); + if (previousstep == null) setBackControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setAllControlButton(true); + if (controller.getPhase() == 1) { + if (previousstep instanceof P1InitStep) + setBackControlButton(false); + phaseonescreen.phaseoneshowPane.update(previousstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(previousstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(previousstep.getDescriptionText(),true); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + if (previousstep instanceof P2InitStep) + setBackControlButton(false); + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false,false); + phasetwoscreen.phasetwoshowPane.update(previousstep,false); + phasetwoscreen.infotabbedPane.setKMPHighlighter(previousstep.getKMPHighlighter()); + int start = ((P2Step)previousstep).getTextPos() - previousstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(previousstep.getDescriptionText(),true); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called when the previous big step should be performed. + * + */ + public void doPreviousBigStep() { + Step previousbigstep = controller.doPreviousBigStep(); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(false); + if (previousbigstep == null) setBackControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setAllControlButton(true); + if (controller.getPhase() == 1) { + if (previousbigstep instanceof P1InitStep) + setBackControlButton(false); + phaseonescreen.phaseoneshowPane.update(previousbigstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(previousbigstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(previousbigstep.getDescriptionText(),true); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + if (previousbigstep instanceof P2InitStep) + setBackControlButton(false); + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false,false); + phasetwoscreen.phasetwoshowPane.update(previousbigstep,false); + phasetwoscreen.infotabbedPane.setKMPHighlighter(previousbigstep.getKMPHighlighter()); + int start = ((P2Step)previousbigstep).getTextPos() - previousbigstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(previousbigstep.getDescriptionText(),true); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called when the algorithm should be rewinded. + * + */ + public void doStartStep() { + Step startstep = controller.doStartStep(); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(false); + if (startstep == null) setAllControlButton(false); + else { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + setForwardControlButton(true); + setBackControlButton(false); + if (controller.getPhase() == 1) { + phaseonescreen.phaseoneshowPane.update(startstep); + phaseonescreen.infotabbedPane.setKMPHighlighter(startstep.getKMPHighlighter()); + phaseonescreen.infotabbedPane.setDescription(startstep.getDescriptionText(),false); + phaseonescreen.updateUI(); + } + if (controller.getPhase() == 2) { + phasetwoscreen.phasetwoinputPane.setLabelResultVisible(false,false); + phasetwoscreen.phasetwoshowPane.update(startstep,false); + phasetwoscreen.infotabbedPane.setKMPHighlighter(startstep.getKMPHighlighter()); + int start = ((P2Step)startstep).getTextPos() - startstep.getPatPos(); + phasetwoscreen.infotabbedPane.setSearchTextHighlighter(start, + start + controller.getPattern().getPattern().length()); + phasetwoscreen.infotabbedPane.setDescription(startstep.getDescriptionText(),false); + phasetwoscreen.updateUI(); + } + } + } + + /** + * The method is called to expand the pattern. + * + */ + public void addPattern() { + modconn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + phaseonescreen.phaseoneinputPane.setTfPatternText(controller.getPattern().getPattern() + + phaseonescreen.phaseoneinputPane.getTfAddPatternText()); + phaseonescreen.phaseoneinputPane.setAddPatternEnabled(false); + phaseonescreen.phaseoneinputPane.setTfAddPatternText(""); + phaseonescreen.phaseoneinputPane.setBtGoOnVisible(false); + restorePhaseOne(); + } + + /** + * The method is called when a key is typed on the pattern input field. + * + */ + public void keyOnTfPattern() { + if (controller.getPhase() == 1) { + if(phaseonescreen.phaseoneinputPane.getTfPatternLength() > 0 && + phaseonescreen.phaseoneinputPane.getTfPatternLength() <= Constants.MAX_PAT_LENGTH) + phaseonescreen.phaseoneinputPane.setPatternEnabled(true); + else phaseonescreen.phaseoneinputPane.setPatternEnabled(false); + } + if (controller.getPhase() == 2) { + if(phasetwoscreen.phasetwoinputPane.getTfPatternLength() > 0 && + phasetwoscreen.phasetwoinputPane.getTfPatternLength() <= Constants.MAX_PAT_LENGTH) { + phasetwoscreen.phasetwoinputPane.setPatternEnabled(true); + } + else phasetwoscreen.phasetwoinputPane.setPatternEnabled(false); + } + } + + /** + * The method is called when a key is typed on the expand-pattern input field. + * + */ + public void keyOnTfAddPattern() { + if(phaseonescreen.phaseoneinputPane.getTfAddPatternLength() > 0 && + phaseonescreen.phaseoneinputPane.getTfAddPatternLength() < 2 && + controller.getPattern().isPatternExpandable()) + phaseonescreen.phaseoneinputPane.setAddPatternEnabled(true); + else phaseonescreen.phaseoneinputPane.setAddPatternEnabled(false); + } + + /** + * Opens a FileChooser to load a searchtext from an ASCII formated file. + * + * @return the searchtext + */ + public String openSearchTextFileChooser() { + JFileChooser fcsearchtext = new JFileChooser(); + ExampleFileFilter filter = new ExampleFileFilter(); + filter.addExtension("txt"); + filter.addExtension("dat"); + filter.setDescription("ASCII-Text-Dateien"); + fcsearchtext.setFileFilter(filter); + int returnVal = fcsearchtext.showOpenDialog(null); + if(returnVal == JFileChooser.APPROVE_OPTION) { + try { + BufferedReader in = new BufferedReader( + new FileReader(fcsearchtext.getCurrentDirectory().getAbsolutePath() + + Constants.FILE_SEPARATOR + fcsearchtext.getSelectedFile().getName())); + String searchtext = ""; + String line = in.readLine(); + while(line != null) { + searchtext += line + Constants.SEPARATOR; + line = in.readLine(); + } + in.close(); + return searchtext; + } + catch(Exception err) { + err.printStackTrace(); + } + } + return null; + } + + /** + * Enables or disables the control buttons. + * + * @param value the value + */ + public void setAllControlButton(boolean value) { + setBackControlButton(value); + setForwardControlButton(value); + } + + /** + * Enables or disables the backward control buttons. + * + * @param value the value + */ + public void setBackControlButton(boolean value) { + abortAction.setEnabled(value); + fastBackwardAction.setEnabled(value); + backwardAction.setEnabled(value); + } + + /** + * Enables or disables the forward control buttons. + * + * @param value the value + */ + public void setForwardControlButton(boolean value) { + forwardAction.setEnabled(value); + fastForwardAction.setEnabled(value); + finishAction.setEnabled(value); + } + + /** + * The method is called when loading a learning example. + * + * @param pattern the pattern + * @param searchtext the searchtext + */ + public void loadLearningExample(String pattern, String searchtext) { + controller.setLoad(false); + controller.getPattern().setPattern(pattern); + controller.setSearchText(searchtext); + } + + /** + * The method is called to set the visiblity of the cycles in phase one on or off. + * + */ + public void setCycles() { + phaseonescreen.phaseoneshowPane.showCycles(phaseonescreen.phaseoneinputPane.isCycleSelected()); + if(phaseonescreen.phaseoneinputPane.isCycleSelected() && beamermode) + phaseonescreen.setDividerLocation(phaseonescreen.getDividerLocation() + GUIConstants.CYCLE_TAB_SIZE); + if((!phaseonescreen.phaseoneinputPane.isCycleSelected()) && beamermode) + phaseonescreen.setDividerLocation(phaseonescreen.getDividerLocation() - GUIConstants.CYCLE_TAB_SIZE); + phaseonescreen.updateUI(); + } + + /** + * Clears the pattern and the searchtext, not the history. + * + */ + public void clearValues() { + modconn.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + controller.getPattern().setPattern(null); + controller.setSearchText(null); + if (controller.getPhase() == 1) phaseonescreen.phaseoneshowPane.update((Step)null); + if (controller.getPhase() == 2) phasetwoscreen.phasetwoshowPane.update((Step)null, false); + } + + /** + * The method is called to scale the viewingscreen. + * + * @param scalefactor the scalefactor + */ + public void scaleScreen(double scalefactor) { + if(controller.getPhase() == 1) { + phaseonescreen.phaseoneshowPane.incFontSize(scalefactor); + phaseonescreen.infotabbedPane.scaleScreen(scalefactor); + phaseonescreen.updateUI(); + } + if(controller.getPhase() == 2) { + phasetwoscreen.phasetwoshowPane.incFontSize(scalefactor); + phasetwoscreen.infotabbedPane.scaleScreen(scalefactor); + phasetwoscreen.updateUI(); + } + } + + /** + * The method is called to set the beamer-mode. + * + * @param value the value + */ + public void doBeamerMode(boolean value) { + beamermode = value; + if(value) { + if(controller.getPhase() == 1) { + phaseonescreen.setDividerLocation(GUIConstants.DIVIDER_LOCATION); + phaseonescreen.setSliderPosition((int)(GUIConstants.SCALEFACTOR * 10)); + phaseonescreen.infotabbedPane.setTabFocus(1); + scaleScreen(GUIConstants.SCALEFACTOR); + } + if(controller.getPhase() == 2) { + phasetwoscreen.setDividerLocation(GUIConstants.DIVIDER_LOCATION); + phasetwoscreen.setSliderPosition((int)(GUIConstants.SCALEFACTOR * 10)); + phasetwoscreen.infotabbedPane.setTabFocus(1); + scaleScreen(GUIConstants.SCALEFACTOR); + } + } + else { + if(controller.getPhase() == 1) { + phaseonescreen.setSliderPosition(10); + scaleScreen(1); + } + if(controller.getPhase() == 2) { + phasetwoscreen.setSliderPosition(10); + scaleScreen(1); + } + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/CVS/Entries b/src/org/jalgo/module/kmp/gui/component/CVS/Entries new file mode 100644 index 0000000..d45f149 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/CVS/Entries @@ -0,0 +1,12 @@ +/InfoTabbedPanel.java/1.1/Fri Jun 30 14:35:18 2006// +/LearningExamplesDialog.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseOneInputPanel.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseOneScreen.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseOneShowPanel.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseTwoInputPanel.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseTwoScreen.java/1.1/Fri Jun 30 14:35:18 2006// +/PhaseTwoShowPanel.java/1.1/Fri Jun 30 14:35:18 2006// +/RandomPatternDialog.java/1.1/Fri Jun 30 14:35:18 2006// +/SearchTextLoadDialog.java/1.1/Fri Jun 30 14:35:18 2006// +/WelcomeButton.java/1.2/Thu Jan 31 20:15:07 2008// +/WelcomeScreen.java/1.1/Fri Jun 30 14:35:18 2006// diff --git a/src/org/jalgo/module/kmp/gui/component/CVS/Repository b/src/org/jalgo/module/kmp/gui/component/CVS/Repository new file mode 100644 index 0000000..27bd2ec --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/gui/component diff --git a/src/org/jalgo/module/kmp/gui/component/CVS/Root b/src/org/jalgo/module/kmp/gui/component/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.java b/src/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.java new file mode 100644 index 0000000..c253d3e --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/InfoTabbedPanel.java @@ -0,0 +1,363 @@ +package org.jalgo.module.kmp.gui.component; + +import java.awt.Color; +import java.awt.Font; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.Insets; +import java.awt.Dimension; + +import java.util.List; + +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JPanel; +import javax.swing.JLabel; +import javax.swing.JTextPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.algorithm.KMPHighlighter; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.event.PhaseOneScreenListener; +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; + +/** + * This is the Panel where the user can choose the visibility of several informations which are: + * the code, the protocol, the code and the protocol in phase one + * and the code, the protocol, the code and the protocol, the code and the searchtext, + * the protocol and the searchtext in phase two. + * + * @author Danilo Lisske + */ +public class InfoTabbedPanel extends JTabbedPane { + private static final long serialVersionUID = 9930886361248572L; + + private PhaseOneScreenListener listener1; + private PhaseTwoScreenListener listener2; + + private JTextPane tacodeonly; + private JTextPane tadesconly; + private JTextPane tacodewithdesc; + private JTextPane tadescwithcode; + private JTextPane tacodewithst; + private JTextPane tadescwithst; + private JTextPane tastwithcode; + private JTextPane tastwithdesc; + + private DefaultStyledDocument descdoc; + private SimpleAttributeSet normalstyle; + private SimpleAttributeSet highlightstyle; + private Font codefont; + private Font stfont; + + /** + * The constructor of the InfoTabbedPanel. + * + * @param l1 the PhaseOneScreenListener + * @param l2 the PhasetwoScreenListener + */ + public InfoTabbedPanel(PhaseOneScreenListener l1, PhaseTwoScreenListener l2) { + listener1 = l1; + listener2 = l2; + boolean isphaseone; + if(listener1 == null) isphaseone = false; + else isphaseone = true; + + setFont(GUIConstants.SCREEN_FONT); + + descdoc = new DefaultStyledDocument(); + codefont = GUIConstants.CODE_FONT; + stfont = GUIConstants.SEARCHTEXT_FONT; + + normalstyle = new SimpleAttributeSet(); + StyleConstants.setFontFamily(normalstyle,"SansSerif"); + StyleConstants.setFontSize(normalstyle, 11); + StyleConstants.setForeground(normalstyle, Color.BLACK); + + highlightstyle = new SimpleAttributeSet(); + StyleConstants.setFontFamily(highlightstyle,"SansSerif"); + StyleConstants.setFontSize(highlightstyle, 14); + StyleConstants.setForeground(highlightstyle, Color.BLUE); + + JLabel lbcodeonly = new JLabel(Messages.getString("kmp","ITP.Label_code") + ":"); + lbcodeonly.setFont(getFont()); + JLabel lbdesconly = new JLabel(Messages.getString("kmp","ITP.Label_desc") + ":"); + lbdesconly.setFont(getFont()); + JLabel lbcodewithdesc = new JLabel(Messages.getString("kmp","ITP.Label_code") + ":"); + lbcodewithdesc.setFont(getFont()); + JLabel lbdescwithcode = new JLabel(Messages.getString("kmp","ITP.Label_desc") + ":"); + lbdescwithcode.setFont(getFont()); + JLabel lbcodewithst = new JLabel(Messages.getString("kmp","ITP.Label_code") + ":"); + lbcodewithst.setFont(getFont()); + JLabel lbdescwithst = new JLabel(Messages.getString("kmp","ITP.Label_desc") + ":"); + lbdescwithst.setFont(getFont()); + JLabel lbstwithcode = new JLabel(Messages.getString("kmp","ITP.Label_searchtext") + ":"); + lbstwithcode.setFont(getFont()); + JLabel lbstwithdesc = new JLabel(Messages.getString("kmp","ITP.Label_searchtext") + ":"); + lbstwithdesc.setFont(getFont()); + + JPanel codeanddescPane = new JPanel(new GridBagLayout()); + JPanel codeonlyPane = new JPanel(new GridBagLayout()); + JPanel desconlyPane = new JPanel(new GridBagLayout()); + JPanel descandstPane = new JPanel(new GridBagLayout()); + JPanel codeandstPane = new JPanel(new GridBagLayout()); + + tacodeonly = new JTextPane(); + tacodeonly.setEditable(false); + tacodeonly.setName(Messages.getString("kmp","ITP.TextPane_code_ttt")); + tacodeonly.setFont(codefont); + JScrollPane spcodeonly = new JScrollPane(tacodeonly, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tadesconly = new JTextPane(); + tadesconly.setEditable(false); + tadesconly.setName(Messages.getString("kmp","ITP.TextPane_desc_ttt")); + tadesconly.setDocument(descdoc); + JScrollPane spdesconly = new JScrollPane(tadesconly, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tacodewithdesc = new JTextPane(); + tacodewithdesc.setEditable(false); + tacodewithdesc.setName(Messages.getString("kmp","ITP.TextPane_code_ttt")); + tacodewithdesc.setPreferredSize(new Dimension(codeanddescPane.getPreferredSize().width / 2, + tacodewithdesc.getPreferredSize().height)); + tacodewithdesc.setFont(codefont); + JScrollPane spcodewithdesc = new JScrollPane(tacodewithdesc, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tadescwithcode = new JTextPane(); + tadescwithcode.setEditable(false); + tadescwithcode.setName(Messages.getString("kmp","ITP.TextPane_desc_ttt")); + tadescwithcode.setPreferredSize(new Dimension(codeanddescPane.getPreferredSize().width / 2, + tadescwithcode.getPreferredSize().height)); + tadescwithcode.setDocument(descdoc); + JScrollPane spdescwithcode = new JScrollPane(tadescwithcode, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tacodewithst = new JTextPane(); + tacodewithst.setEditable(false); + tacodewithst.setName(Messages.getString("kmp","ITP.TextPane_code_ttt")); + tacodewithst.setPreferredSize(new Dimension(codeandstPane.getPreferredSize().width / 2, + tacodewithst.getPreferredSize().height)); + tacodewithst.setFont(codefont); + JScrollPane spcodewithst = new JScrollPane(tacodewithst, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tadescwithst = new JTextPane(); + tadescwithst.setEditable(false); + tadescwithst.setName(Messages.getString("kmp","ITP.TextPane_desc_ttt")); + tadescwithst.setPreferredSize(new Dimension(descandstPane.getPreferredSize().width / 2, + tadescwithst.getPreferredSize().height)); + tadescwithst.setDocument(descdoc); + JScrollPane spdescwithst = new JScrollPane(tadescwithst, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tastwithcode = new JTextPane(); + tastwithcode.setEditable(false); + tastwithcode.setName(Messages.getString("kmp","ITP.TextPane_st_ttt")); + tastwithcode.setPreferredSize(new Dimension(codeandstPane.getPreferredSize().width / 2, + tastwithcode.getPreferredSize().height)); + tastwithcode.setFont(stfont); + JScrollPane spstwithcode = new JScrollPane(tastwithcode, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + tastwithdesc = new JTextPane(); + tastwithdesc.setEditable(false); + tastwithdesc.setName(Messages.getString("kmp","ITP.TextPane_st_ttt")); + tastwithdesc.setPreferredSize(new Dimension(descandstPane.getPreferredSize().width / 2, + tastwithdesc.getPreferredSize().height)); + tastwithdesc.setFont(stfont); + JScrollPane spstwithdesc = new JScrollPane(tastwithdesc, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.anchor = GridBagConstraints.NORTHWEST; + c.weightx = 1; + c.insets = new Insets(2,2,2,2); + codeanddescPane.add(lbcodewithdesc,c); + codeonlyPane.add(lbcodeonly,c); + desconlyPane.add(lbdesconly,c); + codeandstPane.add(lbcodewithst,c); + descandstPane.add(lbdescwithst,c); + c.gridx = 1; + codeanddescPane.add(lbdescwithcode,c); + codeandstPane.add(lbstwithcode,c); + descandstPane.add(lbstwithdesc,c); + c.gridx = 0; + c.gridy = 1; + c.fill = GridBagConstraints.BOTH; + c.anchor = GridBagConstraints.CENTER; + c.weighty = 1; + codeanddescPane.add(spcodewithdesc,c); + codeandstPane.add(spcodewithst,c); + descandstPane.add(spdescwithst,c); + c.gridx = 1; + codeanddescPane.add(spdescwithcode,c); + codeandstPane.add(spstwithcode,c); + descandstPane.add(spstwithdesc,c); + c.gridx = 0; + codeonlyPane.add(spcodeonly,c); + desconlyPane.add(spdesconly,c); + + addTab(Messages.getString("kmp","ITP.Tab_codeanddesc"),codeanddescPane); + addTab(Messages.getString("kmp","ITP.Tab_codeonly"),codeonlyPane); + addTab(Messages.getString("kmp","ITP.Tab_desconly"),desconlyPane); + if(!isphaseone) { + tacodeonly.addMouseListener(listener2); + tadesconly.addMouseListener(listener2); + tacodewithdesc.addMouseListener(listener2); + tadescwithcode.addMouseListener(listener2); + tacodewithst.addMouseListener(listener2); + tadescwithst.addMouseListener(listener2); + tastwithcode.addMouseListener(listener2); + tastwithdesc.addMouseListener(listener2); + addTab(Messages.getString("kmp","ITP.Tab_codeandst"),codeandstPane); + addTab(Messages.getString("kmp","ITP.Tab_descandst"),descandstPane); + } + else { + tacodeonly.addMouseListener(listener1); + tadesconly.addMouseListener(listener1); + tacodewithdesc.addMouseListener(listener1); + tadescwithcode.addMouseListener(listener1); + tacodewithst.addMouseListener(listener1); + tadescwithst.addMouseListener(listener1); + tastwithcode.addMouseListener(listener1); + tastwithdesc.addMouseListener(listener1); + } + } + + /** + * Sets the highlighters in the code textarea. + * + * @param hl a List of KMPHighlighter + */ + public void setKMPHighlighter(List hl) { + try { + tacodeonly.getHighlighter().removeAllHighlights(); + tacodewithdesc.getHighlighter().removeAllHighlights(); + tacodewithst.getHighlighter().removeAllHighlights(); + for(KMPHighlighter kmph : hl) { + tacodeonly.getHighlighter().addHighlight(kmph.getStartPos(),kmph.getEndPos(),kmph.getHightlightPainter()); + tacodewithdesc.getHighlighter().addHighlight(kmph.getStartPos(),kmph.getEndPos(),kmph.getHightlightPainter()); + tacodewithst.getHighlighter().addHighlight(kmph.getStartPos(),kmph.getEndPos(),kmph.getHightlightPainter()); + } + } + catch(BadLocationException ble) { + ble.printStackTrace(); + } + catch(NullPointerException npe) { + + } + } + + /** + * Sets the highlighter in the searchtextarea. + * + * @param start the startvalue + * @param end the endvalue + */ + public void setSearchTextHighlighter(int start, int end) { + try { + tastwithcode.getHighlighter().removeAllHighlights(); + tastwithdesc.getHighlighter().removeAllHighlights(); + tastwithcode.getHighlighter().addHighlight(start, end, + new DefaultHighlighter.DefaultHighlightPainter(GUIConstants.SEARCHTEXT_HIGHLIGHT)); + tastwithdesc.getHighlighter().addHighlight(start, end, + new DefaultHighlighter.DefaultHighlightPainter(GUIConstants.SEARCHTEXT_HIGHLIGHT)); + } + catch(BadLocationException ble) { + ble.printStackTrace(); + } + catch(NullPointerException npe) { + + } + } + + /** + * Sets the searchtext in the searchtextareas. + * + * @param s the searchtext + */ + public void setSearchText(String s) { + tastwithcode.setText(s); + tastwithdesc.setText(s); + } + + /** + * Sets the codetext in the codeareas. + * + * @param c the code text + */ + public void setCode(String c) { + tacodeonly.setText(c); + tacodewithdesc.setText(c); + tacodewithst.setText(c); + } + + /** + * Sets the protocol. Either append the new text or clears the old one and writes only the + * new text to the protocolareas. + * + * @param d the protocoltext + * @param append append the text + */ + public void setDescription(String d, boolean append) { + try { + if(append) descdoc.setCharacterAttributes(0, descdoc.getLength(), normalstyle, true); + else descdoc.remove(0, descdoc.getLength()); + descdoc.insertString(descdoc.getLength(), Constants.SEPARATOR + d, highlightstyle); + tadesconly.setCaretPosition(descdoc.getLength()); + tadescwithcode.setCaretPosition(descdoc.getLength()); + tadescwithst.setCaretPosition(descdoc.getLength()); + } + catch (BadLocationException ble) { + ble.printStackTrace(); + } + } + + /** + * The method is called when the sizeslider is moved to another value. + * + * @param scalefactor the scalefactor + */ + public void scaleScreen(double scalefactor) { + Font newcodefont = new Font(GUIConstants.CODE_FONT.getName(), + GUIConstants.CODE_FONT.getStyle(),(int)(GUIConstants.CODE_FONT.getSize()*scalefactor)); + Font newstfont = new Font(GUIConstants.SEARCHTEXT_FONT.getName(), + GUIConstants.SEARCHTEXT_FONT.getStyle(),(int)(GUIConstants.SEARCHTEXT_FONT.getSize()*scalefactor)); + tacodeonly.setFont(newcodefont); + tacodewithdesc.setFont(newcodefont); + tacodewithst.setFont(newcodefont); + tastwithcode.setFont(newstfont); + tastwithdesc.setFont(newstfont); + StyleConstants.setFontSize(normalstyle,(int)(11*scalefactor)); + StyleConstants.setFontSize(highlightstyle,(int)(14*scalefactor)); + descdoc.setCharacterAttributes(0, descdoc.getLength(), normalstyle, true); + } + + /** + * Sets the focus to the code tab. + * + * @param tab the tab number + */ + public void setTabFocus(int tab) { + setSelectedIndex(tab); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.java b/src/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.java new file mode 100644 index 0000000..d843d4f --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/LearningExamplesDialog.java @@ -0,0 +1,280 @@ +package org.jalgo.module.kmp.gui.component; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JRadioButton; +import javax.swing.ButtonGroup; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.ButtonModel; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.Insets; + +import org.jalgo.module.kmp.gui.event.WelcomeScreenListener; +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIConstants; + +/** + * This is the dialog where the user can choose one of ten examples. + * + * @author Danilo Lisske + */ +public class LearningExamplesDialog extends JDialog { + private static final long serialVersionUID = 2338105141588581154L; + + private WelcomeScreenListener listener; + private JTextPane tpdescription; + private ButtonGroup bgexamples; + + /** + * The constructor of the LearningExamplesDialog + * + * @param l the WelcomeScreenListener + */ + public LearningExamplesDialog(WelcomeScreenListener l) { + listener = l; + setTitle(Messages.getString("kmp","LED.Title")); + setSize(500,500); + setFont(GUIConstants.SCREEN_FONT); + setResizable(false); + addWindowFocusListener(listener); + setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.gridheight = 20; + c.anchor = GridBagConstraints.WEST; + tpdescription = new JTextPane(); + tpdescription.setEditable(false); + tpdescription.setFont(getFont()); + tpdescription.setPreferredSize(new Dimension(120,400)); + tpdescription.setBackground(Color.LIGHT_GRAY); + JScrollPane scrollPane = new JScrollPane(tpdescription, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + add(scrollPane,c); + bgexamples = new ButtonGroup(); + JRadioButton rb0 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_0"),true); + JLabel lb0 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_0")); + JRadioButton rb1 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_1"),true); + JLabel lb1 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_1")); + JRadioButton rb2 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_2"),true); + JLabel lb2 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_2")); + JRadioButton rb3 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_3"),true); + JLabel lb3 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_3")); + JRadioButton rb4 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_4"),true); + JLabel lb4 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_4")); + JRadioButton rb5 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_5"),true); + JLabel lb5 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_5")); + JRadioButton rb6 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_6"),true); + JLabel lb6 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_6")); + JRadioButton rb7 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_7"),true); + JLabel lb7 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_7")); + JRadioButton rb8 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_8"),true); + JLabel lb8 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_8")); + JRadioButton rb9 = new JRadioButton(Messages.getString("kmp","LED.RB_Title") + + ": " + Messages.getString("kmp","LED.Example_pattern_9"),true); + JLabel lb9 = new JLabel(Messages.getString("kmp","LED.LB_Title") + ": " + + Messages.getString("kmp","LED.Example_searchtext_9")); + bgexamples.add(rb0); + bgexamples.add(rb1); + bgexamples.add(rb2); + bgexamples.add(rb3); + bgexamples.add(rb4); + bgexamples.add(rb5); + bgexamples.add(rb6); + bgexamples.add(rb7); + bgexamples.add(rb8); + bgexamples.add(rb9); + rb0.addMouseListener(listener); + rb0.setActionCommand("0"); + rb0.setName("0"); + rb0.setFont(getFont()); + lb0.addMouseListener(listener); + lb0.setName("0"); + lb0.setFont(getFont()); + rb1.addMouseListener(listener); + rb1.setActionCommand("1"); + rb1.setName("1"); + rb1.setFont(getFont()); + lb1.addMouseListener(listener); + lb1.setName("1"); + lb1.setFont(getFont()); + rb2.addMouseListener(listener); + rb2.setActionCommand("2"); + rb2.setName("2"); + rb2.setFont(getFont()); + lb2.addMouseListener(listener); + lb2.setName("2"); + lb2.setFont(getFont()); + rb3.addMouseListener(listener); + rb3.setActionCommand("3"); + rb3.setName("3"); + rb3.setFont(getFont()); + lb3.addMouseListener(listener); + lb3.setName("3"); + lb3.setFont(getFont()); + rb4.addMouseListener(listener); + rb4.setActionCommand("4"); + rb4.setName("4"); + rb4.setFont(getFont()); + lb4.addMouseListener(listener); + lb4.setName("4"); + lb4.setFont(getFont()); + rb5.addMouseListener(listener); + rb5.setActionCommand("5"); + rb5.setName("5"); + rb5.setFont(getFont()); + lb5.addMouseListener(listener); + lb5.setName("5"); + lb5.setFont(getFont()); + rb6.addMouseListener(listener); + rb6.setActionCommand("6"); + rb6.setName("6"); + rb6.setFont(getFont()); + lb6.addMouseListener(listener); + lb6.setName("6"); + lb6.setFont(getFont()); + rb7.addMouseListener(listener); + rb7.setActionCommand("7"); + rb7.setName("7"); + rb7.setFont(getFont()); + lb7.addMouseListener(listener); + lb7.setName("7"); + lb7.setFont(getFont()); + rb8.addMouseListener(listener); + rb8.setActionCommand("8"); + rb8.setName("8"); + rb8.setFont(getFont()); + lb8.addMouseListener(listener); + lb8.setName("8"); + lb8.setFont(getFont()); + rb9.addMouseListener(listener); + rb9.setActionCommand("9"); + rb9.setName("9"); + rb9.setFont(getFont()); + lb9.addMouseListener(listener); + lb9.setName("9"); + lb9.setFont(getFont()); + c.gridx = 1; + c.gridheight = 1; + add(rb0,c); + c.gridy = 1; + c.insets = new Insets(0,20,0,0); + add(lb0,c); + c.gridy = 2; + c.insets = new Insets(0,0,0,0); + add(rb1,c); + c.gridy = 3; + c.insets = new Insets(0,20,0,0); + add(lb1,c); + c.gridy = 4; + c.insets = new Insets(0,0,0,0); + add(rb2,c); + c.gridy = 5; + c.insets = new Insets(0,20,0,0); + add(lb2,c); + c.gridy = 6; + c.insets = new Insets(0,0,0,0); + add(rb3,c); + c.gridy = 7; + c.insets = new Insets(0,20,0,0); + add(lb3,c); + c.gridy = 8; + c.insets = new Insets(0,0,0,0); + add(rb4,c); + c.gridy = 9; + c.insets = new Insets(0,20,0,0); + add(lb4,c); + c.gridy = 10; + c.insets = new Insets(0,0,0,0); + add(rb5,c); + c.gridy = 11; + c.insets = new Insets(0,20,0,0); + add(lb5,c); + c.gridy = 12; + c.insets = new Insets(0,0,0,0); + add(rb6,c); + c.gridy = 13; + c.insets = new Insets(0,20,0,0); + add(lb6,c); + c.gridy = 14; + c.insets = new Insets(0,0,0,0); + add(rb7,c); + c.gridy = 15; + c.insets = new Insets(0,20,0,0); + add(lb7,c); + c.gridy = 16; + c.insets = new Insets(0,0,0,0); + add(rb8,c); + c.gridy = 17; + c.insets = new Insets(0,20,0,0); + add(lb8,c); + c.gridy = 18; + c.insets = new Insets(0,0,0,0); + add(rb9,c); + c.gridy = 19; + c.insets = new Insets(0,20,0,0); + add(lb9,c); + c.gridx = 0; + c.gridy = 20; + c.anchor = GridBagConstraints.EAST; + c.insets = new Insets(2,2,2,2); + JButton btapply = new JButton(Messages.getString("kmp","LED.Button_apply")); + btapply.setActionCommand("setlearningexample"); + btapply.addActionListener(listener); + btapply.setFont(getFont()); + add(btapply,c); + c.gridx = 1; + c.anchor = GridBagConstraints.WEST; + JButton btcancel = new JButton(Messages.getString("kmp","LED.Button_cancel")); + btcancel.setActionCommand("cancellearningexample"); + btcancel.addActionListener(listener); + btcancel.setFont(getFont()); + add(btcancel,c); + } + + /** + * Sets the content of the description text to the selected number. + * + * @param number the number which has to be set + */ + public void setTfDescriptionText(String number) { + if(number.equals("mouseoff")) + tpdescription.setText(Messages.getString("kmp","LED.Example_description_"+getSelectedIndex())); + else tpdescription.setText(Messages.getString("kmp","LED.Example_description_"+number)); + } + + /** + * Returns the selected learning example. + * + * @return the selected index + */ + public String getSelectedIndex() { + return ((ButtonModel)bgexamples.getSelection()).getActionCommand(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.java b/src/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.java new file mode 100644 index 0000000..b6b5c25 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseOneInputPanel.java @@ -0,0 +1,231 @@ +package org.jalgo.module.kmp.gui.component; + +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Dimension; +import java.awt.ComponentOrientation; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.event.PhaseOneScreenListener; + +/** + * This is the input panel of the phase one. + * + * @author Danilo Lisske + */ +public class PhaseOneInputPanel extends JPanel { + private static final long serialVersionUID = 4627572670136569244L; + + private PhaseOneScreenListener listener; + private JButton btset; + private JButton btaddpattern; + private JButton btgoon; + private JTextField tfpattern; + private JTextField tfaddpattern; + private JCheckBox jbcycle; + + /** + * The constructor of the PhaseOneInputPanel. + * + * @param l1 the PhaseOneScreenListener + */ + public PhaseOneInputPanel(PhaseOneScreenListener l1) { + listener = l1; + + setFont(GUIConstants.SCREEN_FONT); + setLayout(new BorderLayout()); + + JPanel patternPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); + + JLabel lbpattern = new JLabel(Messages.getString("kmp","InputPanel.Label_pattern") + ":"); + lbpattern.setFont(getFont()); + patternPane.add(lbpattern); + + tfpattern = new JTextField(); + tfpattern.setName("tfpattern"); + tfpattern.setFont(getFont()); + tfpattern.setToolTipText(Messages.getString("kmp","InputPanel.TextField_pattern_ttt")); + tfpattern.setPreferredSize(new Dimension(120,tfpattern.getPreferredSize().height)); + tfpattern.addKeyListener(listener); + tfpattern.addMouseListener(listener); + patternPane.add(tfpattern); + + btset = new JButton(Messages.getString("kmp","InputPanel.Button_set")); + btset.setActionCommand("setpattern"); + btset.addActionListener(listener); + btset.addMouseListener(listener); + btset.setToolTipText(Messages.getString("kmp","InputPanel.Button_set_ttt")); + btset.setFont(getFont()); + patternPane.add(btset); + + JButton btrandom = new JButton(Messages.getString("kmp","InputPanel.Button_random")); + btrandom.setActionCommand("random"); + btrandom.addActionListener(listener); + btrandom.addMouseListener(listener); + btrandom.setToolTipText(Messages.getString("kmp","InputPanel.Button_random_ttt")); + btrandom.setFont(getFont()); + patternPane.add(btrandom); + + JPanel goonPane = new JPanel(new FlowLayout(FlowLayout.CENTER)); + + btgoon = new JButton(Messages.getString("kmp","InputPanel.Button_goon")); + btgoon.setActionCommand("goon"); + btgoon.addActionListener(listener); + btgoon.addMouseListener(listener); + btgoon.setForeground(GUIConstants.MOVE_ON_TO_PHASE_TWO); + btgoon.setToolTipText(Messages.getString("kmp","InputPanel.Button_goon_ttt")); + btgoon.setFont(getFont()); + btgoon.setVisible(false); + goonPane.add(btgoon); + + JPanel extpatternPane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + + jbcycle = new JCheckBox(Messages.getString("kmp","InputPanel.CheckBox_cycle") + ":",true); + jbcycle.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + jbcycle.setActionCommand("cyclechange"); + jbcycle.addActionListener(listener); + jbcycle.addMouseListener(listener); + jbcycle.setToolTipText(Messages.getString("kmp","InputPanel.CheckBox_cycle_ttt")); + jbcycle.setFont(getFont()); + extpatternPane.add(jbcycle); + + JLabel lbaddpattern = new JLabel(Messages.getString("kmp","InputPanel.Label_extension") + ":"); + extpatternPane.add(lbaddpattern); + + tfaddpattern = new JTextField(); + tfaddpattern.setName("tfaddpattern"); + tfaddpattern.setFont(getFont()); + tfaddpattern.setToolTipText(Messages.getString("kmp","InputPanel.TextField_addpattern_ttt")); + tfaddpattern.setPreferredSize(new Dimension(20,tfaddpattern.getPreferredSize().height)); + tfaddpattern.addKeyListener(listener); + tfaddpattern.addMouseListener(listener); + extpatternPane.add(tfaddpattern); + + btaddpattern = new JButton(Messages.getString("kmp","InputPanel.Button_addpattern")); + btaddpattern.setActionCommand("addpattern"); + btaddpattern.addActionListener(listener); + btaddpattern.addMouseListener(listener); + btaddpattern.setToolTipText(Messages.getString("kmp","InputPanel.Button_addpattern_ttt")); + btaddpattern.setFont(getFont()); + extpatternPane.add(btaddpattern); + + add(patternPane,BorderLayout.WEST); + add(goonPane,BorderLayout.CENTER); + add(extpatternPane,BorderLayout.EAST); + } + + /** + * Enables or disables the button to set the pattern. + * + * @param value the value + */ + public void setPatternEnabled(boolean value) { + btset.setEnabled(value); + } + + /** + * Returns the status of the button to set the pattern. + * + * @return if the button is enabled + */ + public boolean isPatternEnabled() { + return btset.isEnabled(); + } + + /** + * Returns the text in the pattern textfield. + * + * @return the text in the pattern textfield + */ + public String getTfPatternText() { + return tfpattern.getText(); + } + + /** + * Sets the content of the pattern textfield. + * + * @param p the content + */ + public void setTfPatternText(String p) { + tfpattern.setText(p); + } + + /** + * Returns the length of the content in the pattern textfield. + * + * @return the length + */ + public int getTfPatternLength() { + return tfpattern.getText().length(); + } + + /** + * Enables or disables the pattern expand button. + * + * @param value the value + */ + public void setAddPatternEnabled(boolean value) { + btaddpattern.setEnabled(value); + } + + /** + * Returns the status of the expand pattern button. + * + * @return if the expand pattern button is enabled + */ + public boolean isAddPatternEnabled() { + return btaddpattern.isEnabled(); + } + + /** + * Returns the content of the expand pattern textfield. + * + * @return the text + */ + public String getTfAddPatternText() { + return tfaddpattern.getText(); + } + + /** + * Sets the content of the expand pattern textfield. + * + * @param s the text + */ + public void setTfAddPatternText(String s) { + tfaddpattern.setText(s); + } + + /** + * Returns the length of the content in the expand pattern textfield. + * + * @return the length + */ + public int getTfAddPatternLength() { + return tfaddpattern.getText().length(); + } + + /** + * Returns the status of the cycle checkbox. + * + * @return if cycles is selected + */ + public boolean isCycleSelected() { + return jbcycle.isSelected(); + } + + /** + * Sets the visibility of the go on button. + * + * @param value the value + */ + public void setBtGoOnVisible(boolean value) { + btgoon.setVisible(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseOneScreen.java b/src/org/jalgo/module/kmp/gui/component/PhaseOneScreen.java new file mode 100644 index 0000000..6ac8785 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseOneScreen.java @@ -0,0 +1,107 @@ +package org.jalgo.module.kmp.gui.component; + +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JSplitPane; +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.event.PhaseOneScreenListener; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; + +/** + * This is the main screen of the phase one. + * + * @author Danilo Lisske + */ +public class PhaseOneScreen extends JPanel implements GUIConstants { + private static final long serialVersionUID = -902635070485942488L; + + private PhaseOneScreenListener listener; + /** the input panel of phase one */ + public PhaseOneInputPanel phaseoneinputPane; + /** the show panel of phase one */ + public PhaseOneShowPanel phaseoneshowPane; + /** the info panel of phase one */ + public InfoTabbedPanel infotabbedPane; + private JSplitPane phaseonesplitPane; + private JSlider sizeslider; + + /** + * The constructor of the phase one screen. + * + * @param gc the GUIController + */ + public PhaseOneScreen(GUIController gc) { + listener = new PhaseOneScreenListener(gc, this); + phaseoneinputPane = new PhaseOneInputPanel(listener); + phaseoneshowPane = new PhaseOneShowPanel(listener); + infotabbedPane = new InfoTabbedPanel(listener,null); + + setFont(new Font("SansSerif", Font.PLAIN, 14)); + setLayout(new BorderLayout()); + + JPanel showPane = new JPanel(new BorderLayout()); + + sizeslider = new JSlider(JSlider.VERTICAL,10,20,10); + sizeslider.setMinorTickSpacing(1); + sizeslider.setBackground(Color.WHITE); + sizeslider.setToolTipText(Messages.getString("kmp","Screen.Slider_ttt")); + sizeslider.addChangeListener(listener); + sizeslider.addMouseListener(listener); + sizeslider.setPaintTicks(true); + + showPane.add(phaseoneshowPane,BorderLayout.CENTER); + showPane.add(sizeslider,BorderLayout.EAST); + + phaseoneinputPane.setPreferredSize(new Dimension(phaseoneinputPane.getPreferredSize().width,40)); + infotabbedPane.setPreferredSize(new Dimension(infotabbedPane.getPreferredSize().width,211)); + + phaseonesplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + showPane, infotabbedPane); + phaseonesplitPane.setOneTouchExpandable(true); + phaseonesplitPane.setResizeWeight(1); + + add(phaseoneinputPane,BorderLayout.NORTH); + add(phaseonesplitPane,BorderLayout.CENTER); + } + + /** + * Returns the scalefactor of the size slider. + * + * @return the scalefactor + */ + public int getScaleFactor() { + return sizeslider.getValue(); + } + + /** + * Returns the divider location. + * + * @return the divider location + */ + public int getDividerLocation() { + return phaseonesplitPane.getDividerLocation(); + } + + /** + * Sets the divider location. + * + * @param size the position + */ + public void setDividerLocation(int size) { + phaseonesplitPane.setDividerLocation(size); + } + + /** + * Sets the slider position. + * + * @param value the value + */ + public void setSliderPosition(int value) { + sizeslider.setValue(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.java b/src/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.java new file mode 100644 index 0000000..7627e98 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseOneShowPanel.java @@ -0,0 +1,741 @@ +package org.jalgo.module.kmp.gui.component; + +import org.jalgo.main.util.Messages; + +import org.jalgo.module.kmp.algorithm.*; +import org.jalgo.module.kmp.algorithm.phaseone.*; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.event.PhaseOneScreenListener; + +import java.awt.*; +import java.awt.geom.*; + +import javax.swing.*; + + +/** + * This class paints the table for the generation of the pattern in phase 1. + * + * @author Sebastian Patschorke + */ +public class PhaseOneShowPanel extends JPanel { + private static final long serialVersionUID = 8296370714586057895L; + + /** just a listener */ + @SuppressWarnings("unused") + private PhaseOneScreenListener listener; + + /** holds the (importent) pattern */ + private Pattern pattern; + + /** holds the actual step of the history, which should be shown */ + private Step actStep; + + /** the basic font */ + private Font showPanelFont; + + /** letter arithmetics of the basic font (showPanelFont) */ + private int letterWidth; + + /** letter arithmetics of the basic font (showPanelFont) */ + private int letterHeight; + + /** how many letters is the pattern long */ + private int patternLength; + + /** how many pixel is the table head width */ + private int headLength; + + /** arithmetics of one cell */ + private int cellWidth; + + /** arithmetics of one cell */ + private int cellHeight; + + /** cellspacing in one cell, distance between left border and one Character in the cell */ + private int cellspacingHorizontal; + + /** cellspacing in one cell, distance between top border and the Character */ + private int cellspacingVertical; + + /** maximal letter length of all table headings */ + private int maxHeadLetterLength; + + /** what stands in the head of the pattern characters */ + private String headPattern; + + /** what stands in the head of the pattern tableentries */ + private String headTable; + + /** what stands in the head of the pattern indicies */ + private String headIndex; + + /** what stands in the head of the cycles */ + private String headCycles; + + /** should the cycles be shown */ + private boolean showCycles = true; + + /** this is (normally) GUIConstants.P1_Y_OFFSET, + * only for showCycles==true a bit more */ + private int yOffset; + + /** table arithmetics */ + private int tabWidth; + + /** table arithmetics */ + private int tabHeight; + + /** + * The constructor of the PhaseOneShowPanel. + * It initialises some variables. + * + * @param l PhaseOneScreenListener + */ + public PhaseOneShowPanel(PhaseOneScreenListener l) { + listener = l; + + /* initial setting of the constant font */ + showPanelFont = GUIConstants.SHOW_PANEL_FONT; + + /* get the table headings */ + headPattern = Messages.getString("kmp", "ShowPanel.Head_pattern"); + headTable = Messages.getString("kmp", "ShowPanel.Head_table"); + headIndex = Messages.getString("kmp", "ShowPanel.Head_index"); + headCycles = Messages.getString("kmp", "ShowPanel.Head_cycles"); + + /* finds the maximum length of the headings */ + maxHeadLetterLength = headPattern.length(); + + if (headTable.length() > maxHeadLetterLength) { + maxHeadLetterLength = headTable.length(); + } + + if (headIndex.length() > maxHeadLetterLength) { + maxHeadLetterLength = headIndex.length(); + } + + if (headCycles.length() > maxHeadLetterLength) { + maxHeadLetterLength = headCycles.length(); + } + } + + /** + * Sets the pattern for the showPanel. So all importent informations + * are available. + * + * @param p Pattern + */ + public void setPattern(Pattern p) { + this.pattern = p; + } + + /** + * Sets the actual step which should be visualated. + * + * @param step algorithm step + */ + public void update(Step step) { + this.actStep = step; + } + + /** + * Switch for Showing the cycles in the visualisation + * + * @param sc show cycles + */ + public void showCycles(boolean sc) { + this.showCycles = sc; + } + + /** + * increments the font size in comparison to the constans font.

          + * incFontSize(3); incFontSize(3);
          has the same result as
          incFontSize(3); + * + * @param s factor + */ + public void incFontSize(double s) { + showPanelFont = new Font(GUIConstants.SHOW_PANEL_FONT.getName(), + GUIConstants.SHOW_PANEL_FONT.getStyle(), + (int) (GUIConstants.SHOW_PANEL_FONT.getSize() * s)); + } + + /** + * This Method is called automaticly if the GUI was scaled. + * Or it's called after setting a new step + * + * @param g Graphics + */ + public void paintComponent(Graphics g) { + setBackground(Color.WHITE); + super.paintComponent(g); + + Graphics2D g2 = (Graphics2D) g; + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + initPainting(); + paintBasicTab(g2); + paintStep(g2); + } + + /** + * It is (only) called from this.paintComponent
          + * Some often used values and the basic layout will be calculated. + */ + private void initPainting() { + FontMetrics fm = getFontMetrics(showPanelFont); + letterHeight = fm.getAscent(); + letterWidth = fm.charWidth('A'); /* it's monospaced */ + + cellspacingVertical = letterHeight / 2; + + if (pattern != null) { + patternLength = pattern.getPattern().length(); + } else { + patternLength = 6; /* fictiv number to paint something */ + } + + headLength = (2 * cellspacingVertical) + + (maxHeadLetterLength * letterWidth); + + cellWidth = (getWidth() - headLength - (2 * GUIConstants.P1_X_OFFSET)) / (patternLength + + 1); + + int minCW = (int) (letterWidth * GUIConstants.P1_MIN_CELL_WIDTH); /* min cellWidth */ + int maxCW = (int) (letterWidth * GUIConstants.P1_MAX_CELL_WIDTH); /* max cellWidth */ + + if (cellWidth > maxCW) { + cellWidth = maxCW; + } else if (cellWidth < minCW) { + cellWidth = minCW; + } + + /* 'correction' that the patPos-pointer could be seen after the table (at the end) */ + int rest = getWidth() - headLength - (2 * GUIConstants.P1_X_OFFSET) - + ((patternLength + 1) * cellWidth); + + if ((rest >= 0) && (rest < (cellWidth / 2))) { + cellWidth -= (((cellWidth / 2) - rest) / (patternLength + 1)); + } + + if (cellWidth < minCW) { + cellWidth = minCW; + } + + cellspacingHorizontal = (cellWidth - letterWidth) / 2; + cellHeight = (2 * cellspacingVertical) + letterHeight; + yOffset = GUIConstants.P1_Y_OFFSET; + + if (showCycles) { + yOffset += cellHeight; + } + + tabWidth = ((patternLength + 1) * cellWidth) + headLength; + tabHeight = 3 * cellHeight; + } + + /** + * It is (only) called from this.paintComponent and + * paints the static table. + * + * @param g2 Graphics2D + */ + private void paintBasicTab(Graphics2D g2) { + /* (only) gives the head a color */ + g2.setColor(GUIConstants.HEAD_COLOR); + g2.fill(new Rectangle(GUIConstants.P1_X_OFFSET, yOffset, headLength, + tabHeight)); + + g2.setColor(Color.BLACK); + + /* left collumline */ + g2.draw(new Line2D.Double(GUIConstants.P1_X_OFFSET, yOffset, + GUIConstants.P1_X_OFFSET, yOffset + tabHeight)); + + /* all other collumlines */ + int x = GUIConstants.P1_X_OFFSET + headLength; + + for (int i = 0; i <= (patternLength + 1); i++) { + g2.draw(new Line2D.Double(x, yOffset, x, yOffset + tabHeight)); + x += cellWidth; + } + + /* row lines */ + int y = yOffset; + + for (int i = 0; i < 4; i++) { + g2.draw(new Line2D.Double(GUIConstants.P1_X_OFFSET, y, + GUIConstants.P1_X_OFFSET + tabWidth, y)); + y += cellHeight; + } + + /* fills the head with life + here: cellspacingHorizontal =^ cellspacingVertical */ + setFont(showPanelFont); + y = yOffset + letterHeight + cellspacingVertical; + g2.drawString(headPattern, + GUIConstants.P1_X_OFFSET + cellspacingVertical, y); + g2.drawString(headTable, + GUIConstants.P1_X_OFFSET + cellspacingVertical, y + cellHeight); + g2.drawString(headIndex, + GUIConstants.P1_X_OFFSET + cellspacingVertical, y + + (2 * cellHeight)); + + if (showCycles) { + g2.setColor(Color.YELLOW); + g2.fill(new Rectangle(GUIConstants.P1_X_OFFSET, + yOffset - cellHeight, headLength, cellHeight)); + g2.setColor(Color.BLACK); + g2.draw(new Rectangle(GUIConstants.P1_X_OFFSET, + yOffset - cellHeight, headLength, cellHeight)); + g2.draw(new Line2D.Double(GUIConstants.P1_X_OFFSET, + yOffset - cellHeight, GUIConstants.P1_X_OFFSET + tabWidth, + yOffset - cellHeight)); + g2.draw(new Line2D.Double(GUIConstants.P1_X_OFFSET + tabWidth, + yOffset, GUIConstants.P1_X_OFFSET + tabWidth, + yOffset - cellHeight)); + g2.drawString(headCycles, + GUIConstants.P1_X_OFFSET + cellspacingVertical, y - cellHeight); + } + } + + /** + * It is (only) called from this.paintComponent. + * paints the part of the visualisation which is specific for each step + * + * @param g2 Graphics2D + */ + private void paintStep(Graphics2D g2) { + if (actStep != null) { + int vglInd = ((P1Step) actStep).getVglInd(); + int patPos = actStep.getPatPos(); + + paintPointers(g2, patPos, vglInd); + + if (showCycles && (patPos < patternLength)) { + paintCycles(g2, patPos, patPos); + } + + if (actStep instanceof P1InitStep) { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + printTableEntrys(g2, 0, 0, GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + } else if (actStep instanceof P1BeginForStep) { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + printTableEntrys(g2, 0, patPos - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + } else if (actStep instanceof P1IfTrueStep) { + printPatternChars(g2, 0, vglInd - 1, Color.BLACK); + printPatternChars(g2, vglInd, vglInd, GUIConstants.TRUE_COLOR); + printPatternChars(g2, vglInd + 1, patPos - 1, Color.BLACK); + printPatternChars(g2, patPos, patPos, GUIConstants.TRUE_COLOR); + printPatternChars(g2, patPos + 1, patternLength - 1, Color.BLACK); + printTableEntrys(g2, 0, patPos - 1, Color.BLACK); + printTableEntrys(g2, patPos, patPos, + GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + paintBox(g2, vglInd, 1, 1, 1, GUIConstants.BOX_COLOR); + paintArrow(g2, vglInd, patPos, GUIConstants.ARROW_COLOR); + } else if (actStep instanceof P1IfFalseStep) { + printPatternChars(g2, 0, vglInd - 1, Color.BLACK); + printPatternChars(g2, vglInd, vglInd, GUIConstants.FALSE_COLOR); + printPatternChars(g2, vglInd + 1, patPos - 1, Color.BLACK); + printPatternChars(g2, patPos, patPos, GUIConstants.FALSE_COLOR); + printPatternChars(g2, patPos + 1, patternLength - 1, Color.BLACK); + printTableEntrys(g2, 0, patPos - 1, Color.BLACK); + printTableEntrys(g2, patPos, patPos, + GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + paintBox(g2, vglInd, 2, 1, 1, GUIConstants.BOX_COLOR); + paintArrow(g2, vglInd, patPos, GUIConstants.ARROW_COLOR); + } else if (actStep instanceof P1WhileStep) { + if (((P1WhileStep) actStep).isLastWhileStep()) { + if (vglInd == -1) { + paintBox(g2, -1, 0, 1, 3, GUIConstants.FALSE_COLOR); + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + } else { + printPatternChars(g2, 0, vglInd - 1, Color.BLACK); + printPatternChars(g2, vglInd, vglInd, + GUIConstants.TRUE_COLOR); + printPatternChars(g2, vglInd + 1, patPos - 1, + Color.BLACK); + printPatternChars(g2, patPos, patPos, + GUIConstants.TRUE_COLOR); + printPatternChars(g2, patPos + 1, patternLength - 1, + Color.BLACK); + } + + printTableEntrys(g2, 0, patPos, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + } else { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + + int oldVgl = ((P1WhileStep) actStep).getOldVglind(); + printTableEntrys(g2, 0, oldVgl - 1, Color.BLACK); + printTableEntrys(g2, oldVgl, oldVgl, + GUIConstants.HIGHLIGHT_COLOR); + printTableEntrys(g2, oldVgl + 1, patPos, Color.BLACK); + printPatternIndicies(g2, -1, vglInd - 1, Color.BLACK); + printPatternIndicies(g2, vglInd, vglInd, + GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2, vglInd + 1, patternLength - 1, + Color.BLACK); + } + } else if (actStep instanceof P1EndForStep) { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + printTableEntrys(g2, 0, patPos, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + } + } else { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.BLACK); + } + } + + /** + * paints the pattern characters + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printPatternChars(Graphics2D g2, int start, int end, Color col) { + if (pattern != null) { + if (start < -1) { + start = -1; + } + + if (end >= patternLength) { + end = patternLength - 1; + } + + Color oldcolor = g2.getColor(); + g2.setColor(col); + + int x = GUIConstants.P1_X_OFFSET + headLength + + cellspacingHorizontal + ((start + 1) * cellWidth); + int y = yOffset + cellspacingVertical + letterHeight; + + String pat = new String(pattern.getPattern()); + + for (int i = start; i <= end; i++) { + g2.drawString(pat.substring(i, i + 1), x, y); + x += cellWidth; + } + + g2.setColor(oldcolor); + } + } + + /** + * paints the table entries + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printTableEntrys(Graphics2D g2, int start, int end, Color col) { + if (pattern != null) { + Color oldcolor = g2.getColor(); + g2.setColor(col); + + if (start < 0) { + start = 0; + } + + if (end >= patternLength) { + end = patternLength - 1; + } + + int x = GUIConstants.P1_X_OFFSET + headLength + + cellspacingHorizontal + ((start + 1) * cellWidth); + int y = yOffset + cellspacingVertical + letterHeight + cellHeight; + int nr; + + for (int i = start; i <= end; i++) { + nr = pattern.getTblEntryAt(i); + + if ((nr >= 0) && (nr < 10)) { /* have it to print 1 or 2 chars (f.e. "-1") */ + g2.drawString(new Integer(nr).toString(), x, y); + } else { + g2.drawString(new Integer(nr).toString(), + x - (letterWidth / 2), y); + } + + x += cellWidth; + } + + g2.setColor(oldcolor); + } + } + + /** + * paints the table indicies + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printPatternIndicies(Graphics2D g2, int start, int end, + Color col) { + if (start < -1) { + start = -1; + } + + if (end >= patternLength) { + end = patternLength - 1; + } + + Color oldcolor = g2.getColor(); + g2.setColor(col); + + int x = GUIConstants.P1_X_OFFSET + headLength + cellspacingHorizontal + + ((start + 1) * cellWidth); + int y = yOffset + cellspacingVertical + letterHeight + + (2 * cellHeight); + + if (start == -1) { /* paints the -1 separatly, because it is 2 Characters long*/ + g2.drawString(new Integer(-1).toString(), + (x - cellspacingHorizontal + (cellWidth / 2)) - letterWidth, y); + x += cellWidth; + start = 0; + } + + for (int i = start; i <= end; i++) { + g2.drawString(new Integer(i).toString(), x, y); + x += cellWidth; + } + + g2.setColor(oldcolor); + } + + /** + * paints the cycles + * + * @param g2 Graphics2D + * @param pos actual position + * @param patPos actual pattern position + */ + private void paintCycles(Graphics2D g2, int pos, int patPos) { + if (pattern != null) { + int[] cyc = pattern.getCycleDataAt(patPos); + Color oldColor = g2.getColor(); + g2.setColor(Color.MAGENTA); + + Stroke oldStroke = g2.getStroke(); + int dist = cellHeight / (GUIConstants.MAX_SHOW_CYCLES + 1); + int thickness = dist / 2; + thickness = (95 * thickness) / 100; + g2.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND, + BasicStroke.JOIN_MITER)); + + for (int i = 0; i < cyc.length; i++) { + if (cyc[i] <= pos) { + if (i < GUIConstants.MAX_SHOW_CYCLES) { + int level; + + if (GUIConstants.MAX_SHOW_CYCLES > cyc.length) { + level = cyc.length - i; + } else { + level = GUIConstants.MAX_SHOW_CYCLES - i; + } + + g2.draw(new Line2D.Double(GUIConstants.P1_X_OFFSET + + headLength + ((cyc[i] + 1) * cellWidth), + yOffset - (level * dist), + (GUIConstants.P1_X_OFFSET + headLength + + ((pos + 2) * cellWidth)) - 5, /* the 5 is only for correction, that a cycle is not over any table line */ + yOffset - (level * dist))); + } else { + int x = GUIConstants.P1_X_OFFSET + headLength + + ((cyc[i] + 1) * cellWidth); + g2.draw(new Line2D.Double(x, yOffset - (dist / 2), x, + yOffset - dist - (dist / 2))); + } + } + } + + g2.setStroke(oldStroke); + g2.setColor(oldColor); + } + } + + /** + * paints the two pointers (patpos & vglind) below the table + * + * @param g2 Graphics2D + * @param patPos pattern position + * @param vglInd actual index to compare (german: Vergleichsindex) + */ + private void paintPointers(Graphics2D g2, int patPos, int vglInd) { + /* xPos, yPos are the top coords of the arrow */ + Font pointerFont = new Font(showPanelFont.getName(), + showPanelFont.getStyle(), (int) (showPanelFont.getSize() * 0.68)); + FontMetrics fm = getFontMetrics(pointerFont); + int lh = fm.getAscent(); + int lw = fm.charWidth('A'); /* monospaced! */ + + int pH = (int) (lh * 2); /* pointer height */ + int pHH = (int) (lh * 1); /* 'half' pointer height */ + int pHW = (int) (lw * 1.6); /* half pointer width */ + int pQW = (int) (lw * 0.8); /* 'quarter' pointer width */ + + int sP = (int) (pHW * 0.5); /* space between 'overlapping' pointers */ + int yO = 5; /* y Offset below table */ + + if (g2 != null) { + Color oldcolor = g2.getColor(); + Font oldfont = g2.getFont(); + g2.setFont(pointerFont); + + /* vglInd */ + int xPos = GUIConstants.P1_X_OFFSET + headLength + (cellWidth / 2) + + ((vglInd + 1) * cellWidth); + int yPos = yOffset + tabHeight + yO; + + if ((vglInd == patPos) && (patPos > 0)) { + xPos -= sP; + } + + int[] xpointsV = { + xPos, xPos + pHW, xPos + pQW, xPos + pQW, xPos - pQW, + xPos - pQW, xPos - pHW + }; + int[] ypointsV = { + yPos, yPos + pHH, yPos + pHH, yPos + pH, yPos + pH, + yPos + pHH, yPos + pHH + }; + Polygon arrowVgl = new Polygon(xpointsV, ypointsV, 7); + g2.setColor(GUIConstants.VGLIND_POINTER_COLOR); + g2.fill(arrowVgl); + g2.setColor(Color.BLACK); + g2.draw(arrowVgl); + + Color c = GUIConstants.VGLIND_POINTER_COLOR; + Color charColor = new Color(255 - c.getRed(), 255 - c.getGreen(), + 255 - c.getBlue()); + g2.setColor(charColor); + g2.drawString("V", xPos - (lw / 2), (yPos + pH) - (int) (lh * 0.3)); + + /* patPos */ + if (patPos > 0) { + if (vglInd == patPos) { + xPos += sP; + } + + xPos += ((-vglInd + patPos) * cellWidth); + + int[] xpointsP = { + xPos, xPos + pHW, xPos + pQW, xPos + pQW, xPos - pQW, + xPos - pQW, xPos - pHW + }; + int[] ypointsP = { + yPos, yPos + pHH, yPos + pHH, yPos + pH, yPos + pH, + yPos + pHH, yPos + pHH + }; + Polygon arrowPat = new Polygon(xpointsP, ypointsP, 7); + + if (patPos < patternLength) { + g2.setColor(GUIConstants.PATPOS_POINTER_COLOR); + } else { + g2.setColor(GUIConstants.FALSE_COLOR); + } + + c = g2.getColor(); + charColor = new Color(255 - c.getRed(), 255 - c.getGreen(), + 255 - c.getBlue()); + g2.fill(arrowPat); + g2.setColor(Color.BLACK); + g2.draw(arrowPat); + g2.setColor(charColor); + g2.drawString("P", xPos - (lw / 2), + (yPos + pH) - (int) (lh * 0.3)); + } + + g2.setFont(oldfont); + g2.setColor(oldcolor); + } + } + + /** + * paints an arrow over the table to show what value is copied to which 'cell' + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param color Color + */ + private void paintArrow(Graphics2D g2, int start, int end, Color color) { + Color oldColor = g2.getColor(); + Stroke oldStroke = g2.getStroke(); + g2.setColor(color); + g2.setStroke(new BasicStroke((int) (letterHeight * 0.18), + BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); + + int xStart = GUIConstants.P1_X_OFFSET + headLength + + ((start + 1) * cellWidth) + (cellWidth / 2); + int xEnd = GUIConstants.P1_X_OFFSET + headLength + + ((end + 1) * cellWidth) + (cellWidth / 2); + int y = yOffset; + + if (showCycles) { + y -= cellHeight; + } + + int plusminus = 0; /* needed if start==end, that there can be seen an arrow */ + + if (start == end) { + plusminus = cellWidth / 4; + } + + /* start */ + g2.draw(new Line2D.Double(xStart - plusminus, y - 5, + xStart - plusminus, y - 20)); + /* end */ + g2.draw(new Line2D.Double(xEnd + plusminus, y - 5, xEnd + plusminus, + y - 20)); + /* line */ + g2.draw(new Line2D.Double(xStart - plusminus, y - 20, xEnd + plusminus, + y - 20)); + /* left top */ + g2.draw(new Line2D.Double(xEnd - 5 + plusminus, y - 8, + xEnd + plusminus, y - 5)); + /* right top */ + g2.draw(new Line2D.Double(xEnd + plusminus, y - 5, + xEnd + 5 + plusminus, y - 8)); + + g2.setStroke(oldStroke); + g2.setColor(oldColor); + } + + /** + * paints a rectangle, a box, arround cells + * + * @param g2 Graphics2D + * @param startCol start collum + * @param startRow start row + * @param cols #collums + * @param rows #rows + * @param col Color + */ + private void paintBox(Graphics2D g2, int startCol, int startRow, int cols, + int rows, Color col) { + Color oldColor = g2.getColor(); + g2.setColor(col); + + Stroke oldStroke = g2.getStroke(); + g2.setStroke(new BasicStroke((int) (letterHeight * 0.24), + BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); + g2.draw(new Rectangle(GUIConstants.P1_X_OFFSET + headLength + + ((startCol + 1) * cellWidth), + yOffset + (startRow * cellHeight), cols * cellWidth, + rows * cellHeight)); + g2.setStroke(oldStroke); + g2.setColor(oldColor); + } +} diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.java b/src/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.java new file mode 100644 index 0000000..93ade4c --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseTwoInputPanel.java @@ -0,0 +1,184 @@ +package org.jalgo.module.kmp.gui.component; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; + +/** + * This is the input panel of the phase two. + * + * @author Danilo Lisske + */ +public class PhaseTwoInputPanel extends JPanel { + private static final long serialVersionUID = -3852311834926117075L; + + private PhaseTwoScreenListener listener; + private JButton btset; + private JButton btgenerst; + private JTextField tfpattern; + private JLabel lbresult; + + /** + * The constructor of the PhaseTwoInputPanel. + * + * @param l2 the PhaseTwoScreenListener + */ + public PhaseTwoInputPanel(PhaseTwoScreenListener l2) { + listener = l2; + + setFont(GUIConstants.SCREEN_FONT); + setLayout(new BorderLayout()); + + JPanel patternPane = new JPanel(); + patternPane.setLayout(new FlowLayout(FlowLayout.LEFT)); + + JLabel lbpattern = new JLabel(Messages.getString("kmp","InputPanel.Label_pattern") + ":"); + lbpattern.setFont(getFont()); + patternPane.add(lbpattern); + + tfpattern = new JTextField(); + tfpattern.setName("tfpattern"); + tfpattern.setFont(getFont()); + tfpattern.setToolTipText(Messages.getString("kmp","InputPanel.TextField_pattern_ttt")); + tfpattern.setPreferredSize(new Dimension(120,tfpattern.getPreferredSize().height)); + tfpattern.addKeyListener(listener); + tfpattern.addMouseListener(listener); + patternPane.add(tfpattern); + + btset = new JButton(Messages.getString("kmp","InputPanel.Button_set")); + btset.setActionCommand("setpattern"); + btset.addActionListener(listener); + btset.addMouseListener(listener); + btset.setToolTipText(Messages.getString("kmp","InputPanel.Button_set_ttt")); + btset.setFont(getFont()); + patternPane.add(btset); + + JButton btrandom = new JButton(Messages.getString("kmp","InputPanel.Button_random")); + btrandom.setActionCommand("random"); + btrandom.addActionListener(listener); + btrandom.addMouseListener(listener); + btrandom.setToolTipText(Messages.getString("kmp","InputPanel.Button_random_ttt")); + btrandom.setFont(getFont()); + patternPane.add(btrandom); + + JPanel resultPane = new JPanel(new FlowLayout(FlowLayout.CENTER)); + + lbresult = new JLabel(); + lbresult.addMouseListener(listener); + lbresult.setToolTipText(Messages.getString("kmp","InputPanel.Label_result_ttt")); + lbresult.setFont(GUIConstants.RESULT_FONT); + lbresult.setVisible(false); + resultPane.add(lbresult); + + JPanel searchtextPane = new JPanel(); + searchtextPane.setLayout(new FlowLayout(FlowLayout.CENTER)); + + JLabel lbsearchtext = new JLabel(Messages.getString("kmp","InputPanel.Label_searchtext") + ":"); + lbsearchtext.setFont(getFont()); + searchtextPane.add(lbsearchtext); + + JButton btloadst = new JButton(Messages.getString("kmp","InputPanel.Button_loadst")); + btloadst.setActionCommand("loadst"); + btloadst.addActionListener(listener); + btloadst.addMouseListener(listener); + btloadst.setToolTipText(Messages.getString("kmp","InputPanel.Button_loadst_ttt")); + btloadst.setFont(getFont()); + searchtextPane.add(btloadst); + + btgenerst = new JButton(Messages.getString("kmp","InputPanel.Button_generst")); + btgenerst.setActionCommand("generst"); + btgenerst.addActionListener(listener); + btgenerst.addMouseListener(listener); + btgenerst.setToolTipText(Messages.getString("kmp","InputPanel.Button_generst_ttt")); + btgenerst.setFont(getFont()); + searchtextPane.add(btgenerst); + + add(patternPane,BorderLayout.WEST); + add(resultPane,BorderLayout.CENTER); + add(searchtextPane,BorderLayout.EAST); + } + + /** + * Enables or disables the button to set the pattern. + * + * @param value the value + */ + public void setPatternEnabled(boolean value) { + btset.setEnabled(value); + } + + /** + * Returns the status of the button to set the pattern. + * + * @return if the button is enabled + */ + public boolean isPatternEnabled() { + return btset.isEnabled(); + } + + /** + * Returns the text in the pattern textfield. + * + * @return the text in the pattern textfield + */ + public String getTfPatternText() { + return tfpattern.getText(); + } + + /** + * Sets the content of the pattern textfield. + * + * @param p the content + */ + public void setTfPatternText(String p) { + tfpattern.setText(p); + } + + /** + * Returns the length of the content in the pattern textfield. + * + * @return the length + */ + public int getTfPatternLength() { + return tfpattern.getText().length(); + } + + /** + * Enables or disables the button to generate a random searchtext. + * + * @param value the value + */ + public void setGenerateSearchTextEnabled(boolean value) { + btgenerst.setEnabled(value); + } + + /** + * Sets the visibility of the label which displays the result of the search. + * + * @param value the value + * @param isfound is the end reached + */ + public void setLabelResultVisible(boolean value, boolean isfound) { + if(value) { + if(isfound) { + lbresult.setForeground(Color.GREEN.darker()); + lbresult.setText(Messages.getString("kmp","InputPanel.Label_result_true")); + } + else { + lbresult.setForeground(Color.RED); + lbresult.setText(Messages.getString("kmp","InputPanel.Label_result_false")); + } + } + lbresult.setVisible(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.java b/src/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.java new file mode 100644 index 0000000..2d5307a --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseTwoScreen.java @@ -0,0 +1,99 @@ +package org.jalgo.module.kmp.gui.component; + +import javax.swing.JPanel; +import javax.swing.JSlider; +import javax.swing.JSplitPane; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; + +/** + * This is the main screen of the phase two. + * + * @author Danilo Lisske + */ +public class PhaseTwoScreen extends JPanel implements GUIConstants { + private static final long serialVersionUID = -24048124349086693L; + + private PhaseTwoScreenListener listener; + /** the input panel of phase two */ + public PhaseTwoInputPanel phasetwoinputPane; + /** the show panel of phase two */ + public PhaseTwoShowPanel phasetwoshowPane; + /** the info panel of phase two */ + public InfoTabbedPanel infotabbedPane; + private JSplitPane phasetwosplitPane; + private JSlider sizeslider; + + /** + * The constructor of the phase two screen. + * + * @param gc the GUIController + */ + public PhaseTwoScreen(GUIController gc) { + listener = new PhaseTwoScreenListener(gc,this); + phasetwoinputPane = new PhaseTwoInputPanel(listener); + phasetwoshowPane = new PhaseTwoShowPanel(listener); + infotabbedPane = new InfoTabbedPanel(null,listener); + + setFont(new Font("SansSerif", Font.PLAIN, 14)); + setLayout(new BorderLayout()); + + JPanel showPane = new JPanel(new BorderLayout()); + + sizeslider = new JSlider(JSlider.VERTICAL,10,20,10); + sizeslider.setMinorTickSpacing(1); + sizeslider.setBackground(Color.WHITE); + sizeslider.setToolTipText(Messages.getString("kmp","Screen.Slider_ttt")); + sizeslider.addChangeListener(listener); + sizeslider.addMouseListener(listener); + sizeslider.setPaintTicks(true); + + showPane.add(phasetwoshowPane,BorderLayout.CENTER); + showPane.add(sizeslider,BorderLayout.EAST); + + infotabbedPane.setPreferredSize(new Dimension(infotabbedPane.getPreferredSize().width,211)); + phasetwoinputPane.setPreferredSize(new Dimension(phasetwoinputPane.getPreferredSize().width,40)); + + phasetwosplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + showPane, infotabbedPane); + phasetwosplitPane.setOneTouchExpandable(true); + phasetwosplitPane.setResizeWeight(1); + + add(phasetwoinputPane,BorderLayout.NORTH); + add(phasetwosplitPane,BorderLayout.CENTER); + } + + /** + * Sets the scalefactor of the size slider. + * + * @param value the scalefactor + */ + public void setScaleFactor(int value) { + sizeslider.setValue(value); + } + + /** + * Sets the divider location. + * + * @param size the position + */ + public void setDividerLocation(int size) { + phasetwosplitPane.setDividerLocation(size); + } + + /** + * Sets the slider position. + * + * @param value the value + */ + public void setSliderPosition(int value) { + sizeslider.setValue(value); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.java b/src/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.java new file mode 100644 index 0000000..bcc4672 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/PhaseTwoShowPanel.java @@ -0,0 +1,914 @@ +package org.jalgo.module.kmp.gui.component; + +import org.jalgo.main.util.Messages; + +import org.jalgo.module.kmp.algorithm.*; +import org.jalgo.module.kmp.algorithm.phasetwo.*; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; + +import java.awt.*; +import java.awt.geom.*; + +import javax.swing.*; + + +/** + * This class paints the text & the pattern table for the visualisation + * of the kmp algorithmin in action. + * + * @author Sebastian Patschorke + * + */ +public class PhaseTwoShowPanel extends JPanel { + private static final long serialVersionUID = 888797759979595933L; + + /** Searchtext-Arithmetics */ + private Rectangle searchTextBounds; + + /** GraphicObject for the Searchtext(animation) */ + private Graphics2D g2SearchT; + + /** buffers the searchtext for animation */ + private Image searchTImage; + + /** buffers the whole panel without searchtext and + * viewwindow for animation */ + private Image panelImage; + + /** was the animation shown */ + private boolean animated = false; + + /** is the animation in process */ + private boolean animationStarted = false; + + /** The Thread for the animation */ + private Thread aniThread; + + /** just a listener */ + @SuppressWarnings("unused") + private PhaseTwoScreenListener listener; + + /** holds the (importent) pattern */ + private Pattern pattern; + + /** holds the Text in which the pattern is searched */ + private String searchText; + + /** holds the actual step of the history, which should be shown */ + private Step actStep; + + /** the basic font */ + private Font showPanelFont; + + /** distance between each table and heading. */ + private int distance; + + /** letter arithmetics of the basic font (showPanelFont) */ + private int letterWidth; + + /** letter arithmetics of the basic font (showPanelFont) */ + private int letterHeight; + + /** how many letters is the pattern long */ + private int patternLength; + + /** how many pixel is the table head width */ + private int headLength; + + /** how many cells are there in the searchtext row */ + private int cellNr; + + /** after how many searchtext cells starts the pattern */ + private int patternOffset; + + /** arithmetics of one cell */ + private int cellWidth; + + /** arithmetics of one cell */ + private int cellHeight; + + /** cellspacing in one cell, distance between left border + * and one Character in the cell */ + private int cellspacingHorizontal; + + /** cellspacing in one cell, distance between top border + * and the Character */ + private int cellspacingVertical; + + /** maximal letter length of all table headings */ + private int maxHeadLetterLength; + + /** what stands in the head of the text indicies */ + private String headTextPos; + + /** what stands in the head of the text */ + private String headText; + + /** what stands in the head of the pattern characters */ + private String headPattern; + + /** what stands in the head of the pattern tableentries */ + private String headTable; + + /** what stands in the head of the pattern indicies */ + private String headIndex; + + /** + * The constructor of the PhaseTwoShowPanel. + * It initialises some variables. + * + * @param l PhaseTwoScreenListener + */ + public PhaseTwoShowPanel(PhaseTwoScreenListener l) { + listener = l; + + this.setDoubleBuffered(true); + + /* initial setting of the constant font */ + showPanelFont = GUIConstants.SHOW_PANEL_FONT; + + /* get the table headings */ + headTextPos = Messages.getString("kmp", "ShowPanel.Head_textposition"); + headText = Messages.getString("kmp", "ShowPanel.Head_text"); + headPattern = Messages.getString("kmp", "ShowPanel.Head_pattern"); + headTable = Messages.getString("kmp", "ShowPanel.Head_table"); + headIndex = Messages.getString("kmp", "ShowPanel.Head_index"); + + /* finds the maximum length of the headings */ + maxHeadLetterLength = headTextPos.length(); + + if (headText.length() > maxHeadLetterLength) { + maxHeadLetterLength = headText.length(); + } + + if (headPattern.length() > maxHeadLetterLength) { + maxHeadLetterLength = headPattern.length(); + } + + if (headTable.length() > maxHeadLetterLength) { + maxHeadLetterLength = headTable.length(); + } + + if (headIndex.length() > maxHeadLetterLength) { + maxHeadLetterLength = headIndex.length(); + } + } + + /** + * Sets the pattern for the showPanel. So all importent informations are available. + * + * @param pattern Pattern + */ + public void setPattern(Pattern pattern) { + this.pattern = pattern; + } + + /** + * Sets the text, in which the pattern will be found or not. + * + * @param searchText Text to search in + */ + public void setSearchText(String searchText) { + this.searchText = searchText; + } + + /** + * Sets the actual step which should be visualated. + * + * @param step algorithm step + * @param isforward update in forward direction + */ + public void update(Step step, boolean isforward) { + animated = false; + + if (!isforward) { + animated = true; + } + + this.actStep = step; + + if (aniThread != null) { + aniThread.interrupt(); + animationStarted = false; + paintComponent(this.getGraphics()); + } + } + + /** + * increments the font size in comparison to the constans font.

          + * incFontSize(3); incFontSize(3);
          has the same result as
          incFontSize(3); + * + * @param s factor + */ + public void incFontSize(double s) { + showPanelFont = new Font(GUIConstants.SHOW_PANEL_FONT.getName(), + GUIConstants.SHOW_PANEL_FONT.getStyle(), + (int) (GUIConstants.SHOW_PANEL_FONT.getSize() * s)); + } + + /** + * This Method is called automaticly if the GUI was scaled. + * Or it's called after setting a new step. + * + * @param g Graphics + */ + public void paintComponent(Graphics g) { + initPainting(); + + if (!animationStarted) { /* during animation the screen is buffered */ + setBackground(Color.WHITE); + super.paintComponent(g); + + Graphics2D g2 = (Graphics2D) g; + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_SPEED); + g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, + RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); + + paintBasicTabs(g2); + + boolean ani = animated; /* temporary for the viewwindow (paintstep() changes the value */ + paintStep(g2); + + if (searchTImage != null) { + int x = GUIConstants.P2_X_OFFSET + headLength + distance; + int y = GUIConstants.P2_Y_OFFSET; + int w = cellNr * cellWidth; + int h = 2 * cellHeight; + g.drawImage(searchTImage, x, y, x + w + 1, y + h + 1, 0, 0, + w + 1, h + 1, this); /* '+1' because technical reason */ + } + + if (actStep != null) { + int patPos = actStep.getPatPos(); + + if (!(actStep instanceof P2InnerWhileStep) || ani) { + paintViewWindow(g2, patPos, 0); + } + + if (actStep instanceof P2InnerWhileStep) { + if (((P2InnerWhileStep) actStep).getJumpDistance() == 0) { + paintViewWindow(g2, patPos, 0); + } + } + } + } + } + + /** + * It is (only) called from this.paintComponent
          + * Some often used values and the basic layout will be calculated. + */ + private void initPainting() { + FontMetrics fm = getFontMetrics(showPanelFont); + letterHeight = fm.getAscent(); + letterWidth = fm.charWidth('A'); /* it is monospaced */ + + distance = (int) (letterHeight * 0.6); + + cellspacingVertical = (int) (letterHeight * 0.4); + + if (pattern != null) { + patternLength = pattern.getPattern().length(); + } else { /* if there is still no pattern */ + patternLength = 5; /* fictiv number to paint something */ + } + + headLength = (2 * cellspacingVertical) + + (maxHeadLetterLength * letterWidth); + + /* prefered number of cells */ + cellNr = patternLength + (2 * GUIConstants.P2_PREFERED_CELL_OFFSET); + + /* how many pixel are there for the cells */ + int availableSpace = getWidth() - (2 * GUIConstants.P2_X_OFFSET) - + headLength - distance; + /* now all cells get their width */ + cellWidth = availableSpace / cellNr; + + if (cellWidth < GUIConstants.P2_MIN_CELL_WIDTH) { + cellWidth = GUIConstants.P2_MIN_CELL_WIDTH; + } else if (cellWidth > GUIConstants.P2_MAX_CELL_WIDTH) { + cellWidth = GUIConstants.P2_MAX_CELL_WIDTH; + } + + /* if there is not enough space for the prefered number of cells + reduces the number of cells, but there are at least 2 cells more + than the pattern has */ + while (((cellNr - 2) > patternLength) && + ((cellNr * cellWidth) > availableSpace)) { + cellNr--; + } + + /* if there is enough space increment the number of cells */ + int rest = availableSpace - (cellNr * cellWidth); + + while (rest > GUIConstants.P2_MAX_CELL_WIDTH) { + cellNr++; + rest -= GUIConstants.P2_MAX_CELL_WIDTH; + } + + /* after how many cells the pattern starts */ + patternOffset = ((cellNr - patternLength) / 2); + + cellspacingHorizontal = (cellWidth - letterWidth) / 2; + cellHeight = (2 * cellspacingVertical) + letterHeight; + searchTextBounds = new Rectangle(GUIConstants.P2_X_OFFSET + headLength + + distance, GUIConstants.P2_Y_OFFSET, (cellNr * cellWidth) + 1, + (2 * cellHeight) + 1); + } + + /** + * It is (only) called from this.paintComponent and + * paints the static table witout the searchtext body + * + * @param g2 Graphics2D + */ + private void paintBasicTabs(Graphics2D g2) { + /* (only) gives the head a color */ + g2.setColor(GUIConstants.HEAD_COLOR); + g2.fill(new Rectangle(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET, headLength, 2 * cellHeight)); + g2.fill(new Rectangle(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + distance + (2 * cellHeight), + headLength, 3 * cellHeight)); + + g2.setColor(Color.BLACK); + + /* paints the head of the text table */ + for (int i = 0; i < 3; i++) + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + (i * cellHeight), + GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET + (i * cellHeight))); + + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET, GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + (2 * cellHeight))); + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET, + GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET + (2 * cellHeight))); + + /* paints the head of the pattern table */ + for (int i = 0; i < 4; i++) { + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + distance + + ((i + 2) * cellHeight), + GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET + distance + + ((i + 2) * cellHeight))); + } + + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + (2 * cellHeight) + distance, + GUIConstants.P2_X_OFFSET, + GUIConstants.P2_Y_OFFSET + (5 * cellHeight) + distance)); + g2.draw(new Line2D.Double(GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET + (2 * cellHeight) + distance, + GUIConstants.P2_X_OFFSET + headLength, + GUIConstants.P2_Y_OFFSET + (5 * cellHeight) + distance)); + + /* fills the head with life */ + g2.setFont(showPanelFont); + + int y = GUIConstants.P2_Y_OFFSET + letterHeight + cellspacingVertical; + g2.drawString(headTextPos, + GUIConstants.P2_X_OFFSET + cellspacingVertical, y); + g2.drawString(headText, GUIConstants.P2_X_OFFSET + cellspacingVertical, + y += cellHeight); + g2.drawString(headPattern, + GUIConstants.P2_X_OFFSET + cellspacingVertical, + y += (cellHeight + distance)); + g2.drawString(headTable, + GUIConstants.P2_X_OFFSET + cellspacingVertical, y += cellHeight); + g2.drawString(headIndex, + GUIConstants.P2_X_OFFSET + cellspacingVertical, y += cellHeight); + + /* paints the body of the pattern table + startX for the pattern table body */ + int startX = GUIConstants.P2_X_OFFSET + headLength + distance + + (patternOffset * cellWidth); + + /* row lines */ + for (int i = 0; i < 4; i++) { + g2.draw(new Line2D.Double(startX - cellWidth, + GUIConstants.P2_Y_OFFSET + distance + + ((i + 2) * cellHeight), + startX + (patternLength * cellWidth), + GUIConstants.P2_Y_OFFSET + distance + + ((i + 2) * cellHeight))); + } + + /* collum lines */ + for (int i = -1; i <= patternLength; i++) { + g2.draw(new Line2D.Double(startX + (i * cellWidth), + GUIConstants.P2_Y_OFFSET + distance + (2 * cellHeight), + startX + (i * cellWidth), + GUIConstants.P2_Y_OFFSET + distance + (5 * cellHeight))); + } + + if (pattern != null) { + printPatternChars(g2, 0, patternLength - 1, Color.BLACK); + } + } + + /** + * It is (only) called from this.paintComponent and + * paints the part of the visualisation which is specific for each step. + * + * @param g2 Graphics2D + */ + private void paintStep(Graphics2D g2) { + if (actStep != null) { + int textPos = ((P2Step) actStep).getTextPos(); + int patPos = actStep.getPatPos(); + + if (actStep instanceof P2InitStep) { + printPatternEntries(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.GRAY); + printSearchtext(textPos - patPos, false); + paintSearchtextArrows(g2, textPos - patPos); + } else if (actStep instanceof P2OuterWhileStep) { + printPatternEntries(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.GRAY); + printSearchtext(textPos - patPos, false); + paintSearchtextArrows(g2, textPos - patPos); + } else if (actStep instanceof P2InnerWhileStep) { + int jD = ((P2InnerWhileStep) actStep).getJumpDistance(); + + if (!animated && (jD > 0)) { + animated = true; + + printSearchtext(textPos - patPos - jD, true); + paintSearchtextArrows(g2, textPos - patPos - jD); + + doAnimation(g2, patPos, jD); + } else { + if (jD > 0) { + printPatternEntries(g2, 0, (patPos + jD) - 1, + Color.BLACK); + printPatternEntries(g2, patPos + jD, patPos + jD, + GUIConstants.HIGHLIGHT_COLOR); + printPatternEntries(g2, patPos + jD + 1, + patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patPos - 1, Color.GRAY); + printPatternIndicies(g2, patPos, patPos, + GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2, patPos + 1, patternLength - 1, + Color.GRAY); + } else { + printPatternEntries(g2, 0, patternLength - 1, + Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, + Color.GRAY); + } + + printSearchtext(textPos - patPos, false); + paintSearchtextArrows(g2, textPos - patPos); + } + } else if (actStep instanceof P2InnerSetStep) { + printPatternEntries(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.GRAY); + printSearchtext(textPos - patPos, false); + paintSearchtextArrows(g2, textPos - patPos); + } else if (actStep instanceof P2EndStep) { + printPatternEntries(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.GRAY); + printSearchtext(textPos - patPos, false); + paintSearchtextArrows(g2, textPos - patPos); + } + } else { /* actStep is null */ + + if (pattern != null) { + printPatternEntries(g2, 0, patternLength - 1, Color.BLACK); + printPatternIndicies(g2, -1, patternLength - 1, Color.GRAY); + } + + printSearchtext(0, false); + paintSearchtextArrows(g2, 0); + } + } + + /** + * It is (only) called from paintStep, + * paints the basic and static searchtext body and + * prints the searchtext in the basic table at the position the step is. + * + * @param startTextPos is the index at the beginning of the pattern + * @param animation print it for an animation? + */ + private void printSearchtext(int startTextPos, boolean animation) { + if (!animationStarted) { + int jumpDistance = 0; + int offset = (cellNr - patternLength) / 2; + + if (!animation) { + searchTImage = createImage(searchTextBounds.width, + searchTextBounds.height); + } else { + jumpDistance = ((P2InnerWhileStep) actStep).getJumpDistance(); + searchTImage = createImage(searchTextBounds.width + + (jumpDistance * cellWidth), searchTextBounds.height); + } + + g2SearchT = (Graphics2D) searchTImage.getGraphics(); + g2SearchT.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2SearchT.setBackground(Color.WHITE); + g2SearchT.clearRect(0, 0, searchTImage.getWidth(this), + searchTImage.getHeight(this)); + + /* paints the body */ + for (int i = 0; i < 3; i++) { + g2SearchT.draw(new Line2D.Double(0, i * cellHeight, + (cellNr + jumpDistance) * cellWidth, i * cellHeight)); + } + + for (int i = 0; i <= (cellNr + jumpDistance); i++) { + g2SearchT.draw(new Line2D.Double(i * cellWidth, 0, + i * cellWidth, 2 * cellHeight)); + } + + /* paints the characters */ + if (searchText != null) { + if (startTextPos < 0) { + startTextPos = 0; + } + + int index; + + g2SearchT.setFont(showPanelFont); + + String tmpString; + + for (int i = 0; i < (cellNr + jumpDistance); i++) { + index = (startTextPos + i) - offset; + + if ((index >= 0) && (index < searchText.length())) { + tmpString = (new Integer(index)).toString(); + + /* if number is to long f.e.: 2543764 "become" ..3764 */ + if (tmpString.length() > (cellWidth / letterWidth)) { + tmpString = tmpString.substring(3); + + while ((tmpString.length() + 2) > (cellWidth / letterWidth)) { + tmpString = tmpString.substring(1); + } + + tmpString = ".." + tmpString; + } + + g2SearchT.setColor(Color.GRAY); + g2SearchT.drawString(tmpString, + ((i * cellWidth) + (cellWidth / 2)) - + ((tmpString.length() * letterWidth) / 2), + cellspacingVertical + letterHeight); + + g2SearchT.setColor(Color.BLACK); + g2SearchT.drawString(searchText.substring(index, + index + 1), + (i * cellWidth) + cellspacingHorizontal, + cellspacingVertical + letterHeight + cellHeight); + } + } + } + } + } + + /** + * It paints arrows, if the searchtext goes on the left + * or right side in the nirvana. + * + * @param g2 Graphics2D + * @param startTextPos start postition of the searchtext + */ + private void paintSearchtextArrows(Graphics2D g2, int startTextPos) { + int offset = (cellNr - patternLength) / 2; + + int hch = cellHeight / 2; /* half cellHeight */ + int hd = distance / 2; /* half distance */ + + if (searchText != null) { + int xPos; + int yPos; + + /* left side */ + if ((startTextPos - offset) > 0) { + xPos = (GUIConstants.P2_X_OFFSET + headLength + distance) - + (hd / 2); + yPos = GUIConstants.P2_Y_OFFSET + cellHeight; + + int[] xpoints = { xPos, xPos, xPos - hd }; + int[] ypoints = { yPos - hch, yPos + hch, yPos }; + Polygon arrow = new Polygon(xpoints, ypoints, 3); + g2.fill(arrow); + } + + /* right side */ + if (((startTextPos + cellNr) - offset) < searchText.length()) { + xPos = GUIConstants.P2_X_OFFSET + headLength + distance + + (cellNr * cellWidth) + (hd / 2); + yPos = GUIConstants.P2_Y_OFFSET + cellHeight; + + int[] xpoints = { xPos, xPos, xPos + hd }; + int[] ypoints = { yPos - hch, yPos + hch, yPos }; + Polygon arrow = new Polygon(xpoints, ypoints, 3); + g2.fill(arrow); + } + } + } + + /** + * It paints the pattern characters. + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printPatternChars(Graphics2D g2, int start, int end, Color col) { + if (pattern != null) { + Color oldcolor = g2.getColor(); + g2.setColor(col); + + int y = GUIConstants.P2_Y_OFFSET + (2 * cellHeight) + distance + + cellspacingVertical + letterHeight; + int startX = GUIConstants.P2_X_OFFSET + headLength + distance + + (patternOffset * cellWidth); + + for (int i = start; i <= end; i++) { + g2.drawString(pattern.getPattern().substring(i, i + 1), + startX + (i * cellWidth) + cellspacingHorizontal, y); + } + + g2.setColor(oldcolor); + } + } + + /** + * It paints the table entries. + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printPatternEntries(Graphics2D g2, int start, int end, + Color col) { + if (pattern != null) { + Color oldcolor = g2.getColor(); + g2.setColor(col); + + int y = GUIConstants.P2_Y_OFFSET + (2 * cellHeight) + distance + + cellspacingVertical + letterHeight; + int startX = GUIConstants.P2_X_OFFSET + headLength + distance + + (patternOffset * cellWidth); + + for (int i = start; i <= end; i++) { + int nr = pattern.getTblEntryAt(i); + + if ((nr >= 0) && (nr < 10)) { /* have it to print 1 or 2 chars (f.e. "-1") */ + g2.drawString(new Integer(nr).toString(), + startX + (i * cellWidth) + cellspacingHorizontal, + y + cellHeight); + } else { + g2.drawString(new Integer(nr).toString(), + (startX + (i * cellWidth) + cellspacingHorizontal) - + (letterWidth / 2), y + cellHeight); + } + } + + g2.setColor(oldcolor); + } + } + + /** + * It paints the table indicies. + * + * @param g2 Graphics2D + * @param start start position + * @param end end position + * @param col Color + */ + private void printPatternIndicies(Graphics2D g2, int start, int end, + Color col) { + Color oldcolor = g2.getColor(); + g2.setColor(col); + + int y = GUIConstants.P2_Y_OFFSET + (2 * cellHeight) + distance + + cellspacingVertical + letterHeight; + int startX = GUIConstants.P2_X_OFFSET + headLength + distance + + (patternOffset * cellWidth); + + for (int i = start; i <= end; i++) { + if ((i >= 0) && (i < 10)) { /* have it to print 1 or 2 chars (f.e. "-1") */ + g2.drawString(new Integer(i).toString(), + startX + (i * cellWidth) + cellspacingHorizontal, + y + (2 * cellHeight)); + } else { + g2.drawString(new Integer(i).toString(), + (startX + (i * cellWidth) + cellspacingHorizontal) - + (letterWidth / 2), y + (2 * cellHeight)); + } + } + + g2.setColor(oldcolor); + } + + /** + * It is (only) called from paintStep and + * paints a view window around the actual compared characters. + * + * @param g2 Graphics2D + * @param pos pattern position + * @param animationOffset Offset (in px) for the animation + */ + private void paintViewWindow(Graphics2D g2, int pos, int animationOffset) { + if (actStep != null) { + Stroke oldStroke = g2.getStroke(); + g2.setStroke(new BasicStroke((int) (letterHeight * 0.26), + BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); + + Color oldColor = g2.getColor(); + g2.setColor(GUIConstants.VIEW_WINDOW_COLOR); + g2.draw(new Rectangle((GUIConstants.P2_X_OFFSET + headLength + + distance + ((pos + patternOffset) * cellWidth)) - + animationOffset, GUIConstants.P2_Y_OFFSET, cellWidth, + (5 * cellHeight) + distance)); + g2.setColor(oldColor); + g2.setStroke(oldStroke); + } + } + + /** + * As the name it says.
          + * It paints the whole showpanel and the searchtext + * and makes two static images of it. After that the animation + * thread will be started. + * + * @param g2 Graphics2D + * @param patPos actual pattern position + * @param jD #cells pattern jumped + */ + private void doAnimation(Graphics2D g2, int patPos, int jD) { + if (searchTImage != null) { + animationStarted = true; + + /* buffers the panelgraphics */ + Graphics g = this.getGraphics(); + panelImage = createImage(getWidth(), getHeight()); + + Graphics2D g2Panel = (Graphics2D) panelImage.getGraphics(); + g2Panel.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2Panel.setBackground(Color.WHITE); + g2Panel.clearRect(0, 0, getWidth(), getHeight()); + this.paintComponent(g); + setBackground(Color.WHITE); + super.paintComponent(g); + initPainting(); + + int pixel = jD * cellWidth; + + paintBasicTabs(g2Panel); + printPatternEntries(g2Panel, 0, (patPos + jD) - 1, Color.BLACK); + printPatternEntries(g2Panel, patPos + jD, patPos + jD, + GUIConstants.HIGHLIGHT_COLOR); + printPatternEntries(g2Panel, patPos + jD + 1, patternLength - 1, + Color.BLACK); + printPatternIndicies(g2Panel, -1, patPos - 1, Color.GRAY); + printPatternIndicies(g2Panel, patPos, patPos, + GUIConstants.HIGHLIGHT_COLOR); + printPatternIndicies(g2Panel, patPos + 1, patternLength - 1, + Color.GRAY); + + g.drawImage(panelImage, 0, 0, this); + + aniThread = new Thread(new AniThread(g, g2, pixel, patPos, jD, this)); + aniThread.start(); /* The animation is started */ + } + } + + /** + * Thread for the animation in phase 2. + * + * @author Sebastian Patschorke + */ + private class AniThread implements Runnable { + private Graphics g; + private Graphics2D g2; + private int pixel; + private int patPos; + private int JumpDis; + private java.awt.image.ImageObserver io; + + /** + * The constructor of AniThread with some essential values. + * + * @param g Graphics + * @param g2 Graphics2D + * @param pixel Animation length in px + * @param patPos pattern position + * @param JumpDis distance to animate in 'cells' or better pattern positions + * @param io ImageObserver + */ + public AniThread(Graphics g, Graphics2D g2, int pixel, int patPos, + int JumpDis, java.awt.image.ImageObserver io) { + this.g = g; + this.g2 = g2; + this.pixel = pixel; + this.patPos = patPos; + this.JumpDis = JumpDis; + this.io = io; + } + + /** + * what should the thread do
          + * it's started (indirectly) from super.start() + */ + public void run() { + int imageOffset = 0; + int x = GUIConstants.P2_X_OFFSET + headLength + distance; + int y = GUIConstants.P2_Y_OFFSET; + int w = cellNr * cellWidth; + int h = 2 * cellHeight; + + try { + while (pixel >= imageOffset) { + g.drawImage(panelImage, 0, 0, io); + + g.drawImage(searchTImage, x, y, x + w + 1, y + h + 1, + 0 + imageOffset, 0, w + imageOffset + 1, h + 1, io); + paintViewWindow((Graphics2D) g, patPos + JumpDis, + imageOffset); + Thread.sleep(getTimeToSleep(imageOffset, pixel, 0.3)); + imageOffset++; + } + + animationStarted = false; + paintStep(g2); + } catch (InterruptedException ie) { + animationStarted = false; + paintStep(g2); + } + } + + /** + * Returns the time the animation thread had to sleep between each shown pixel step.
          + * Includes a kind of acceleration: At the begin there is a quadratic reduce of the time + * and at the end an increment. In between there is the constants minimum. + * + * @see GUIConstants + * + * @param pp Pixel Position + * @param pixel animation length + * @param per percents of param pixel for acceleration + * @return time thread had to sleep + */ + private int getTimeToSleep(int pp, int pixel, double per) { + if (pp > pixel) { + pp = pixel; + } + + if (pp < 0) { + pp = 0; + } + + if (per < 0.0) { + per = 0.0; + } + + if (per > 0.5) { + per = 0.5; + } + + double acc = GUIConstants.ACC_LENGTH; + + if (acc > (pixel / 2)) { + acc = pixel / 2; + } + + double max = (double) GUIConstants.MAX_PERIOD_TIME; + double min = (double) GUIConstants.MIN_PERIOD_TIME; + + if ((pp >= acc) && (pp <= (pixel - acc))) { + return GUIConstants.MIN_PERIOD_TIME; + } else { + if (pp > (pixel - acc)) { + pp -= pixel; + pp = -pp; + } + + double tts = ((max - min) / (acc * acc) * (double) pp * (double) pp) - + ((2.0 * (max - min)) / acc * (double) pp) + max; + + return (int) tts; + } + } + } +} diff --git a/src/org/jalgo/module/kmp/gui/component/RandomPatternDialog.java b/src/org/jalgo/module/kmp/gui/component/RandomPatternDialog.java new file mode 100644 index 0000000..8f0329b --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/RandomPatternDialog.java @@ -0,0 +1,117 @@ +package org.jalgo.module.kmp.gui.component; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JLabel; + +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +import org.jalgo.module.kmp.gui.event.PhaseOneScreenListener; +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; +import org.jalgo.module.kmp.Constants; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.main.util.Messages; + +/** + * This is the dialog for generating the random pattern. + * + * @author Danilo Lisske + */ +public class RandomPatternDialog extends JDialog { + private static final long serialVersionUID = 7323667361401103501L; + + private boolean isphaseone; + private PhaseOneScreenListener listener1; + private PhaseTwoScreenListener listener2; + private JComboBox cbsizealphabet; + private JComboBox cbsizepattern; + + /** + * The constructor of the random pattern dialog. + * + * @param l1 the PhaseOneScreenListener + * @param l2 the PhaseTwoScreenListener + */ + public RandomPatternDialog(PhaseOneScreenListener l1, PhaseTwoScreenListener l2) { + listener1 = l1; + listener2 = l2; + if(listener1 == null) isphaseone = false; + else isphaseone = true; + setTitle(Messages.getString("kmp","RPD.Title")); + setFont(GUIConstants.SCREEN_FONT); + setResizable(false); + setLayout(new GridBagLayout()); + setSize(220,120); + if(isphaseone) addWindowFocusListener(listener1); + else addWindowFocusListener(listener2); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.anchor = GridBagConstraints.WEST; + JLabel lbsizealphabet = new JLabel(Messages.getString("kmp","RPD.Label_alphabet") + ":"); + lbsizealphabet.setFont(getFont()); + add(lbsizealphabet,c); + c.gridx = 1; + cbsizealphabet = new JComboBox(); + cbsizealphabet.setEditable(false); + cbsizealphabet.setFont(getFont()); + for(int i = 1; i <= Constants.ALPHABET_SIZE; i++) { + cbsizealphabet.addItem(String.valueOf(i)); + } + add(cbsizealphabet,c); + c.gridx = 0; + c.gridy = 1; + JLabel lbsizepattern = new JLabel(Messages.getString("kmp","RPD.Label_pattern") + ":"); + lbsizepattern.setFont(getFont()); + add(lbsizepattern,c); + c.gridx = 1; + cbsizepattern = new JComboBox(); + cbsizepattern.setEditable(false); + cbsizepattern.setFont(getFont()); + for(int i = 1; i <= Constants.MAX_PAT_LENGTH; i++) { + cbsizepattern.addItem(String.valueOf(i)); + } + add(cbsizepattern,c); + c.gridx = 0; + c.gridy = 2; + c.gridwidth = 2; + c.insets = new Insets(4,4,4,4); + JPanel buttonPane = new JPanel(new BorderLayout()); + JButton btapply = new JButton(Messages.getString("kmp","RPD.Button_apply")); + btapply.setActionCommand("setrandom"); + btapply.setFont(getFont()); + if(isphaseone) btapply.addActionListener(listener1); + else btapply.addActionListener(listener2); + buttonPane.add(btapply,BorderLayout.CENTER); + JButton btcancel = new JButton(Messages.getString("kmp","RPD.Button_cancel")); + btcancel.setActionCommand("cancelrandom"); + btcancel.setFont(getFont()); + if(isphaseone) btcancel.addActionListener(listener1); + else btcancel.addActionListener(listener2); + buttonPane.add(btcancel,BorderLayout.EAST); + add(buttonPane,c); + } + + /** + * Returns the size of the alphabet. + * + * @return the size of the alphabet + */ + public int getAlphabetSize() { + return cbsizealphabet.getSelectedIndex() + 1; + } + + /** + * Returns the length of the pattern. + * + * @return the length of the pattern + */ + public int getPatternLength() { + return cbsizepattern.getSelectedIndex() + 1; + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.java b/src/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.java new file mode 100644 index 0000000..68b82dd --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.java @@ -0,0 +1,108 @@ +package org.jalgo.module.kmp.gui.component; + +import java.awt.Dimension; +import java.awt.Cursor; +import java.awt.BorderLayout; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.Insets; + +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.JButton; +import javax.swing.ScrollPaneConstants; + +import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.main.util.Messages; + +/** + * This is the dialog for loading a searchtext. + * + * @author Danilo Lisske + */ +public class SearchTextLoadDialog extends JDialog { + private static final long serialVersionUID = 5735872302716708982L; + + private PhaseTwoScreenListener listener; + private JTextPane tasearchtext; + + /** + * The constructor of the searchtext loading dialog. + * + * @param l2 the PhaseTwoScreenListener + */ + public SearchTextLoadDialog(PhaseTwoScreenListener l2) { + listener = l2; + setTitle(Messages.getString("kmp","STLD.Title")); + setSize(240,190); + setFont(GUIConstants.SCREEN_FONT); + setLayout(new GridBagLayout()); + setResizable(false); + addWindowFocusListener(listener); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.gridy = 0; + c.anchor = GridBagConstraints.WEST; + JLabel lbsearchtext = new JLabel(Messages.getString("kmp","STLD.Label_searchtext") + ":"); + lbsearchtext.setFont(getFont()); + add(lbsearchtext,c); + c.gridx = 1; + c.insets = new Insets(4,4,4,4); + c.anchor = GridBagConstraints.EAST; + JButton btopenfc = new JButton(Messages.getString("kmp","STLD.Button_load")); + btopenfc.setActionCommand("stfilechooser"); + btopenfc.addActionListener(listener); + btopenfc.setFont(getFont()); + add(btopenfc,c); + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 2; + c.insets = new Insets(0,0,0,0); + c.fill = GridBagConstraints.BOTH; + c.anchor = GridBagConstraints.CENTER; + tasearchtext = new JTextPane(); + tasearchtext.setPreferredSize(new Dimension(190,60)); + tasearchtext.setFont(getFont()); + JScrollPane scrollPane = new JScrollPane(tasearchtext, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scrollPane.setCursor(new Cursor(Cursor.TEXT_CURSOR)); + add(scrollPane,c); + c.gridy = 2; + c.insets = new Insets(4,4,4,4); + JPanel buttonPane = new JPanel(new BorderLayout()); + JButton btapply = new JButton(Messages.getString("kmp","STLD.Button_apply")); + btapply.setActionCommand("setsearchtext"); + btapply.addActionListener(listener); + btapply.setFont(getFont()); + buttonPane.add(btapply,BorderLayout.CENTER); + JButton btcancel = new JButton(Messages.getString("kmp","STLD.Button_cancel")); + btcancel.setActionCommand("cancelsearchtext"); + btcancel.addActionListener(listener); + btcancel.setFont(getFont()); + buttonPane.add(btcancel,BorderLayout.EAST); + add(buttonPane,c); + } + + /** + * Returns the searchtext. + * + * @return the searchtext + */ + public String getTaSearchText() { + return tasearchtext.getText(); + } + + /** + * Sets the searchtext to the input area of this dialog. + * + * @param s the searchtext + */ + public void setTaSearchText(String s) { + tasearchtext.setText(s); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/component/WelcomeButton.java b/src/org/jalgo/module/kmp/gui/component/WelcomeButton.java new file mode 100644 index 0000000..def91cb --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/WelcomeButton.java @@ -0,0 +1,90 @@ +/* j-Algo - j-Algo is an algorithm visualization tool, especially useful for students and lecturers of computer science. It is written in Java and platform independent. j-Algo is developed with the help of Dresden University of Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 19.04.2005 */ +package org.jalgo.module.kmp.gui.component; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +import org.jalgo.module.kmp.gui.event.WelcomeScreenListener; + +/** + * The class WelcomeButton represents a rollover-enabled graphical + * button with a description, which can be displayed on mouse hovering. + * + * @author Danilo Lißke + */ +public class WelcomeButton extends JToggleButton { + private static final long serialVersionUID = 284727572046563255L; + + private final ImageIcon desc; + + /** + * Constructs a WelcomeButton object with the given parameters. + * The description string is represented as a bitmap image, because of better + * layout on different platforms and the missing antialiasing of text on Swing + * components. + * + * @param defaultIcon the icon, which is displayed, when button is not selected + * @param rolloverIcon the icon, which is displayed on mouse hovering + * @param description the description string as image + * @param actionCommand the action command + * @param action an event handler implementing ActionListener + * and MouseListener + */ + public WelcomeButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, + ImageIcon description, String actionCommand, + WelcomeScreenListener action) { + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + //the standard rollover mechanism isn't used because of the following bug: + //click on an button holds the rollover state so that 2nd opening + //of welcome screen still highlights the button, even if mouse is not over + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + desc = description; + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension( + getIcon().getIconWidth(), + getIcon().getIconHeight())); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + + setActionCommand(actionCommand); + addActionListener(action); + addMouseListener(action); + } + + /** + * Retrieves the description of this WelcomeButton as image. + * + * @return the description string as image + */ + public ImageIcon getDescription() { + return desc; + } +} diff --git a/src/org/jalgo/module/kmp/gui/component/WelcomeScreen.java b/src/org/jalgo/module/kmp/gui/component/WelcomeScreen.java new file mode 100644 index 0000000..7e9604b --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/component/WelcomeScreen.java @@ -0,0 +1,140 @@ +package org.jalgo.module.kmp.gui.component; + +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; + +import org.jalgo.main.util.Messages; +import org.jalgo.main.util.Settings; +import org.jalgo.module.kmp.gui.component.WelcomeButton; +import org.jalgo.module.kmp.gui.GUIConstants; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.event.WelcomeScreenListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +/** + * Class WelcomeScreen represents a screen with four buttons, + * where the user can choose what to do. The buttons are rollover enabled and a + * description of the selected task is displayed. + * + * @author Danilo Lisske + */ +public class WelcomeScreen extends JPanel implements GUIConstants { + private static final long serialVersionUID = 1152679735426768226L; + + private WelcomeScreenListener listener; + + private WelcomeButton phaseoneButton; + private WelcomeButton phasetwoButton; + private WelcomeButton openButton; + private WelcomeButton exampleButton; + private JLabel descriptionLabel; + + /** + * Constructs a WelcomeScreen object with the given + * reference. + * + * @param gui the GUIController instance + */ + public WelcomeScreen(GUIController gui) { + listener = new WelcomeScreenListener(gui, this); + + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + + String lang = Settings.getString("main", "Language"); + if (!lang.equals("de")) lang = "en"; + phaseoneButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phaseone")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phaseone_rollover")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phaseone_description_"+lang)), + "startPhaseOne", listener); + phasetwoButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phasetwo")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phasetwo_rollover")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_phasetwo_description_"+lang)), + "startPhaseTwo", listener); + openButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_open")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_open_rollover")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_open_description_"+lang)), + "openFile", listener); + exampleButton = new WelcomeButton( + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_example")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_example_rollover")), + new ImageIcon( + Messages.getResourceURL("kmp", "Welcome_example_description_"+lang)), + "loadExample", listener); + + descriptionLabel = new JLabel(); + descriptionLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(WELCOME_SCREEN_BACKGROUND); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(phaseoneButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(phasetwoButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(openButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(exampleButton); + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descriptionLabel); + } + + /** + * Displays the given string description on the screen. + * + * @param desc the task description string + */ + public void setDescription(Icon desc) { + descriptionLabel.setIcon(desc); + descriptionLabel.updateUI(); + } + + /** + * Sets the enabled status of the buttons. If the given value is + * false, also the description string is removed from the + * screen. + * + * @param b true, if the buttons should be enabled, + * false otherwise + */ + public void setButtonsEnabled(boolean b) { + phaseoneButton.setEnabled(b); + phasetwoButton.setEnabled(b); + openButton.setEnabled(b); + exampleButton.setEnabled(b); + if (!b) setDescription(null); + } + + /** + * Draws the background with a beautyful color ;o). Normally there would be + * the background color set with setBackground(..), but, under + * linux (GTK) this has no effect. So this is a workaround... + */ + protected void paintComponent(Graphics g) { + g.setColor(WELCOME_SCREEN_BACKGROUND); + g.fillRect(0, 0, getWidth(), getHeight()); + } +} diff --git a/src/org/jalgo/module/kmp/gui/event/AbortAction.java b/src/org/jalgo/module/kmp/gui/event/AbortAction.java new file mode 100644 index 0000000..59f8afb --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/AbortAction.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 14.05.2006 */ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class AbortAction defines an Action object, + * which can be added to toolbars and menus. Performing this action aborts the + * currently running algorithm. + * + * @author Danilo Lisske + */ +public class AbortAction extends AbstractAction { + private static final long serialVersionUID = -2735790526306954726L; + + private GUIController gui; + + /** + * Constructs an AbortAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public AbortAction(GUIController gui) { + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "Abort")); + putValue(SHORT_DESCRIPTION,Messages.getString("kmp", "Abort_tooltip")); + putValue(SMALL_ICON, + new ImageIcon(Messages.getResourceURL("main", "Icon.Abort_algorithm"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doStartStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/BackwardAction.java b/src/org/jalgo/module/kmp/gui/event/BackwardAction.java new file mode 100644 index 0000000..e060330 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/BackwardAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class BackwardAction defines an Action object, + * which can be added to toolbars and menus. Performing this action moves backward + * in the currently running algorithm. + * + * @author Danilo Lisske + */ +public class BackwardAction extends AbstractAction { + private static final long serialVersionUID = -2182592701926208241L; + + private GUIController gui; + + /** + * Constructs an BackwardAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public BackwardAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "Back")); + putValue(SHORT_DESCRIPTION, Messages.getString("kmp", "Back_tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_step"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doPreviousStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/BeamerModeAction.java b/src/org/jalgo/module/kmp/gui/event/BeamerModeAction.java new file mode 100644 index 0000000..548fd2f --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/BeamerModeAction.java @@ -0,0 +1,78 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 12.06.2005 */ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class BeamerModeAction defines a checkbox menuitem for + * switching between beamer mode and pc mode.
          + * Here the Singleton design pattern is implemented, in order that this setting + * takes global effect for all open instances of the KMP module.
          + * + * @author Danilo Lisske + */ +public class BeamerModeAction extends JCheckBoxMenuItem implements ActionListener { + private static final long serialVersionUID = 5523818288828234644L; + private static BeamerModeAction instance; + private static GUIController guicontroller; + + /** + * Constructs the singleton instance of BeamerModeAction. + */ + private BeamerModeAction() { + super(Messages.getString("kmp", "Beamer_mode"), + new ImageIcon(Messages.getResourceURL("main", "Icon.Beamer_mode")), false); + addActionListener(this); + } + + /** + * Retrieves and, if necessary, initializes the singleton instance of + * BeamerModeAction. + * + * @param gc the GUIController + * + * @return the singleton instance + */ + public static BeamerModeAction getInstance(GUIController gc) { + guicontroller = gc; + if (instance == null) instance = new BeamerModeAction(); + return instance; + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + guicontroller.doBeamerMode(isSelected()); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/CVS/Entries b/src/org/jalgo/module/kmp/gui/event/CVS/Entries new file mode 100644 index 0000000..cbbd7e0 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/CVS/Entries @@ -0,0 +1,11 @@ +/AbortAction.java/1.2/Thu Jan 31 20:15:11 2008// +/BackwardAction.java/1.1/Fri Jun 30 14:35:19 2006// +/BeamerModeAction.java/1.2/Thu Jan 31 20:15:11 2008// +/FastBackwardAction.java/1.1/Fri Jun 30 14:35:18 2006// +/FastForwardAction.java/1.1/Fri Jun 30 14:35:18 2006// +/FinishAction.java/1.2/Thu Jan 31 20:15:11 2008// +/ForwardAction.java/1.1/Fri Jun 30 14:35:19 2006// +/PhaseOneScreenListener.java/1.1/Fri Jun 30 14:35:19 2006// +/PhaseTwoScreenListener.java/1.1/Fri Jun 30 14:35:18 2006// +/WelcomeAction.java/1.2/Thu Jan 31 20:15:11 2008// +/WelcomeScreenListener.java/1.1/Fri Jun 30 14:35:19 2006// diff --git a/src/org/jalgo/module/kmp/gui/event/CVS/Repository b/src/org/jalgo/module/kmp/gui/event/CVS/Repository new file mode 100644 index 0000000..558aed8 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/kmp/gui/event diff --git a/src/org/jalgo/module/kmp/gui/event/CVS/Root b/src/org/jalgo/module/kmp/gui/event/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/kmp/gui/event/FastBackwardAction.java b/src/org/jalgo/module/kmp/gui/event/FastBackwardAction.java new file mode 100644 index 0000000..86abf18 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/FastBackwardAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class FastBackwardAction defines an Action object, + * which can be added to toolbars and menus. Performing this action moves fast backward + * in the currently running algorithm. + * + * @author Danilo Lisske + */ +public class FastBackwardAction extends AbstractAction { + private static final long serialVersionUID = 2252270830798753137L; + + private GUIController gui; + + /** + * Constructs an FastBackwardAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public FastBackwardAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "FastBack")); + putValue(SHORT_DESCRIPTION, Messages.getString("kmp", "FastBack_tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Undo_blockstep"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doPreviousBigStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/FastForwardAction.java b/src/org/jalgo/module/kmp/gui/event/FastForwardAction.java new file mode 100644 index 0000000..7dd5151 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/FastForwardAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class FastForwardAction defines an Action object, + * which can be added to toolbars and menus. Performing this action moves fast forward + * in the currently running algorithm. + * + * @author Danilo Lisske + */ +public class FastForwardAction extends AbstractAction { + private static final long serialVersionUID = -803759150116357558L; + + private GUIController gui; + + /** + * Constructs a FastForwardAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public FastForwardAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "FastForward")); + putValue(SHORT_DESCRIPTION, Messages.getString("kmp", "FastForward_tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Perform_blockstep"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doNextBigStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/FinishAction.java b/src/org/jalgo/module/kmp/gui/event/FinishAction.java new file mode 100644 index 0000000..10f56c0 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/FinishAction.java @@ -0,0 +1,67 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 14.05.2006 */ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class FinishAction defines an Action + * object, which can be added to toolbars and menus. Performing this action + * finishes the currently running algorithm. + * + * @author Danilo Lisske + */ +public class FinishAction extends AbstractAction { + private static final long serialVersionUID = 3302515416723636450L; + + private GUIController gui; + + /** + * Constructs a FinishAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public FinishAction(GUIController gui) { + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "Finish")); + putValue(SHORT_DESCRIPTION, Messages.getString("kmp", "Finish_tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Finish_algorithm"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doEndStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/ForwardAction.java b/src/org/jalgo/module/kmp/gui/event/ForwardAction.java new file mode 100644 index 0000000..eb796e4 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/ForwardAction.java @@ -0,0 +1,44 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +/** + * The class ForwardAction defines an Action object, + * which can be added to toolbars and menus. Performing this action moves forward + * in the currently running algorithm. + * + * @author Danilo Lisske + */ +public class ForwardAction extends AbstractAction { + private static final long serialVersionUID = 5491712020638562272L; + + private GUIController gui; + + /** + * Constructs an ForwardAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public ForwardAction(GUIController gui) { + super(); + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "Forward")); + putValue(SHORT_DESCRIPTION, Messages.getString("kmp", "Forward_tooltip")); + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL( + "main", "Icon.Perform_step"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.doNextStep(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.java b/src/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.java new file mode 100644 index 0000000..9c43163 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/PhaseOneScreenListener.java @@ -0,0 +1,134 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.KeyListener; +import java.awt.event.KeyEvent; +import java.awt.event.WindowFocusListener; +import java.awt.event.WindowEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.ChangeEvent; + +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JTextPane; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.component.PhaseOneScreen; +import org.jalgo.module.kmp.gui.component.RandomPatternDialog;; + +/** + * This is the PhaseOneScreenListener which is responsible for + * actions happening in the phase one screen. + * + * @author Danilo Lisske + */ +public class PhaseOneScreenListener implements ActionListener, MouseListener, + KeyListener, WindowFocusListener, ChangeListener { + private GUIController guicontroller; + private PhaseOneScreen phaseonescreen; + private RandomPatternDialog rpd; + + /** + * The constructor of the PhaseOneScreenListener. + * + * @param g the GUIController instance + * @param w the PhaseOneScreen instance + */ + public PhaseOneScreenListener(GUIController g, PhaseOneScreen w) { + guicontroller = g; + phaseonescreen = w; + } + + public void actionPerformed(ActionEvent e) { + if(e.getActionCommand().equals("setpattern")) guicontroller.setPattern(); + if(e.getActionCommand().equals("random")) { + rpd = new RandomPatternDialog(this,null); + rpd.setLocationRelativeTo(phaseonescreen); + rpd.setVisible(true); + } + if(e.getActionCommand().equals("addpattern")) guicontroller.addPattern(); + if(e.getActionCommand().equals("setrandom")) { + guicontroller.createRandomPattern(rpd.getAlphabetSize(),rpd.getPatternLength()); + rpd.dispose(); + } + if(e.getActionCommand().equals("cancelrandom")) rpd.dispose(); + if(e.getActionCommand().equals("cyclechange")) + guicontroller.setCycles(); + if(e.getActionCommand().equals("goon")) guicontroller.installPhaseTwoScreen(); + } + + public void mouseClicked(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been pressed on a component. + */ + public void mousePressed(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been released on a component. + */ + public void mouseReleased(MouseEvent e) { + + } + + /** + * Invoked when the mouse enters a component. + */ + public void mouseEntered(MouseEvent e) { + if(e.getSource() instanceof JTextPane) + JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getName()); + else JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getToolTipText()); + } + + /** + * Invoked when the mouse leaves a component. + */ + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + public void keyTyped(KeyEvent e) { + + } + + public void keyPressed(KeyEvent e) { + + } + + public void keyReleased(KeyEvent e) { + if(e.getComponent().getName().equals("tfpattern")) { + guicontroller.keyOnTfPattern(); + if(e.getKeyCode() == KeyEvent.VK_ENTER && phaseonescreen.phaseoneinputPane.isPatternEnabled()) + guicontroller.setPattern(); + } + if(e.getComponent().getName().equals("tfaddpattern")) { + guicontroller.keyOnTfAddPattern(); + if(e.getKeyCode() == KeyEvent.VK_ENTER && phaseonescreen.phaseoneinputPane.isAddPatternEnabled()) + guicontroller.addPattern(); + } + } + + public void windowLostFocus(WindowEvent e) { + e.getComponent().requestFocus(); + } + + public void windowGainedFocus(WindowEvent e) { + + } + + public void stateChanged(ChangeEvent e) { + JSlider source = (JSlider)e.getSource(); + double newsize = source.getValue(); + guicontroller.scaleScreen(newsize * 0.1); + } +} diff --git a/src/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.java b/src/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.java new file mode 100644 index 0000000..61eb02b --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/PhaseTwoScreenListener.java @@ -0,0 +1,142 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.KeyListener; +import java.awt.event.KeyEvent; +import java.awt.event.WindowFocusListener; +import java.awt.event.WindowEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.ChangeEvent; + +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JTextPane; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.component.PhaseTwoScreen; +import org.jalgo.module.kmp.gui.component.RandomPatternDialog; +import org.jalgo.module.kmp.gui.component.SearchTextLoadDialog; + +/** + * This is the PhaseTwoScreenListener which is responsible for + * actions happening in the phase two screen. + * + * @author Danilo Lisske + */ +public class PhaseTwoScreenListener implements ActionListener, MouseListener, + KeyListener, WindowFocusListener, ChangeListener { + private GUIController guicontroller; + private PhaseTwoScreen phasetwoscreen; + private RandomPatternDialog rpd; + private SearchTextLoadDialog stld; + + /** + * The constructor of the PhaseOneScreenListener. + * + * @param g the GUIController instance + * @param w the PhaseTwoScreen instance + */ + public PhaseTwoScreenListener(GUIController g, PhaseTwoScreen w) { + guicontroller = g; + phasetwoscreen = w; + } + + public void actionPerformed(ActionEvent e) { + if(e.getActionCommand().equals("setpattern")) guicontroller.setPattern(); + if(e.getActionCommand().equals("random")) { + rpd = new RandomPatternDialog(null,this); + rpd.setLocationRelativeTo(phasetwoscreen); + rpd.setVisible(true); + } + if(e.getActionCommand().equals("loadst")) { + stld = new SearchTextLoadDialog(this); + stld.setTaSearchText(guicontroller.getSearchText()); + stld.setLocationRelativeTo(phasetwoscreen); + stld.setVisible(true); + } + if(e.getActionCommand().equals("generst")) guicontroller.createRandomSearchText(); + if(e.getActionCommand().equals("stfilechooser")) { + String text = guicontroller.openSearchTextFileChooser(); + if (text != null && text != "") stld.setTaSearchText(text); + } + if(e.getActionCommand().equals("setrandom")) { + guicontroller.createRandomPattern(rpd.getAlphabetSize(),rpd.getPatternLength()); + rpd.dispose(); + } + if(e.getActionCommand().equals("cancelrandom")) rpd.dispose(); + if(e.getActionCommand().equals("setsearchtext")) { + guicontroller.setSearchText(stld.getTaSearchText()); + stld.dispose(); + } + if(e.getActionCommand().equals("cancelsearchtext")) stld.dispose(); + } + + public void mouseClicked(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been pressed on a component. + */ + public void mousePressed(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been released on a component. + */ + public void mouseReleased(MouseEvent e) { + + } + + /** + * Invoked when the mouse enters a component. + */ + public void mouseEntered(MouseEvent e) { + if(e.getSource() instanceof JTextPane) + JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getName()); + else JAlgoGUIConnector.getInstance().setStatusMessage( + ((JComponent)e.getSource()).getToolTipText()); + } + + /** + * Invoked when the mouse leaves a component. + */ + public void mouseExited(MouseEvent e) { + JAlgoGUIConnector.getInstance().setStatusMessage(null); + } + + public void keyTyped(KeyEvent e) { + + } + + public void keyPressed(KeyEvent e) { + + } + + public void keyReleased(KeyEvent e) { + if(e.getComponent().getName().equals("tfpattern")) { + guicontroller.keyOnTfPattern(); + if(e.getKeyCode() == KeyEvent.VK_ENTER && phasetwoscreen.phasetwoinputPane.isPatternEnabled()) + guicontroller.setPattern(); + } + } + + public void windowLostFocus(WindowEvent e) { + e.getComponent().requestFocus(); + } + + public void windowGainedFocus(WindowEvent e) { + + } + + public void stateChanged(ChangeEvent e) { + JSlider source = (JSlider)e.getSource(); + guicontroller.scaleScreen(source.getValue() * 0.1); + } +} diff --git a/src/org/jalgo/module/kmp/gui/event/WelcomeAction.java b/src/org/jalgo/module/kmp/gui/event/WelcomeAction.java new file mode 100644 index 0000000..361c21e --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/WelcomeAction.java @@ -0,0 +1,86 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.gui.DialogConstants; +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.GUIController; + +import org.jalgo.main.gui.JAlgoGUIConnector; + +/** + * The class WelcomeAction defines an Action + * object, which can be added to toolbars and menus. Performing this action asks + * the user for discarding his changes, and if so, switches the layout of the + * current KMP module instance to the welcome screen and clears the tree. If the + * user doesn't want to discard his changes, a new instance of the KMP module is + * opened. The question dialog can be cancelled too. + * + * @author Danilo Lisske + */ +public class WelcomeAction extends AbstractAction { + private static final long serialVersionUID = -4393334839778312693L; + + private GUIController gui; + + /** + * Constructs a WelcomeAction object with the given + * references. + * + * @param gui the GUIController instance of the KMP module + */ + public WelcomeAction(GUIController gui) { + this.gui = gui; + putValue(NAME, Messages.getString("kmp", "Show_welcome_screen")); + putValue(SHORT_DESCRIPTION, Messages.getString( + "kmp", "Show_welcome_screen_tooltip")); + putValue(SMALL_ICON, new ImageIcon( + Messages.getResourceURL("kmp", "Module_logo"))); + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + switch (JAlgoGUIConnector.getInstance().showConfirmDialog( + Messages.getString("kmp", "Wish_to_discard"), + DialogConstants.YES_NO_CANCEL_OPTION)) { + case DialogConstants.YES_OPTION: + gui.clearValues(); + gui.installWelcomeScreen(); + break; + case DialogConstants.NO_OPTION: + JAlgoGUIConnector.getInstance().newModuleInstanceByName( + Messages.getString("kmp", "Module_name")); + break; + case DialogConstants.CANCEL_OPTION: + return; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.java b/src/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.java new file mode 100644 index 0000000..7cc1564 --- /dev/null +++ b/src/org/jalgo/module/kmp/gui/event/WelcomeScreenListener.java @@ -0,0 +1,122 @@ +package org.jalgo.module.kmp.gui.event; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowFocusListener; + +import javax.swing.JRadioButton; +import javax.swing.JLabel; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.kmp.gui.component.WelcomeButton; +import org.jalgo.module.kmp.gui.GUIController; +import org.jalgo.module.kmp.gui.component.WelcomeScreen; +import org.jalgo.module.kmp.gui.component.LearningExamplesDialog; + +/** + * This is the WelcomeScreenListener which is responsible for + * actions happening in the welcome screen. + * + * @author Danilo Lisske + */ +public class WelcomeScreenListener implements ActionListener, MouseListener, WindowFocusListener { + private GUIController gui; + private WelcomeScreen welcomescreen; + private LearningExamplesDialog led; + + /** + * The constructor of the PhaseOneScreenListener. + * + * @param gc the GUIController instance + * @param ws the WelcomeScreen instance + */ + public WelcomeScreenListener(GUIController gc, WelcomeScreen ws) { + gui = gc; + welcomescreen = ws; + } + + public void actionPerformed(ActionEvent e) { + if(e.getActionCommand().equals("startPhaseOne")) + gui.installPhaseOneScreen(); + else if(e.getActionCommand().equals("startPhaseTwo")) + gui.installPhaseTwoScreen(); + else if(e.getActionCommand().equals("openFile")) + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + else if(e.getActionCommand().equals("loadExample")) { + led = new LearningExamplesDialog(this); + led.setLocationRelativeTo(welcomescreen); + led.setVisible(true); + } + else if(e.getActionCommand().equals("setlearningexample")) { + gui.loadLearningExample(Messages.getString("kmp","LED.Example_pattern_"+led.getSelectedIndex()), + Messages.getString("kmp","LED.Example_searchtext_"+led.getSelectedIndex())); + gui.installPhaseOneScreen(); + led.dispose(); + } + else if(e.getActionCommand().equals("cancellearningexample")) led.dispose(); + else { + ((WelcomeButton)e.getSource()).setSelected(false); + welcomescreen.setDescription(null); + } + + } + + public void mouseClicked(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been pressed on a component. + */ + public void mousePressed(MouseEvent e) { + + } + + /** + * Invoked when a mouse button has been released on a component. + */ + public void mouseReleased(MouseEvent e) { + + } + + /** + * Invoked when the mouse enters a component. + */ + public void mouseEntered(MouseEvent e) { + if(e.getSource() instanceof WelcomeButton) { + WelcomeButton source = (WelcomeButton)e.getSource(); + if (!source.isEnabled()) return; + source.setSelected(true); + welcomescreen.setDescription(source.getDescription()); + } + if(e.getSource() instanceof JRadioButton) + led.setTfDescriptionText(((JRadioButton)e.getSource()).getName()); + if(e.getSource() instanceof JLabel) + led.setTfDescriptionText(((JLabel)e.getSource()).getName()); + } + + /** + * Causes the event source button to be displayed normally and to remove the + * description string from the screen. + */ + public void mouseExited(MouseEvent e) { + if(e.getSource() instanceof WelcomeButton) { + ((WelcomeButton)e.getSource()).setSelected(false); + welcomescreen.setDescription(null); + } + if(e.getSource() instanceof JRadioButton || e.getSource() instanceof JLabel) + led.setTfDescriptionText("mouseoff"); + } + + public void windowLostFocus(WindowEvent e) { + e.getComponent().requestFocus(); + } + + public void windowGainedFocus(WindowEvent e) { + + } +} diff --git a/src/org/jalgo/module/kmp/res.properties b/src/org/jalgo/module/kmp/res.properties new file mode 100644 index 0000000..8b0ee2c --- /dev/null +++ b/src/org/jalgo/module/kmp/res.properties @@ -0,0 +1,20 @@ +Module_logo=/kmp_pix/logo.gif + +HelpSet_Name=/help/jhelp/kmp_help.hs + +Welcome_phaseone=/kmp_pix/welcome_phaseone.gif +Welcome_phaseone_rollover=/kmp_pix/welcome_phaseone_rollover.gif +Welcome_phaseone_description_de=/kmp_pix/welcome_phaseone_desc_de.gif +Welcome_phaseone_description_en=/kmp_pix/welcome_phaseone_desc_en.gif +Welcome_phasetwo=/kmp_pix/welcome_phasetwo.gif +Welcome_phasetwo_rollover=/kmp_pix/welcome_phasetwo_rollover.gif +Welcome_phasetwo_description_de=/kmp_pix/welcome_phasetwo_desc_de.gif +Welcome_phasetwo_description_en=/kmp_pix/welcome_phasetwo_desc_en.gif +Welcome_open=/kmp_pix/welcome_open.gif +Welcome_open_rollover=/kmp_pix/welcome_open_rollover.gif +Welcome_open_description_de=/kmp_pix/welcome_open_desc_de.gif +Welcome_open_description_en=/kmp_pix/welcome_open_desc_en.gif +Welcome_example=/kmp_pix/welcome_example.gif +Welcome_example_rollover=/kmp_pix/welcome_example_rollover.gif +Welcome_example_description_de=/kmp_pix/welcome_example_desc_de.gif +Welcome_example_description_en=/kmp_pix/welcome_example_desc_en.gif \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/CVS/Entries b/src/org/jalgo/module/lambda/CVS/Entries new file mode 100644 index 0000000..471e968 --- /dev/null +++ b/src/org/jalgo/module/lambda/CVS/Entries @@ -0,0 +1,11 @@ +/Constants.java/1.1/Thu Aug 6 14:39:01 2009// +/LambdaCalculus.g/1.1/Thu Aug 6 14:39:01 2009/-kb/ +/ModuleConnector.java/1.1/Thu Aug 6 14:39:01 2009// +/ModuleInfo.java/1.1/Thu Aug 6 14:39:01 2009// +/ShortcutHandler.java/1.1/Thu Aug 6 14:39:01 2009// +D/controller//// +/de.properties/1.1/Thu Aug 6 14:39:01 2009// +/en.properties/1.1/Thu Aug 6 14:39:01 2009// +D/model//// +/res.properties/1.1/Thu Aug 6 14:39:01 2009// +D/view//// diff --git a/src/org/jalgo/module/lambda/CVS/Repository b/src/org/jalgo/module/lambda/CVS/Repository new file mode 100644 index 0000000..dc4e83c --- /dev/null +++ b/src/org/jalgo/module/lambda/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/lambda diff --git a/src/org/jalgo/module/lambda/CVS/Root b/src/org/jalgo/module/lambda/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/lambda/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/lambda/Constants.java b/src/org/jalgo/module/lambda/Constants.java new file mode 100644 index 0000000..20cd27f --- /dev/null +++ b/src/org/jalgo/module/lambda/Constants.java @@ -0,0 +1,11 @@ +package org.jalgo.module.lambda; + +public class Constants { + + // Unicode-constants + public static final String ALPHA = "\u03B1"; + public static final String BETA = "\u03B2"; + public static final String LAMBDA = "\u03BB"; + public static final String ARROW_R = "\u21D2"; + +} diff --git a/src/org/jalgo/module/lambda/LambdaCalculus.g b/src/org/jalgo/module/lambda/LambdaCalculus.g new file mode 100644 index 0000000..731839f --- /dev/null +++ b/src/org/jalgo/module/lambda/LambdaCalculus.g @@ -0,0 +1,112 @@ +grammar LambdaCalculus; + + +options { + output = AST; + } + +tokens { + LAMBDA = '\u03BB'; + POINT = '.'; + POPEN = '('; + PCLOSE = ')'; + SPOPEN = '<'; + SPCLOSE = '>'; + ABSTRACTION; + APPLICATION; + ATOM; + SHORTCUT; + } + +@header { + package parser; + import model.*; + +} + +@lexer::header { + + package parser; + import model.*; + +} + +@members { + + + Term t; +protected void mismatch(IntStream input, int ttype, BitSet follow) + throws RecognitionException +{ + System.out.println("aki1"); + throw new MismatchedTokenException(ttype, input); + +} +protected Object recoverFromMismatchedToken(IntStream input, + int ttype, + BitSet follow) + throws RecognitionException +{ + System.out.println("aki2"); + throw new MismatchedTokenException(ttype, input); +} + + +} + + + +// Alter code generation so catch-clauses get replace with +// this action. +@rulecatch { +catch (RecognitionException e) { + throw e; +} +} +// END:override LAMBDA = '\u03BB'; + + +/*------------------------------------------------------------------ + * PARSER RULES + *------------------------------------------------------------------*/ + +start : term EOF; +term : atom + | abstraction + | application + | shortcut + /*| (POPEN term PCLOSE)=> term /* FIXME: this should go */ + | (POPEN atom PCLOSE)=> atom /*FIXME: this should go */ + ; + + +atom : variable + | constant + ; +variable: v=VAR -> ^(ATOM $v); +constant: c=CONS -> ^(ATOM $c); + +abstraction + : POPEN LAMBDA aa=variable POINT at=term PCLOSE -> ^(ABSTRACTION $aa $at) ; +application + : POPEN t1=term t2=term PCLOSE -> ^(APPLICATION $t1 $t2); +shortcut: s=SHORTCUTID -> ^(SHORTCUT $s); +/*------------------------------------------------------------------ + * LEXER RULES + *------------------------------------------------------------------*/ + +VAR : ('k'..'z'); +CONS : ('a'..'j' | '+' | '-' | '*' | '/' | '%' ); + +SHORTCUTID + : SPOPEN(LETTER)+SPCLOSE; +fragment LETTER + : ('a'..'z'|'A'..'Z'|'0'..'9'); +WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ; + +COMMENT + : '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;} + ; +LINE_COMMENT + : '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;} + ; diff --git a/src/org/jalgo/module/lambda/ModuleConnector.java b/src/org/jalgo/module/lambda/ModuleConnector.java new file mode 100644 index 0000000..413f35e --- /dev/null +++ b/src/org/jalgo/module/lambda/ModuleConnector.java @@ -0,0 +1,59 @@ +package org.jalgo.module.lambda; + +import org.jalgo.module.lambda.controller.Controller; +import org.jalgo.module.lambda.controller.IController; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; + +public class ModuleConnector extends AbstractModuleConnector { + + private IController controller; + + @Override + public void init() { + JAlgoGUIConnector.getInstance().getModuleMenu(this).setEnabled(false); + controller = new Controller(this); + } + + @Override + public void run() { + controller.run(); + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + try { + ObjectInputStream in = new ObjectInputStream(data); + controller.loadData(in); + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public ByteArrayOutputStream getDataForFile() { + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream objOut = new ObjectOutputStream(out); + controller.saveData(objOut); + out.close(); + return out; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + @Override + public void print() { + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/ModuleInfo.java b/src/org/jalgo/module/lambda/ModuleInfo.java new file mode 100644 index 0000000..49cd993 --- /dev/null +++ b/src/org/jalgo/module/lambda/ModuleInfo.java @@ -0,0 +1,59 @@ +package org.jalgo.module.lambda; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return Messages.getString("lambda", "Module_name"); + } + + public String getVersion() { + return Messages.getString("lambda", "Module_version"); + } + + public String getAuthor() { + return Messages.getString("lambda", "Module_authors"); + } + + public String getDescription() { + return Messages.getString("lambda", "Module_description_1"); + } + + public URL getLogoURL() { + return Messages.getResourceURL("lambda", "Module_logo"); + } + + public String getLicense() { + return Messages.getString("lambda", "Module_license"); + } + + public URL getHelpSetURL() { + return Messages.getResourceURL("lambda","HelpSet_Name"); + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/ShortcutHandler.java b/src/org/jalgo/module/lambda/ShortcutHandler.java new file mode 100644 index 0000000..3000a24 --- /dev/null +++ b/src/org/jalgo/module/lambda/ShortcutHandler.java @@ -0,0 +1,381 @@ +package org.jalgo.module.lambda; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.jalgo.module.lambda.controller.LambdaException; +import org.jalgo.module.lambda.controller.ParseUnit; +import org.jalgo.module.lambda.model.Abstraction; +import org.jalgo.module.lambda.model.Application; +import org.jalgo.module.lambda.model.Atom; +import org.jalgo.module.lambda.model.ETermType; +import org.jalgo.module.lambda.model.Shortcut; +import org.jalgo.module.lambda.model.Term; + +/** + * Manages Shortcuts like . Therefore it stores a String and Term + * representation of every defined Shortcut. Serves to create Shortcut objects. + * + * + */ +public class ShortcutHandler { + + private LinkedList shortcuts; + + private static ShortcutHandler instance; + + /** + * Private constructor, an object can only be created through getInstance(). + * See "Singleton Design Pattern" + */ + private ShortcutHandler() { + // shortcutList = new TreeMap(); + shortcuts = new LinkedList(); + } + + public boolean prepareShortcutList() { + try { + addShortcut("identity", "(\u03BBy.y)", true); + addShortcut("true", "(\u03BBx.(\u03BBy.x))", true); + // addShortcut("false", "(\u03BBx.(\u03BBy.y))"); == <0> + addShortcut("0", "(\u03BBx.(\u03BBy.y))", true); + addShortcut("1", "(\u03BBx.(\u03BBy.(xy)))", true); + addShortcut("2", "(\u03BBx.(\u03BBy.(x(xy))))", true); + addShortcut("3", "(\u03BBx.(\u03BBy.(x(x(xy)))))", true); + addShortcut("4", "(\u03BBx.(\u03BBy.(x(x(x(xy))))))", true); + addShortcut("5", "(\u03BBx.(\u03BBy.(x(x(x(x(xy)))))))", true); + addShortcut("6", "(\u03BBx.(\u03BBy.(x(x(x(x(x(xy))))))))", true); + addShortcut("7", "(\u03BBx.(\u03BBy.(x(x(x(x(x(x(xy)))))))))", true); + addShortcut("8", "(\u03BBx.(\u03BBy.(x(x(x(x(x(x(x(xy))))))))))", true); + addShortcut("9", "(\u03BBx.(\u03BBy.(x(x(x(x(x(x(x(x(xy)))))))))))", true); + addShortcut("ite", "(\u03BBx.(\u03BBy.(\u03BBz.((xy)z))))", true); + addShortcut("succ", "(\u03BBz.(\u03BBx.(\u03BBy.(x((zx)y)))))", true); + addShortcut("iszero", lambda("(Lk.((k(<0>))))"), true); + addShortcut("pred", lambda("(Lk.(((k(Lp.(Lu.((u((p)))(p)))))(Lu.((u<0>)<0>)))<0>))"), true); + addShortcut("Y", lambda("(Lz.((Lu.(z(uu)))(Lu.(z(uu)))))"), true); + addShortcut("add", lambda("((Lz.(Lx.(Ly.((((x))y)(((z(x))y)))))))"), true); + addShortcut("mult", lambda("((Lz.(Lx.(Ly.((((x))<0>)((y)((z(x))y)))))))"), true); + addShortcut("fac", lambda("((Lz.(Lx.((((x))<1>)((x)(z(x)))))))"), true); + + } catch (LambdaException e) { + return false; + } + return true; + } + + public String lambda(String s) { + return s.replaceAll("L", "\u03BB"); + } + + public Term toLambdaNumber(int i) { + if(i == 0) { + return createShortcutObject("<0>"); + } + Atom x = new Atom("x"); + Atom y = new Atom("y"); + Term t1 = new Application(x, y); + x.setParent(t1); + y.setParent(t1); + Term t0; + while (i > 1) { + x = new Atom("x"); + t0 = t1; + t1 = new Application(x, t0); + x.setParent(t1); + t0.setParent(t1); + i--; + } + x = new Atom("x"); + y = new Atom("y"); + Term t2 = new Abstraction(y, t1); + y.setParent(t2); + t1.setParent(t2); + Term t3 = new Abstraction(x, t2); + x.setParent(t3); + t2.setParent(t3); + t3.recalculateBindingIDs(); + return t3; + } + + public int matchLambdaNumber(Term t) { + Term matchTerm = t.clone(); // clone so the bindingIDs of t stay intact + matchTerm.recalculateBindingIDs(); + if (matchTerm.getTermType() == ETermType.ABSTRACTION) { + matchTerm = matchTerm.getSubTerm("a"); + if (matchTerm.getTermType() == ETermType.ABSTRACTION) { + matchTerm = matchTerm.getSubTerm("a"); + int i = 0; + while (matchTerm.getTermType() == ETermType.APPLICATION + && matchTerm.getSubTerm("l").getTermType() == ETermType.ATOM) { + Atom x = (Atom) matchTerm.getSubTerm("l"); + if (!x.toString().equals("x")) + return -1; + else { + matchTerm = matchTerm.getSubTerm("r"); + i++; + } + } + if (matchTerm.getTermType() == ETermType.ATOM + && ((Atom) matchTerm).toString().equals("y")) + return i; + } + } + return -1; + } + + + /** + * Get the (only) ShortcutHandler instance + * + * @return the ShortcutHandler instance + */ + public static ShortcutHandler getInstance() { + if (instance == null) { + instance = new ShortcutHandler(); + instance.prepareShortcutList(); + } + return instance; + } + + /** + * Add a shortcut definition to shortcutList + * + * @param representation + * String representation of the Shortcut + * @param term + * Term representation of the Shortcut + * @return true if the definition has been added + * @throws LambdaException + */ + public boolean addShortcut(String representation, String term, boolean predefined) + throws LambdaException { + ParseUnit parser = new ParseUnit(); + Term t = null; + int pos = 0; + if (representation.equals("")) + throw new LambdaException("Leere Abkürzung"); + if (term.equals("")) + throw new LambdaException("Leerer Lambdaterm"); + if (!representation.startsWith("<")) + representation = "<" + representation; + if (!representation.endsWith(">")) + representation = representation + ">"; + t = parser.parseString(term); + for (Shortcut sc : shortcuts) { + if (t.toString().length() < sc.getRepresentedTerm().toString() + .length()) { + pos++; + } + if (sc.getRepresentation().equals(representation)) { + throw new LambdaException("Abkürzung schon vergeben"); + } + if (sc.getRepresentedTerm().toString().equals(t.toString())) { + throw new LambdaException( + "Lambdaterm ist schon als Abkürzung vorhanden"); + } + if (sc.getRepresentedTerm().equalsStructure(t)) { + throw new LambdaException( + "Lambdaterm ist schon als Abkürzung vorhanden"); + } + } + t.recalculateBindingIDs(); + shortcuts.add(pos, new Shortcut(representation, t, predefined)); + return true; + } + + /** + * Remove a Shortcut from the list + * + * @param representation + * String representation of the shortcut + * @return true if the shortcut has been removed + */ + public boolean removeShortcut(String representation) { + // Term altTerm; + // altTerm = shortcutList.remove(representation); + for (Shortcut sc : shortcuts) { + if (sc.getRepresentation().equals(representation)) { + return shortcuts.remove(sc); + } + } + // if (altTerm.toString() == representation) + // return true; + // else + return false; + } + + /** + * Remove all non predefined Shortcuts from the list + * + * @return true if the shortcuts have been removed + */ + public void clearShortcuts() { + shortcuts.clear(); + prepareShortcutList(); + } + + /** + * Get a Set of all shortcut String representations + * + * @return Set of all shortcut String representations + */ + public Set getShortcutList() { + Set list = new TreeSet(); + for (Shortcut sc : shortcuts) { + list.add(sc.getRepresentation()); + } + return list; + } + + public List getAllAvailabilShortCuts() { + return shortcuts; + } + + public List getReverseList() { + LinkedList list = new LinkedList(shortcuts); + Collections.reverse(list); + return list; + } + + /** + * Check if the shortcut is predefined. The shortcut is + * identified by its String representation + * + * @param representation + * the shortcuts String representation + * @return true if shortcut predefined + */ + public boolean isShortcutPredefined(String representation) { + for (Shortcut sc : shortcuts) { + if (sc.getRepresentation().equals(representation)) { + return sc.isPredefined(); + } + } + return false; + } + + /** + * Get the Term representation of shortcut identified by its String + * representation + * + * @param representation + * the shortcuts String representation + * @return the shortcuts Term representation + */ + public Term getShortcutTerm(String representation) { + for (Shortcut sc : shortcuts) { + if (sc.getRepresentation().equals(representation)) { + return sc.getRepresentedTerm(); + } + } + // throw new IllegalArgumentException(); + // return shortcutList.get(representation); + return null; + } + + /** + * Get the String representation of shortcut if the shortcutList contains + * a shortcut with the term representation + * + * @param term + * Term representation of the Shortcut + * @return string representation of shortcut + */ + public String getShortcutRepresentation(String term) { + ParseUnit parser = new ParseUnit(); + Term t = null; + try { + t = parser.parseString(term); + } catch (LambdaException e) { + return null; + } + for (Shortcut sc : shortcuts) { + if (sc.getRepresentedTerm().toString().equals(t.toString())) { + return sc.getRepresentation(); + } + if (sc.getRepresentedTerm().equalsStructure(t)) { + return sc.getRepresentation(); + } + } + return null; + } + + public Term getShortcutCloneByRepresentation(String representation) { + for (Shortcut sc : shortcuts) { + if (sc.getRepresentation().equals(representation)) { + return sc.clone(); + } + } + representation=representation.replace(">", ""); + representation=representation.replace("<", ""); + try { + // if(Integer.valueOf(representation).getClass().equals(Integer.class)){ + return new Shortcut("<"+representation+">", toLambdaNumber(Integer + .parseInt(representation)), false); + // } + } catch (NumberFormatException e) { + //System.out.println("fehler bei Zahl " + representation); + } + throw new IllegalArgumentException(representation + " is no Shortcut"); + } + + public Term getShorcutCloneByRepresentedTerm(Term SubTerm) { + int zahl = matchLambdaNumber(SubTerm); + if (zahl != -1) { + return toLambdaNumber(zahl); + } + for (Shortcut sc : shortcuts) { + if (sc.getRepresentedTerm().equalsStructure(SubTerm)) { + return sc.clone(); + } + } + return SubTerm; + } + + /** + * Creates a Shortcut object from a given String. + * + * @param representation + * String representation of the Shortcut to create. + * @return A Shortcut object that fits to the given representation or NULL + * if there is no fitting entry in shortcutList. + */ + public Shortcut createShortcutObject(String representation) { + return new Shortcut(representation, getShortcutTerm(representation), false); + } + + /** + * Creates a Shortcut to a corrosponding int value + * + * @param the int value that should be represented by the Shortcut + * @return the created Shortcut Object + */ + public Shortcut createNumberShortcut(int number) { + return new Shortcut("<" + number + ">", toLambdaNumber(number), false); + } + + /** + * check the subterm if the subterm is a shortcut. + * + * @param subterm + * that should match + * + * @return retruns a shortcut that matchs or the full lambdaterm + */ + public Term matchShortcut(Term subTerm) { + int zahl = matchLambdaNumber(subTerm); + if (zahl > -1) { + return new Shortcut("<" + zahl + ">", toLambdaNumber(zahl), false); + } + for (Shortcut sc : shortcuts) { + if (sc.getRepresentedTerm().equalsStructure(subTerm)) { + return sc.clone(); + } + } + return null; + } + +} diff --git a/src/org/jalgo/module/lambda/controller/CVS/Entries b/src/org/jalgo/module/lambda/controller/CVS/Entries new file mode 100644 index 0000000..1afe073 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/CVS/Entries @@ -0,0 +1,12 @@ +/Controller.java/1.1/Thu Aug 6 14:39:02 2009// +/EToken.java/1.1/Thu Aug 6 14:39:02 2009// +/HistoryStep.java/1.1/Thu Aug 6 14:39:02 2009// +/HistoryTerm.java/1.1/Thu Aug 6 14:39:02 2009// +/IController.java/1.1/Thu Aug 6 14:39:02 2009// +/IParseUnit.java/1.1/Thu Aug 6 14:39:02 2009// +/LambdaCalculus.tokens/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/LambdaCalculusLexer.java/1.1/Thu Aug 6 14:39:02 2009// +/LambdaCalculusParser.java/1.1/Thu Aug 6 14:39:02 2009// +/LambdaException.java/1.1/Thu Aug 6 14:39:02 2009// +/ParseUnit.java/1.1/Thu Aug 6 14:39:02 2009// +/TermHistory.java/1.1/Thu Aug 6 14:39:02 2009// diff --git a/src/org/jalgo/module/lambda/controller/CVS/Repository b/src/org/jalgo/module/lambda/controller/CVS/Repository new file mode 100644 index 0000000..318f72c --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/lambda/controller diff --git a/src/org/jalgo/module/lambda/controller/CVS/Root b/src/org/jalgo/module/lambda/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/lambda/controller/Controller.java b/src/org/jalgo/module/lambda/controller/Controller.java new file mode 100644 index 0000000..cf33ada --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/Controller.java @@ -0,0 +1,491 @@ +/** + * Class Controller + * + * @author Tobias Reiher + * @version 1.0 + */ +package org.jalgo.module.lambda.controller; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.LinkedList; +import java.util.List; +import java.util.Observer; +import java.util.Set; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; +import org.jalgo.module.lambda.ModuleConnector; +import org.jalgo.module.lambda.ShortcutHandler; +import org.jalgo.module.lambda.model.Atom; +import org.jalgo.module.lambda.model.EAvailability; +import org.jalgo.module.lambda.model.EStepKind; +import org.jalgo.module.lambda.model.ITermHandler; +import org.jalgo.module.lambda.model.Shortcut; +import org.jalgo.module.lambda.view.GUIController; + +public class Controller implements IController { + + private GUIController gui; + private TermHistory termHistory; + private ITermHandler termHandler; + private IParseUnit parseUnit; + private String workingPosition; + + /** + * initializes attributes and instantiates GUIController, TermHistory and ParseUnit + * + * @param moduleConnector + */ + public Controller(ModuleConnector moduleConnector) { + gui = new GUIController(moduleConnector, this); + termHistory = new TermHistory(gui); + parseUnit = new ParseUnit(); + workingPosition = ""; + } + + /** + * install the welcome screen + */ + public void run() { + gui.installWelcomeScreen(); + } + + /** + * loads the current term and shortcuts from file + * + * @param data + */ + public void loadData(ObjectInputStream in) { + try { + gui.installWorkScreen(); + gui.clearComment(); + + Integer c = (Integer) in.readObject(); + String s = (String) in.readObject(); + + ShortcutHandler.getInstance().clearShortcuts(); + for (int i = 0; i < c.intValue(); i++) + ShortcutHandler.getInstance().addShortcut((String) in.readObject(), (String) in.readObject(), false); + gui.refreshShortcutList(); + + gui.setInputTextField(s); + processInputString(s, gui); + } catch (IOException e) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "lambda", "ModuleConnector.Load_Error") + e.getMessage()); + } catch (ClassNotFoundException e) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "lambda", "ModuleConnector.Load_Error") + + System.getProperty("line.separator") + + Messages.getString("lambda", "ModuleConnector.File_damaged")); + } catch (LambdaException e) { + JAlgoGUIConnector.getInstance().showErrorMessage(e.getMessage()); + } + } + + /** + * writes the current term and the self-defined shortcuts into file + * + * @param out ObjectOutputStream + */ + public void saveData(ObjectOutputStream out) { + try { + List shortcutList = ShortcutHandler.getInstance().getAllAvailabilShortCuts(); + + int i = 0; + for (Shortcut s : shortcutList) { + if (!s.isPredefined()) { + i++; + } + } + + out.writeObject(new Integer(i)); + out.writeObject(termHistory.getFirstTerm()); + + for (Shortcut s : shortcutList) { + if (!s.isPredefined()) { + out.writeObject(s.getRepresentation()); + out.writeObject(s.getRepresentedTerm().toString()); + } + } + } catch (IOException e) { + JAlgoGUIConnector.getInstance().showErrorMessage(Messages.getString( + "lambda", "ModuleConnector.Save_Error") + e.getMessage()); + } + } + + /** + * validates the input string + * + * @param s input string + * @return null if input string is a valid term, otherwise a LambdaException + */ + public LambdaException validateInputString(String s) { + try { + parseUnit.parseString(s); + } catch (LambdaException e) { + return e; + } + return null; + } + + /** + * parses the input string and set the new term handler + * + * @param s input string + * @param o observer + * @return null if parsing successful, otherwise a LambdaException + */ + public LambdaException processString(String s, Observer o) { + try { + termHandler = parseUnit.parseString(s, o); + workingPosition = ""; + return null; + } catch (LambdaException e) { + return e; + } + } + + /** + * save the input string in an empty CTerm, if term processing was successful + * + * @param s input string + * @param o observer + * @return null if successful, otherwise a LambdaException + */ + public LambdaException processInputString(String s, Observer o) { + termHistory.createTerm(); + LambdaException le = processString(s, o); + if (le == null) { + termHistory.addStep(s, "", 0); + } + return le; + } + + /** + * creates the term representation of the selected shortcut and saves it in the current CTerm + * + * @return true if successful + */ + public boolean eliminateShortcut() { + if (termHandler.eliminateShortcut(workingPosition)) { + termHistory.addStep(termHandler.toString(), "=", 0); + workingPosition = ""; + return true; + } + return false; + } + + /** + * creates the term representation of all shortcuts at working position and saves it in the current CTerm + * + * @return true if successful + */ + public boolean eliminateAllShortcuts() { + termHandler.eliminateAllShortcuts(workingPosition); + if (!termHistory.getCurrentTerm().equals(termHandler.toString())) { + termHistory.addStep(termHandler.toString(), "=", 0); + workingPosition = ""; + return true; + } + return false; + } + + /** + * matches the selected term with its shortcut representation and save it in the current CTerm + * + * @return true if successful + */ + public boolean matchShortcut() { + if (termHandler.matchShortcut(workingPosition)) { + termHistory.addStep(termHandler.toString(), "=", 0); + workingPosition = ""; + return true; + } + return false; + } + + /** + * matches all selected terms with their shortcut representations and save the result in the current CTerm + * + * @return true if successful + */ + public boolean makeAllShortcuts() { + termHandler.makeAllShortcuts(workingPosition); + if (!termHistory.getCurrentTerm().equals(termHandler.toString())) { + termHistory.addStep(termHandler.toString(), "=", 0); + workingPosition = ""; + return true; + } + return false; + } + + /** + * does an alpha conversion at working position and save the result in the current CTerm + * + * @param subst substitution variable + * @return true if successful, false if no conversion possible at working position + */ + public boolean doAlphaConversion(String subst) { + if (!termHandler.alphaConvert(workingPosition, subst)) + return false; + termHistory.addStep(termHandler.toString(), "\u03b1", 1); + workingPosition = ""; + return true; + } + + /** + * does an beta reduction at working position and save the result in the current CTerm + * + * @return availability of beta reduction at working position + */ + public EAvailability doBetaReduction() { + EAvailability availability = termHandler.betaReduce(workingPosition); + if (availability == EAvailability.AVAILABLE) { + termHistory.addStep(termHandler.toString(), "\u03b2", 1); + } + return availability; + } + + /** + * does next useful step at working position and save the result in the current CTerm + * + * @return applied operation as unicode character + */ + public String doStep() { + eliminateAllShortcuts(); + String operation; + EStepKind stepKind = termHandler.doLowLevelAutoStep(workingPosition); + if (stepKind == EStepKind.ALPHA) { + operation = "\u03b1"; + } else if (stepKind == EStepKind.BETA) { + operation = "\u03b2"; + } else + return null; + termHistory.addStep(termHandler.toString(), operation, 1); + workingPosition = ""; + return operation; + } + + /** + * does a shortcut step at working position and save the result in the current CTerm + * + * @return applied operation as unicode character + */ + public String doShortcutStep() { + String operation; + EStepKind stepKind = termHandler.doHighLevelAutoStep(workingPosition); + if (stepKind == EStepKind.SHORTCUT) { + operation = "*"; + } else + return null; + termHistory.addStep(termHandler.toString(), operation, 1); + workingPosition = ""; + return operation; + } + + /** + * does fully reduce the term at working position and save the result in the current CTerm + * breakes processing after 100 steps or if the term hasn't changed as an infinte loop protection + * + * @return applied operation as unicode character + */ + public String doAllSteps() { + int i = 0; + String operation = null; + EStepKind stepKind, oldStepKind = EStepKind.NONE; + + stepKind = termHandler.doHighLevelAutoStep(workingPosition); + while (stepKind != EStepKind.NONE) { + if (termHandler.toString().equals(termHistory.getCurrentTerm())) + break; + if (i >= 100) + break; + i++; + oldStepKind = stepKind; + stepKind = termHandler.doHighLevelAutoStep(workingPosition); + } + + termHandler.eliminateAllShortcuts(workingPosition); + + stepKind = termHandler.doLowLevelAutoStep(workingPosition); + while (stepKind != EStepKind.NONE) { + if (termHandler.toString().equals(termHistory.getCurrentTerm())) + break; + if (i >= 100) + break; + i++; + oldStepKind = stepKind; + stepKind = termHandler.doLowLevelAutoStep(workingPosition); + } + + if (oldStepKind == EStepKind.ALPHA) { + operation = "\u03b1"; + } else if (oldStepKind == EStepKind.BETA) { + operation = "\u03b2"; + } + if (oldStepKind == EStepKind.SHORTCUT || i > 1) { + operation = "*"; + } + + if (i > 0) { + termHistory.addStep(termHandler.toString(), operation, i); + workingPosition = ""; + } + + if (makeAllShortcuts()) { + operation = "="; + } + + return operation; + } + + /** + * @return true if term is normalized + */ + public boolean isNormalized() { + if (termHandler.getPossibleBetaReductions("").isEmpty() && termHandler.getNeededAlphaConversions("").isEmpty()) + return true; + return false; + } + + /** + * @return true if undo step is possible + */ + public boolean isUndoStepPossible() { + return termHistory.isUndoStepPossible(); + } + + /** + * @return true if redo step is possible + */ + public boolean isRedoStepPossible() { + return termHistory.isRedoStepPossible(); + } + + /** + * undo last step + * + * @param o observer + * @return applied operation as unicode character + */ + public String undoStep(Observer o) { + if (isUndoStepPossible()) { + termHistory.undoStep(); + processString(termHistory.getCurrentTerm(), o); + return termHistory.getCurrentOperation(); + } + return null; + } + + /** + * undo all steps + * + * @param o observer + * @return applied operation as unicode character + */ + public String undoAllSteps(Observer o) { + if (isUndoStepPossible()) { + termHistory.undoAllSteps(); + processString(termHistory.getCurrentTerm(), o); + return termHistory.getCurrentOperation(); + } + return null; + } + + /** + * redo step + * + * @param o observer + * @return applied operation as unicode character + */ + public String redoStep(Observer o) { + if (isRedoStepPossible()) { + termHistory.redoStep(); + processString(termHistory.getCurrentTerm(), o); + return termHistory.getCurrentOperation(); + } + return null; + } + + /** + * redo all steps + * + * @param o observer + * @return applied operation as unicode character + */ + public String redoAllSteps(Observer o) { + if (isRedoStepPossible()) { + termHistory.redoAllSteps(); + processString(termHistory.getCurrentTerm(), o); + return termHistory.getCurrentOperation(); + } + return null; + } + + /** + * sets a new working position + * + * @param pos working position + */ + public void selectTerm(String pos) { + workingPosition = pos; + } + + /** + * @return list of unused variables + */ + public Set getAllUnusedVars() { + return termHandler.getAllUnusedVars(); + } + + /** + * returns a list of positions of free vars in the selected subterm + * + * @return list of positions of free vars in the selected subterm + */ + public List getFreeVars() { + List l = new LinkedList(); + + //BindingIDs für Teilterm berechnen + termHandler.getSubTerm(workingPosition).recalculateBindingIDs(); + + for (Atom t : termHandler.getSubTerm(workingPosition).getFreeVarOccurences()) + l.add(t.getPosition()); + + //BindingIDs für root-Term wiederherstellen + termHandler.getSubTerm("").recalculateBindingIDs(); + + return l; + } + + /** + * returns a list of positions of bound vars in the selected subterm + * + * @return list of positions of bound vars in the selected subterm + */ + public List getBoundVars() { + List l = new LinkedList(); + + //BindingIDs für Teilterm berechnen + termHandler.getSubTerm(workingPosition).recalculateBindingIDs(); + + for (Atom t : termHandler.getSubTerm(workingPosition).getBoundVarOccurences()) + l.add(t.getPosition()); + + //BindingIDs für root-Term wiederherstellen + termHandler.getSubTerm("").recalculateBindingIDs(); + + return l; + } + + /** + * @return current term + */ + public String toString() { + return termHandler.toString(); + } + +} diff --git a/src/org/jalgo/module/lambda/controller/EToken.java b/src/org/jalgo/module/lambda/controller/EToken.java new file mode 100644 index 0000000..c33c981 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/EToken.java @@ -0,0 +1,5 @@ +package org.jalgo.module.lambda.controller; + +public enum EToken { + POPEN, PCLOSE, LAMBDA, SHORTCUT ,OTHER +} diff --git a/src/org/jalgo/module/lambda/controller/HistoryStep.java b/src/org/jalgo/module/lambda/controller/HistoryStep.java new file mode 100644 index 0000000..6f4f7a1 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/HistoryStep.java @@ -0,0 +1,55 @@ +/** + * Class Step + * + * @author Tobias Reiher + * @version 1.0 + */ +package org.jalgo.module.lambda.controller; + +public class HistoryStep { + + private String term; + private String operation; + private int stepNumber; + + /** + * initiates a step + * + * @param t term + * @param o applied operation + * @param n number of steps + */ + public HistoryStep(String t, String o, int n) { + term = t; + operation = o; + stepNumber = n; + } + + /** + * returns the term + * + * @return term + */ + public String getTerm() { + return term; + } + + /** + * returns the applied operation + * + * @return applied operation + */ + public String getOperation() { + return operation; + } + + /** + * returns the number of step + * + * @return number of step + */ + public int getStepNumber() { + return stepNumber; + } + +} diff --git a/src/org/jalgo/module/lambda/controller/HistoryTerm.java b/src/org/jalgo/module/lambda/controller/HistoryTerm.java new file mode 100644 index 0000000..a996da5 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/HistoryTerm.java @@ -0,0 +1,77 @@ +/** + * Class CTerm + * + * @author Tobias Reiher + * @version 1.0 + */ +package org.jalgo.module.lambda.controller; + +import java.util.ArrayList; +import java.util.List; + +public class HistoryTerm { + + private List list; + + public HistoryTerm() { + list = new ArrayList(); + } + + /** + * appends the step to the end of this list + * + * @param s step to be appended to this list + */ + public void add(HistoryStep s) { + list.add(s); + } + + /** + * removes the step at the specified position in this list + * + * @param index index of the step to be removed + */ + public void remove(int index) { + list.remove(index); + } + + /** + * returns the step at the specified position in this list + * + * @param index index of the step to return + * @return step at the specified position in this list + */ + public HistoryStep get(int index) { + return list.get(index); + } + + /** + * sets a view of the portion of this list between the specified + * fromIndex, inclusive, and toIndex, exclusive + * + * @param fromIndex low endpoint (inclusive) of the subList + * @param toIndex high endpoint (exclusive) of the subList + */ + public void setSubList(int fromIndex, int toIndex) { + list = list.subList(fromIndex, toIndex); + } + + /** + * returns the number of steps in this list + * + * @return number of steps in this list + */ + public int size() { + return list.size(); + } + + /** + * returns true if this list contains no steps + * + * @return true if this list contains no steps + */ + public boolean isEmpty() { + return list.isEmpty(); + } + +} diff --git a/src/org/jalgo/module/lambda/controller/IController.java b/src/org/jalgo/module/lambda/controller/IController.java new file mode 100644 index 0000000..b1e3c8a --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/IController.java @@ -0,0 +1,62 @@ +package org.jalgo.module.lambda.controller; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; +import java.util.Observer; +import java.util.Set; + +import org.jalgo.module.lambda.model.EAvailability; + +public interface IController { + + void run(); + + void loadData(ObjectInputStream in); + + void saveData(ObjectOutputStream out); + + LambdaException validateInputString(String s); + + LambdaException processInputString(String s, Observer o); + + boolean eliminateShortcut(); + + boolean eliminateAllShortcuts(); + + boolean matchShortcut(); + + boolean makeAllShortcuts(); + + boolean doAlphaConversion(String subst); + + EAvailability doBetaReduction(); + + String doStep(); + + String doShortcutStep(); + + String doAllSteps(); + + boolean isNormalized(); + + boolean isUndoStepPossible(); + + boolean isRedoStepPossible(); + + String undoStep(Observer o); + + String undoAllSteps(Observer o); + + String redoStep(Observer o); + + String redoAllSteps(Observer o); + + void selectTerm(String pos); + + Set getAllUnusedVars(); + + List getFreeVars(); + + List getBoundVars(); +} diff --git a/src/org/jalgo/module/lambda/controller/IParseUnit.java b/src/org/jalgo/module/lambda/controller/IParseUnit.java new file mode 100644 index 0000000..48837b6 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/IParseUnit.java @@ -0,0 +1,13 @@ +package org.jalgo.module.lambda.controller; + +import java.util.Observer; + +import org.jalgo.module.lambda.model.*; + +public interface IParseUnit { + + ITermHandler parseString(String s, Observer o) throws LambdaException; + + Term parseString(String s) throws LambdaException; + +} diff --git a/src/org/jalgo/module/lambda/controller/LambdaCalculus.tokens b/src/org/jalgo/module/lambda/controller/LambdaCalculus.tokens new file mode 100644 index 0000000..03d70d1 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/LambdaCalculus.tokens @@ -0,0 +1,23 @@ +SPOPEN=8 +ABSTRACTION=10 +LINE_COMMENT=20 +POPEN=6 +POINT=5 +APPLICATION=11 +LETTER=17 +SHORTCUTID=16 +WHITESPACE=18 +ATOM=12 +SHORTCUT=13 +PCLOSE=7 +CONS=15 +VAR=14 +LAMBDA=4 +COMMENT=19 +SPCLOSE=9 +'<'=8 +'('=6 +')'=7 +'.'=5 +'>'=9 +'\u03BB'=4 diff --git a/src/org/jalgo/module/lambda/controller/LambdaCalculusLexer.java b/src/org/jalgo/module/lambda/controller/LambdaCalculusLexer.java new file mode 100644 index 0000000..2ff26b2 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/LambdaCalculusLexer.java @@ -0,0 +1,648 @@ +// $ANTLR 3.1.3 Mar 18, 2009 10:09:25 /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g 2009-06-09 21:31:03 + + +package org.jalgo.module.lambda.controller; + +import org.antlr2.runtime.*; + + +public class LambdaCalculusLexer extends Lexer { + public static final int SPOPEN=8; + public static final int ABSTRACTION=10; + public static final int POPEN=6; + public static final int LINE_COMMENT=20; + public static final int POINT=5; + public static final int APPLICATION=11; + public static final int LETTER=17; + public static final int SHORTCUTID=16; + public static final int WHITESPACE=18; + public static final int ATOM=12; + public static final int EOF=-1; + public static final int SHORTCUT=13; + public static final int PCLOSE=7; + public static final int CONS=15; + public static final int VAR=14; + public static final int LAMBDA=4; + public static final int COMMENT=19; + public static final int SPCLOSE=9; + + // delegates + // delegators + + public LambdaCalculusLexer() {;} + public LambdaCalculusLexer(CharStream input) { + this(input, new RecognizerSharedState()); + } + public LambdaCalculusLexer(CharStream input, RecognizerSharedState state) { + super(input,state); + + } + public String getGrammarFileName() { return "/usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g"; } + + // $ANTLR start "LAMBDA" + public final void mLAMBDA() throws RecognitionException { + try { + int _type = LAMBDA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:10:8: ( '\\u03BB' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:10:10: '\\u03BB' + { + match('\u03BB'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "LAMBDA" + + // $ANTLR start "POINT" + public final void mPOINT() throws RecognitionException { + try { + int _type = POINT; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:11:7: ( '.' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:11:9: '.' + { + match('.'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "POINT" + + // $ANTLR start "POPEN" + public final void mPOPEN() throws RecognitionException { + try { + int _type = POPEN; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:12:7: ( '(' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:12:9: '(' + { + match('('); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "POPEN" + + // $ANTLR start "PCLOSE" + public final void mPCLOSE() throws RecognitionException { + try { + int _type = PCLOSE; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:13:8: ( ')' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:13:10: ')' + { + match(')'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "PCLOSE" + + // $ANTLR start "SPOPEN" + public final void mSPOPEN() throws RecognitionException { + try { + int _type = SPOPEN; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:14:8: ( '<' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:14:10: '<' + { + match('<'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "SPOPEN" + + // $ANTLR start "SPCLOSE" + public final void mSPCLOSE() throws RecognitionException { + try { + int _type = SPCLOSE; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:15:9: ( '>' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:15:11: '>' + { + match('>'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "SPCLOSE" + + // $ANTLR start "VAR" + public final void mVAR() throws RecognitionException { + try { + int _type = VAR; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:98:6: ( ( 'k' .. 'z' ) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:98:8: ( 'k' .. 'z' ) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:98:8: ( 'k' .. 'z' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:98:9: 'k' .. 'z' + { + matchRange('k','z'); + + } + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "VAR" + + // $ANTLR start "CONS" + public final void mCONS() throws RecognitionException { + try { + int _type = CONS; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:99:6: ( ( 'a' .. 'j' | '+' | '-' | '*' | '/' | '%' ) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:99:8: ( 'a' .. 'j' | '+' | '-' | '*' | '/' | '%' ) + { + if ( input.LA(1)=='%'||(input.LA(1)>='*' && input.LA(1)<='+')||input.LA(1)=='-'||input.LA(1)=='/'||(input.LA(1)>='a' && input.LA(1)<='j') ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "CONS" + + // $ANTLR start "SHORTCUTID" + public final void mSHORTCUTID() throws RecognitionException { + try { + int _type = SHORTCUTID; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:102:2: ( SPOPEN ( LETTER )+ SPCLOSE ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:102:4: SPOPEN ( LETTER )+ SPCLOSE + { + mSPOPEN(); + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:102:10: ( LETTER )+ + int cnt1=0; + loop1: + do { + int alt1=2; + int LA1_0 = input.LA(1); + + if ( ((LA1_0>='0' && LA1_0<='9')||(LA1_0>='A' && LA1_0<='Z')||(LA1_0>='a' && LA1_0<='z')) ) { + alt1=1; + } + + + switch (alt1) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:102:11: LETTER + { + mLETTER(); + + } + break; + + default : + if ( cnt1 >= 1 ) break loop1; + EarlyExitException eee = + new EarlyExitException(1, input); + throw eee; + } + cnt1++; + } while (true); + + mSPCLOSE(); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "SHORTCUTID" + + // $ANTLR start "LETTER" + public final void mLETTER() throws RecognitionException { + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:104:2: ( ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' ) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:104:4: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' ) + { + if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + } + finally { + } + } + // $ANTLR end "LETTER" + + // $ANTLR start "WHITESPACE" + public final void mWHITESPACE() throws RecognitionException { + try { + int _type = WHITESPACE; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:105:12: ( ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:105:15: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:105:15: ( '\\t' | ' ' | '\\r' | '\\n' | '\\u000C' )+ + int cnt2=0; + loop2: + do { + int alt2=2; + int LA2_0 = input.LA(1); + + if ( ((LA2_0>='\t' && LA2_0<='\n')||(LA2_0>='\f' && LA2_0<='\r')||LA2_0==' ') ) { + alt2=1; + } + + + switch (alt2) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g: + { + if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||(input.LA(1)>='\f' && input.LA(1)<='\r')||input.LA(1)==' ' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + break; + + default : + if ( cnt2 >= 1 ) break loop2; + EarlyExitException eee = + new EarlyExitException(2, input); + throw eee; + } + cnt2++; + } while (true); + + _channel = HIDDEN; + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "WHITESPACE" + + // $ANTLR start "COMMENT" + public final void mCOMMENT() throws RecognitionException { + try { + int _type = COMMENT; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:108:5: ( '/*' ( options {greedy=false; } : . )* '*/' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:108:9: '/*' ( options {greedy=false; } : . )* '*/' + { + match("/*"); + + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:108:14: ( options {greedy=false; } : . )* + loop3: + do { + int alt3=2; + int LA3_0 = input.LA(1); + + if ( (LA3_0=='*') ) { + int LA3_1 = input.LA(2); + + if ( (LA3_1=='/') ) { + alt3=2; + } + else if ( ((LA3_1>='\u0000' && LA3_1<='.')||(LA3_1>='0' && LA3_1<='\uFFFF')) ) { + alt3=1; + } + + + } + else if ( ((LA3_0>='\u0000' && LA3_0<=')')||(LA3_0>='+' && LA3_0<='\uFFFF')) ) { + alt3=1; + } + + + switch (alt3) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:108:42: . + { + matchAny(); + + } + break; + + default : + break loop3; + } + } while (true); + + match("*/"); + + _channel=HIDDEN; + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "COMMENT" + + // $ANTLR start "LINE_COMMENT" + public final void mLINE_COMMENT() throws RecognitionException { + try { + int _type = LINE_COMMENT; + int _channel = DEFAULT_TOKEN_CHANNEL; + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:5: ( '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:7: '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' + { + match("//"); + + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:12: (~ ( '\\n' | '\\r' ) )* + loop4: + do { + int alt4=2; + int LA4_0 = input.LA(1); + + if ( ((LA4_0>='\u0000' && LA4_0<='\t')||(LA4_0>='\u000B' && LA4_0<='\f')||(LA4_0>='\u000E' && LA4_0<='\uFFFF')) ) { + alt4=1; + } + + + switch (alt4) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:12: ~ ( '\\n' | '\\r' ) + { + if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFF') ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + break; + + default : + break loop4; + } + } while (true); + + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:26: ( '\\r' )? + int alt5=2; + int LA5_0 = input.LA(1); + + if ( (LA5_0=='\r') ) { + alt5=1; + } + switch (alt5) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:111:26: '\\r' + { + match('\r'); + + } + break; + + } + + match('\n'); + _channel=HIDDEN; + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "LINE_COMMENT" + + public void mTokens() throws RecognitionException { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:8: ( LAMBDA | POINT | POPEN | PCLOSE | SPOPEN | SPCLOSE | VAR | CONS | SHORTCUTID | WHITESPACE | COMMENT | LINE_COMMENT ) + int alt6=12; + alt6 = dfa6.predict(input); + switch (alt6) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:10: LAMBDA + { + mLAMBDA(); + + } + break; + case 2 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:17: POINT + { + mPOINT(); + + } + break; + case 3 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:23: POPEN + { + mPOPEN(); + + } + break; + case 4 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:29: PCLOSE + { + mPCLOSE(); + + } + break; + case 5 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:36: SPOPEN + { + mSPOPEN(); + + } + break; + case 6 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:43: SPCLOSE + { + mSPCLOSE(); + + } + break; + case 7 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:51: VAR + { + mVAR(); + + } + break; + case 8 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:55: CONS + { + mCONS(); + + } + break; + case 9 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:60: SHORTCUTID + { + mSHORTCUTID(); + + } + break; + case 10 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:71: WHITESPACE + { + mWHITESPACE(); + + } + break; + case 11 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:82: COMMENT + { + mCOMMENT(); + + } + break; + case 12 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:1:90: LINE_COMMENT + { + mLINE_COMMENT(); + + } + break; + + } + + } + + + protected DFA6 dfa6 = new DFA6(this); + static final String DFA6_eotS = + "\5\uffff\1\13\2\uffff\1\12\6\uffff"; + static final String DFA6_eofS = + "\17\uffff"; + static final String DFA6_minS = + "\1\11\4\uffff\1\60\2\uffff\1\52\6\uffff"; + static final String DFA6_maxS = + "\1\u03bb\4\uffff\1\172\2\uffff\1\57\6\uffff"; + static final String DFA6_acceptS = + "\1\uffff\1\1\1\2\1\3\1\4\1\uffff\1\6\1\7\1\uffff\1\12\1\10\1\5\1"+ + "\11\1\13\1\14"; + static final String DFA6_specialS = + "\17\uffff}>"; + static final String[] DFA6_transitionS = { + "\2\11\1\uffff\2\11\22\uffff\1\11\4\uffff\1\12\2\uffff\1\3\1"+ + "\4\2\12\1\uffff\1\12\1\2\1\10\14\uffff\1\5\1\uffff\1\6\42\uffff"+ + "\12\12\20\7\u0340\uffff\1\1", + "", + "", + "", + "", + "\12\14\7\uffff\32\14\6\uffff\32\14", + "", + "", + "\1\15\4\uffff\1\16", + "", + "", + "", + "", + "", + "" + }; + + static final short[] DFA6_eot = DFA.unpackEncodedString(DFA6_eotS); + static final short[] DFA6_eof = DFA.unpackEncodedString(DFA6_eofS); + static final char[] DFA6_min = DFA.unpackEncodedStringToUnsignedChars(DFA6_minS); + static final char[] DFA6_max = DFA.unpackEncodedStringToUnsignedChars(DFA6_maxS); + static final short[] DFA6_accept = DFA.unpackEncodedString(DFA6_acceptS); + static final short[] DFA6_special = DFA.unpackEncodedString(DFA6_specialS); + static final short[][] DFA6_transition; + + static { + int numStates = DFA6_transitionS.length; + DFA6_transition = new short[numStates][]; + for (int i=0; i", "", "", "", "LAMBDA", "POINT", "POPEN", "PCLOSE", "SPOPEN", "SPCLOSE", "ABSTRACTION", "APPLICATION", "ATOM", "SHORTCUT", "VAR", "CONS", "SHORTCUTID", "LETTER", "WHITESPACE", "COMMENT", "LINE_COMMENT" + }; + public static final int SPOPEN=8; + public static final int ABSTRACTION=10; + public static final int LINE_COMMENT=20; + public static final int POPEN=6; + public static final int POINT=5; + public static final int APPLICATION=11; + public static final int LETTER=17; + public static final int SHORTCUTID=16; + public static final int WHITESPACE=18; + public static final int ATOM=12; + public static final int EOF=-1; + public static final int SHORTCUT=13; + public static final int PCLOSE=7; + public static final int CONS=15; + public static final int VAR=14; + public static final int LAMBDA=4; + public static final int COMMENT=19; + public static final int SPCLOSE=9; + + // delegates + // delegators + + + public LambdaCalculusParser(TokenStream input) { + this(input, new RecognizerSharedState()); + } + public LambdaCalculusParser(TokenStream input, RecognizerSharedState state) { + super(input, state); + + } + + protected TreeAdaptor adaptor = new CommonTreeAdaptor(); + + public void setTreeAdaptor(TreeAdaptor adaptor) { + this.adaptor = adaptor; + } + public TreeAdaptor getTreeAdaptor() { + return adaptor; + } + + public String[] getTokenNames() { return LambdaCalculusParser.tokenNames; } + public String getGrammarFileName() { return "/usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g"; } + + + + + Term t; + protected void mismatch(IntStream input, int ttype, BitSet follow) + throws RecognitionException + { + System.out.println("aki1"); + throw new MismatchedTokenException(ttype, input); + + } + protected Object recoverFromMismatchedToken(IntStream input, + int ttype, + BitSet follow) + throws RecognitionException + { + + throw new MismatchedTokenException(ttype, input); + } + + + + + public static class start_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "start" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:73:1: start : term EOF ; + public final LambdaCalculusParser.start_return start() throws RecognitionException { + LambdaCalculusParser.start_return retval = new LambdaCalculusParser.start_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token EOF2=null; + LambdaCalculusParser.term_return term1 = null; + + + Object EOF2_tree=null; + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:73:7: ( term EOF ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:73:9: term EOF + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_term_in_start135); + term1=term(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, term1.getTree()); + EOF2=(Token)match(input,EOF,FOLLOW_EOF_in_start137); if (state.failed) return retval; + if ( state.backtracking==0 ) { + EOF2_tree = (Object)adaptor.create(EOF2); + adaptor.addChild(root_0, EOF2_tree); + } + + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "start" + + public static class term_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "term" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:74:1: term : ( atom | abstraction | application | shortcut | ( POPEN atom PCLOSE )=> atom ); + public final LambdaCalculusParser.term_return term() throws RecognitionException { + LambdaCalculusParser.term_return retval = new LambdaCalculusParser.term_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + LambdaCalculusParser.atom_return atom3 = null; + + LambdaCalculusParser.abstraction_return abstraction4 = null; + + LambdaCalculusParser.application_return application5 = null; + + LambdaCalculusParser.shortcut_return shortcut6 = null; + + LambdaCalculusParser.atom_return atom7 = null; + + + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:74:6: ( atom | abstraction | application | shortcut | ( POPEN atom PCLOSE )=> atom ) + int alt1=5; + switch ( input.LA(1) ) { + case VAR: + { + int LA1_1 = input.LA(2); + + if ( (true) ) { + alt1=1; + } + else if ( (synpred1_LambdaCalculus()) ) { + alt1=5; + } + else { + if (state.backtracking>0) {state.failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("", 1, 1, input); + + throw nvae; + } + } + break; + case CONS: + { + int LA1_2 = input.LA(2); + + if ( (true) ) { + alt1=1; + } + else if ( (synpred1_LambdaCalculus()) ) { + alt1=5; + } + else { + if (state.backtracking>0) {state.failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("", 1, 2, input); + + throw nvae; + } + } + break; + case POPEN: + { + int LA1_3 = input.LA(2); + + if ( (LA1_3==LAMBDA) ) { + alt1=2; + } + else if ( (LA1_3==POPEN||(LA1_3>=VAR && LA1_3<=SHORTCUTID)) ) { + alt1=3; + } + else { + if (state.backtracking>0) {state.failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("", 1, 3, input); + + throw nvae; + } + } + break; + case SHORTCUTID: + { + alt1=4; + } + break; + default: + if (state.backtracking>0) {state.failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("", 1, 0, input); + + throw nvae; + } + + switch (alt1) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:74:8: atom + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_atom_in_term144); + atom3=atom(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, atom3.getTree()); + + } + break; + case 2 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:75:5: abstraction + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_abstraction_in_term150); + abstraction4=abstraction(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, abstraction4.getTree()); + + } + break; + case 3 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:76:5: application + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_application_in_term157); + application5=application(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, application5.getTree()); + + } + break; + case 4 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:77:5: shortcut + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_shortcut_in_term164); + shortcut6=shortcut(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, shortcut6.getTree()); + + } + break; + case 5 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:79:5: ( POPEN atom PCLOSE )=> atom + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_atom_in_term183); + atom7=atom(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, atom7.getTree()); + + } + break; + + } + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "term" + + public static class atom_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "atom" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:83:1: atom : ( variable | constant ); + public final LambdaCalculusParser.atom_return atom() throws RecognitionException { + LambdaCalculusParser.atom_return retval = new LambdaCalculusParser.atom_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + LambdaCalculusParser.variable_return variable8 = null; + + LambdaCalculusParser.constant_return constant9 = null; + + + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:83:7: ( variable | constant ) + int alt2=2; + int LA2_0 = input.LA(1); + + if ( (LA2_0==VAR) ) { + alt2=1; + } + else if ( (LA2_0==CONS) ) { + alt2=2; + } + else { + if (state.backtracking>0) {state.failed=true; return retval;} + NoViableAltException nvae = + new NoViableAltException("", 2, 0, input); + + throw nvae; + } + switch (alt2) { + case 1 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:83:9: variable + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_variable_in_atom199); + variable8=variable(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, variable8.getTree()); + + } + break; + case 2 : + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:84:5: constant + { + root_0 = (Object)adaptor.nil(); + + pushFollow(FOLLOW_constant_in_atom206); + constant9=constant(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) adaptor.addChild(root_0, constant9.getTree()); + + } + break; + + } + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "atom" + + public static class variable_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "variable" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:86:1: variable : v= VAR -> ^( ATOM $v) ; + public final LambdaCalculusParser.variable_return variable() throws RecognitionException { + LambdaCalculusParser.variable_return retval = new LambdaCalculusParser.variable_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token v=null; + + Object v_tree=null; + RewriteRuleTokenStream stream_VAR=new RewriteRuleTokenStream(adaptor,"token VAR"); + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:86:9: (v= VAR -> ^( ATOM $v) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:86:11: v= VAR + { + v=(Token)match(input,VAR,FOLLOW_VAR_in_variable216); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_VAR.add(v); + + + + // AST REWRITE + // elements: v + // token labels: v + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + if ( state.backtracking==0 ) { + retval.tree = root_0; + RewriteRuleTokenStream stream_v=new RewriteRuleTokenStream(adaptor,"token v",v); + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (Object)adaptor.nil(); + // 86:17: -> ^( ATOM $v) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:86:20: ^( ATOM $v) + { + Object root_1 = (Object)adaptor.nil(); + root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(ATOM, "ATOM"), root_1); + + adaptor.addChild(root_1, stream_v.nextNode()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0;} + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "variable" + + public static class constant_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "constant" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:87:1: constant : c= CONS -> ^( ATOM $c) ; + public final LambdaCalculusParser.constant_return constant() throws RecognitionException { + LambdaCalculusParser.constant_return retval = new LambdaCalculusParser.constant_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token c=null; + + Object c_tree=null; + RewriteRuleTokenStream stream_CONS=new RewriteRuleTokenStream(adaptor,"token CONS"); + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:87:9: (c= CONS -> ^( ATOM $c) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:87:11: c= CONS + { + c=(Token)match(input,CONS,FOLLOW_CONS_in_constant233); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_CONS.add(c); + + + + // AST REWRITE + // elements: c + // token labels: c + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + if ( state.backtracking==0 ) { + retval.tree = root_0; + RewriteRuleTokenStream stream_c=new RewriteRuleTokenStream(adaptor,"token c",c); + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (Object)adaptor.nil(); + // 87:18: -> ^( ATOM $c) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:87:21: ^( ATOM $c) + { + Object root_1 = (Object)adaptor.nil(); + root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(ATOM, "ATOM"), root_1); + + adaptor.addChild(root_1, stream_c.nextNode()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0;} + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "constant" + + public static class abstraction_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "abstraction" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:89:1: abstraction : POPEN LAMBDA aa= variable POINT at= term PCLOSE -> ^( ABSTRACTION $aa $at) ; + public final LambdaCalculusParser.abstraction_return abstraction() throws RecognitionException { + LambdaCalculusParser.abstraction_return retval = new LambdaCalculusParser.abstraction_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token POPEN10=null; + Token LAMBDA11=null; + Token POINT12=null; + Token PCLOSE13=null; + LambdaCalculusParser.variable_return aa = null; + + LambdaCalculusParser.term_return at = null; + + + Object POPEN10_tree=null; + Object LAMBDA11_tree=null; + Object POINT12_tree=null; + Object PCLOSE13_tree=null; + RewriteRuleTokenStream stream_PCLOSE=new RewriteRuleTokenStream(adaptor,"token PCLOSE"); + RewriteRuleTokenStream stream_LAMBDA=new RewriteRuleTokenStream(adaptor,"token LAMBDA"); + RewriteRuleTokenStream stream_POPEN=new RewriteRuleTokenStream(adaptor,"token POPEN"); + RewriteRuleTokenStream stream_POINT=new RewriteRuleTokenStream(adaptor,"token POINT"); + RewriteRuleSubtreeStream stream_term=new RewriteRuleSubtreeStream(adaptor,"rule term"); + RewriteRuleSubtreeStream stream_variable=new RewriteRuleSubtreeStream(adaptor,"rule variable"); + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:90:2: ( POPEN LAMBDA aa= variable POINT at= term PCLOSE -> ^( ABSTRACTION $aa $at) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:90:4: POPEN LAMBDA aa= variable POINT at= term PCLOSE + { + POPEN10=(Token)match(input,POPEN,FOLLOW_POPEN_in_abstraction251); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_POPEN.add(POPEN10); + + LAMBDA11=(Token)match(input,LAMBDA,FOLLOW_LAMBDA_in_abstraction253); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_LAMBDA.add(LAMBDA11); + + pushFollow(FOLLOW_variable_in_abstraction257); + aa=variable(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) stream_variable.add(aa.getTree()); + POINT12=(Token)match(input,POINT,FOLLOW_POINT_in_abstraction259); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_POINT.add(POINT12); + + pushFollow(FOLLOW_term_in_abstraction263); + at=term(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) stream_term.add(at.getTree()); + PCLOSE13=(Token)match(input,PCLOSE,FOLLOW_PCLOSE_in_abstraction265); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_PCLOSE.add(PCLOSE13); + + + + // AST REWRITE + // elements: aa, at + // token labels: + // rule labels: retval, at, aa + // token list labels: + // rule list labels: + // wildcard labels: + if ( state.backtracking==0 ) { + retval.tree = root_0; + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + RewriteRuleSubtreeStream stream_at=new RewriteRuleSubtreeStream(adaptor,"rule at",at!=null?at.tree:null); + RewriteRuleSubtreeStream stream_aa=new RewriteRuleSubtreeStream(adaptor,"rule aa",aa!=null?aa.tree:null); + + root_0 = (Object)adaptor.nil(); + // 90:50: -> ^( ABSTRACTION $aa $at) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:90:53: ^( ABSTRACTION $aa $at) + { + Object root_1 = (Object)adaptor.nil(); + root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(ABSTRACTION, "ABSTRACTION"), root_1); + + adaptor.addChild(root_1, stream_aa.nextTree()); + adaptor.addChild(root_1, stream_at.nextTree()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0;} + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "abstraction" + + public static class application_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "application" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:91:1: application : POPEN t1= term t2= term PCLOSE -> ^( APPLICATION $t1 $t2) ; + public final LambdaCalculusParser.application_return application() throws RecognitionException { + LambdaCalculusParser.application_return retval = new LambdaCalculusParser.application_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token POPEN14=null; + Token PCLOSE15=null; + LambdaCalculusParser.term_return t1 = null; + + LambdaCalculusParser.term_return t2 = null; + + + Object POPEN14_tree=null; + Object PCLOSE15_tree=null; + RewriteRuleTokenStream stream_PCLOSE=new RewriteRuleTokenStream(adaptor,"token PCLOSE"); + RewriteRuleTokenStream stream_POPEN=new RewriteRuleTokenStream(adaptor,"token POPEN"); + RewriteRuleSubtreeStream stream_term=new RewriteRuleSubtreeStream(adaptor,"rule term"); + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:92:2: ( POPEN t1= term t2= term PCLOSE -> ^( APPLICATION $t1 $t2) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:92:4: POPEN t1= term t2= term PCLOSE + { + POPEN14=(Token)match(input,POPEN,FOLLOW_POPEN_in_application286); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_POPEN.add(POPEN14); + + pushFollow(FOLLOW_term_in_application290); + t1=term(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) stream_term.add(t1.getTree()); + pushFollow(FOLLOW_term_in_application294); + t2=term(); + + state._fsp--; + if (state.failed) return retval; + if ( state.backtracking==0 ) stream_term.add(t2.getTree()); + PCLOSE15=(Token)match(input,PCLOSE,FOLLOW_PCLOSE_in_application296); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_PCLOSE.add(PCLOSE15); + + + + // AST REWRITE + // elements: t2, t1 + // token labels: + // rule labels: t2, retval, t1 + // token list labels: + // rule list labels: + // wildcard labels: + if ( state.backtracking==0 ) { + retval.tree = root_0; + RewriteRuleSubtreeStream stream_t2=new RewriteRuleSubtreeStream(adaptor,"rule t2",t2!=null?t2.tree:null); + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + RewriteRuleSubtreeStream stream_t1=new RewriteRuleSubtreeStream(adaptor,"rule t1",t1!=null?t1.tree:null); + + root_0 = (Object)adaptor.nil(); + // 92:33: -> ^( APPLICATION $t1 $t2) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:92:36: ^( APPLICATION $t1 $t2) + { + Object root_1 = (Object)adaptor.nil(); + root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(APPLICATION, "APPLICATION"), root_1); + + adaptor.addChild(root_1, stream_t1.nextTree()); + adaptor.addChild(root_1, stream_t2.nextTree()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0;} + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "application" + + public static class shortcut_return extends ParserRuleReturnScope { + Object tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "shortcut" + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:93:1: shortcut : s= SHORTCUTID -> ^( SHORTCUT $s) ; + public final LambdaCalculusParser.shortcut_return shortcut() throws RecognitionException { + LambdaCalculusParser.shortcut_return retval = new LambdaCalculusParser.shortcut_return(); + retval.start = input.LT(1); + + Object root_0 = null; + + Token s=null; + + Object s_tree=null; + RewriteRuleTokenStream stream_SHORTCUTID=new RewriteRuleTokenStream(adaptor,"token SHORTCUTID"); + + try { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:93:9: (s= SHORTCUTID -> ^( SHORTCUT $s) ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:93:11: s= SHORTCUTID + { + s=(Token)match(input,SHORTCUTID,FOLLOW_SHORTCUTID_in_shortcut316); if (state.failed) return retval; + if ( state.backtracking==0 ) stream_SHORTCUTID.add(s); + + + + // AST REWRITE + // elements: s + // token labels: s + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + if ( state.backtracking==0 ) { + retval.tree = root_0; + RewriteRuleTokenStream stream_s=new RewriteRuleTokenStream(adaptor,"token s",s); + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (Object)adaptor.nil(); + // 93:24: -> ^( SHORTCUT $s) + { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:93:27: ^( SHORTCUT $s) + { + Object root_1 = (Object)adaptor.nil(); + root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(SHORTCUT, "SHORTCUT"), root_1); + + adaptor.addChild(root_1, stream_s.nextNode()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0;} + } + + retval.stop = input.LT(-1); + + if ( state.backtracking==0 ) { + + retval.tree = (Object)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + } + } + + catch (RecognitionException e) { + throw e; + } + finally { + } + return retval; + } + // $ANTLR end "shortcut" + + // $ANTLR start synpred1_LambdaCalculus + public final void synpred1_LambdaCalculus_fragment() throws RecognitionException { + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:79:5: ( POPEN atom PCLOSE ) + // /usr/users/sonstige/s9527146/Desktop/trunk/grammar/LambdaCalculus.g:79:6: POPEN atom PCLOSE + { + match(input,POPEN,FOLLOW_POPEN_in_synpred1_LambdaCalculus175); if (state.failed) return ; + pushFollow(FOLLOW_atom_in_synpred1_LambdaCalculus177); + atom(); + + state._fsp--; + if (state.failed) return ; + match(input,PCLOSE,FOLLOW_PCLOSE_in_synpred1_LambdaCalculus179); if (state.failed) return ; + + } + } + // $ANTLR end synpred1_LambdaCalculus + + // Delegated rules + + public final boolean synpred1_LambdaCalculus() { + state.backtracking++; + int start = input.mark(); + try { + synpred1_LambdaCalculus_fragment(); // can never throw exception + } catch (RecognitionException re) { + System.err.println("impossible: "+re); + } + boolean success = !state.failed; + input.rewind(start); + state.backtracking--; + state.failed=false; + return success; + } + + + + + public static final BitSet FOLLOW_term_in_start135 = new BitSet(new long[]{0x0000000000000000L}); + public static final BitSet FOLLOW_EOF_in_start137 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_atom_in_term144 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_abstraction_in_term150 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_application_in_term157 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_shortcut_in_term164 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_atom_in_term183 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_atom199 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_constant_in_atom206 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_VAR_in_variable216 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_CONS_in_constant233 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_POPEN_in_abstraction251 = new BitSet(new long[]{0x0000000000000010L}); + public static final BitSet FOLLOW_LAMBDA_in_abstraction253 = new BitSet(new long[]{0x0000000000004000L}); + public static final BitSet FOLLOW_variable_in_abstraction257 = new BitSet(new long[]{0x0000000000000020L}); + public static final BitSet FOLLOW_POINT_in_abstraction259 = new BitSet(new long[]{0x000000000001C040L}); + public static final BitSet FOLLOW_term_in_abstraction263 = new BitSet(new long[]{0x0000000000000080L}); + public static final BitSet FOLLOW_PCLOSE_in_abstraction265 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_POPEN_in_application286 = new BitSet(new long[]{0x000000000001C040L}); + public static final BitSet FOLLOW_term_in_application290 = new BitSet(new long[]{0x000000000001C040L}); + public static final BitSet FOLLOW_term_in_application294 = new BitSet(new long[]{0x0000000000000080L}); + public static final BitSet FOLLOW_PCLOSE_in_application296 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_SHORTCUTID_in_shortcut316 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_POPEN_in_synpred1_LambdaCalculus175 = new BitSet(new long[]{0x000000000000C000L}); + public static final BitSet FOLLOW_atom_in_synpred1_LambdaCalculus177 = new BitSet(new long[]{0x0000000000000080L}); + public static final BitSet FOLLOW_PCLOSE_in_synpred1_LambdaCalculus179 = new BitSet(new long[]{0x0000000000000002L}); + +} diff --git a/src/org/jalgo/module/lambda/controller/LambdaException.java b/src/org/jalgo/module/lambda/controller/LambdaException.java new file mode 100644 index 0000000..4d6dd73 --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/LambdaException.java @@ -0,0 +1,23 @@ +package org.jalgo.module.lambda.controller; + +public class LambdaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + + private int index; + + public LambdaException(){} + public LambdaException(String msg){ + super(msg); + } + public LambdaException(String msg, int index){ + super(msg); + this.index=index; + } + public int getIndex(){ + return this.index; + } + +} diff --git a/src/org/jalgo/module/lambda/controller/ParseUnit.java b/src/org/jalgo/module/lambda/controller/ParseUnit.java new file mode 100644 index 0000000..39648be --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/ParseUnit.java @@ -0,0 +1,505 @@ +package org.jalgo.module.lambda.controller; + +import java.util.LinkedList; +import java.util.Observer; + +import org.jalgo.module.lambda.ShortcutHandler; +import org.jalgo.module.lambda.model.Abstraction; +import org.jalgo.module.lambda.model.Application; +import org.jalgo.module.lambda.model.Atom; +import org.jalgo.module.lambda.model.Term; + +import org.antlr2.runtime.*; +import org.antlr2.runtime.tree.Tree; + +import org.jalgo.module.lambda.model.*; +import org.jalgo.main.util.Messages; + +/** + * The ParseUnit translates a given String into a Lambda Term Structure + * + * + */ +public class ParseUnit implements IParseUnit { + + private LinkedList klammers; + private LinkedList lambda; + + /** + * translates a given String into a Lambda Term Structure and puts it into an ITermHandler + * @param s the String to translate + * @param o the view that should observe the ITermHandler + * @return the ITermHandler object + * @throws RecognitionException + */ + public ITermHandler parseString(String s, Observer o) throws LambdaException { + Term term; + ITermHandler termHandler; + term = parseString(s); + termHandler = new TermHandler(term, o); + return termHandler; + } + + /** + * translates a given String into a Lambda Term Structure + * @param s the String to translate + * @return the Term structure + * @throws RecognitionException throws an ANTLR RecognitionException if there was an error during the parsing process + */ + public Term parseString(String s) throws LambdaException { + isValid(s); + this.klammers = new LinkedList(); + this.lambda = new LinkedList(); + s = preProcessing(s); + if(s == null) { + throw new LambdaException("Unbekannter Syntaxfehler!"/*Messages.getString("lambda", "ltxt.recognitionEx")*/); + } + LambdaCalculusLexer lex = new LambdaCalculusLexer(new ANTLRStringStream(s)); + CommonTokenStream tokens = new CommonTokenStream(lex); + LambdaCalculusParser parser = new LambdaCalculusParser(tokens); + try { + LambdaCalculusParser.start_return start = parser.start(); + Term t = translateAST((Tree)start.getTree()); + return t; + } catch (RecognitionException e){ + if(e instanceof MismatchedTokenException){ + int index; + if(e.charPositionInLine==-1) + index = decreaseIndex(e.index); + else + index = decreaseIndex(e.charPositionInLine); + String expected = nameToken(((MismatchedTokenException) e).expecting); + String found = nameToken(e.c); + String msg = Messages.getString("lambda","ltxt.recognitionEx2"); + msg = msg.replaceFirst("X", ""+index).replaceFirst("Y", expected).replaceFirst("Z",found); + throw new LambdaException(msg,index); + } + else{ + int index; + if(e.charPositionInLine==-1) + index = decreaseIndex(e.index); + else + index = decreaseIndex(e.charPositionInLine); + throw new LambdaException(Messages.getString("lambda","ltxt.recognitionEx").replaceFirst("X", ""+index),index); + } + } + } + /** + * Store the index of all the parenthesis add in the term + * @param list the list of the token + * @param index the index in the term list + */ + private void addIndexKlammer(LinkedListlist, int index){ + int n=-1; + for(int i=0;i=this.klammers.get(i)) + count++; + } + for(int i = 0;i=this.lambda.get(i)) + count+=2; + } + return index-count; + + } + /** + * Given some token return the name of the token in a Human readable form + * @param token the token + * @return the token's name + */ + private String nameToken(int token) { + switch (token) { + case LambdaCalculusLexer.ABSTRACTION: return Messages.getString("lambda","ltxt.errorAbstraction"); + case LambdaCalculusLexer.APPLICATION: return Messages.getString("lambda","ltxt.errorApplication"); + case LambdaCalculusLexer.LAMBDA: return "\u03BB"; + case LambdaCalculusLexer.POPEN: return "("; + case LambdaCalculusLexer.PCLOSE: return ")"; + case LambdaCalculusLexer.SPCLOSE: return "<"; + case LambdaCalculusLexer.SPOPEN: return ">"; + case LambdaCalculusLexer.ATOM: return Messages.getString("lambda","ltxt.errorAtom"); + case LambdaCalculusLexer.LETTER: return Messages.getString("lambda","ltxt.errorLetter"); + case LambdaCalculusLexer.CONS: return Messages.getString("lambda","ltxt.errorCons"); + case LambdaCalculusLexer.VAR: return Messages.getString("lambda","ltxt.errorLetter"); + case LambdaCalculusLexer.SHORTCUT: return Messages.getString("lambda","ltxt.errorShortcut1"); + case LambdaCalculusLexer.SHORTCUTID: return Messages.getString("lambda","ltxt.errorShortcut1"); + case LambdaCalculusLexer.POINT: return Messages.getString("lambda","ltxt.errorPoint"); + case LambdaCalculusLexer.EOF: return Messages.getString("lambda","ltxt.errorEof"); + default: return ""+token; + } + } + + /** + * translates an abstract synthax tree into a Term structure + * @param t the tree to translate + * @return the Term structure + */ + private Term translateAST(Tree t) throws LambdaException { + if(t.toString() == "nil") { + return translateAST(t.getChild(0)); + } + else if(t.toString() == "SHORTCUT") { + Term term; + try{ + term = ShortcutHandler.getInstance().getShortcutCloneByRepresentation(t.getChild(0).toString()); + return term; + } + catch(IllegalArgumentException ex){ + String msg = Messages.getString("lambda","ltxt.errorShortcut").replaceFirst("X", t.getChild(0).toString()); + throw new LambdaException(msg); + } + + } + else if(t.toString() == "ATOM") { + return new Atom(t.getChild(0).toString()); + } + else if(t.toString() == "APPLICATION") { + if(t.getChildCount() == 2){ + Term rterm = translateAST(t.getChild(0)); + Term lterm = translateAST(t.getChild(1)); + Application application = new Application(rterm,lterm); + rterm.setParent(application); + lterm.setParent(application); + return application; + } + else + throw new LambdaException(Messages.getString("lambda","ltxt.errorApplication")); + } + else if(t.toString() == "ABSTRACTION") { + if(t.getChildCount() == 2 && t.getChild(0).toString() == "ATOM"){ + Atom var = (Atom)translateAST(t.getChild(0)); + Term child = translateAST(t.getChild(1)); + Abstraction abstraction = new Abstraction(var, child); + var.setParent(abstraction); + child.setParent(abstraction); + return abstraction; + } + else + throw new LambdaException(Messages.getString("lambda","ltxt.errorAbstraction")); + } + return null; + } + /** + * verify if the term given is valid + * @param s term to validate + * @return True if term is valid, false otherwise + */ + private boolean isValid(String s) throws LambdaException { + //return true; + String allowed = new String ("+-*/%().<>Y"); //allowed character + allowed+='\u03BB'; + for(int i=0; i= 'a' && s.charAt(i) <= 'z') &&!(s.charAt(i) >= '0' && s.charAt(i) <= '9') && !(allowed.contains(""+s.charAt(i))) ) + throw new LambdaException(Messages.getString("lambda","ltxt.errorForbidden"),i); + } + + return true; + } + /** + * PreProcessing parser: the PreProcessing transform the term given for the user and + * transform it to a "vollklammer" term + * @param input term to Parser + * @return a list with the tokens found. + */ + private LinkedList spliter(String input){ + try{ + int j; + LinkedList list = new LinkedList(); + + for(int i=0; i < input.length(); i++){ + switch (input.charAt(i)){ + case ' ': + break; + case '(': + String [] s = {EToken.POPEN.toString() ,input.charAt(i)+""}; + list.add(s); + break; + case')': + String [] s1 = {EToken.PCLOSE.toString(),input.charAt(i)+""}; + list.add(s1); + break; + case '\u03BB': + String aux=""; + for(j=i;j separateLambda(LinkedList list, int index){ + + if(!list.get(index)[0].equals(EToken.LAMBDA.toString())) + return list; + int count = 0; + String [] neue, aux; + String tmp; + aux = list.get(index); + String lambda = aux[1]; + + while(lambda.length()>3){ + tmp = lambda.charAt(2)+""; + lambda = lambda.substring(0, 2) + lambda.substring(2+1, lambda.length()); + aux[1] = lambda; + list.set(index, aux); + + neue = new String [2]; + neue[0] = EToken.LAMBDA.toString(); + neue[1] = '\u03BB' + tmp+"."; + + list.add(index+1+count, neue); + count+=1; + + int n=-1; + for(int i=0;i insertBeforLambda(LinkedList list, int index){ + String [] current; + int countP=0; + String [] POpen = {EToken.POPEN.toString() ,"("}; + String [] PClose = {EToken.PCLOSE.toString(),")"}; + list.add(index, POpen); + + for(int i=index+1;i < list.size(); i++){ + current = list.get(i); + if(current[0].equals(EToken.POPEN.toString())){ + countP++; + } + else if(current[0].equals(EToken.PCLOSE.toString())){ + countP--; + } + if(countP < 0){ + addIndexKlammer(list, index); + addIndexKlammer(list, i); + list.add(i, PClose); + break; + } + + } + + + return list; + } + /** + * Insert the parenthesis in a founded application + * @param list The list with the Tokens + * @param index the index where the application was found. + * @return a list with the tokens + */ + private LinkedList insertP(LinkedList list, int index){ + String [] current; + int i, countP=0; + String [] POpen = {EToken.POPEN.toString() ,"("}; + String [] PClose = {EToken.PCLOSE.toString(),")"}; + addIndexKlammer(list, index+1); + list.add(index+1, PClose); + for(i=index; i>0 ;i--){ + current = list.get(i); + if(current[0].equals(EToken.POPEN.toString())){ + countP--; + } + else if(current[0].equals(EToken.PCLOSE.toString())){ + countP++; + } + if(countP < 0) + break; + } + addIndexKlammer(list, i); + list.add(i, POpen); + + return list; + } + /** + * Insert the parenthesis in a founded Abstraction + * @param list The list with the Tokens + * @param index the index where the application was found. + * @return a list with the tokens + */ + private LinkedList insertPInAbstraction(LinkedList list, int index){ + separateLambda(list,index); + + String [] current, befor, next; + int countP=0; + int count=0; + String [] POpen = {EToken.POPEN.toString() ,"("}; + String [] PClose = {EToken.PCLOSE.toString(),")"}; + + if(index+10) + befor = list.get(i-1); + else + befor= null; + if(!current[0].equals(EToken.PCLOSE.toString())) + count++; + if(current[0].equals(EToken.POPEN.toString())){ + countP++; + } + else if(current[0].equals(EToken.PCLOSE.toString())){ + countP--; + } + if(countP < 0 || i+1 >= list.size()){ + if((count>1 && befor != null &&!befor[0].equals(EToken.PCLOSE.toString())) + || (next!=null && !next[0].equals(EToken.POPEN.toString()) && count >1)){ + addIndexKlammer(list, index+1); + addIndexKlammer(list, i); + list.add(i, PClose); + } + else + list.remove(index+1); + break; + } + + + } + return list; + + } + /** + * Transform the term given for the user to a expression with all + * the parenthesis needed for the Lexer and the Parser(this will would + * name it "vollklammer term"). + * @param list The list with the Tokens + * @return a "vollklammer" term + */ + private String vollklammer(LinkedList list){ + int index; + int count=0; + String [] current; + String next, befor, first, last=""; + String [] POpen = {EToken.POPEN.toString() ,"("}; + String [] PClose = {EToken.PCLOSE.toString(),")"}; + + first = list.get(0)[0]; + if(list.size()>0) + last = list.get(list.size()-1)[0]; + + // Check if the term have the first and the last parenthesis. + if((first!= EToken.POPEN.toString() || last != EToken.PCLOSE.toString()) && list.size()>1){ + list.add(0, POpen); + addIndexKlammer(list, 0); + list.add(list.size(), PClose); + addIndexKlammer(list, list.size()); + } + + for(index=0; index < list.size(); index++){ + current = list.get(index); + if(index-1 >0) + befor = list.get(index-1)[0]; + else + befor = null; + if(index+1 < list.size()) + next = list.get(index+1)[0]; + else + next = null; + + if(current[0].equals(EToken.LAMBDA.toString())){ + if(befor!= null &&!befor.equals(EToken.POPEN.toString())){ + insertBeforLambda(list, index); + index++; + } + list = insertPInAbstraction(list, index); + + }else if(current[0].equals(EToken.OTHER.toString())){ + count++; + } + else if(current[0].equals(EToken.SHORTCUT.toString())) + count++; + else + count=0; + + if((befor!= null && befor.equals(EToken.PCLOSE.toString()) && count >=1 && next != null && !next.equals(EToken.PCLOSE.toString()) ) + ||(count==2 && next != null && !next.equals(EToken.PCLOSE.toString()))){ + list = insertP(list, index); + index++; + count--; + } + } + String fin=""; + String [] a; + for(int i = 0; i< list.size();i++) + { + a= list.get(i); + fin += a[1]; + } + return fin; + } + /** + * Transform the term given for the user to a expression with all + * the parenthesis needed for the Lexer and the Parser + * @param input the term given for the user + * @return the term with all the parenthesis + */ + public String preProcessing(String input){ + LinkedList list = this.spliter(input); + if(list == null) + return null; + + return this.vollklammer(list); + } + + +} diff --git a/src/org/jalgo/module/lambda/controller/TermHistory.java b/src/org/jalgo/module/lambda/controller/TermHistory.java new file mode 100644 index 0000000..f5c902f --- /dev/null +++ b/src/org/jalgo/module/lambda/controller/TermHistory.java @@ -0,0 +1,173 @@ +/** + * Class TermHistory + * + * @author Tobias Reiher + * @version 1.0 + */ +package org.jalgo.module.lambda.controller; + +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; + +public class TermHistory extends Observable { + + private List termList; + private int currentTerm; + private int currentStep; + + /** + * initializes attributes and add observer + * + * @param o observer + */ + public TermHistory(Observer o) { + this.addObserver(o); + termList = new LinkedList(); + currentTerm = -1; + currentStep = -1; + } + + /** + * creates a new empty HistoryTerm and deletes all further steps + */ + public void createTerm() { + if (currentTerm > -1) { + termList.get(currentTerm).setSubList(0, currentStep+1); + termList = termList.subList(0, currentTerm+1); + } + if (currentTerm == -1 || !termList.get(currentTerm).isEmpty()) { + currentStep = -1; + termList.add(new HistoryTerm()); + currentTerm++; + } + } + + /** + * adds step to current term + * + * @param term term + * @param operation operation as unicode character + * @param i step number + */ + public void addStep(String term, String operation, int i) { + termList.get(currentTerm).setSubList(0, currentStep+1); + termList = termList.subList(0, currentTerm+1); + termList.get(currentTerm).add(new HistoryStep(term, operation, getCurrentStepNumber()+i)); + currentStep++; + setChanged(); + notifyObservers(); + } + + /** + * @return true if undo step is possible + */ + public boolean isUndoStepPossible() { + if (currentTerm > 0 || currentStep > 0) + return true; + return false; + } + + /** + * @return true if redo step is possible + */ + public boolean isRedoStepPossible() { + if (termList.size() > 0 && (currentTerm < termList.size()-1 || currentStep < termList.get(currentTerm).size()-1)) + return true; + return false; + } + + /** + * undo last step + */ + public void undoStep() { + currentStep--; + if (currentStep < 0) { + currentTerm--; + currentStep = termList.get(currentTerm).size()-1; + } + setChanged(); + notifyObservers(termList.get(currentTerm).get(0).getTerm()); + } + + /** + * undo all steps + */ + public void undoAllSteps() { + currentTerm = 0; + currentStep = 0; + setChanged(); + notifyObservers(termList.get(currentTerm).get(0).getTerm()); + } + + /** + * redo step + */ + public void redoStep() { + currentStep++; + if (currentStep >= termList.get(currentTerm).size()) { + currentTerm++; + currentStep = 0; + } + setChanged(); + notifyObservers(termList.get(currentTerm).get(0).getTerm()); + } + + /** + * redo all steps + */ + public void redoAllSteps() { + currentTerm = termList.size()-1; + currentStep = termList.get(currentTerm).size()-1; + setChanged(); + notifyObservers(termList.get(currentTerm).get(0).getTerm()); + } + + /** + * returns a concatenated list of strings: performed operation as unicode character + term + * + * @return list of HistoryTerm steps from first to current step, null if current step is lower equal 0 + */ + public List getCurrentTermSteps() { + List list = new LinkedList(); + if (currentStep <= 0) { + return null; + } + for (int i = 0; i <= currentStep-1; i++) { + list.add(termList.get(currentTerm).get(i).getOperation() + termList.get(currentTerm).get(i).getTerm()); + } + return list; + } + + /** + * @return number of current step + */ + public int getCurrentStepNumber() { + if (currentTerm >= 0 && currentStep >= 0) + return termList.get(currentTerm).get(currentStep).getStepNumber(); + return 0; + } + + /** + * @return term of the first step of the current term + */ + public String getFirstTerm() { + return termList.get(currentTerm).get(0).getTerm(); + } + + /** + * @return term of the current step of the current term + */ + public String getCurrentTerm() { + return termList.get(currentTerm).get(currentStep).getTerm(); + } + + /** + * @return operation of the current step of the current term + */ + public String getCurrentOperation() { + return termList.get(currentTerm).get(currentStep).getOperation(); + } + +} diff --git a/src/org/jalgo/module/lambda/de.properties b/src/org/jalgo/module/lambda/de.properties new file mode 100644 index 0000000..991a81f --- /dev/null +++ b/src/org/jalgo/module/lambda/de.properties @@ -0,0 +1,88 @@ +Module_name=Lambda Kalkül +Module_version=1.0 +Module_authors=Frank Dietze, Tobias Reiher, Benjamin Schneider, Nico Braunisch, Joshua Peschke, Francisco Rojas +Module_license=GNU General Public License +Module_description_1=Dieses Modul behandelt das Lambda Kalkül. +Module_description_2=... + +btxt.done=OK +btxt.clear=Löschen +btxt.toList=zur Liste + +bts.done=Eingabe beenden. +bts.clear=Löscht das Eingabefeld. +bts.insertSC=Fügt die Abkürzung an der Cursorposition ein. +bts.deleteSC=Löscht die markierte Abkürzung. +bts.newSC=Erstellt aus dem Term im Eingabefeld eine neue Abkürzung. +bts.toList=Fügt den Term der Liste hinzu. +bts.doStep=Führt den nächsten Schritt aus. +bts.doShortcutStep=Führt einen Rechenschritt auf Abkürzungen aus. +bts.undoStep=Nimmt den aktuellen Schritt zurück. +bts.doAllSteps=Führt alle Schritte aus. +bts.undoAllSteps=Nimmt alle Schritte zurück. +bts.alpha=Führt eine Alpha-Konversion durch. +bts.beta=Führt eine Beta-Reduktion durch. +bts.markFreeVars=Zeigt alle freien Variablen. +bts.markBoundVars=Zeigt alle gebundenen Variablen. +bts.showhideBrackets=Zeigt oder verbirgt Klammern. +bts.shortcutDialog=Zeigt/Verbirgt die Auswahlliste der Abkürzungen. +bts.shortcutEliminate=Löst einen Shortcut auf. +bts.shortcutMatch=Ersetzt den selektierten Term durch eine definierte Abkürzung. +bts.doAutoStep=Führt einen automatischen Rechenschritt aus. +bts.doAllAutoSteps=Führt so viele Rechenschritte wie möglich automatisch aus. + +ltxt.input=Bitte Lambda-Term eingeben (mit Variablen k..z, allen Klammern und \u03bb = backslash). +ltxt.toList=Term wurde in die Liste eingetragen. +ltxt.termCorrect=Lambda-Term korrekt. +ltxt.termIncorrect=Lambda-Term nicht korrekt. +ltxt.alphaFailed=Alpha-Conversion fehlgeschlagen. Markieren Sie eine Abstraktion! +ltxt.alphaNoVars=Alpha-Conversion nicht möglich, alle Variablen verbraucht. +ltxt.betaFailed=Beta-Reduktion fehlgeschlagen. Markieren Sie eine Applikation! +ltxt.alphaNeeded=Zunächst ist eine Alpha-Conversion erforderlich! + +ltxt.recognitionEx=Syntaxfehler bei Zeichen Nummer X gefunden. +ltxt.recognitionEx2= An Position X wurde Y erwartet aber Z gefunden. +ltxt.errorApplication= Die Applikation hatte weniger als 2 Kinder. +ltxt.errorAbstraction=Die Abstraktion hatte weniger als 2 Kinder. +ltxt.errorForbidden=Es sind verbotene Zeichen enthalten. Erlaubt sind a..z,(,),+,-,*,/ und % sowie definierte Abkürzungen. +ltxt.errorAbstraction =eine Abstraktion +ltxt.errorApplication =eine Applikation +ltxt.errorAtom =eine Variable oder eine Konstante +ltxt.errorLetter =eine Variable +ltxt.errorCons =eine Konstante +ltxt.errorShortcut1 =eine Abkürzung +ltxt.errorPoint =ein Punkt +ltxt.errorEof =nichts +ltxt.errorShortcut=Die Abkürzung X wurde nicht gefunden. +ltxt.inputSCTerm=Bitte geben Sie den Term der Abkürzung ein (mit Variablen k..z, allen Klammern und \u03bb = backslash). +ltxt.scNameFault=Abkürzungen müssen mit < beginnen und mit > enden! +ltxt.scNameExists=Dieser Name existiert bereits für eine Abkürzung! Bitte anderen Namen eingeben. +ltxt.scTermExists=Dieser Term ist bereits als Abkürzung vorhanden! + +dia.alphaTitle=Auswahldialog der Variablen-Ersetzung +dia.alphaMessage=Bitte wählen Sie aus den verfügbaren Variablen eine aus. +dia.clearMessage=Soll dieser Term aus der Liste entfernt werden? +dia.newclearMessageTitel=Auswahl-Liste bearbeiten +dia.newTermMessage=Soll dieser Term in die Liste aufgenommen werden? + +scDlg.title=Shortcut auswählen oder erstellen +scDlg.clsBtn=Schließen +scDlg.insBtn=Einf +scDlg.delBtn=Entf +scDlg.newBtn=Neu +scDlg.crtBtn=Erstellen +scDlg.lblTxt=Shortcut Text +scDlg.lblTrm=Shortcut Term +scDlg.ShortcutEmpty=Das Shortcutfeld ist leer +scDlg.TermEmpty=Das Termfeld ist leer. +scDlg.ShortcutExist=Dieser Shortcut ist schon vorhanden. +scDlg.ListLabel=Liste der Abkürzungen +scDlg.ListLabel2=Neue Abkürzungen definieren +scDlg.inputSCLabel=Name der Abkürzung + +wlc.new=Lambdaterm eingeben +wlc.load=Lambdaterm laden + +ModuleConnector.Load_Error=Fehler beim Laden der Datei. +ModuleConnector.Save_Error=Fehler beim Speichern der Datei. +ModuleConnector.File_damaged=Datei beschädigt. \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/en.properties b/src/org/jalgo/module/lambda/en.properties new file mode 100644 index 0000000..255cc24 --- /dev/null +++ b/src/org/jalgo/module/lambda/en.properties @@ -0,0 +1,88 @@ +Module_name=Lambda Calculus +Module_version=1.0 +Module_authors=Frank Dietze, Tobias Reiher, Benjamin Schneider, Nico Braunisch, Joshua Peschke, Francisco Rojas +Module_license=GNU General Public License +Module_description_1=This module handels the lambda calculus. +Module_description_2=... + +btxt.done=OK +btxt.clear=Clear +btxt.toList=add to List + +bts.done=Finish the input. +bts.clear=Clears the inputfield. +bts.insertSC=Inserts the selected shortcut at cursor position. +bts.deleteSC=Deletes the selected shortcut. +bts.newSC=Creates a new shortcut from the term of the inputfield. +bts.toList=Adds the term to the list. +bts.doStep=Do the next step. +bts.doShortcutStep=Performs a step on shortcuts. +bts.undoStep=Undo the last step. +bts.doAllSteps=Do all steps. +bts.undoAllSteps=Undo all steps. +bts.alpha=Do alpha-conversion. +bts.beta=Do beta-reduction. +bts.markFreeVars=Mark free variables. +bts.markBoundVars=Mark bound variables. +bts.showhideBrackets=Show or hide brackets. +bts.shortcutDialog=Show/Hide list of shortcuts. +bts.shortcutEliminate=Break shortcut(s) down. +bts.shortcutMatch=Makes a defined shortcut out of the selected term. +bts.doAutoStep=Performs an automatic step. +bts.doAllAutoSteps=Performs as many automatic steps as possible. + +ltxt.input=Please input Lambda-Term (with k..z as variables, all brackets and \u03bb = backslash) +ltxt.toList=Term was added to the list. +ltxt.termCorrect=Lambda-Term correct. +ltxt.termIncorrect=Lambda-Term incorrect. +ltxt.alphaFailed=Alpha-Conversion failed. Mark an Abstraction! +ltxt.alphaNoVars=Alpha-Conversion impossible, no unused variables left. +ltxt.betaFailed=Beta-Reduction failed. Mark an Application. +ltxt.alphaNeeded=Alpha-Conversion needed. + +ltxt.recognitionEx=An error occured while parsing at letter number X. +ltxt.recognitionEx2=Expected X at position Y but found Z. +ltxt.errorApplication=Application had less than 2 children. +ltxt.errorAbstraction=Abstraction had less than 2 children. +ltxt.errorForbidden=There are forbidden characters. Allowed are a..z,(,),+,-,*,/ and % as well as defined shortcuts. +ltxt.errorAbstraction =an abstraction +ltxt.errorApplication =an application +ltxt.errorAtom =a variable or constant +ltxt.errorLetter =a variable +ltxt.errorCons =a constant +ltxt.errorShortcut1 =a shortcut +ltxt.errorPoint =a point +ltxt.errorEof=no character +ltxt.errorShortcut = The shortcut X was not found. +ltxt.inputSCTerm=Please input the term of the shortcut (with k..z as variables, all brackets and \u03bb = backslash) +ltxt.scNameFault=Shortcut-names have to start with < and end with > ! +ltxt.scNameExists=This shortcut-name already exists! Please input another name. +ltxt.scTermExists=This term already exists as a shortcut! + +dia.alphaTitle=Select variable +dia.alphaMessage=Please choose one of the available variables. +dia.clearMessage=Should this term be removed from the list? +dia.newclearMessageTitel=Change dropdown-list +dia.newTermMessage=Should this term be added to the list? + +scDlg.title=Choose or Create Shortcut +scDlg.clsBtn=Close +scDlg.insBtn=Ins +scDlg.delBtn=Del +scDlg.newBtn=New +scDlg.crtBtn=Create +scDlg.lblTxt=Shortcut Text +scDlg.lblTrm=Shortcut Term +scDlg.ShortcutEmpty=The shortcut field is empty. +scDlg.TermEmpty=The term field is empty. +scDlg.ShortcutExist=This Shortcut already exists. +scDlg.ListLabel=List of shortcuts +scDlg.ListLabel2=Define new shortcuts +scDlg.inputSCLabel=Name of the shortcut + +wlc.new=Enter Lambdaterm +wlc.load=Load Lambdaterm + +ModuleConnector.Load_Error=Error while loading file. +ModuleConnector.Save_Error=Error while saving file. +ModuleConnector.File_damaged=File damaged. \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/model/Abstraction.java b/src/org/jalgo/module/lambda/model/Abstraction.java new file mode 100644 index 0000000..4cc7da7 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Abstraction.java @@ -0,0 +1,265 @@ +/** + * Class abstraction that represent a abstraction in the labdaterme + * This Class is Composit of the Term Composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +public class Abstraction extends Term { + + private Term term; + + private Atom var; + + public Abstraction(Atom var, Term term) { + this.term = term; + this.var = var; + } + + /** + * This Method return all subterms of the current term include the current term + * @return List of all Children + */ + public List getAllChildren() { + List children = new LinkedList(); + children.add(this); + //children.addAll(var.getAllChildren()); + children.addAll(term.getAllChildren()); + return children; + } + + @Override + /** + * Getter for TermType + * return termtype of abstraction + */ + public ETermType getTermType() { + return ETermType.ABSTRACTION; + } + + @Override + /** + * Getter for subterms + * + * @param position l = linker Teilterm r = rechter Teilterm + * + * @return term at position + */ + public Term getSubTerm(String position) { + if (position != null) { + if (!position.equals("")) { + if (position.startsWith("a")) { + position = position.substring(1); + return term.getSubTerm(position); + } else { + throw new NoSuchElementException(); + } + } else { + return this; + } + } else { + throw new IllegalArgumentException(" @ "+ position); + } + } + + @Override + /* + * * + * + * @return String represents a lambaterm without format + */ + public String toString() { + return "(\u03bb" + var.toString() + "." + term.toString() + ")"; + } + + @Override + /* + * * + * + * @param position l = linker Teilterm r = rechter Teilterm *@param + * showBrackets vollgeklammert = true + * + * @return list of subterms with format + */ + public List toFormatString(String pos, boolean showBrackets) { + + this.position = pos; + + LinkedList fliste = new LinkedList(); + Set format = new HashSet(); + if (showBrackets) { + fliste.add(new FormatString("(", format, pos)); + fliste.add(new FormatString("\u03bb" + var.toString() + ".", + format, pos)); + fliste.addAll(term.toFormatString(pos + "a", showBrackets)); + fliste.add(new FormatString(")", format, pos)); + } else { + if ((parent == null) + || (parent.getTermType() != ETermType.ABSTRACTION)) { + fliste.add(new FormatString("\u03bb", format, pos)); + } + fliste.add(new FormatString(var.toString(), format, pos)); + if (term.getTermType() != ETermType.ABSTRACTION) { + fliste.add(new FormatString(".", format, pos)); + } + fliste.addAll(term.toFormatString(pos + "a", showBrackets)); + } + return fliste; + } + + @Override + /* + * * + * + * @param boundvars Set of Variables bound by Abstraction + */ + public void recalculateBindingIDs(Set boundvars) { + var.setBindingID(getPosition()); + Set newBoundvars = new HashSet(); + newBoundvars.add(var); + newBoundvars.addAll(boundvars); + term.recalculateBindingIDs(newBoundvars); + } + + @Override + /* + * * + * + * @param pos Positionstring l = linker Teilterm r = rechter Teilterm + * + * @param newTerm new subterm for position + */ + public boolean replaceChild(String pos, Term newterm) { + if (pos != null) { + if (pos.equals("a")) { + term = newterm; + //term.setParent(this); + return true; + } else if (pos.equals("v")) { + var = (Atom) newterm; + //var.setParent(this); + return true; + } else if (pos.startsWith("a")) { + return term.replaceChild(pos.substring(1), newterm); + } else { + throw new NoSuchElementException(); + } + } else { + throw new IllegalArgumentException(); + } + + } + + @Override + /* + * * + * + * @return returns left and right part of abstraction + */ + public List getChildren() { + List children = new LinkedList(); + children.add(var); + children.add(term); + return children; + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newName name for variable at position + * + * @return true= alphaconversion solved + */ + public boolean alphaConvert(String bindingID, String newName) { + boolean t = term.alphaConvert(bindingID, newName); + boolean v = var.alphaConvert(bindingID, newName); + return (t || v); + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newTerm new subterm for position + * + * @return further Term at position + */ + public Term replaceVarsByBindingID(String bindingID, Term t) { + if (bindingID.equals(getPosition())) + throw new RuntimeException( + "Bound var about was about to be replaced!"); + + Term newTerm = new Abstraction((Atom) var.clone(), term.replaceVarsByBindingID(bindingID, t)); + //newTerm.setParent(this.parent); + + return newTerm; + } + + /** + * @ return returns cloned term + */ + public Term clone() { + Abstraction a = new Abstraction((Atom)var.clone(), term.clone()); + //a.setParent(parent); + return a; + } + + @Override + /* + * * + * + * @ return returns set of bound Variables + */ + public Set getBoundVars() { + Set set = new HashSet(); + set.add(var); + set.addAll(term.getBoundVars()); + return set; + } + + public List getBoundVarOccurences() { + List l = new LinkedList(); + l.addAll(term.getBoundVarOccurences()); + return l; + } + + public List getFreeVarOccurences() { + List l = new LinkedList(); + l.addAll(term.getFreeVarOccurences()); + return l; + } + + @Override + /** + * @param boundVars set of bound Variables + * + * @return returns set of free Variables + */ + public Set getFreeVars(Set boundVars) { + Set set = new HashSet(); + set.add(var); + set.addAll(boundVars); + return term.getFreeVars(set); + } + + @Override + public boolean equalsStructure(Term t) { + if(t.getTermType() != ETermType.ABSTRACTION) + return false; + else + return (term.equalsStructure(t.getSubTerm("a"))); + } +} diff --git a/src/org/jalgo/module/lambda/model/Application.java b/src/org/jalgo/module/lambda/model/Application.java new file mode 100644 index 0000000..7d4285e --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Application.java @@ -0,0 +1,264 @@ +/** + * Class Application that represent a application in the labdaterme + * This Class is Composit of the Term Composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ + +package org.jalgo.module.lambda.model; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +public class Application extends Term { + + private Term lterm; + + private Term rterm; + + public Application(Term lterm, Term rterm) { + this.rterm = rterm; + this.lterm = lterm; + } + + @Override + /** + * Getter for TermType + * return termtype of application + */ + public ETermType getTermType() { + + return ETermType.APPLICATION; + } + + @Override + /** + * This Method return all subterms of the current term include the current term + * @return List of all Children + */ + public List getAllChildren() { + List children = new LinkedList(); + children.add(this); + //children.add(lterm); + children.addAll(lterm.getAllChildren()); + //children.add(rterm); + children.addAll(rterm.getAllChildren()); + return children; + } + + @Override + /** + * Getter for subterms + * @param position l = linker Teilterm r = rechter Teilterm + * + * @return returns term at position + * + * @throws thrwos NoSuchElementException() if the first char of position is + * not l or r + */ + public Term getSubTerm(String position) { + if (position != null) { + if (!position.equals("")) { + if (position.startsWith("l")) { + return lterm.getSubTerm(position.substring(1)); + } else if (position.startsWith("r")) { + return rterm.getSubTerm(position.substring(1)); + } else { + throw new NoSuchElementException(toString()); + } + } else { + return this; + } + } else { + throw new IllegalArgumentException(); + } + } + + @Override + /** + * + * @return String represents a lambaterm without format + */ + public String toString() { + return "(" + lterm.toString() + rterm.toString() + ")"; + } + + @Override + /** + * @param pos Positionstring l = linker Teilterm r = rechter Teilterm + * + * @param showBrackets vollgeklammert = true + */ + public List toFormatString(String pos, boolean showBrackets) { + LinkedList fliste = new LinkedList(); + Set format = new HashSet(); + if (showBrackets) { + fliste.add(new FormatString("(", format, pos)); + fliste.addAll(lterm.toFormatString(pos + "l", showBrackets)); + fliste.addAll(rterm.toFormatString(pos + "r", showBrackets)); + fliste.add(new FormatString(")", format, pos)); + } else { + if(lterm.getTermType() == ETermType.ABSTRACTION){ + fliste.add(new FormatString("(", format, pos)); + } + fliste.addAll(lterm.toFormatString(pos + "l", showBrackets)); + if(lterm.getTermType() == ETermType.ABSTRACTION){ + fliste.add(new FormatString(")", format, pos)); + } + if(rterm.getTermType() == ETermType.ABSTRACTION){ + fliste.add(new FormatString("(", format, pos)); + } + fliste.addAll(rterm.toFormatString(pos + "r", showBrackets)); + if(rterm.getTermType() == ETermType.ABSTRACTION){ + fliste.add(new FormatString(")", format, pos)); + } + } + return fliste; + } + + @Override + /** + * + * @param boundVars Menge der gebundnen variablen + */ + public void recalculateBindingIDs(Set boundvars) { + lterm.recalculateBindingIDs(boundvars); + rterm.recalculateBindingIDs(boundvars); + } + + @Override + /** + * + * @param pos Positionstring l = linker Teilterm r = rechter Teilterm + * + * @param newTerm new subterm for position + */ + public boolean replaceChild(String pos, Term newterm) { + if (pos != null) { + if (pos.equals("l")) { + lterm = newterm; + //lterm.setParent(this); + return true; + } else if (pos.equals("r")) { + rterm = newterm; + //rterm.setParent(this); + return true; + } else if (pos.startsWith("r")) { + return rterm.replaceChild(pos.substring(1), newterm); + } else if (pos.startsWith("l")) { + return lterm.replaceChild(pos.substring(1), newterm); + } else { + throw new NoSuchElementException(); + } + } else { + throw new IllegalArgumentException(); + } + + } + + @Override + /* + * * + * + * @return returns left and right part of abstraction + */ + public List getChildren() { + List children = new LinkedList(); + children.add(lterm); + children.add(rterm); + return children; + } + + @Override + /** + * + * @param bindingID position der bindenen abstraktion + * + * @param newName name for variable at position + */ + public boolean alphaConvert(String bindingID, String newName) { + boolean l = lterm.alphaConvert(bindingID, newName); + boolean r = rterm.alphaConvert(bindingID, newName); + return (l || r); //TODO return (l && r); ??? + } + + @Override + /** + * + * @param bindingID position der bindenen abstraktion + * + * @param newTerm new subterm for position + */ + public Term replaceVarsByBindingID(String bindingID, Term t) { + Term newLTerm = lterm.replaceVarsByBindingID(bindingID, t); + Term newRTerm = rterm.replaceVarsByBindingID(bindingID, t); + //newLTerm.setParent(this); + //newRTerm.setParent(this); + Term newTerm = new Application(newLTerm, newRTerm); + //newTerm.setParent(this.parent); //TODO abs wird wegreduziert + return newTerm; + } + + /** + * @ return returns cloned term + */ + public Term clone() { + Application a = new Application(lterm.clone(), rterm.clone()); + //a.setParent(parent); + return a; + } + + @Override + /** + * + * @return Set Menge der gebundnen variablen + */ + public Set getBoundVars() { + Set set = new HashSet(); + set.addAll(lterm.getBoundVars()); + set.addAll(rterm.getBoundVars()); + return set; + } + + public List getBoundVarOccurences() { + List l = new LinkedList(); + l.addAll(lterm.getBoundVarOccurences()); + l.addAll(rterm.getBoundVarOccurences()); + return l; + } + + @Override + /** + * + * @param boundVars set of bound Variables + * + * @return returns set of free Variables + */ + public Set getFreeVars(Set boundVars) { + Set set = new HashSet(); + set.addAll(lterm.getFreeVars(boundVars)); + set.addAll(rterm.getFreeVars(boundVars)); + return set; + } + + public List getFreeVarOccurences() { + List l = new LinkedList(); + l.addAll(lterm.getFreeVarOccurences()); + l.addAll(rterm.getFreeVarOccurences()); + return l; + } + + @Override + public boolean equalsStructure(Term t) { + if(t.getTermType() != ETermType.APPLICATION) + return false; + else { + return lterm.equalsStructure(t.getSubTerm("l")) && + rterm.equalsStructure(t.getSubTerm("r")); + } + } +} diff --git a/src/org/jalgo/module/lambda/model/Atom.java b/src/org/jalgo/module/lambda/model/Atom.java new file mode 100644 index 0000000..d1754a2 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Atom.java @@ -0,0 +1,265 @@ +/** + * Class Atom that represent a atom in the labdaterme + * This class is a leaf of the term composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ + +package org.jalgo.module.lambda.model; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +public class Atom extends Term { + + private String name; + private String bindingID; + + public Atom(String ident) { + this.name = ident; + bindingID = "0"; + } + + @Override + /* + * * This Method return all subterms of the current term include the current + * term + * + * @return List of all Children + */ + public List getAllChildren() { + List children = new LinkedList(); + children.add(this); + return children; + } + + @Override + /* + * * Getter for TermType return termtype of atom + */ + public ETermType getTermType() { + return ETermType.ATOM; + } + + /** + * Getter for subterms + * + * @param position + * should be "" or thrwos NoSuchElementException() + * @return returns term at position + * @throws thrwos + * NoSuchElementException() if position not "" + */ + public Term getSubTerm(String position) { + if (position.equals("")) { + return this; + } else { + throw new NoSuchElementException(); + } + } + + @Override + /* + * * + * + * @return String represents a lambaterm without format + */ + public String toString() { + return name; + } + + @Override + /* + * * + * + * @param position l = linker Teilterm r = rechter Teilterm + * + * @param showBrackets vollgeklammert = true + */ + public List toFormatString(String pos, boolean showBrackets) { + + this.position = pos; + + LinkedList fliste = new LinkedList(); + Set format = new HashSet(); + if (bindingID.equals("0")) + format.add(Format.FREE_VAR); + else { + format.add(Format.BOUND_VAR); + } + FormatString formatstring = new FormatString(name, format, pos); + fliste.add(formatstring); + return fliste; + } + + @Override + /* + * * + * + * @param boundvars Set of Variables bound by Abstraction + */ + public void recalculateBindingIDs(Set boundvars) { + for (Atom a : boundvars) { + if (a.equals(this)) { + setBindingID(a.getBindingID()); + return; + } + } + bindingID = "0"; + } + + @Override + /* + * * + * + * @param position l = linker Teilterm r = rechter Teilterm + */ + public boolean replaceChild(String pos, Term newterm) + throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + /* + * * + * + * @return new list because a atom has no child + */ + public List getChildren() { + return new LinkedList(); + } + + /** + * + * @return returns true wenn variable frei sonst false + */ + public boolean isFree() { + return bindingID.equals("0"); + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newName name for variable at position + */ + public boolean alphaConvert(String bindingID, String newName) { + if (this.bindingID.equals(bindingID)) { + name = newName; + return true; + } else { + return false; + } + } + + /** + * + * @return position der bindenden abstraktion wenn variabele gebinen ist + * sonst 0 + */ + public String getBindingID() { + return bindingID; + } + + /** + * + * @param bindingID + * position der bindenden abstraktion + */ + public void setBindingID(String bindingID) { + this.bindingID = bindingID; + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newTerm new subterm for position + */ + public Term replaceVarsByBindingID(String bindingID, Term t) { + if (this.bindingID.equals(bindingID)) { + Term newTerm = t.clone(); + newTerm.parent = this.parent; + return newTerm; + } else + return this.clone(); + } + + @Override + /* + * * + * + * @ return returns cloned term + */ + public Term clone() { + Atom a = new Atom(name); + a.setBindingID(bindingID); + // a.setParent(parent); + return a; + } + + @Override + /* + * * + * + * @return set Menge der gebundnen variablen + */ + public Set getBoundVars() { + return new HashSet(); + } + + public List getBoundVarOccurences() { + List l = new LinkedList(); + + if(!this.bindingID.equals("0")) + l.add(this); + + return l; + } + + public List getFreeVarOccurences() { + List l = new LinkedList(); + + if(this.bindingID.equals("0")) + l.add(this); + + return l; + } + + @Override + /** + * + * @param boundVars set of bound Variables + * + * @return returns set of free Variables + */ + public Set getFreeVars(Set boundVars) { + Set set = new HashSet(); + if (!boundVars.contains(this)) { + set.add(this); + } + return set; + } + + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equalsStructure(Term t) { + if (t.getTermType() != ETermType.ATOM) + return false; + else { + Atom tatom = (Atom) t; + return bindingID.equals(tatom.getBindingID()); + } + } +} diff --git a/src/org/jalgo/module/lambda/model/CVS/Entries b/src/org/jalgo/module/lambda/model/CVS/Entries new file mode 100644 index 0000000..66e39a2 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/CVS/Entries @@ -0,0 +1,13 @@ +/Abstraction.java/1.1/Thu Aug 6 14:39:02 2009// +/Application.java/1.1/Thu Aug 6 14:39:02 2009// +/Atom.java/1.1/Thu Aug 6 14:39:02 2009// +/EAvailability.java/1.1/Thu Aug 6 14:39:02 2009// +/EStepKind.java/1.1/Thu Aug 6 14:39:02 2009// +/ETermType.java/1.1/Thu Aug 6 14:39:02 2009// +/Format.java/1.1/Thu Aug 6 14:39:02 2009// +/FormatString.java/1.1/Thu Aug 6 14:39:02 2009// +/ITermHandler.java/1.1/Thu Aug 6 14:39:02 2009// +/Shortcut.java/1.1/Thu Aug 6 14:39:02 2009// +/Term.java/1.1/Thu Aug 6 14:39:02 2009// +/TermHandler.java/1.1/Thu Aug 6 14:39:02 2009// +/TermIterator.java/1.1/Thu Aug 6 14:39:02 2009// diff --git a/src/org/jalgo/module/lambda/model/CVS/Repository b/src/org/jalgo/module/lambda/model/CVS/Repository new file mode 100644 index 0000000..ea97ad1 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/lambda/model diff --git a/src/org/jalgo/module/lambda/model/CVS/Root b/src/org/jalgo/module/lambda/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/lambda/model/EAvailability.java b/src/org/jalgo/module/lambda/model/EAvailability.java new file mode 100644 index 0000000..ce6c3da --- /dev/null +++ b/src/org/jalgo/module/lambda/model/EAvailability.java @@ -0,0 +1,14 @@ +/** + * Class Atom that represent a atom in the labdaterme + * This class is a leaf of the term composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +public enum EAvailability { + + AVAILABLE, NOTAVAILABLE, ALPHANEEDED + +} diff --git a/src/org/jalgo/module/lambda/model/EStepKind.java b/src/org/jalgo/module/lambda/model/EStepKind.java new file mode 100644 index 0000000..1df08b1 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/EStepKind.java @@ -0,0 +1,14 @@ +/** + * Enum EStepKind + * StepKind is the Kind of the last done step + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +public enum EStepKind { + + ALPHA, BETA, SHORTCUT, NONE; + +} diff --git a/src/org/jalgo/module/lambda/model/ETermType.java b/src/org/jalgo/module/lambda/model/ETermType.java new file mode 100644 index 0000000..d4ba1ea --- /dev/null +++ b/src/org/jalgo/module/lambda/model/ETermType.java @@ -0,0 +1,11 @@ +/** + * Enum ETermType + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +public enum ETermType { + ATOM, APPLICATION, ABSTRACTION, SHORTCUT; +} diff --git a/src/org/jalgo/module/lambda/model/Format.java b/src/org/jalgo/module/lambda/model/Format.java new file mode 100644 index 0000000..811e5e6 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Format.java @@ -0,0 +1,15 @@ +/** + * Enum Format + * Format for display needeed alphaconvertations, posible betareductions, free & boundvars in the gui + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +public enum Format { + BOUND_VAR, + FREE_VAR, + ALPHA_NEEDED, + BETA_POSSIBLE +} diff --git a/src/org/jalgo/module/lambda/model/FormatString.java b/src/org/jalgo/module/lambda/model/FormatString.java new file mode 100644 index 0000000..369f215 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/FormatString.java @@ -0,0 +1,75 @@ +/** + * Class FormatString + * + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +import java.util.Iterator; +import java.util.Set; + +public class FormatString { + + private String text; + private Set format; + private String position; + private Iterator formatIterator; + + /** + * + * @param text plaintext of subterm + * @param format format of subterm + * @param position position of subterm + */ + public FormatString(String text, Set format, String position) { + this.text = text; + this.format = format; + this.position = position; + this.formatIterator=format.iterator(); + } + /** + * + * @return plaintext of subterm + */ + public String getText() { + return this.text; + } + /** + * + * @return returns absolut position of current term from root + */ + public String getPosition() { + return this.position; + } + /** + * + * @return set of format + */ + public Set getFormat() { + return this.format; + } + + /** + * + * @return true if one more format is avaibal + */ + public boolean hasNext(){ + return formatIterator.hasNext(); + } + /** + * + * @return next format + */ + public Format next(){ + return formatIterator.next(); + } + /** + * + * @return plaintext of subterm + */ + public String toString(){ + return text; + } +} diff --git a/src/org/jalgo/module/lambda/model/ITermHandler.java b/src/org/jalgo/module/lambda/model/ITermHandler.java new file mode 100644 index 0000000..cd37a1a --- /dev/null +++ b/src/org/jalgo/module/lambda/model/ITermHandler.java @@ -0,0 +1,46 @@ +package org.jalgo.module.lambda.model; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +public interface ITermHandler { + + public void highlightPossibleBetaReductions(String position, + boolean highligh); + + public Term getSubTerm(String position); + + public EAvailability checkPossibleBetaReduction(String position); + + public EAvailability betaReduce(String position); + + public boolean alphaConvert(String position, String newname); + + public Iterator getFormatString(boolean showBrackets); + + public Set getPossibleBetaReductions(String position); + + public Set getNeededAlphaConversions(String position); + + public boolean eliminateShortcut(String position); + + public boolean matchShortcut(String position); + + public void eliminateAllShortcuts(String position); + + public void makeAllShortcuts(String position); + + public String getLastOperationOutput(); + + public EStepKind doLowLevelAutoStep(String position); + + public EStepKind doHighLevelAutoStep(String position); + + public Set getAllUnusedVars(); + + public boolean replaceSubTerm(String position, Term newterm); + + public List getAllChildren(String position); + +} diff --git a/src/org/jalgo/module/lambda/model/Shortcut.java b/src/org/jalgo/module/lambda/model/Shortcut.java new file mode 100644 index 0000000..f1a0849 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Shortcut.java @@ -0,0 +1,251 @@ +/** + * Class Shortcut that represent a shortcut of a complex labdaterme + * This class is a leaf of the term composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ + +package org.jalgo.module.lambda.model; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +public class Shortcut extends Term { + + private String representation; + private Term representedTerm; + private boolean predefined; + private int number; + + public Shortcut(String representation, Term repTerm, boolean predefined) { + this.representation = representation; + this.representedTerm = repTerm; + repTerm.recalculateBindingIDs(); + this.predefined = predefined; + String numberString = representation.replace(">", ""); + numberString = numberString.replace("<", ""); + try { + number = Integer.valueOf(numberString).intValue(); + } + catch (NumberFormatException e) { + number = -1; + } + } + + public int getNumber() { + return number; + } + + /** + * @return returns lambdaterm of shortcut + */ + public Term getRepresentedTerm() { + return representedTerm; + } + + /** + * + * @return returns symbol of shortcut + */ + public String getRepresentation() { + return representation; + } + + /** + * + * @return predefined + */ + public boolean isPredefined() { + return predefined; + } + + @Override + /* + * * + * + * @return returns list of Children of the represented Lambdaterm + */ + public List getChildren() { + return new LinkedList(); + } + + @Override + /** + * + * Getter for subterms + * @param position l = linker Teilterm r = rechter Teilterm a=abstraction + * + * @return term at position + */ + public Term getSubTerm(String position) { + if (position.equals("")){ + return this; + }else { + throw new NoSuchElementException(); + } + } + + @Override + /* + * * + * + * @return retuns Termtype of reopresented Lambdaterm if shortcut is + * eliminated else return Termtype shortcut + */ + public ETermType getTermType() { + + return ETermType.SHORTCUT; + + } + + @Override + /* + * * + * + * @param position l = linker Teilterm r = rechter Teilterm + * + * @param showBrackets vollgeklammert = true + * + * @return returns list of subterms with format if shortcut is eliminated + * else retuns name of shortcut + */ + public List toFormatString(String pos, boolean showBreckets) { + LinkedList fliste = new LinkedList(); + FormatString formatstring = new FormatString(representation, + new HashSet(), pos); + fliste.add(formatstring); + return fliste; + } + + @Override + /* + * * + * + * @return String represents a lambaterm without format if shortcut is + * eliminated else return name of shortcut + */ + public String toString() { + return representation; + } + + @Override + /** + * This Method return all subterms of the current term include the current term + * @return List of all Children + */ + public List getAllChildren() { + List children = new LinkedList(); + children.add(this); + return children; + } + + @Override + /* + * * + * + * @param boundvars Set of Variables bound by Abstraction + */ + public void recalculateBindingIDs(Set boundVars) { + + } + + @Override + /* + * * + * + * @param pos Positionstring l = linker Teilterm r = rechter Teilterm a = + * position + * + * @param newTerm new subterm for position + */ + public boolean replaceChild(String pos, Term newterm) + throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newName name for variable at position + */ + public boolean alphaConvert(String bindingID, String newName) { + return false; + } + + @Override + /* + * * + * + * @param bindingID position der bindenen abstraktion + * + * @param newTerm new subterm for position + */ + public Term replaceVarsByBindingID(String bindingID, Term t) { + throw new UnsupportedOperationException(); + } + + @Override + /* + * * + * + * @ return returns cloned term + */ + public Term clone() { + return new Shortcut(representation, representedTerm.clone(), predefined); + } + + @Override + /* + * * + * + * @return set Menge der gebundnen variablen + */ + public Set getBoundVars() { + return new HashSet(); + } + + @Override + /* + * * + * + * @param boundVars set of bound Variables + * + * @return returns set of free Variables + */ + public Set getFreeVars(Set boundVars) { + return new HashSet(); + } + + @Override + public Set getFreeVars() { + return new HashSet(); + } + + @Override + public boolean equalsStructure(Term t) { + if (t.getTermType() != ETermType.SHORTCUT) + return false; + else { + Shortcut tsh = (Shortcut) t; + return representedTerm.equalsStructure(tsh.getRepresentedTerm()); + } + } + + @Override + public List getBoundVarOccurences() { + throw new UnsupportedOperationException(); + } + + @Override + public List getFreeVarOccurences() { + throw new UnsupportedOperationException(); + } +} diff --git a/src/org/jalgo/module/lambda/model/Term.java b/src/org/jalgo/module/lambda/model/Term.java new file mode 100644 index 0000000..344aa7e --- /dev/null +++ b/src/org/jalgo/module/lambda/model/Term.java @@ -0,0 +1,256 @@ +/** + * Abstract class term + * This class is a component of the term composit + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.HashSet; + +public abstract class Term implements Iterable { + + protected Term parent; + protected String position; + + /** + * @param position + * l = linker Teilterm r = rechter Teilterm a=abstraction + * @return term at position + */ + public abstract Term getSubTerm(String position); + + /** + * This method calculates the free variables. + * + * @return returns set of free Variables + */ + public Set getFreeVars() { + return getFreeVars(new HashSet()); + } + + /** + * This method calculates the free variables. + * + * @param boundVars + * Menge der gebundnen variablen + * @return returns set of free Variables + */ + public abstract Set getFreeVars(Set boundVars); + + /** + * This method calculates the free variables. + * @ return returns set of bound Variables + */ + public abstract Set getBoundVars(); + + /** + * This method replace Variables + * + * @param bindingID + * position der bindenen abstraktion + * @param newTerm + * new subterm for position + */ + public abstract Term replaceVarsByBindingID(String bindingID, Term t); + + /** + * This method realise the Alpha Convertion + * + * @param bindingID + * position der bindenen abstraktion + * @param newName + * name for variable at position + */ + public abstract boolean alphaConvert(String bindingID, String newName); + + /** + * Returns a string that represent the lambdaterm + * + * @return String represents a lambaterm without format + */ + public abstract String toString(); + + /** + * Returns a complex object that represent the lambdaterm with format + * + * @param pos + * Positionstring l = linker Teilterm r = rechter Teilterm + * @param showBrackets + * vollgeklammert = true + */ + public abstract List toFormatString(String pos, + boolean showBreckets); + + /** + * Getter for parent + * + * @return parent of curent term + */ + public Term getParent() { + return parent; + } + + /** + * Setter for Parent + * + * @param parent + * parent of current term + */ + public void setParent(Term parent) { + this.parent = parent; + } + + /** + * Check equality of 2 terms + * + * @return true if object o is same kind of term like current term + * @param o + * should be term + */ + public boolean equals(Object o) { + return (o.toString().equals(this.toString())); + } + + /** + * Getter for Termtype + * + * @return termtype of current term + */ + public abstract ETermType getTermType(); + + /** + * This Method return all subterms of the current term include the current + * term + * + * @return List of all Children + */ + public abstract List getAllChildren(); + + /** + * This Method return all subterms of the current term include the current + * term + * + * @return returns direct subterm ob current term + */ + public abstract List getChildren(); + + /** + * Recalculate binding id for Atoms The bindi id is the position of the + * Abstraction that bind the atom + * + * @param boundvars + * Set of Variables bound by Abstraction + */ + public abstract void recalculateBindingIDs(Set boundvars); + + /** + * Recalculate binding id for Atoms The bindi id is the position of the + * Abstraction that bind the atom + * + * @param boundvars + * Set of Variables bound by Abstraction + */ + public void recalculateBindingIDs() { + recalculateBindingIDs(new HashSet()); + } + + /** + * Relpace subterm at position + * + * @param pos + * Positionstring l = linker Teilterm r = rechter Teilterm + * @param newTerm + * new subterm for position + */ + public abstract boolean replaceChild(String pos, Term newterm); + + /** + * Calculate the position of the subterm + * + * @return returns absolut position of current term from root + */ + public String getPosition() { + String pos = ""; + Term parent = getParent(); + Term current = this; + while (parent != null) { + ETermType tType = parent.getTermType(); + switch (tType) { + case ABSTRACTION: + pos = "a" + pos; + break; + case APPLICATION: + if (current == parent.getSubTerm("l")) // TODO geht das mit '==' + // ??? + pos = "l" + pos; + else + pos = "r" + pos; + break; + case ATOM: + throw new RuntimeException("Atoms cant have childresn"); + case SHORTCUT: + throw new RuntimeException("Shortcuts cant have children"); + } + current = parent; + parent = parent.getParent(); + } + return pos; + } + + /** + * Reculculate all parents Top-Down + * + * @param p + * Subterm + */ + public void recalculateParentsRecursive(Term p) { + this.parent = p; + + for (Term c : this.getChildren()) { + c.recalculateParentsRecursive(this); + } + } + + /** + * Clone the subterm @ return returns cloned term + */ + public abstract Term clone(); + + /** + * This method check the syntactic equality of 2 terms + * + * @param t + * @return return true if the t has the same semantic as the current term + */ + public abstract boolean equalsStructure(Term t); + + /** + * Iterates over the term + * + * @return returns TermIterator + */ + public TermIterator iterator() { + return new TermIterator(this); + } + + public List getVarOccurences(Atom var) { + TermIterator termIt = this.iterator(); + List list = new LinkedList(); + while(termIt.hasNext()) { + Term t = termIt.next(); + if(t.equals(var)) { + list.add((Atom)t); + } + } + return list; + } + + public abstract List getBoundVarOccurences(); + + public abstract List getFreeVarOccurences(); +} diff --git a/src/org/jalgo/module/lambda/model/TermHandler.java b/src/org/jalgo/module/lambda/model/TermHandler.java new file mode 100644 index 0000000..4336f10 --- /dev/null +++ b/src/org/jalgo/module/lambda/model/TermHandler.java @@ -0,0 +1,653 @@ +/** + * Class TermHandler + * + * @author Joshua Peschke + * @author Nico Braunisch + * @version 1.0 + */ +package org.jalgo.module.lambda.model; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; +import java.util.Set; + +import org.jalgo.module.lambda.ShortcutHandler; +import org.jalgo.module.lambda.view.EMessageType; + +public class TermHandler extends Observable implements ITermHandler { + + private Term root; + private String lastOperationOutput; + + /** + * + * @param t + * rootterm + * @param o + * obsever for termevent + */ + public TermHandler(Term t, Observer o) { + this.root = t; + this.addObserver(o); + // root.recalculateParents(); + root.recalculateBindingIDs(); + setChanged(); + notifyObservers(EMessageType.OUTPUTSTRING_CHANGED); + } + + /** + * Do autostep + * @param position of autostep + * @return Kind of operation + */ + public EStepKind doLowLevelAutoStep(String position) { + String betaPos = getPossibleBetaReduction(position); + if (betaPos != null) { + if (betaReduce(betaPos) == EAvailability.AVAILABLE) + return EStepKind.BETA; + else + throw new RuntimeException("Automatic Beta Reduction failed..."); + } + //alpha + Term alpha = getNeededAlphaConversion(position); + String bindingIDtoConvert = ""; + if (alpha != null) { + Term abs = alpha.getSubTerm("la"); + Term rterm = alpha.getSubTerm("r"); + Set absBoundVars = abs.getBoundVars(); + Set rFreeVars = rterm.getFreeVars(); + for (Atom a : absBoundVars) { + if (rFreeVars.contains(a)) { + bindingIDtoConvert = a.getBindingID(); + break; + } + } + if (!bindingIDtoConvert.equals("")) { + Iterator it; + it = getAllUnusedVars().iterator(); + if (it.hasNext()) { + if (alphaConvert(bindingIDtoConvert, it.next())) + return EStepKind.ALPHA; + } else + throw new RuntimeException("No unused vars available!"); + } + throw new RuntimeException("Automatic Alpha Conversion failed..."); + } + return EStepKind.NONE; + } + + public EStepKind doHighLevelAutoStep(String position) { + if(simplifyAShortcut(position)) { + return EStepKind.SHORTCUT; + } + else return EStepKind.NONE; + } + + /** + * Generate shortcut + * @param position off posible shortcut + */ + public void makeAllShortcuts(String position) { + TermIterator termIt; + boolean solved = true; + while (solved) { + solved = false; + termIt = getSubTerm(position).iterator(); + while (termIt.hasNext()) { + String tpos = termIt.getCurrentPos(); + Term t = termIt.next(); + if (t.getTermType() != ETermType.SHORTCUT) { + t = ShortcutHandler.getInstance().matchShortcut(t); + if (t.getTermType() == ETermType.SHORTCUT) { + if (replaceSubTerm(tpos, t)) { + solved = true; + break; + } + } + } + } + } + } + + /** + * @return succes of alpha conversion + * @param position + * position of Atom that should be converted + * @param newName + * new name of Atom that should be converted + */ + public boolean alphaConvert(String position, String newName) { + Term t = root.getSubTerm(position); + if (t.getTermType() == ETermType.ABSTRACTION) { + String bID = ((Atom) t.getChildren().get(0)).getBindingID(); + boolean success = t.alphaConvert(bID, newName); + if (success) { + setChanged(); + notifyObservers(EMessageType.OUTPUTSTRING_CHANGED); + } + return success; + } else + return false; + } + + /** + * @return succes of beta conversion + * @param position + * position of sub that should be converted + */ + public EAvailability betaReduce(String position) { + EAvailability availability = checkPossibleBetaReduction(position); + if (availability == EAvailability.AVAILABLE) { + Term t = getSubTerm(position); + Term lterm = t.getSubTerm("l"); + Term rterm = t.getSubTerm("r"); + String bindingID = position + "l"; + Term absTerm = lterm.getSubTerm("a"); + Term newTerm = absTerm.replaceVarsByBindingID(bindingID, rterm); + if (replaceSubTerm(position, newTerm)) + return EAvailability.AVAILABLE; + else + return EAvailability.NOTAVAILABLE; + } + return availability; + } + + /** + * + * @param t + * term that should be reduced + * @return status of betreduction + */ + public EAvailability checkPossibleBetaReduction(Term t) { + if (t.getTermType() == ETermType.APPLICATION) { + Term lterm = t.getSubTerm("l"); + Term rterm = t.getSubTerm("r"); + if (lterm.getTermType() == ETermType.ABSTRACTION) { + Term absTerm = lterm.getSubTerm("a"); + Set absTermBoundVars = absTerm.getBoundVars(); + Set rtermFreeVars = rterm.getFreeVars(); + for (Atom a : absTermBoundVars) { + for (Atom b : rtermFreeVars) { + if (a.equals(b)) + return EAvailability.ALPHANEEDED; + } + } + return EAvailability.AVAILABLE; + } + } + return EAvailability.NOTAVAILABLE; + } + + /** + * + * @param position + * position of term that should be reduced + * @return status of betreduction + */ + public EAvailability checkPossibleBetaReduction(String position) { + Term t = getSubTerm(position); + return checkPossibleBetaReduction(t); + } + + /** + * @param position + * of shortcut should be eliminated + * @return returns true if shortcut would be eliminated + */ + public boolean eliminateShortcut(String position) { + if (root.getSubTerm(position).getTermType() == ETermType.SHORTCUT) { + Term newTerm = ((Shortcut) root.getSubTerm(position)) + .getRepresentedTerm().clone(); + return replaceSubTerm(position, newTerm); + // return replaceSubTerm(position.substring(1), newTerm); + // return root.getSubTerm(position).equals(newTerm); + } else { + return false; + } + } + /** + * Generate shortcut + * @param position off posible shortcut + */ + public boolean matchShortcut(String position) { + Term t = getSubTerm(position); + + t.recalculateParentsRecursive(null); + t.recalculateBindingIDs(); + + if (t.getTermType() != ETermType.SHORTCUT) { + Term newTerm = ShortcutHandler.getInstance().matchShortcut(t) + .clone(); + + if (newTerm == null) { + root.recalculateParentsRecursive(null); + root.recalculateBindingIDs(); + return false; + } + + root.recalculateParentsRecursive(null); + root.recalculateBindingIDs(); + return replaceSubTerm(position, newTerm); + // return replaceSubTerm(position.substring(1), newTerm); + // return root.getSubTerm(position).equals(newTerm); + } else { + root.recalculateParentsRecursive(null); + root.recalculateBindingIDs(); + return false; + } + } + + /** + * Dissolve all shortcuts at position + * eliminate all shortcut in the root term + */ + public void eliminateAllShortcuts(String position) { + Iterator iter; + boolean solved = true; + while (solved) { + solved = false; + iter = getSubTerm(position).getAllChildren().iterator(); + while (iter.hasNext() && !solved) { + solved = solved || eliminateShortcut(iter.next().getPosition()); + } + } + } + + /** + * This Method return all subterms of the current term include the current + * term + * + * @return List of all Children + */ + public List getAllChildren() { + List children = new LinkedList(); + children.add(root); + children.addAll(root.getAllChildren()); + return children; + } + + /** + * @return iterator of formatstring of subterms + * @param showBrackets + * vollgeklammert = true + */ + public Iterator getFormatString(boolean showBrackets) { + return root.toFormatString("", showBrackets).iterator(); + } + + /** + * @return im dont care + */ + public String getLastOperationOutput() { + return lastOperationOutput; + } + + /** + * Get all needed alphaconversions + * @return A set of position Strings that identify Applications where a beta + * reduction would be possible after an alpha conversion was + * performed. + */ + public Set getNeededAlphaConversions(String position) { + List allSubTerms = root.getSubTerm(position).getAllChildren(); + allSubTerms.add(root); + Set alphaNeededPositions = new HashSet(); + for (Term t : allSubTerms) { + if (checkPossibleBetaReduction(t) == EAvailability.ALPHANEEDED) { + alphaNeededPositions.add(t.getPosition()); + } + } + return alphaNeededPositions; + } + + /** + * Get one needed alphaconversions + * @return Applications where a beta reduction would be possible after an alpha conversion was + * performed. + */ + public Term getNeededAlphaConversion(String position) { + Iterator termIt = root.getSubTerm(position).iterator(); + Term t; + while(termIt.hasNext()) { + t = termIt.next(); + if(checkPossibleBetaReduction(t) == EAvailability.ALPHANEEDED) { + return t; + } + } + return null; + } + /** + * Get all posibel betareductions + * @return A set of position Strings that identify Applications where a beta + * reduction is possible. + */ + public Set getPossibleBetaReductions(String position) { + List allSubTerms = getAllChildren(position); + Set betaPossiblePositions = new HashSet(); + for (Term t : allSubTerms) { + if (checkPossibleBetaReduction(t) == EAvailability.AVAILABLE) { + betaPossiblePositions.add(t.getPosition()); + } + } + return betaPossiblePositions; + } + /** + * Get one posibel betareduction + * @return position Strings that identify Applications where a beta + * reduction is possible. + */ + public String getPossibleBetaReduction(String position) { + TermIterator termIt = (TermIterator) root.getSubTerm(position).iterator(); + String betaPos; + while(termIt.hasNext()) { + betaPos = termIt.nextPosition(); + if(checkPossibleBetaReduction(betaPos) == EAvailability.AVAILABLE) { + return betaPos; + } + } + return null; + } + + /** + * Get subterm of the root term + * @param pos + * Positionstring l = linker Teilterm r = rechter Teilterm + * @return subterm for position + */ + public Term getSubTerm(String position) { + return root.getSubTerm(position); + + } + + /** + * @param position + * Positionstring + * @param highligh + * true if posible betareduction should be highlighted + */ + public void highlightPossibleBetaReductions(String position, + boolean highligh) { + // TODO Auto-generated method stub + + } + + /** + * MUSS NOCH PRIVAT WERDEN IN FINALER VERSION relace subterm at position + * + * @param pos + * Positionstring l = linker Teilterm r = rechter Teilterm + * @param newTerm + * new subterm for position + */ + public boolean replaceSubTerm(String position, Term newterm) { + if (position.equals("")) { + root = newterm; + // root.setParent(null); + root.recalculateParentsRecursive(null); + root.recalculateBindingIDs(); + setChanged(); + notifyObservers(EMessageType.OUTPUTSTRING_CHANGED); + return true; + } else { + Term newT = newterm/* .clone() */; + // Term parentTerm = getSubTerm(position).parent; + // newT.setParent(parentTerm); + if (root.replaceChild(position, newT)) { + root.recalculateParentsRecursive(null); + root.recalculateBindingIDs(); + setChanged(); + notifyObservers(EMessageType.OUTPUTSTRING_CHANGED); + return true; + } else { + return false; + } + + } + } + + /** + * This method calculates the free variables. + * + * @return returns set of free Variables + */ + public Set getFreeVars(String position) { + + return getSubTerm(position).getFreeVars(); + } + + /** + * This method calculates the free variables. + * @ return returns set of bound Variables + */ + public Set getBoundVars(String position) { + return getSubTerm(position).getBoundVars(); + } + + // /** + // * @return returns set of free Variables at position + // */ + // public Set getFreeVars() { + // + // return root.getFreeVars(); + // } + + // /** + // * @return returns set of free Variables at position + // * @param position + // * of subterm + // */ + // public Set getFreeVarsSubTerm(String position) { + // return root.getSubTerm(position).getFreeVars(new HashSet()); + // } + + // /** + // * @return returns set of bound Variables + // */ + // public Set getBoundVars() { + // return root.getBoundVars(); + // } + + // /** + // * @return returns set of bound Variables + // * @param position + // * of subterm + // */ + // public Set getBoundVarsSubTerm(String position) { + // return root.getSubTerm(position).getBoundVars(); + // } + + /** + * Returns root term without format + * @return String represents a lambaterm without format + */ + public String toString() { + return root.toString(); + } + + /** + * Return all used variables + * @return Set of all variables which will be used in the current term + */ + public Set getAllUsedVars() { + Set usedvars = new HashSet(); + Set atoms = new HashSet(); + atoms.addAll(root.getBoundVars()); + atoms.addAll(root.getFreeVars()); + for (Atom a : atoms) { + usedvars.add(a.toString()); + } + return usedvars; + } + + /** + * Return all unused variables + * @return Set of all variables which will be not used in the current term + */ + public Set getAllUnusedVars() { + Set unusedvars = new HashSet(); + //Auskommentierte zeilen für variablen x1...xn + //int varIndex = -1; + //while(unusedvars.isEmpty()) { + for (int i = 107; i < 123; i++) { + String varname = new Character((char) i).toString(); + /*if(varIndex >= 0) { + varname += intToSubscriptNumber(varIndex); + }*/ + unusedvars.add(varname); + } + unusedvars.removeAll(getAllUsedVars()); + //} + return unusedvars; + } + + /* + //helper for getAllUnusedVars + //creates subscript string out of an int + private String intToSubscriptNumber(int varIndex) throws RuntimeException{ + String s = String.valueOf(varIndex); + String subscript = ""; + for(int i = 0; i getAllChildren(String position) { + List children = new LinkedList(); + children.add(getSubTerm(position)); + children.addAll(getSubTerm(position).getAllChildren()); + return children; + } + + public boolean simplifyAShortcut(String position) { + TermIterator termIt = getSubTerm(position).iterator(); + while(termIt.hasNext()) { + String pos = termIt.getCurrentPos(); + Term t = termIt.next(); + if(t.getTermType() == ETermType.APPLICATION) { + Term lterm = t.getSubTerm("l"); + Term rterm = t.getSubTerm("r"); + if( lterm.getTermType() == ETermType.SHORTCUT && + rterm.getTermType() == ETermType.SHORTCUT) { + if(lterm.toString().equals("")) { + return replaceSubTerm(pos, lterm); + } + int number = ((Shortcut)rterm).getNumber(); + if(number >= 0) { + if(lterm.toString().equals("")) { + Term newTerm = ShortcutHandler.getInstance().createNumberShortcut(Math.max(0, number-1)); + return replaceSubTerm(pos, newTerm); + } + if(lterm.toString().equals("")) { + Term newTerm = ShortcutHandler.getInstance().createNumberShortcut(Math.max(0, number+1)); + return replaceSubTerm(pos, newTerm); + } + if(lterm.toString().equals("")) { + int fac = number; + while(number > 1) { + number = number-1; + fac = fac*number; + } + Term newTerm = ShortcutHandler.getInstance().createNumberShortcut(fac); + return replaceSubTerm(pos, newTerm); + } + if(lterm.toString().equals("")) { + Term newTerm; + if(number == 0) + newTerm = ShortcutHandler.getInstance().createShortcutObject(""); + else + newTerm = ShortcutHandler.getInstance().createNumberShortcut(0); + return replaceSubTerm(pos, newTerm); + } + } + } + if( lterm.getTermType() == ETermType.APPLICATION && + rterm.getTermType() == ETermType.SHORTCUT) { + Term llterm = lterm.getSubTerm("l"); + Term lrterm = lterm.getSubTerm("r"); + if( llterm.getTermType() == ETermType.SHORTCUT && + lrterm.getTermType() == ETermType.SHORTCUT) { + int number1 = ((Shortcut)lrterm).getNumber(); + int number2 = ((Shortcut)rterm).getNumber(); + if(number1 >= 0 && number2 >= 0) { + if(llterm.toString().equals("")) { + Term newTerm = ShortcutHandler.getInstance().createNumberShortcut(number1*number2); + return replaceSubTerm(pos, newTerm); + } + else if(llterm.toString().equals("")) { + Term newTerm = ShortcutHandler.getInstance().createNumberShortcut(number1+number2); + return replaceSubTerm(pos, newTerm); + } + } + } + if( llterm.getTermType() == ETermType.APPLICATION && + lrterm.getTermType() == ETermType.SHORTCUT) { + Term lllterm = llterm.getSubTerm("l"); + Term llrterm = llterm.getSubTerm("r"); + if( lllterm.getTermType() == ETermType.SHORTCUT && + llrterm.getTermType() == ETermType.SHORTCUT) { + if(lllterm.toString().equals("")) { + if( llrterm.toString().equals("")|| + llrterm.toString().equals("<1>")) { + return replaceSubTerm(pos, lrterm); + } + else if(llrterm.toString().equals("")|| + llrterm.toString().equals("<0>")) { + return replaceSubTerm(pos, rterm); + } + } + } + } + } + } + } + return false; + } + + +} diff --git a/src/org/jalgo/module/lambda/model/TermIterator.java b/src/org/jalgo/module/lambda/model/TermIterator.java new file mode 100644 index 0000000..134490b --- /dev/null +++ b/src/org/jalgo/module/lambda/model/TermIterator.java @@ -0,0 +1,89 @@ +package org.jalgo.module.lambda.model; + +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +public class TermIterator implements Iterator { + + private Term term; + private Term currentTerm; + private String currentPos; + private Set visited; + private Boolean hasnext; + + public TermIterator(Term term) { + this.term = term; + currentPos = ""; + currentTerm = term; + hasnext = true; + visited = new TreeSet(); + } + + public boolean hasNext() { + if(hasnext == null) { + if(!currentPos.contains("l") && currentTerm.getChildren().size() <= 0) { + hasnext = false; + } + else if(currentTerm.getChildren().size() == 0) { + int lastL = currentPos.lastIndexOf('l'); + if(lastL == 0) { + currentPos = ""; + currentTerm = term; + } + else { + currentPos = currentPos.substring(0, lastL); + currentTerm = term.getSubTerm(currentPos); + } + hasnext = hasNext(); + } + else if(currentTerm.getChildren().size() == 2) { + if(currentTerm.getTermType() == ETermType.ABSTRACTION) { + currentTerm = currentTerm.getSubTerm("a"); + currentPos += 'a'; + } + else { + if(!visited.contains(currentPos)) { + visited.add(currentPos); + currentTerm = currentTerm.getSubTerm("l"); + currentPos += 'l'; + } + else { + currentTerm = currentTerm.getSubTerm("r"); + currentPos += 'r'; + } + } + hasnext = true; + } + } + return hasnext; + } + + public Term next() { + if(hasNext()) { + hasnext = null; + return currentTerm; + } + return null; + } + + public String nextPosition() { + if(hasNext()) { + hasnext = null; + return currentPos; + } + return null; + } + + public String getCurrentPos() { + if(hasNext()) { + return currentPos; + } + return null; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/org/jalgo/module/lambda/res.properties b/src/org/jalgo/module/lambda/res.properties new file mode 100644 index 0000000..97a9eba --- /dev/null +++ b/src/org/jalgo/module/lambda/res.properties @@ -0,0 +1,22 @@ +Module_logo=/lambda_pix/logo.jpg +Icon.alpha=/lambda_pix/alpha.png +Icon.beta=/lambda_pix/beta.png +Icon.freeVar=/lambda_pix/freeVar.png +Icon.boundVar=/lambda_pix/boundVar.png +Icon.brackets=/lambda_pix/brackets.png +Icon.sc_brackets=/lambda_pix/sc_brackets.png +Icon.sc_brackets_x=/lambda_pix/sc_brackets_x.png +Icon.welcomeNew=/lambda_pix/WelcomeNew.png +Icon.welcomeLoad=/lambda_pix/WelcomeOpen.png +Icon.welcomeNewOver=/lambda_pix/WelcomeNewOver.png +Icon.welcomeLoadOver=/lambda_pix/WelcomeOpenOver.png + +file.terms=/lambda/terms.txt +file.shortcuts=/lambda/shortcuts.txt + +Icon.Clear=/main_pix/clear.gif +Icon.Add=/images/plus_button.gif +Icon.autoStep=/lambda_pix/autoStep.png +Icon.shortcutStep=/lambda_pix/shortcutStep.png + +HelpSet_Name=/help/jhelp/lambda_help.hs \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/view/.merge.tmp b/src/org/jalgo/module/lambda/view/.merge.tmp new file mode 100644 index 0000000..e69de29 diff --git a/src/org/jalgo/module/lambda/view/CVS/Entries b/src/org/jalgo/module/lambda/view/CVS/Entries new file mode 100644 index 0000000..3f38736 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/CVS/Entries @@ -0,0 +1,10 @@ +/.merge.tmp/1.1/Thu Aug 6 14:39:02 2009/-kb/ +/EMessageType.java/1.1/Thu Aug 6 14:39:02 2009// +/ExchangeTextField.java/1.1/Thu Aug 6 14:39:02 2009// +/GUIController.java/1.1/Thu Aug 6 14:39:02 2009// +/RenderElement.java/1.1/Thu Aug 6 14:39:02 2009// +/RenderLabel.java/1.1/Thu Aug 6 14:39:02 2009// +/Renderer.java/1.1/Thu Aug 6 14:39:02 2009// +/WelcomeScreen.java/1.1/Thu Aug 6 14:39:02 2009// +/WelcomeScreenButton.java/1.1/Thu Aug 6 14:39:02 2009// +/WorkScreen.java/1.1/Thu Aug 6 14:39:02 2009// diff --git a/src/org/jalgo/module/lambda/view/CVS/Repository b/src/org/jalgo/module/lambda/view/CVS/Repository new file mode 100644 index 0000000..971b5cc --- /dev/null +++ b/src/org/jalgo/module/lambda/view/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/lambda/view diff --git a/src/org/jalgo/module/lambda/view/CVS/Root b/src/org/jalgo/module/lambda/view/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/lambda/view/EMessageType.java b/src/org/jalgo/module/lambda/view/EMessageType.java new file mode 100644 index 0000000..6137bcf --- /dev/null +++ b/src/org/jalgo/module/lambda/view/EMessageType.java @@ -0,0 +1,8 @@ +package org.jalgo.module.lambda.view; + +public enum EMessageType { + ERROR_OCCOURED, + OUTPUTSTRING_CHANGED, + OUTPUTSTRING_UPDATE, + SIMPLE_STRING +} diff --git a/src/org/jalgo/module/lambda/view/ExchangeTextField.java b/src/org/jalgo/module/lambda/view/ExchangeTextField.java new file mode 100644 index 0000000..73bdb75 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/ExchangeTextField.java @@ -0,0 +1,78 @@ +package org.jalgo.module.lambda.view; + + +import java.awt.Component; + +import javax.swing.ComboBoxEditor; +import javax.swing.JTextField; +import javax.swing.text.*; + +import org.jalgo.module.lambda.Constants; + + /** + * The class ExchangeTextField extends JTextField + * to make a LAMBDA (Unicode 03BB) out of a "\" when typed. + * + * @author Frank + * + */ + +public class ExchangeTextField extends JTextField implements ComboBoxEditor { + private static final long serialVersionUID = 1L; + + public ExchangeTextField() { + super(); + this.setBorder(null); + } + + public ExchangeTextField(String s) { + super(s); + this.setBorder(null); + } + + public ExchangeTextField(int cols) { + super(cols); + this.setBorder(null); + } + + protected Document createDefaultModel() { + return new ExchangeDocument(); + } + + static class ExchangeDocument extends PlainDocument { + private static final long serialVersionUID = 1L; + + public void insertString(int offs, String str, AttributeSet a) + throws BadLocationException { + + if (str == null) { + return; + } + + /** + * Here the Conversion is performed. + */ + char[] change = str.toCharArray(); + for (int i = 0; i < change.length; i++) { + if (change[i] == '\\') change[i] = Constants.LAMBDA.charAt(0); + } + super.insertString(offs, new String(change), a); + } + } + + public Component getEditorComponent() { + return this; + } + + public Object getItem() { + return this.getText(); + } + + public void setItem(Object item) { + if (item == null) { + this.setText(""); + } else { + this.setText(item.toString()); + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/view/GUIController.java b/src/org/jalgo/module/lambda/view/GUIController.java new file mode 100644 index 0000000..e43fb83 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/GUIController.java @@ -0,0 +1,765 @@ +package org.jalgo.module.lambda.view; + +import org.jalgo.module.lambda.ModuleConnector; +import org.jalgo.module.lambda.Constants; +import org.jalgo.module.lambda.ShortcutHandler; +import org.jalgo.module.lambda.controller.*; +import org.jalgo.module.lambda.model.EAvailability; +import org.jalgo.module.lambda.model.FormatString; +import org.jalgo.module.lambda.model.ITermHandler; +import org.jalgo.module.lambda.model.TermHandler; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; + +import java.awt.Color; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Observable; +import java.util.Observer; +import java.util.Set; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + + +/** + * Main GUI Class. Creates the GUI and is the observer for the model. + * + */ +public class GUIController implements Observer { + + private Renderer renderer; + private IController controller; + private ModuleConnector mc; + + //GUI Komponenten + private WelcomeScreen welcomeScreen; + private WorkScreen workScreen; + + private JButton redoStepButton; + private JButton undoStepButton; + private JButton redoAllStepsButton; + private JButton undoAllStepsButton; + + private JButton doAutoStepButton; + private JButton doShortcutStepButton; + private JButton doAllAutoStepsButton; + + private JButton alphaButton; + private JButton betaButton; + private JButton markFreeVarsButton; + private JButton markBoundVarsButton; + private JButton showhideBracketsButton; + private JButton eliminateSCButton; + private JButton matchSCButton; + + private JComponent contentPane; + private JToolBar toolbar; + + public static final Font INPUT_FONT = new Font("Serif", 0, 28); + public static final String TERM_FONT_HTML = ""; + public static final Font TERM_FONT = new Font("Serif", Font.BOLD, 32); + public static final Font TOOLBAR_FONT = new Font("Serif", Font.BOLD, 18); + + public static final Color goodNews = new Color(30, 159, 30); + public static final Color badNews = new Color(185, 0, 0); + + private Iterator currentOutputString; + private List renderedTerm = new LinkedList(); + + private boolean markFreeVars = false; + private boolean markBoundVars = false; + private boolean hideBrackets = false; + + private String currentTerm; + private int inpCaret; + + public GUIController(ModuleConnector mc, Controller controller) { + this.mc = mc; + this.controller = controller; + + //get JAlgos GUI components + contentPane = JAlgoGUIConnector.getInstance().getModuleComponent(mc); + toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar(mc); + } + + /** + * intitializes and shows the welcomeScreen + */ + public void installWelcomeScreen() { + contentPane.removeAll(); + welcomeScreen = new WelcomeScreen(this); + contentPane.add(welcomeScreen); + } + + /** + * intitializes and shows the workScreen + */ + public void installWorkScreen() { + contentPane.removeAll(); + workScreen = new WorkScreen(); + contentPane.add(workScreen); + initToolbar(); + renderer = new Renderer(workScreen.getRenderLabel()); //initialize Renderer with RenderTarget + installActionListeners(); + writeComment(Messages.getString("lambda", "ltxt.input"), true); + updateButtonStatus(); + workScreen.getInputTextField().requestFocus(); + } + + /** + * creates the toolbar for the WorkScreen + */ + private void initToolbar() { + //create the toolbar + redoStepButton = new JButton(new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_step"))); + redoStepButton.setToolTipText(Messages.getString("lambda","bts.doStep")); + undoStepButton = new JButton(new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_step"))); + undoStepButton.setToolTipText(Messages.getString("lambda","bts.undoStep")); + redoAllStepsButton = new JButton(new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_all"))); + redoAllStepsButton.setToolTipText(Messages.getString("lambda","bts.doAllSteps")); + undoAllStepsButton = new JButton(new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_all"))); + undoAllStepsButton.setToolTipText(Messages.getString("lambda","bts.undoAllSteps")); + + doAutoStepButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.autoStep"))); + doAutoStepButton.setToolTipText(Messages.getString("lambda", "bts.doAutoStep")); + doShortcutStepButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.shortcutStep"))); + doShortcutStepButton.setToolTipText(Messages.getString("lambda", "bts.doShortcutStep")); + doAllAutoStepsButton = new JButton(new ImageIcon(Messages.getResourceURL("main", "Icon.Finish_algorithm"))); + doAllAutoStepsButton.setToolTipText(Messages.getString("lambda", "bts.doAllAutoSteps")); + + alphaButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.alpha"))); + alphaButton.setToolTipText(Messages.getString("lambda","bts.alpha")); + betaButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.beta"))); + betaButton.setToolTipText(Messages.getString("lambda","bts.beta")); + markFreeVarsButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.freeVar"))); + markFreeVarsButton.setToolTipText(Messages.getString("lambda","bts.markFreeVars")); + markBoundVarsButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.boundVar"))); + markBoundVarsButton.setToolTipText(Messages.getString("lambda","bts.markBoundVars")); + + showhideBracketsButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.brackets"))); + showhideBracketsButton.setToolTipText(Messages.getString("lambda","bts.showhideBrackets")); + + eliminateSCButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.sc_brackets_x"))); + eliminateSCButton.setToolTipText(Messages.getString("lambda","bts.shortcutEliminate")); + + matchSCButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.sc_brackets"))); + matchSCButton.setToolTipText(Messages.getString("lambda","bts.shortcutMatch")); + + alphaButton.setFont(TOOLBAR_FONT); + betaButton.setFont(TOOLBAR_FONT); + showhideBracketsButton.setFont(TOOLBAR_FONT); + matchSCButton.setFont(TOOLBAR_FONT); + + toolbar.add(undoAllStepsButton); + toolbar.add(undoStepButton); + toolbar.add(redoStepButton); + toolbar.add(redoAllStepsButton); + toolbar.addSeparator(); + toolbar.add(doAutoStepButton); + toolbar.add(doShortcutStepButton); + toolbar.add(doAllAutoStepsButton); + toolbar.addSeparator(); + toolbar.add(alphaButton); + toolbar.add(betaButton); + toolbar.addSeparator(); + toolbar.add(markFreeVarsButton); + toolbar.add(markBoundVarsButton); + toolbar.add(showhideBracketsButton); + toolbar.addSeparator(); + toolbar.add(eliminateSCButton); + toolbar.add(matchSCButton); + } + + /** + * adds ActionListeners to the buttons and fields + */ + private void installActionListeners() { + + workScreen.getInputTextField().addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent ke) { + int key = ke.getKeyCode(); + if (key == KeyEvent.VK_ENTER) { + inputCompleteAction(); + } + } + }); + + workScreen.getDoneButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + inputCompleteAction(); + } + }); + + workScreen.getClearButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + workScreen.getInputTextField().setText(""); + workScreen.getInputTextField().requestFocus(); + workScreen.getOutputTextArea().setText(""); + workScreen.getRenderLabel().clear(); + writeComment(Messages.getString("lambda","ltxt.input"), true); + } + }); + + alphaButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + Set uuv; + clearComment(); + uuv = controller.getAllUnusedVars(); + if (uuv.isEmpty()) { + writeComment(Messages.getString("lambda","ltxt.alphaNoVars"), false); + } else if (!controller.doAlphaConversion(selectNewAlphaVar(uuv))) { + writeComment(Messages.getString("lambda","ltxt.alphaFailed"), false); + } else { + renderer.setOpcode("\u03b1"); + } + } + }); + + betaButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + EAvailability availability = controller.doBetaReduction(); + if (availability == EAvailability.NOTAVAILABLE) { + writeComment(Messages.getString("lambda","ltxt.betaFailed"), false); + } else if (availability == EAvailability.ALPHANEEDED) { + writeComment(Messages.getString("lambda","ltxt.alphaNeeded"), false); + } else { + renderer.setOpcode("\u03b2"); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + redoStepButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.redoStep(GUIController.this); + if (oc != null) { + renderer.setOpcode(oc); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + undoStepButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.undoStep(GUIController.this); + if (oc != null) { + renderer.setOpcode(oc); + } + } + }); + + redoAllStepsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.redoAllSteps(GUIController.this); + if (oc != null) { + renderer.setOpcode(oc); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + undoAllStepsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.undoAllSteps(GUIController.this); + if (oc != null) { + renderer.setOpcode(oc); + } + } + }); + + doAutoStepButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.doStep(); + if (oc != null) { + renderer.setOpcode(oc); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + doShortcutStepButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.doShortcutStep(); + if (oc != null) { + renderer.setOpcode(oc); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + doAllAutoStepsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + clearComment(); + String oc = controller.doAllSteps(); + if (oc != null) { + renderer.setOpcode(oc); + } + if (controller.isNormalized()) { + writeComment("Normalform erreicht.", true); + } + } + }); + + markFreeVarsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + + markFreeVars = !markFreeVars; + + List l = controller.getFreeVars(); + + for(RenderElement re : renderedTerm) { + if(l.contains(re.getTermPosition())) { + re.markAsFreeVar(markFreeVars); + + } else + re.markAsFreeVar(false); + re.repaint(); + } + } + }); + + markBoundVarsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + + markBoundVars = !markBoundVars; + + List l = controller.getBoundVars(); + + for(RenderElement re : renderedTerm) { + if(l.contains(re.getTermPosition())) { + re.markAsBoundVar(markBoundVars); + + } else + re.markAsBoundVar(false); + + re.repaint(); + } + } + }); + + workScreen.getRenderLabel().addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent arg0) { + markBoundVars = false; + markFreeVars = false; + + for(RenderElement re : renderedTerm) { + re.setSelected(false); + re.markAsBoundVar(markBoundVars); + re.markAsFreeVar(markFreeVars); + re.repaint(); + } + controller.selectTerm(""); + } + }); + + showhideBracketsButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + hideBrackets = !hideBrackets; + + for(RenderElement re : renderedTerm) { + re.hideBrackets(hideBrackets); + re.repaint(); + } + } + }); + + eliminateSCButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + if (controller.eliminateAllShortcuts()) { + renderer.setOpcode("="); + } + } + }); + + matchSCButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + if (controller.matchShortcut()) { + renderer.setOpcode("="); + } + } + }); + + workScreen.getShortcutListField().addListSelectionListener(new ListSelectionListener() { + public void valueChanged(ListSelectionEvent e) { + if (ShortcutHandler.getInstance().isShortcutPredefined((String) workScreen.getShortcutListField().getSelectedValue())) + workScreen.getDeleteButton().setEnabled(false); + else + workScreen.getDeleteButton().setEnabled(true); + } + }); + + workScreen.getInsertButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + insertShortcut(); + } + }); + + workScreen.getShortcutListField().addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent me) { + if ((me.getButton() == MouseEvent.BUTTON1) + && (me.getClickCount() == 2)) { + insertShortcut(); + } + } + }); + + workScreen.getDeleteButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + deleteShortcut(); + } + }); + + workScreen.getNewSCButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + createShortcut(); + } + }); + + workScreen.getInputSCName().addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent ke) { + int key = ke.getKeyCode(); + if (key == KeyEvent.VK_ENTER) { + inputSCAction(); + } + } + }); + + workScreen.getInputSCOKButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + inputSCAction(); + } + }); + + workScreen.getInputSCCancelButton().addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + workScreen.changeVisibility(); + } + }); + + } + + /** + * Highlights the position where the mousecursor is over. + * + * @param pos Position to be highlighted. + */ + public void highlightPosition(String pos) { + for(RenderElement re : renderedTerm) { + if(re.getTermPosition().startsWith(pos)) { + re.setHighlighted(true); + } + else + re.setHighlighted(false); + + re.repaint(); + } + } + + /** + * voids the highlightning of the term when the mousecursor isn't over the renderLabel anymore. + */ + public void unhighlight() { + for(RenderElement re : renderedTerm) { + re.setHighlighted(false); + re.repaint(); + } + } + + /** + * Selects/marks a position when a mousebutton is clicked over the renderLabel and hands pos over to the Controller. + * + * @param pos Position to be selected + */ + public void selectPosition(String pos) { + for(RenderElement re : renderedTerm) { + if(re.getTermPosition().startsWith(pos)) { + re.setSelected(true); + } + else + re.setSelected(false); + + re.repaint(); + } + controller.selectTerm(pos); + } + + /** + * implements the Observer-Pattern + * + * @param o the Model or Controller which caused the call + * @param arg unused + */ + public void update(Observable o, Object arg) { + if (o instanceof TermHistory) { + setOutputTextArea(((TermHistory)o).getCurrentTermSteps()); + + if (arg != null) + setInputTextField((String)arg); + + } else if (o instanceof TermHandler) { + currentOutputString = ((ITermHandler)o).getFormatString(true); + + //clear RenderTarget + workScreen.getRenderLabel().clear(); + + //render new term + renderedTerm = renderer.drawTerm(currentOutputString, this); + + markFreeVars = false; + markBoundVars = false; + + } else { + writeComment("Unknown Observable!", false); + } + } + + /** + * Sets the content of the input text field. + * + * @param s string + */ + public void setInputTextField(String s) { + workScreen.getInputTextField().setText(s); + } + + /** + * Sets the content of the output text area. + * + * @param list list of strings + */ + public void setOutputTextArea(List list) { + workScreen.getOutputTextArea().setText(TERM_FONT_HTML + listToString((List)list) + ""); + updateButtonStatus(); + } + + /** + * Refreshes the shortcut list. + */ + public void refreshShortcutList() { + workScreen.refreshListModel(); + } + + /** + * Writes a comment to the commentLine Label. + * + * @param comment the Commentstring + * @param ok success or error comment + */ + public void writeComment(String comment, boolean ok) { + if (ok) { + workScreen.getCommentLine().setForeground(goodNews); + } else { + workScreen.getCommentLine().setForeground(badNews); + } + workScreen.getCommentLine().setText(comment); + } + + public void clearComment() { + workScreen.getCommentLine().setText(" "); + } + + /** + * Generates formatted outputString for outputTextField + * from history of mementos. + * + * @param List of Strings + */ + public String listToString(List l) { + String s, res = ""; + if (l != null) { + Iterator i = l.iterator(); + s = i.next(); + s = s.replaceAll("<", "<"); + s = s.replaceAll(">", ">"); + res = "       " + s + "
          "; + while (i.hasNext()) { + s = i.next(); + s = s.replaceAll("<", "<"); + s = s.replaceAll(">", ">"); + if (s.charAt(0) == '=') + res = res + "" + s.charAt(0) + "" + " " + s.substring(1) + "
          "; + else + res = res + "" + Constants.ARROW_R + "" + "" + s.charAt(0) + "" + " " + s.substring(1) + "
          "; + } + } + return res; + } + + /** + * helperfunction for ShortcutPanel to insert a shortcut + * + * @param the "" to be insert + */ + public void insertShortcut() { + + if (workScreen.getShortcutListField().getSelectedValue() != null) { + String s = (String) workScreen.getShortcutListField().getSelectedValue(); + if(s != null) { + String tft = workScreen.getInputTextField().getText(); + inpCaret = workScreen.getInputTextField().getSelectionStart(); + String part1 = tft.substring(0, inpCaret); + String part2 = tft.substring(workScreen.getInputTextField().getSelectionEnd()); + workScreen.getInputTextField().setText(part1 + s + part2); + workScreen.getInputTextField().setCaretPosition(inpCaret + s.length()); + workScreen.getInputTextField().requestFocus(); + } + } + } + + /** + * helperfunction for ShortcutPanel to delete a shortcut from the shortcutList + * + */ + public void deleteShortcut() { + if (workScreen.getShortcutListField().getSelectedValue() != null) { + String s = (String) workScreen.getShortcutListField().getSelectedValue(); + if (s != null && !ShortcutHandler.getInstance().isShortcutPredefined(s)) { + ShortcutHandler.getInstance().removeShortcut(s); + workScreen.refreshListModel(); + } + } + } + + /** + * helperfunction for ShortcutPanel to create a new shortcut for the shortcutList + * + */ + public void createShortcut() { + if (workScreen.getInputTextField().getText().replaceAll(" ", "").equals("")) { + writeComment(Messages.getString("lambda","ltxt.inputSCTerm"), false); + } else { + currentTerm = workScreen.getInputTextField().getText().replaceAll(" ", ""); + workScreen.getInputTextField().setText(currentTerm); + + if (ShortcutHandler.getInstance().getShortcutRepresentation(currentTerm) != null) { + writeComment(Messages.getString("lambda","ltxt.scTermExists") + " (" + + ShortcutHandler.getInstance().getShortcutRepresentation(currentTerm) + ")",false); + } else { + LambdaException le = controller.validateInputString(currentTerm); + if (le != null) { + writeComment("Error: " + le.getMessage(), false); + workScreen.getInputTextField().setCaretPosition(le.getIndex()-1); + workScreen.getInputTextField().moveCaretPosition(le.getIndex()); + } else { + writeComment(Messages.getString("lambda","ltxt.termCorrect"), true); + clearComment(); + workScreen.changeVisibility(); + workScreen.getInputSCName().setText(""); + workScreen.getInputSCName().setCaretPosition(1); + workScreen.getInputSCName().moveCaretPosition(5); + workScreen.getInputSCName().requestFocus(); + } + } + } + } + + private void inputSCAction() { + String name = workScreen.getInputSCName().getText().replaceAll(" ", ""); + if (!name.startsWith("<") || !name.endsWith(">")) { + writeComment(Messages.getString("lambda","ltxt.scNameFault"), false); + workScreen.getInputSCName().requestFocus(); + } else { + if (ShortcutHandler.getInstance().getShortcutList().contains(name)) { + writeComment(Messages.getString("lambda","ltxt.scNameExists"), false); + workScreen.getInputSCName().requestFocus(); + } else { + try { + ShortcutHandler.getInstance().addShortcut(name, currentTerm, false); + workScreen.changeVisibility(); + workScreen.refreshListModel(); + workScreen.getInputTextField().setText(name); + writeComment(Messages.getString("lambda", "ltxt.input"), true); + workScreen.getInputTextField().requestFocus(); + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } catch (LambdaException e) { + e.printStackTrace(); + } + } + } + } + + /** + * opens a dialog to select a new name for the Variable which should be alphaconverted + * + * @param unusedVars a Set of Strings containing all possible choices + * @return returns the choosen name for the Alphaconversion + */ + public String selectNewAlphaVar(Set unusedVars) { + String[] unused = unusedVars.toArray(new String[0]); + return unused[JOptionPane.showOptionDialog(this.contentPane, + Messages.getString("lambda","dia.alphaMessage"), + Messages.getString("lambda","dia.alphaTitle"), + JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, + null, unused, unused[0])]; + } + + /** + * action after the input is completed + */ + public void inputCompleteAction() { + currentTerm = workScreen.getInputTextField().getText(); + currentTerm = currentTerm.replaceAll(" ", ""); + workScreen.getInputTextField().setText(currentTerm); + if (currentTerm.length() == 0) return; + clearComment(); + renderer.setOpcode(""); + LambdaException le = controller.processInputString(currentTerm, GUIController.this); + + workScreen.getInputTextField().requestFocus(); + if(le == null) { + writeComment(Messages.getString("lambda","ltxt.termCorrect"), true); + mc.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + else { + writeComment("Error: " + le.getMessage(), false); + workScreen.getInputTextField().setCaretPosition(le.getIndex()); + workScreen.getInputTextField().moveCaretPosition(le.getIndex()+1); + workScreen.getOutputTextArea().setText(""); + workScreen.getRenderLabel().clear(); + } + } + + /** + * enables/disables the redo/undo buttons when redo/undo is(n't) possible + */ + private void updateButtonStatus() { + redoStepButton.setEnabled(controller.isRedoStepPossible()); + undoStepButton.setEnabled(controller.isUndoStepPossible()); + redoAllStepsButton.setEnabled(controller.isRedoStepPossible()); + undoAllStepsButton.setEnabled(controller.isUndoStepPossible()); + } + +} diff --git a/src/org/jalgo/module/lambda/view/RenderElement.java b/src/org/jalgo/module/lambda/view/RenderElement.java new file mode 100644 index 0000000..d3703e6 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/RenderElement.java @@ -0,0 +1,164 @@ +package org.jalgo.module.lambda.view; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.Set; + +import javax.swing.JLabel; + +import org.jalgo.module.lambda.model.Format; + +/** + * Represents the particular rendered Termparts in the renderLabel. + * Instances are created by the Renderer. + */ +public class RenderElement extends JLabel implements MouseListener { + + private static final long serialVersionUID = 1322379355306466942L; + + private String text; + private String termPosition; + private boolean showBoundVar; + private boolean showFreeVar; + private boolean show_alpha_possible; + private boolean show_beta_possible; + private boolean isSelected; + private boolean isHighlighted; + private boolean hideBrackets; + private GUIController parent; + + public static final Color BOUND_VAR_COLOR = new Color(255, 0, 0); + public static final Color FREE_VAR_COLOR = new Color(0, 255, 0); + + public static final Color HIGHLIGHT_COLOR = new Color(255, 215, 0); + public static final Color NORMAL_COLOR = Color.black; + + public static final Color BRACKET_COLOR = new Color(220, 220, 220); + + public static final Color SELECTED_COLOR = new Color(255, 160, 122); + public static final Color NONSELECTED_COLOR = Color.white; + + + public RenderElement(Set format, String text, String termPos, GUIController parent) { + this.text = text; + this.setText(this.text); + this.termPosition = termPos; + this.parent = parent; + + this.setFont(GUIController.TERM_FONT); + + this.setOpaque(true); + this.setVisible(true); + + this.addMouseListener(this); + + this.validate(); + } + + public void paintComponent(Graphics g) { + super.paintComponent(g); + + //set default values + if((this.text == "(" || this.text == ")") && hideBrackets) { + this.setForeground(BRACKET_COLOR); + } + else { + this.setForeground(NORMAL_COLOR); + } + this.setBackground(NONSELECTED_COLOR); + + //overwrite with format values - order gives priority of the formats + if(this.showFreeVar) { + this.setForeground(FREE_VAR_COLOR); + } + + if(this.showBoundVar) { + this.setForeground(BOUND_VAR_COLOR); + } + + if(this.show_alpha_possible) { + + } + + if(this.show_beta_possible) { + + } + + if(this.isSelected) { + this.setBackground(SELECTED_COLOR); + } + + if(this.isHighlighted) { + this.setForeground(HIGHLIGHT_COLOR); + } + } + + public String getTermPosition() { + return this.termPosition; + } + + public void mouseClicked(MouseEvent arg0) { + + parent.selectPosition(this.termPosition); + + this.repaint(); + } + + public void mouseEntered(MouseEvent arg0) { + + parent.highlightPosition(this.termPosition); + + this.repaint(); + } + + public void mouseExited(MouseEvent arg0) { + + parent.unhighlight(); + + this.repaint(); + } + + public void mousePressed(MouseEvent arg0) { + } + + public void mouseReleased(MouseEvent arg0) { + } + + public void setSelected(boolean s) { + this.isSelected = s; + } + + public void setHighlighted(boolean h) { + this.isHighlighted = h; + } + + public boolean getSelected() { + return this.isSelected; + } + + public boolean getHighlighted() { + return this.isHighlighted; + } + + public void markAsFreeVar(boolean s) { + this.showFreeVar = s; + } + + public void markAsBoundVar(boolean s) { + this.showBoundVar = s; + } + + public void showAlphaPossible(boolean s) { + this.show_alpha_possible = s; + } + + public void showBetaPossible(boolean s) { + this.show_beta_possible = s; + } + + public void hideBrackets(boolean h) { + hideBrackets = h; + } +} diff --git a/src/org/jalgo/module/lambda/view/RenderLabel.java b/src/org/jalgo/module/lambda/view/RenderLabel.java new file mode 100644 index 0000000..8fb5142 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/RenderLabel.java @@ -0,0 +1,31 @@ +package org.jalgo.module.lambda.view; + +import java.awt.Dimension; +import javax.swing.JPanel; + +/** + * wrapper class for a JLabel, fixing the setMinimumSize bug + * + * @author ben + * + */ + +public class RenderLabel extends JPanel { + static final long serialVersionUID = 1L; + + public void clear() { + this.removeAll(); + this.repaint(); + } + + public Dimension getPreferredSize() + { + Dimension pSize = super.getPreferredSize(); + Dimension mSize = getMinimumSize(); + int wid, ht; + + wid = pSize.width < mSize.width ? mSize.width : pSize.width; + ht = pSize.height < mSize.height ? mSize.height: pSize.height; + return new Dimension(wid, ht); + } +} diff --git a/src/org/jalgo/module/lambda/view/Renderer.java b/src/org/jalgo/module/lambda/view/Renderer.java new file mode 100644 index 0000000..86ce679 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/Renderer.java @@ -0,0 +1,93 @@ +package org.jalgo.module.lambda.view; + +import java.awt.FlowLayout; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import javax.swing.JComponent; +import javax.swing.JLabel; + +import org.jalgo.module.lambda.Constants; +import org.jalgo.module.lambda.model.FormatString; + +/** + * Creates instances of RenderElement to display the current working term at the renderLabel. + */ +public class Renderer { + + private JComponent renderTarget; + private JLabel opcode; + + public Renderer(JComponent rt) { + this.renderTarget = rt; + renderTarget.setLayout(new FlowLayout()); + ((FlowLayout)renderTarget.getLayout()).setVgap(0); + ((FlowLayout)renderTarget.getLayout()).setHgap(2); + ((FlowLayout)renderTarget.getLayout()).setAlignment(FlowLayout.LEADING); + + opcode = new JLabel(); + opcode.setFont(GUIController.TERM_FONT); + opcode.setText(Constants.ARROW_R + " "); + } + + /** + * adds the RenderElement re to the renderTarget (i.e. renderLabel) and makes it visible. + * @param re the RenderElement to be displayed + */ + public void drawRenderElement(RenderElement re) { + renderTarget.add(re); + re.setVisible(true); + } + /** + * Break the outputString down and render it as RenderElements. + * + * @param it iterator to the outputString + * @param parent GUIController to which the RenderElements should be added + */ + public List drawTerm(Iterator it, GUIController parent) { + + renderTarget.add(opcode); + + List l = new LinkedList(); + + // Term zerlegen und stueckweise rendern + RenderElement re; + FormatString fs; + + while(it.hasNext()) { + fs = it.next(); + re = new RenderElement(fs.getFormat(), fs.getText(), fs.getPosition(), parent); + drawRenderElement(re); + l.add(re); + } + + renderTarget.validate(); + + return l; + } + + public void setOpcode(String opcodeString) { + if (opcodeString == "" || opcodeString == "=") + opcode.setText(opcodeString + " "); + else + opcode.setText(Constants.ARROW_R + opcodeString + " "); + } + + /** + * Sets the renderTarget where the drawTerm method draws the RenderElements. + * @param rt the new renderTarget + */ + public void setRenderTarget(JComponent rt) { + this.renderTarget = rt; + } + + /** + * Removes all RenderElements from the renderTarget. + */ + public void clearRenderTarget() { + renderTarget.removeAll(); + renderTarget.repaint(); + renderTarget.validate(); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/lambda/view/WelcomeScreen.java b/src/org/jalgo/module/lambda/view/WelcomeScreen.java new file mode 100644 index 0000000..a792dcb --- /dev/null +++ b/src/org/jalgo/module/lambda/view/WelcomeScreen.java @@ -0,0 +1,117 @@ +package org.jalgo.module.lambda.view; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; + +public class WelcomeScreen extends JPanel implements ActionListener, MouseListener { + static final long serialVersionUID = 1L; + + private GUIController gui; + + private WelcomeScreenButton newButton; + private WelcomeScreenButton loadButton; + + private JLabel descLabel; + + public static final Color WELCOME_BACKGROUND_COLOR = new Color(238, 173, 14); + + public WelcomeScreen(GUIController gui) { + this.gui = gui; + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + descLabel = new JLabel(); + descLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + descLabel.setFont(new Font("Arial", Font.BOLD, 17)); + + newButton = new WelcomeScreenButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.welcomeNew")), + new ImageIcon(Messages.getResourceURL("lambda", "Icon.welcomeNewOver")), + Messages.getString("lambda", "wlc.new")); + loadButton = new WelcomeScreenButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.welcomeLoad")), + new ImageIcon(Messages.getResourceURL("lambda", "Icon.welcomeLoadOver")), + Messages.getString("lambda", "wlc.load")); + + newButton.addActionListener(this); + loadButton.addActionListener(this); + newButton.addMouseListener(this); + loadButton.addMouseListener(this); + + JPanel buttonPane = new JPanel(); + buttonPane.setBackground(WELCOME_BACKGROUND_COLOR); + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + buttonPane.add(newButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + buttonPane.add(loadButton); + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + + add(Box.createVerticalStrut(150)); + add(buttonPane); + add(Box.createVerticalStrut(50)); + add(descLabel); + } + + //@Override + public void actionPerformed(ActionEvent e) { + if(e.getSource().equals(newButton)) { + gui.installWorkScreen(); + } + + if(e.getSource().equals(loadButton)) { + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + } + } + + //@Override + public void mouseClicked(MouseEvent e) { + // TODO Auto-generated method stub + + } + + //@Override + public void mouseEntered(MouseEvent e) { + descLabel.setText(((WelcomeScreenButton)e.getSource()).getDescText()); + ((WelcomeScreenButton)e.getSource()).setSelected(true); + } + + //@Override + public void mouseExited(MouseEvent e) { + descLabel.setText(""); + ((WelcomeScreenButton)e.getSource()).setSelected(false); + } + + //@Override + public void mousePressed(MouseEvent e) { + // TODO Auto-generated method stub + + } + + //@Override + public void mouseReleased(MouseEvent e) { + // TODO Auto-generated method stub + + } + + /** + * paint function to set background + */ + protected void paintComponent(Graphics g) { + g.setColor(WELCOME_BACKGROUND_COLOR); + g.fillRect(0, 0, getWidth(), getHeight()); + } +} diff --git a/src/org/jalgo/module/lambda/view/WelcomeScreenButton.java b/src/org/jalgo/module/lambda/view/WelcomeScreenButton.java new file mode 100644 index 0000000..8201738 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/WelcomeScreenButton.java @@ -0,0 +1,33 @@ +package org.jalgo.module.lambda.view; + +import java.awt.Dimension; +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +public class WelcomeScreenButton extends JToggleButton { + private static final long serialVersionUID = 1L; + + private String descText; + + public WelcomeScreenButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, String descText) { + this.descText = descText; + + setIcon(defaultIcon); + setDisabledIcon(defaultIcon); + + setSelectedIcon(rolloverIcon); + setPressedIcon(rolloverIcon); + + setFocusPainted(false); + setBorder(new EmptyBorder(0, 0, 0, 0)); + setBorderPainted(false); + setMinimumSize(new Dimension(80, 80)); + setMaximumSize(getMinimumSize()); + setPreferredSize(getMinimumSize()); + } + + public String getDescText() { + return descText; + } +} diff --git a/src/org/jalgo/module/lambda/view/WorkScreen.java b/src/org/jalgo/module/lambda/view/WorkScreen.java new file mode 100644 index 0000000..0b39c13 --- /dev/null +++ b/src/org/jalgo/module/lambda/view/WorkScreen.java @@ -0,0 +1,376 @@ +package org.jalgo.module.lambda.view; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.Set; + +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.text.html.HTMLEditorKit; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.lambda.ShortcutHandler; + +public class WorkScreen extends JPanel{ + + /** + * builds the GUI for working + */ + private static final long serialVersionUID = 7414195714028071904L; + private ExchangeTextField inputTextField; + + private GridBagLayout gbl; + private GridBagConstraints c; + + private JButton clearButton; + private JButton doneButton; + private JButton toListButton; + + private JScrollPane outputAreaScrollPane; + private JEditorPane outputTextArea; + + private JLabel scTitle1; + private JList shortcutListField; + private DefaultListModel model; + private JScrollPane listScrollPane; + private JButton insertButton; + private JButton deleteButton; + private JButton newSCButton; + private JLabel scTitle2; + private JTextField inputSCName; + private JButton inputSCOKButton; + private JButton inputSCCancelButton; + + private RenderLabel renderLabel; + private JScrollPane renderScrollPane; + + private JLabel commentLine; + + private boolean scListVisible = true; + + public WorkScreen() { + + gbl = new GridBagLayout(); + setLayout(gbl); + + c = new GridBagConstraints(); + c.insets = new Insets(3,3,3,3); + + //special ComboBox for typing the LAMBDA + inputTextField = new ExchangeTextField(); + inputTextField.setFont(GUIController.INPUT_FONT); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 1.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(inputTextField, c); + add(inputTextField); + + //buttons relating to inputField + //clicked when inputterm has been typed + doneButton = new JButton(Messages.getString("lambda","btxt.done")); + doneButton.setToolTipText(Messages.getString("lambda","bts.done")); + c.gridx = 1; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(doneButton, c); + add(doneButton); + + //clears the inputBox + clearButton = new JButton(new ImageIcon(Messages.getResourceURL("lambda", "Icon.Clear"))); + clearButton.setToolTipText(Messages.getString("lambda","bts.clear")); + c.gridx = 3; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(clearButton, c); + add(clearButton); + + //make the outputTextArea scrollable + outputAreaScrollPane = new JScrollPane(); + outputTextArea = new JEditorPane(); + outputTextArea.setEditorKit(new HTMLEditorKit()); + outputTextArea.setEditable(false); + outputTextArea.setFont(GUIController.TERM_FONT); + outputAreaScrollPane.setViewportView(outputTextArea); + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 1; + c.gridheight = 3; + c.weightx = 1.0; + c.weighty = 1.0; + c.fill = GridBagConstraints.BOTH; + gbl.setConstraints(outputAreaScrollPane, c); + add(outputAreaScrollPane); + + //create title1 + scTitle1 = new JLabel(Messages.getString("lambda", "scDlg.ListLabel")); + scTitle1.setVisible(scListVisible); + c.gridx = 1; + c.gridy = 1; + c.gridwidth = 3; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(scTitle1, c); + add(scTitle1); + + //create the shortcutListField + model = new DefaultListModel(); + refreshListModel(); + shortcutListField = new JList(model); + shortcutListField.setFont(GUIController.INPUT_FONT); + listScrollPane = new JScrollPane(); + listScrollPane.setViewportView(shortcutListField); + listScrollPane.setVisible(scListVisible); + c.gridx = 1; + c.gridy = 2; + c.gridwidth = 3; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 1.0; + c.fill = GridBagConstraints.BOTH; + gbl.setConstraints(listScrollPane, c); + add(listScrollPane); + + //create buttons + insertButton = new JButton(Messages.getString("lambda", "scDlg.insBtn")); + insertButton.setToolTipText(Messages.getString("lambda","bts.insertSC")); + insertButton.setVisible(scListVisible); + c.gridx = 1; + c.gridy = 3; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(insertButton, c); + add(insertButton); + + deleteButton = new JButton(Messages.getString("lambda", "scDlg.delBtn")); + deleteButton.setToolTipText(Messages.getString("lambda","bts.deleteSC")); + deleteButton.setVisible(scListVisible); + deleteButton.setEnabled(false); + c.gridx = 2; + c.gridy = 3; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(deleteButton, c); + add(deleteButton); + + newSCButton = new JButton(Messages.getString("lambda", "scDlg.newBtn")); + newSCButton.setToolTipText(Messages.getString("lambda","bts.newSC")); + newSCButton.setVisible(scListVisible); + c.gridx = 3; + c.gridy = 3; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.NONE; + gbl.setConstraints(newSCButton, c); + add(newSCButton); + + //create title2 + scTitle2 = new JLabel(Messages.getString("lambda", "scDlg.ListLabel2")); + scTitle2.setVisible(!scListVisible); + c.gridx = 1; + c.gridy = 1; + c.gridwidth = 3; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(scTitle2, c); + add(scTitle2); + + //inputField for names of shortcuts + inputSCName = new JTextField(); + inputSCName.setEditable(true); + inputSCName.setFont(GUIController.INPUT_FONT); + inputSCName.setVisible(!scListVisible); + c.gridx = 1; + c.gridy = 2; + c.gridwidth = 3; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(inputSCName, c); + add(inputSCName); + + //button for confirm shortcut naming + inputSCOKButton = new JButton("OK"); + inputSCOKButton.setVisible(!scListVisible); + c.gridx = 1; + c.gridy = 3; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(inputSCOKButton, c); + add(inputSCOKButton); + + //button for cancel shortcut naming + inputSCCancelButton = new JButton("X"); + inputSCCancelButton.setVisible(!scListVisible); + c.gridx = 2; + c.gridy = 3; + c.gridwidth = 1; + c.gridheight = 1; + c.weightx = 0.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.HORIZONTAL; + gbl.setConstraints(inputSCCancelButton, c); + add(inputSCCancelButton); + + //setup the renderLabel + renderLabel = new RenderLabel(); + renderLabel.setOpaque(true); + renderLabel.setMinimumSize(new Dimension(0, 60)); + renderLabel.setBackground(Color.white); + renderLabel.setForeground(Color.white); + renderLabel.setVisible(true); + renderScrollPane = new JScrollPane(); + renderScrollPane.setViewportView(renderLabel); + renderScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); + renderScrollPane.setMinimumSize(new Dimension(0, 60)); + c.gridx = 0; + c.gridy = 4; + c.gridwidth = 4; + c.gridheight = 1; + c.weightx = 1.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.BOTH; + gbl.setConstraints(renderScrollPane, c); + add(renderScrollPane); + + //create a comment line for messages and states + commentLine = new JLabel(" "); + commentLine.setOpaque(true); + commentLine.setBackground(Color.white); + commentLine.setFont(GUIController.INPUT_FONT); + c.gridx = 0; + c.gridy = 5; + c.gridwidth = 4; + c.gridheight = 1; + c.weightx = 1.0; + c.weighty = 0.0; + c.fill = GridBagConstraints.BOTH; + gbl.setConstraints(commentLine, c); + add(commentLine); + + validate(); + } + + /** + * updates the Model of the shortcutList + */ + public void refreshListModel() { + model.clear(); + //add listentries from ShortcutHandler + Set shortcutSet = ShortcutHandler.getInstance().getShortcutList(); + for(String s : shortcutSet) { + if (s.length() > 0) model.addElement(s); + } + } + + /** + * switch the shortcutPanel to creation-view + * and back to list-view + */ + public void changeVisibility() { + scListVisible = !scListVisible; + + scTitle1.setVisible(scListVisible); + listScrollPane.setVisible(scListVisible); + insertButton.setVisible(scListVisible); + deleteButton.setVisible(scListVisible); + newSCButton.setVisible(scListVisible); + + scTitle2.setVisible(!scListVisible); + inputSCName.setVisible(!scListVisible); + inputSCOKButton.setVisible(!scListVisible); + inputSCCancelButton.setVisible(!scListVisible); + } + + public JTextField getInputSCName() { + return inputSCName; + } + + public JButton getInputSCOKButton() { + return inputSCOKButton; + } + + public JButton getInputSCCancelButton() { + return inputSCCancelButton; + } + public ExchangeTextField getInputTextField() { + return inputTextField; + } + + public RenderLabel getRenderLabel() { + return renderLabel; + } + + public JEditorPane getOutputTextArea() { + return outputTextArea; + } + + public JLabel getCommentLine() { + return commentLine; + } + + public JList getShortcutListField() { + return shortcutListField; + } + + public JButton getClearButton() { + return clearButton; + } + + public JButton getDoneButton() { + return doneButton; + } + + public JButton getToListButton() { + return toListButton; + } + + public JButton getInsertButton() { + return insertButton; + } + + public JButton getDeleteButton() { + return deleteButton; + } + + public JButton getNewSCButton() { + return newSCButton; + } +} diff --git a/src/org/jalgo/module/pulsemem/Admin.java b/src/org/jalgo/module/pulsemem/Admin.java new file mode 100644 index 0000000..7895bf5 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/Admin.java @@ -0,0 +1,18 @@ +package org.jalgo.module.pulsemem; + +import java.net.*; +import org.jalgo.main.util.*; + +public abstract class Admin { + private static final String ModuleName = "pulsemem"; + + public static String getLanguageString(String name) + { + return Messages.getString(ModuleName, name); + } + + public static URL getResourceURL(String name) + { + return Messages.getResourceURL(ModuleName, name); + } +} diff --git a/src/org/jalgo/module/pulsemem/CVS/Entries b/src/org/jalgo/module/pulsemem/CVS/Entries new file mode 100644 index 0000000..318b401 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/CVS/Entries @@ -0,0 +1,10 @@ +/Admin.java/1.1/Wed Jan 16 19:19:17 2008/-ko/ +/Controller.java/1.3/Mon Aug 16 12:05:49 2010/-ko/ +/ModuleConnector.java/1.2/Thu Jan 31 20:15:07 2008/-ko/ +/ModuleInfo.java/1.2/Thu Jan 31 20:15:07 2008/-ko/ +/Parsertest.java/1.2/Mon Aug 16 12:05:49 2010/-ko/ +D/core//// +/de.properties/1.1/Wed Jan 16 19:19:17 2008/-ko/ +/en.properties/1.1/Wed Jan 16 19:19:17 2008/-ko/ +D/gui//// +/res.properties/1.1/Wed Jan 16 19:19:17 2008/-ko/ diff --git a/src/org/jalgo/module/pulsemem/CVS/Repository b/src/org/jalgo/module/pulsemem/CVS/Repository new file mode 100644 index 0000000..27ca735 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem diff --git a/src/org/jalgo/module/pulsemem/CVS/Root b/src/org/jalgo/module/pulsemem/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/Controller.java b/src/org/jalgo/module/pulsemem/Controller.java new file mode 100644 index 0000000..d2626b7 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/Controller.java @@ -0,0 +1,241 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +/* Created on 05.05.2007 */ +package org.jalgo.module.pulsemem; + +import java.util.ArrayList; +import java.util.List; +import o3b.antlr.runtime.RecognitionException; +import org.jalgo.module.pulsemem.core.CodeGenerator; +import org.jalgo.module.pulsemem.core.PulsMemLine; +import org.jalgo.module.pulsemem.core.myInterpreter; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; +import org.jalgo.module.pulsemem.gui.components.InlineBreakpoint; +import c00.AST; +import c00.parser.ParseException; + +/** + * Controller.java + *

          + * The class Controller is an important connection between the + * GUI and the working model. + *

          + * + * @version $Revision: 1.21 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + * + */ +public class Controller { + private final ModuleConnector connector; + private final GUIController gui; + private AST.Program program; + private boolean validSourceCode = false; + private myInterpreter interpreter; + private CodeGenerator currentCodeGen; + + /** + * The constructor of the type. + * + * @param c + * An instance of the ModuleConnector, used in the current + * environment. + */ + public Controller(ModuleConnector c) { + currentCodeGen = new CodeGenerator(); + connector = c; + gui = new GUIController(connector, this); + } + + /** + * Returns the instance of the ModuleConnector, used in the current + * environment. + * + * @return The instance of the ModuleConnector, used in the current + * environment. + */ + public ModuleConnector getConnector() { + return connector; + } + + public CodeGenerator getCodeGenerator() { + return currentCodeGen; + } + + /** + * Returns the GUIController used in the current environment. + * + * @return The GUIController used in the current environment. + */ + public GUIController getGUIController() { + return gui; + } + + /** + * Specifies if the source code is valid. + * + * @return true, if the source code is valid. + */ + public boolean isSourceCodeValid() { + return validSourceCode; + } + + /** + * clears the PM (deletes all PM-Lines) + * + */ + public void clearPM() { + if (!(this.interpreter == null)) + this.interpreter.clearPm(); + } + + /** + * parses the given source code. + * + * @param text + * the source code to parse. + * @throws Exception + * the exception thrown. + */ + private void parse(String source) { + try { + program = (AST.Program) AST.parseString(source, "Program", null, false); + } catch (RecognitionException e) { + throw new ParseException(e.getMessage()); + } + } + + /** + * Beautifies the given source. + * + * @param source + * The source code that should be formatted. + * @return The formatted source code or the input string if an error + * occured. + */ + public String beautify(String source) { + String result; + try { + AST.Program program = (AST.Program) AST.parseString(source, "Program"); + CodeGenerator gen = new CodeGenerator(); + gen.SwitchProgram(program); + result = gen.getOutput(); + } catch (Exception e) { + result = source; + } + return result; + } + + /** + * Interprets and beautifies the source code within the source textbox. Is + * either called with the standart method interpretAndBeautify() oder with + * interpretAndBeautifyWithInternalIO, which is used for loading from Jalgo + * Files + * + * @return true, if the source code was successfully parsed and interpreted. + */ + private boolean interpretAndBeautifyCore() { + gui.clearInput(); + String errorMsg = null; + String originalSource = gui.getSourceCode(); + try { + // parsing tier 1 + parse(gui.getSourceCode()); + // beautifier tier 1 + currentCodeGen = new CodeGenerator(); + currentCodeGen.SwitchProgram(program); + // parsing tier 2 + gui.setSourceCode(currentCodeGen.getOutputWithRM()); + parse(currentCodeGen.getOutput()); + currentCodeGen = new CodeGenerator(); + currentCodeGen.SwitchProgram(program); + try { + interpreter.runInterpreter(program); + } catch (ParseException e) { + errorMsg = Admin.getLanguageString("gui.ParsingError"); + throw e; + } catch (Exception e) { + errorMsg = Admin.getLanguageString("gui.InterpretationError"); + throw e; + } + } catch (Throwable e) { + interpreter = null; + System.gc(); + if (errorMsg == null) + errorMsg = Admin.getLanguageString("gui.UnknownInterpretationError"); + errorMsg += ": " + e.getMessage(); + gui.switchParseStopEnabled(GUIConstants.PARSE_DISABLED); + } finally { + if (!(validSourceCode = (errorMsg == null))) { + gui.setSourceCode(originalSource); + gui.showErrorMessage(errorMsg); + } + else { + // add Breakpoints where a Label is 'hardcoded' + InlineBreakpoint inBP = gui.getInlineBreakpoints(); + for (PulsMemLine thisLine : (List) interpreter.getPm()) { + if (thisLine.isLabel()) + inBP.addLine(thisLine.getCodeLine()); + } + gui.updateTableBreakpoints(); + gui.setTableData(interpreter.getPm()); + } + } + return validSourceCode; + } + + /** + * standard-method for interpreting, see interpretAndBeautifyCore() + * + * @return true, if the source code was successfully parsed and + * interpreted.@return + */ + public boolean interpretAndBeautify() { + interpreter = new myInterpreter(); + interpreter.setIOSimulation(gui); + return interpretAndBeautifyCore(); + } + + /** + * method for interpreting with internal IO, used for Loading see + * interpretAndBeautifyCore() + * + * @return true, if the source code was successfully parsed and + * interpreted.@return + */ + public boolean interpretAndBeautifyWithInternalIO() { + interpreter = new myInterpreter(); + interpreter.setIOSimulation(connector); + return interpretAndBeautifyCore(); + } + + /** + * Restores the formatted input Source without return marks. + * + */ + public void restoreEditorModeSourceCode() { + if (currentCodeGen == null) + return; + gui.setSourceCode(currentCodeGen.getOutput()); + } +} diff --git a/src/org/jalgo/module/pulsemem/ModuleConnector.java b/src/org/jalgo/module/pulsemem/ModuleConnector.java new file mode 100644 index 0000000..dcfdbdf --- /dev/null +++ b/src/org/jalgo/module/pulsemem/ModuleConnector.java @@ -0,0 +1,194 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.pulsemem; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintStream; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.NoSuchElementException; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.module.pulsemem.core.IOSimulation; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; +import org.jalgo.module.pulsemem.gui.components.InlineBreakpoint; + +public class ModuleConnector extends AbstractModuleConnector implements IOSimulation { + private Controller controller; + + private GUIController gui; + + private LinkedList savedInput = new LinkedList(); + + static { + File f = new File("out.log"); + + try { + f.createNewFile(); + System.setOut(new PrintStream(f)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + f = new File("err.log"); + + try { + f.createNewFile(); + System.setErr(new PrintStream(f)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void init() { + controller = new Controller(this); + gui = controller.getGUIController(); + } + + @Override + public void run() { + gui.showPulseMem(); + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + try { + ObjectInputStream in = new ObjectInputStream(data); + InlineBreakpoint BPObj = (InlineBreakpoint)in.readObject(); + String CodeObj = (String)in.readObject(); + + InlineBreakpoint inBP = gui.getInlineBreakpoints(); + for (int thisBP : (HashSet)BPObj.getLineOfBreakpoints()) { + inBP.addLine(thisBP); + } + gui.setSourceCode(CodeObj); + + //this Boolean is saved as true, when the User Saved in + //parse-Mode + if (in.readBoolean()) { + this.savedInput.addAll((List)in.readObject());//read saved Input + gui.switchParseStopEnabled(GUIConstants.PARSE_ENABLED); + controller.interpretAndBeautifyWithInternalIO(); + gui.getMemPanel().setVisibleLines(in.readInt());//read Visible Lines + gui.getMemPanel().updateTable(); + } + + } + catch (IOException ex) { + ex.printStackTrace(); + } + catch (ClassNotFoundException ex) { + ex.printStackTrace(); + } + + } + + @Override + public ByteArrayOutputStream getDataForFile() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeObject(this.gui.getInlineBreakpoints()); + + //when in PulseMem-Mode, save the input the User made and currently shown line + if (gui.getGUIMode()==GUIConstants.PARSE_ENABLED) { + objOut.writeObject(this.controller.getCodeGenerator().getOutput()); + objOut.writeBoolean(true); + objOut.writeObject(gui.getInput()); + objOut.writeInt(gui.getMemPanel().getPulseMemTable().getNumberOfVisibleRows()); + } + else { + objOut.writeObject(gui.getSourceCode()); + objOut.writeBoolean(false); + } + + + objOut.close(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + return out; + } + + @Override + public void print() { + // no action performed here, JAlgo still doesn't support printing :-) + } + + /** + * Is called by the interpreter when interpreting with InternalIO + * whenever there is data to ouput. (used for loading jAlgo-files) + * This is exactly the same as in the GUI.output(). + */ + public void output(String output, int line) { + gui.getLinedTextarea().setCaretToLine(line); + Document doc = gui.getConsole().getDocument(); + try { + String outString = Admin + .getLanguageString("GUIController.printf_Start") + + line + + Admin.getLanguageString("GUIController.printf_End") //$NON-NLS-1$ + + output + "\n"; + doc.insertString(doc.getEndPosition().getOffset() - 1, outString, new SimpleAttributeSet()); //$NON-NLS-1$ + } catch (BadLocationException e) { + // ignore the error + } + + } + + /** + * Is called whenever the interpreter needs input while interpreting with InternalIO + * (used for loading jAlgo-files) + * + * @return the inputs the user made before saving, one by one in the order they were entered + */ + public int input(int line) { + try { + gui.getInput().add(savedInput.getFirst()); + return savedInput.removeFirst(); + } + + //this exception should never be thrown, as the number of saved Inputs + //always equals the number of inputs the programm requested (and therefore will request on load) + //(this is also the reason why the error is not translated :-) ) + catch (NoSuchElementException e) { + gui.showErrorMessage("Critical error while loading JAlgoFile!"); + return 0; + } + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/ModuleInfo.java b/src/org/jalgo/module/pulsemem/ModuleInfo.java new file mode 100644 index 0000000..a4447f1 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/ModuleInfo.java @@ -0,0 +1,81 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.pulsemem; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) + instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return Messages.getString("pulsemem", "ModuleInfo.ModuleName"); //$NON-NLS-1$ + } + + public String getVersion() { + return Messages.getString("pulsemem", "ModuleInfo.ModuleVersion"); //$NON-NLS-1$ + } + + public String getAuthor() { + return Messages.getString("pulsemem", "ModuleInfo.Programmers"); //$NON-NLS-1$ + } + + public String getDescription() { + return Admin.getLanguageString("Module.Description"); //$NON-NLS-1$ + } + + public URL getLogoURL() { + return Messages.getResourceURL("pulsemem", "Main_Icon"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public String getLicense() { + return Messages.getString("pulsemem", "ModuleInfo.LicenceType"); //$NON-NLS-1$ + } + + public URL getHelpSetURL() { + return Admin.getResourceURL("HelpSet_Name"); //$NON-NLS-1$ + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/Parsertest.java b/src/org/jalgo/module/pulsemem/Parsertest.java new file mode 100644 index 0000000..08cffb7 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/Parsertest.java @@ -0,0 +1,83 @@ +package org.jalgo.module.pulsemem; + + +import o3b.antlr.runtime.RecognitionException; +import org.jalgo.module.pulsemem.core.CodeGenerator; +import org.jalgo.module.pulsemem.core.PulsMemLine; +import org.jalgo.module.pulsemem.core.bufferedIOSimulation; +import org.jalgo.module.pulsemem.core.myInterpreter; +import c00.AST; + +/** + * This class is for testing purpose only + * + * @author Joachim Protze + */ +public class Parsertest { + + public static void main(String[] args) { + /* CodeGenerator i = new CodeGenerator(); + try { + AST.Program prog = (AST.Program)AST.parseFile("/home/jooschi/testdir/example.c", "Program"); + i.SwitchProgram(prog); + System.out.print(i.getOutput()); + } catch (RecognitionException e) { + e.printStackTrace(); + } +*/ + CodeGenerator cg = new CodeGenerator(); + myInterpreter i = new myInterpreter(); + + bufferedIOSimulation bios = new bufferedIOSimulation(); + bios.addInputBuffer(1); + bios.addInputBuffer(2); + bios.addInputBuffer(3); + bios.addInputBuffer(1); + bios.addInputBuffer(2); + bios.addInputBuffer(3); + + i.setIOSimulation(bios); + AST.Program prog=null; + try { + prog = (AST.Program)AST.parseFile("/home/jooschi/swt-praktikum/cvs-resp/j-Algo/examples/pulsmem/dyn02.c", "Program"); + } catch (RecognitionException e) { + e.printStackTrace(); + } + cg.SwitchProgram(prog); + try { + prog = (AST.Program)AST.parseString(cg.getOutput(), "Program"); + } catch (RecognitionException e) { + e.printStackTrace(); + } + cg = new CodeGenerator(); + cg.SwitchProgram(prog); + System.out.print(cg.getNumberedOutputWithRM()); +// System.out.print(cg.getOutput()); + i.runInterpreter(prog); + for (PulsMemLine pml : i.getPm()){ +// if (cg.getBreakpoints().contains(pml.getCodeLine())) + System.out.print(pml.toString()); + } + for (String integ : bios.getOutputBuffer()){ + System.out.println("printf out: "+integ); + } + bios.clearOutput(); + i.runInterpreter(prog); + for (PulsMemLine pml : i.getPm()){ +// if (cg.getBreakpoints().contains(pml.getCodeLine())) + System.out.print(pml.toString()); + } + for (String integ : bios.getOutputBuffer()){ + System.out.println("printf out: "+integ); + } + bios.clearOutput(); + i.runInterpreter(prog); + for (PulsMemLine pml : i.getPm()){ +// if (cg.getBreakpoints().contains(pml.getCodeLine())) + System.out.print(pml.toString()); + } + for (String integ : bios.getOutputBuffer()){ + System.out.println("printf out: "+integ); + } + } +} diff --git a/src/org/jalgo/module/pulsemem/core/CVS/Entries b/src/org/jalgo/module/pulsemem/core/CVS/Entries new file mode 100644 index 0000000..4f00967 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/CVS/Entries @@ -0,0 +1,13 @@ +/CliIOSimulation.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/CodeGenerator.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/FunctionHandler.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/IOSimulation.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/PulsMemLine.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/Stack.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/SwitchHandler.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/VarInfo.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/Variable.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/Zeiger.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/bufferedIOSimulation.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +D/exceptions//// +/myInterpreter.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ diff --git a/src/org/jalgo/module/pulsemem/core/CVS/Repository b/src/org/jalgo/module/pulsemem/core/CVS/Repository new file mode 100644 index 0000000..f34396d --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem/core diff --git a/src/org/jalgo/module/pulsemem/core/CVS/Root b/src/org/jalgo/module/pulsemem/core/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/core/CliIOSimulation.java b/src/org/jalgo/module/pulsemem/core/CliIOSimulation.java new file mode 100644 index 0000000..a2ccf73 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/CliIOSimulation.java @@ -0,0 +1,34 @@ +package org.jalgo.module.pulsemem.core; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + +public class CliIOSimulation implements IOSimulation{ + + public CliIOSimulation(){ + + } + public int input(int line) { + System.out.print("erwarte Eingabe: "); + InputStreamReader isr = new InputStreamReader ( System.in ); + BufferedReader br = new BufferedReader ( isr ); + String s = null; + try { + while ( (s = br.readLine ()) != null ) { + if (s.split("\n").length>0) break; + } + } + catch ( IOException ioe ) { + } + System.out.print(" - OK\n"); + return (new Integer(s)).intValue(); + } + + public void output(String output, int line) { + System.out.println("Ausgabe durch printf: "+output); + } + + +} diff --git a/src/org/jalgo/module/pulsemem/core/CodeGenerator.java b/src/org/jalgo/module/pulsemem/core/CodeGenerator.java new file mode 100644 index 0000000..71d5361 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/CodeGenerator.java @@ -0,0 +1,1043 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.ArrayList; +import java.util.List; +import c00.AST; +import c00.AST.*; + +/** + * This class generates a formated C00-Code from the AST + * + * @author Joachim Protze + */ +public class CodeGenerator { + private int TabLevel; + private String output=""; + private String outputWithRM=""; + private int ruecksprungMarke=1; + private String tabulator=" "; + private List breakpoints = new ArrayList(); + + /** + * Generates formated Code from the AST + * @param TabLevel + */ + public CodeGenerator(int TabLevel){ + this.TabLevel=TabLevel; + } + + /** + * Generates formated Code from the AST + * + */ + public CodeGenerator(){ + this(0); + } + + /** + * set tabulator-string (default " " - 2 blankspaces) + * @param tabulator + */ + public void setTabulator(String tabulator) { + this.tabulator = tabulator; + } + + /** + * prints TabLevel*2 blackspaces + * @param TabLevel + */ + private void printTab(int TabLevel){ + for (int i=0; i getBreakpoints(){ + return breakpoints; + } + + /** + * returns formated code w/o linenumbers + * @return + */ + public String getOutput(){ + return output; + } + + /** + * returns formated code w/o linenumbers + * @return + */ + public String getOutputWithRM(){ + return outputWithRM; + } + + /** + * returns formated code with linenumbers + * @return formated code with linenumbers + */ + public String getNumberedOutput(){ + String[] tmp=output.split("\n"); + String ret=""; + for (int i=1; i<=tmp.length; i++){ + if (i<10){ret += " ";} + if (i<100){ret += " ";} + ret+=i+" "+tmp[i-1]+"\n"; + } + return ret; + } + + /** + * returns formated code with linenumbers + * @return formated code with linenumbers + */ + public String getNumberedOutputWithRM(){ + String[] tmp=outputWithRM.split("\n"); + String ret=""; + for (int i=1; i<=tmp.length; i++){ + if (i<10){ret += " ";} + if (i<100){ret += " ";} + ret+=i+" "+tmp[i-1]+"\n"; + } + return ret; + } + + /** + * collects the formated code in the output-variable + * @param string + */ + private void myPrint(String string) { + myPrintWithRM(string); + output += string; + } + + /** + * collects the formated code in the output-variable + * @param string + */ + private void myPrintWithRM(String string) { + outputWithRM += string; + } + + /** + * differentiate between the possible Program-instances + * builds formated code from the commited ASTTree + * @param prog + */ + public void SwitchProgram(AST.Program prog){ + HandleExpandProgram((AST.ExpandProgram)prog); + } + + /** + * differentiate between the possible GlobalDeclarations-instances + * builds formated code from the commited ASTTree + * @param decls + */ + public void SwitchGlobalDeclarations(AST.GlobalDeclarations decls) { + if (decls instanceof AST.VarConstGlobDecls){ + HandleVarConstGlobDecls((AST.VarConstGlobDecls)decls); + } + if (decls instanceof AST.FuncGlobDecls){ + HandleFuncGlobDecls((AST.FuncGlobDecls)decls); + } + if (decls instanceof AST.EmptyGlobDecls){ + HandleEmptyGlobDecls((AST.EmptyGlobDecls)decls); + } + } + + /** + * differentiate between the possible Declarations-instances + * builds formated code from the commited ASTTree + * @param decls + */ + public void SwitchDeclarations(Declarations decls) { + if (decls instanceof AST.EmptyDecls){ + HandleEmptyDecls((AST.EmptyDecls)decls); + } + if (decls instanceof AST.PairDecls){ + HandlePairDecls((AST.PairDecls)decls); + } + } + + /** + * differentiate between the possible Declaration-instances + * builds formated code from the commited ASTTree + * @param decl + */ + public void SwitchDeclaration(Declaration decl) { + if (decl instanceof AST.VarDecl){ + HandleVarDecl((AST.VarDecl)decl); + } + if (decl instanceof AST.ConstDecl){ + HandleConstDecl((AST.ConstDecl)decl); + } + } + + /** + * differentiate between the possible ConstDeclarations-instances + * builds formated code from the commited ASTTree + * @param constDecls + */ + public void SwitchConstDeclarations(ConstDeclarations constDecls) { + if (constDecls instanceof AST.LastConstDecls){ + HandleLastConstDecls((AST.LastConstDecls)constDecls); + } + if (constDecls instanceof AST.PairConstDecls){ + HandlePairConstDecls((AST.PairConstDecls)constDecls); + } + } + + /** + * differentiate between the possible VarDeclarations-instances + * builds formated code from the commited ASTTree + * @param varDecls + */ + public void SwitchVarDeclarations(VarDeclarations varDecls) { + if (varDecls instanceof AST.InitVarLastDecls){ + HandleInitVarLastDecl((AST.InitVarLastDecls)varDecls); + } + if (varDecls instanceof AST.InitVarPairDecls){ + HandleInitVarPairDecls((AST.InitVarPairDecls)varDecls); + } + if (varDecls instanceof AST.RefVarLastDecls){ + HandleRefVarLastDecls((AST.RefVarLastDecls)varDecls); + } + if (varDecls instanceof AST.RefVarPairDecls){ + HandleRefVarPairDecls((AST.RefVarPairDecls)varDecls); + } + if (varDecls instanceof AST.VarLastDecls){ + HandleVarLastDecls((AST.VarLastDecls)varDecls); + } + if (varDecls instanceof AST.VarPairDecls){ + HandleVarPairDecls((AST.VarPairDecls)varDecls); + } + } + + /** + * differentiate between the possible FunctionImplementations-instances + * builds formated code from the commited ASTTree + * @param funcImpl + */ + public void SwitchFunctionImplementations(FunctionImplementations funcImpl) { + if (funcImpl instanceof AST.EmptyFuncImpls){ + HandleEmptyFuncImpls((AST.EmptyFuncImpls)funcImpl); + } + if (funcImpl instanceof AST.PairFuncImpls){ + HandlePairFuncImpls((AST.PairFuncImpls)funcImpl); + } + } + + /** + * differentiate between the possible FunctionHeading-instances + * builds formated code from the commited ASTTree + * @param funcHead + */ + public void SwitchFunctionHeading(FunctionHeading funcHead) { + if (funcHead instanceof AST.VoidFuncHead){ + HandleVoidFuncHead((AST.VoidFuncHead)funcHead); + } + if (funcHead instanceof AST.IntFuncHead){ + HandleIntFuncHead((AST.IntFuncHead)funcHead); + } + } + + /** + * differentiate between the possible ParamSections-instances + * builds formated code from the commited ASTTree + * @param prmSects + */ + public void SwitchParamSection(ParamSections prmSects) { + if (prmSects instanceof AST.ValueLastPrmSects){ + HandleValueLastPrmSects((AST.ValueLastPrmSects)prmSects); + } + if (prmSects instanceof AST.RefLastPrmSects){ + HandleRefLastPrmSects((AST.RefLastPrmSects)prmSects); + } + if (prmSects instanceof AST.ValuePairPrmSects){ + HandleValuePairPrmSects((AST.ValuePairPrmSects)prmSects); + } + if (prmSects instanceof AST.RefPairPrmSects){ + HandleRefPairPrmSects((AST.RefPairPrmSects)prmSects); + } + } + + /** + * differentiate between the possible FormalParameters-instances + * builds formated code from the commited ASTTree + * @param formParam + */ + public void SwitchFormalParameters(FormalParameters formParam) { + if (formParam instanceof AST.EmptyFormalParams){ + HandleEmptyFormalParams((AST.EmptyFormalParams)formParam); + } + if (formParam instanceof AST.VoidFormalParams){ + HandleVoidFormalParams((AST.VoidFormalParams)formParam); + } + if (formParam instanceof AST.NonVoidFormalParams){ + HandleNonVoidFormalParams((AST.NonVoidFormalParams)formParam); + } + } + + /** + * differentiate between the possible Block-instances + * builds formated code from the commited ASTTree + * @param block + */ + public void SwitchBlock(Block block) { + HandleExpandBlock((ExpandBlock)block); + } + + /** + * differentiate between the possible StatementSequence-instances + * builds formated code from the commited ASTTree + * @param stmSeq + */ + public void SwitchStatementSequence(StatementSequence stmSeq) { + if (stmSeq instanceof AST.EmptyStmSeq){ + HandleEmptyStmSeq((AST.EmptyStmSeq)stmSeq); + } + if (stmSeq instanceof AST.PairStmSeq){ + HandlePairStmSeq((AST.PairStmSeq)stmSeq); + } + } + + /** + * differentiate between the possible Statement-instances + * builds formated code from the commited ASTTree + * @param stm + */ + public void SwitchStatement(Statement stm) { + printTab(TabLevel); + if (stm instanceof AST.AssignStm){ + HandleAssignStm((AST.AssignStm)stm); + } + if (stm instanceof AST.PureIfStm){ + HandlePureIfStm((AST.PureIfStm)stm); + } + if (stm instanceof AST.ElseIfStm){ + HandleElseIfStm((AST.ElseIfStm)stm); + } + if (stm instanceof AST.SwitchStm){ + HandleSwitchStm((AST.SwitchStm)stm); + } + if (stm instanceof AST.WhileStm){ + HandleWhileStm((AST.WhileStm)stm); + } + if (stm instanceof AST.DoWhileStm){ + HandleDoWhileStm((AST.DoWhileStm)stm); + } + if (stm instanceof AST.ForStm){ + HandleForStm((AST.ForStm)stm); + } + if (stm instanceof AST.ContinueStm){ + HandleContinueStm((AST.ContinueStm)stm); + } + if (stm instanceof AST.BreakStm){ + HandleBreakStm((AST.BreakStm)stm); + } + if (stm instanceof AST.CompStm){ + HandleCompStm((AST.CompStm)stm); + } + if (stm instanceof AST.FuncCallStm){ + HandleFuncCallStm((AST.FuncCallStm)stm); + } + if (stm instanceof AST.EmptyReturnStm){ + HandleEmptyReturnStm((AST.EmptyReturnStm)stm); + } + if (stm instanceof AST.ExprReturnStm){ + HandleExprReturnStm((AST.ExprReturnStm)stm); + } + if (stm instanceof AST.ExprPrintfStm){ + HandleExprPrintfStm((AST.ExprPrintfStm)stm); + } + if (stm instanceof AST.ScanfStm){ + HandleScanfStm((AST.ScanfStm)stm); + } + if (stm instanceof AST.LabelStm){ + HandleLabelStm((AST.LabelStm)stm); + } + } + + /** + * differentiate between the possible Assignment-instances + * builds formated code from the commited ASTTree + * @param assign + */ + public void SwitchAssignment(Assignment assign) { + if (assign instanceof AST.ValueAssign){ + HandleValueAssign((AST.ValueAssign)assign); + } + if (assign instanceof AST.RefAssign){ + HandleRefAssign((AST.RefAssign)assign); + } + } + + /** + * differentiate between the possible SwitchBlock-instances + * builds formated code from the commited ASTTree + * @param switchBlock + */ + public void SwitchSwitchblock(SwitchBlock switchBlock) { + if (switchBlock instanceof AST.NoDefaultSwitchBlock){ + HandleNoDefaultSwitchBlock((AST.NoDefaultSwitchBlock)switchBlock); + } + if (switchBlock instanceof AST.DefaultSwitchBlock){ + HandleDefaultSwitchBlock((AST.DefaultSwitchBlock)switchBlock); + } + } + + /** + * differentiate between the possible CaseSequence-instances + * builds formated code from the commited ASTTree + * @param caseSeq + */ + public void SwitchCaseSequence(CaseSequence caseSeq) { + if (caseSeq instanceof AST.EmptyCaseSeq){ + HandleEmptyCaseSeq((AST.EmptyCaseSeq)caseSeq); + } + if (caseSeq instanceof AST.NoBreakPairCaseSeq){ + HandleNoBreakPairCaseSeq((AST.NoBreakPairCaseSeq)caseSeq); + } + } + + /** + * differentiate between the possible FunctionCall-instances + * builds formated code from the commited ASTTree + * @param funcCall + */ + public void SwitchFunctionCall(FunctionCall funcCall){ + HandleExpandFunctionCall((ExpandFuncCall)funcCall); + } + + /** + * differentiate between the possible ActualParameters-instances + * builds formated code from the commited ASTTree + * @param actParams + */ + public void SwitchActualParameters(ActualParameters actParams) { + if (actParams instanceof AST.EmptyActParams){ + HandleEmptyActParams((AST.EmptyActParams)actParams); + } + if (actParams instanceof AST.ExprListActParams){ + HandleExprListActParams((AST.ExprListActParams)actParams); + } + } + + /** + * differentiate between the possible ExpressionList-instances + * builds formated code from the commited ASTTree + * @param exprList + */ + public void SwitchExpressionList(ExpressionList exprList) { + if (exprList instanceof AST.LastExprList){ + HandleLastExprList((AST.LastExprList)exprList); + } + if (exprList instanceof AST.PairExprList){ + HandlePairExprList((AST.PairExprList)exprList); + } + } + + /** + * differentiate between the possible Expression-instances + * builds formated code from the commited ASTTree + * @param exp + */ + public void SwitchExpression(Expression exp) { + if (exp instanceof AST.PlusExpr){ + HandlePlusExpr((AST.PlusExpr)exp); + } + if (exp instanceof AST.MinusExpr){ + HandleMinusExpr((AST.MinusExpr)exp); + } + if (exp instanceof AST.FirstTermExpr){ + HandleFirstTermExpr((AST.FirstTermExpr)exp); + } + } + + /** + * differentiate between the possible FirstTerm-instances + * builds formated code from the commited ASTTree + * @param firstTerm + */ + public void SwitchFirstTerm(FirstTerm firstTerm) { + if (firstTerm instanceof AST.MultFirstTerm){ + HandleMultFirstTerm((AST.MultFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.DivFirstTerm){ + HandleDivFirstTerm((AST.DivFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.ModFirstTerm){ + HandleModFirstTerm((AST.ModFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.FactorFirstTerm){ + HandleFactorFirstTerm((AST.FactorFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.PlusFactorFirstTerm){ + HandlePlusFactorFirstTerm((AST.PlusFactorFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.MinusFactorFirstTerm){ + HandleMinusFactorFirstTerm((AST.MinusFactorFirstTerm)firstTerm); + } + } + + /** + * differentiate between the possible Term-instances + * builds formated code from the commited ASTTree + * @param term + */ + public void SwitchTerm(Term term) { + if (term instanceof AST.MultTerm){ + HandleMultTerm((AST.MultTerm)term); + } + if (term instanceof AST.DivTerm){ + HandleDivTerm((AST.DivTerm)term); + } + if (term instanceof AST.ModTerm){ + HandleModTerm((AST.ModTerm)term); + } + if (term instanceof AST.FactorTerm){ + HandleFactorTerm((AST.FactorTerm)term); + } + } + + /** + * differentiate between the possible Factor-instances + * builds formated code from the commited ASTTree + * @param factor + */ + public void SwitchFactor(Factor factor) { + if (factor instanceof AST.IdFactor){ + HandleIdFactor((AST.IdFactor)factor); + } + if (factor instanceof AST.RefIdFactor){ + HandleRefIdFactor((AST.RefIdFactor)factor); + } + if (factor instanceof AST.AddIdFactor){ + HandleAddIdFactor((AST.AddIdFactor)factor); + } + if (factor instanceof AST.NumFactor){ + HandleNumFactor((AST.NumFactor)factor); + } + if (factor instanceof AST.FuncCallFactor){ + HandleFuncCallFactor((AST.FuncCallFactor)factor); + } + if (factor instanceof AST.CompFactor){ + HandleCompFactor((AST.CompFactor)factor); + } + } + + /** + * differentiate between the possible BoolExpression-instances + * builds formated code from the commited ASTTree + * @param boolExp + */ + public void SwitchBoolExpression(BoolExpression boolExp) { + if (boolExp instanceof AST.EqBoolExpr){ + HandleEqBoolExpr((AST.EqBoolExpr)boolExp); + } + if (boolExp instanceof AST.NotEqBoolExpr){ + HandleNotEqBoolExpr((AST.NotEqBoolExpr)boolExp); + } + if (boolExp instanceof AST.LessBoolExpr){ + HandleLessBoolExpr((AST.LessBoolExpr)boolExp); + } + if (boolExp instanceof AST.GreatBoolExpr){ + HandleGreatBoolExpr((AST.GreatBoolExpr)boolExp); + } + if (boolExp instanceof AST.LessEqBoolExpr){ + HandleLessEqBoolExpr((AST.LessEqBoolExpr)boolExp); + } + if (boolExp instanceof AST.GreatEqBoolExpr){ + HandleGreatEqBoolExpr((AST.GreatEqBoolExpr)boolExp); + } + } + + private void HandleExpandProgram(AST.ExpandProgram code){ + myPrint("#include \n"); + SwitchGlobalDeclarations(code.globDecl); + SwitchFunctionImplementations(code.funcImpl); + myPrint("\nint main ("); + SwitchFormalParameters(code.formParam); + myPrint(")\n"); + SwitchBlock(code.block); + myPrint("\n"); + } + + private void HandleEmptyGlobDecls(EmptyGlobDecls decls) { +// myPrint(" /*epsilon*/ "); + } + + private void HandleFuncGlobDecls(FuncGlobDecls decls) { + SwitchFunctionHeading(decls.funcHead); + myPrint(";\n"); + SwitchGlobalDeclarations(decls.globDecls); + } + + private void HandleVarConstGlobDecls(VarConstGlobDecls decls) { + SwitchDeclaration(decls.decl); + SwitchGlobalDeclarations(decls.globDecls); + } + + private void HandleEmptyDecls(EmptyDecls decls) { +// myPrint(" /*epsilon*/ "); + } + + private void HandlePairDecls(PairDecls decls) { + SwitchDeclaration(decls.decl); + SwitchDeclarations(decls.decls); + } + + private void HandleVarDecl(VarDecl decl) { + printTab(TabLevel); + myPrint("int "); + SwitchVarDeclarations(decl.varDecls); + myPrint(";\n"); + } + + private void HandleConstDecl(ConstDecl decl) { + printTab(TabLevel); + myPrint("const int "); + SwitchConstDeclarations(decl.constDecls); + myPrint(";\n"); + } + + private void HandlePairConstDecls(PairConstDecls decls) { + myPrint(decls.ident + " = " + decls.number + ", "); + SwitchConstDeclarations(decls.constDecls); + } + + private void HandleLastConstDecls(LastConstDecls decls) { + myPrint(decls.ident + " = " + decls.number); + } + + private void HandleVarPairDecls(VarPairDecls decls) { + myPrint(decls.ident+", "); + SwitchVarDeclarations(decls.varDecls); + } + + private void HandleVarLastDecls(VarLastDecls decls) { + myPrint(decls.ident); + } + + private void HandleRefVarPairDecls(RefVarPairDecls decls) { + myPrint("*" + decls.ident + ", "); + SwitchVarDeclarations(decls.varDecls); + } + + private void HandleRefVarLastDecls(RefVarLastDecls decls) { + myPrint("*" + decls.ident); + } + + private void HandleInitVarPairDecls(InitVarPairDecls decls) { + myPrint(decls.ident + " = " + decls.number + ", "); + SwitchVarDeclarations(decls.varDecls); + } + + private void HandleInitVarLastDecl(InitVarLastDecls decls) { + myPrint(decls.ident + " = " + decls.number); + } + + private void HandlePairFuncImpls(PairFuncImpls impls) { + myPrint("\n"); + SwitchFunctionHeading(impls.funcHead); + myPrint("\n"); + SwitchBlock(impls.block); + SwitchFunctionImplementations(impls.funcImpls); + } + + private void HandleEmptyFuncImpls(EmptyFuncImpls impls) { +// myPrint(" /*epsilon*/ "); + } + + private void HandleIntFuncHead(IntFuncHead head) { + myPrint("int " + head.ident + " ("); + SwitchFormalParameters(head.formParams); + myPrint(")"); + } + + private void HandleVoidFuncHead(VoidFuncHead head) { + myPrint("void " + head.ident + " ("); + SwitchFormalParameters(head.formParams); + myPrint(")"); + } + + private void HandleEmptyFormalParams(EmptyFormalParams params) { +// myPrint(" /*epsilon*/ "); + } + + private void HandleVoidFormalParams(VoidFormalParams params) { + myPrint(" void "); + } + + private void HandleNonVoidFormalParams(NonVoidFormalParams params) { + SwitchParamSection(params.prmSects); + } + + private void HandleValueLastPrmSects(ValueLastPrmSects sects) { + myPrint("int "+sects.ident); + } + + private void HandleRefLastPrmSects(RefLastPrmSects sects) { + myPrint("int *"+sects.ident); + } + + private void HandleValuePairPrmSects(ValuePairPrmSects sects) { + myPrint("int "+sects.ident+", "); + SwitchParamSection(sects.prmSects); + } + + private void HandleRefPairPrmSects(RefPairPrmSects sects) { + myPrint("int *"+sects.ident+", "); + SwitchParamSection(sects.prmSects); + } + + private void HandleExpandBlock(ExpandBlock block) { + printTab(TabLevel); + myPrint("{\n"); + TabLevel++; + SwitchDeclarations(block.decls); + SwitchStatementSequence(block.stmSeq); + TabLevel--; + printTab(TabLevel); + myPrint("}\n"); + } + + private void HandlePairStmSeq(PairStmSeq seq) { + SwitchStatement(seq.stm); + SwitchStatementSequence(seq.stmSeq); + } + + private void HandleEmptyStmSeq(EmptyStmSeq seq) { +// myPrint(" /*epsilon*/ "); + } + + private void HandleAssignStm(AssignStm stm) { + SwitchAssignment(stm.assign); + myPrint(";\n"); + } + + private void HandlePureIfStm(PureIfStm stm) { + myPrint("if ("); + SwitchBoolExpression(stm.boolExp); + myPrint(")\n"); + if (!(stm.stm instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm); + if (!(stm.stm instanceof AST.CompStm)) TabLevel--; + } + + private void HandleElseIfStm(ElseIfStm stm) { + myPrint("if ("); + SwitchBoolExpression(stm.boolExp); + myPrint(")\n"); + if (!(stm.stm1 instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm1); + if (!(stm.stm1 instanceof AST.CompStm)) TabLevel--; + printTab(TabLevel); + myPrint("else\n"); + if (!(stm.stm2 instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm2); + if (!(stm.stm2 instanceof AST.CompStm)) TabLevel--; + } + + private void HandleSwitchStm(SwitchStm stm) { + myPrint("switch ("); + SwitchExpression(stm.exp); + myPrint(")\n"); + SwitchSwitchblock(stm.switchBlock); + } + + private void HandleWhileStm(WhileStm stm) { + myPrint("while ("); + SwitchBoolExpression(stm.boolExp); + myPrint(")\n"); + if (!(stm.stm instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm); + if (!(stm.stm instanceof AST.CompStm)) TabLevel--; + } + + private void HandleDoWhileStm(DoWhileStm stm) { + myPrint("do \n"); + if (!(stm.stm instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm); + if (!(stm.stm instanceof AST.CompStm)) TabLevel--; + myPrint(" while ("); + SwitchBoolExpression(stm.boolExp); + myPrint(")\n"); + } + + private void HandleForStm(ForStm stm) { + myPrint("for ("); + SwitchAssignment(stm.assign1); + myPrint("; "); + SwitchBoolExpression(stm.boolExp); + myPrint("; "); + SwitchAssignment(stm.assign2); + myPrint(")\n"); + if (!(stm.stm instanceof AST.CompStm)) TabLevel++; + SwitchStatement(stm.stm); + if (!(stm.stm instanceof AST.CompStm)) TabLevel--; + } + + private void HandleContinueStm(ContinueStm stm) { + myPrint("continue; \n"); + } + + private void HandleBreakStm(BreakStm stm) { + myPrint("break; \n"); + } + + private void HandleCompStm(CompStm stm) { +// printTab(TabLevel); + myPrint("{\n"); + TabLevel++; + SwitchDeclarations(stm.decls); +// myPrint(" "); + SwitchStatementSequence(stm.stmSeq); + TabLevel--; + printTab(TabLevel); + myPrint("}\n"); + } + + private void HandleFuncCallStm(FuncCallStm stm) { + SwitchFunctionCall(stm.funcCall); + myPrint("; \n"); + } + + private void HandleEmptyReturnStm(EmptyReturnStm stm) { + myPrint("return; \n"); + } + + private void HandleExprReturnStm(ExprReturnStm stm) { + myPrint("return "); + SwitchExpression(stm.expr); + myPrint(";\n"); + } + + private void HandleExprPrintfStm(ExprPrintfStm stm) { + myPrint("printf(\"" + stm.string + "\", "); + this.SwitchExpressionList(stm.exprList); + myPrint(");\n"); + } + + private void HandleScanfStm(ScanfStm stm) { + myPrint("scanf(\"%i\", &" + stm.ident + ");\n"); + } + + private void HandleLabelStm(LabelStm stm) { + breakpoints.add(stm.startLine); + myPrint("/*label " + stm.number + "*/\n"); + } + + private void HandleValueAssign(ValueAssign assign) { + myPrint(assign.ident +" = "); + SwitchExpression(assign.expr); + } + + private void HandleRefAssign(RefAssign assign) { + myPrint("*" + assign.ident +" = "); + SwitchExpression(assign.expr); + } + + + + private void HandleNoDefaultSwitchBlock(NoDefaultSwitchBlock block) { + printTab(TabLevel); + myPrint("{\n"); + TabLevel++; + SwitchCaseSequence(block.caseSeq); + TabLevel--; + printTab(TabLevel); + myPrint("}\n"); + } + + private void HandleDefaultSwitchBlock(DefaultSwitchBlock block) { + printTab(TabLevel); + myPrint("{\n"); + TabLevel++; + SwitchCaseSequence(block.caseSeq); + myPrint("default: \n"); + SwitchStatementSequence(block.stmSeq); + TabLevel--; + printTab(TabLevel); + myPrint("}\n"); + } + + private void HandleEmptyCaseSeq(EmptyCaseSeq seq) { +// myPrint("/*epsilon*/"); + } + + private void HandleNoBreakPairCaseSeq(NoBreakPairCaseSeq seq) { + myPrint("case "+ seq.number + ": \n"); + SwitchStatementSequence(seq.stmSeq); + SwitchCaseSequence(seq.caseSeq); + } + + private void HandleExpandFunctionCall(ExpandFuncCall funcCall) { + myPrint(funcCall.ident + "("); + SwitchActualParameters(funcCall.actParams); + myPrint(")"); + myPrintWithRM("/* $"+ruecksprungMarke+" */"); + funcCall.extra=ruecksprungMarke; + ruecksprungMarke++; + } + + + private void HandleEmptyActParams(EmptyActParams params) { +// myPrint("/*epsilon*/"); + } + + private void HandleExprListActParams(ExprListActParams params) { + SwitchExpressionList(params.exprList); + } + + private void HandleLastExprList(LastExprList list) { + SwitchExpression(list.expr); + } + + private void HandlePairExprList(PairExprList list) { + SwitchExpression(list.expr); + myPrint(", "); + SwitchExpressionList(list.exprList); + } + + private void HandlePlusExpr(PlusExpr expr) { + SwitchExpression(expr.expr); + myPrint(" + "); + SwitchTerm(expr.term); + } + + private void HandleMinusExpr(MinusExpr expr) { + SwitchExpression(expr.expr); + myPrint(" - "); + SwitchTerm(expr.term); + } + + private void HandleFirstTermExpr(FirstTermExpr expr) { + SwitchFirstTerm(expr.firstTerm); + } + + private void HandleMultFirstTerm(MultFirstTerm term) { + SwitchFirstTerm(term.firstTerm); + myPrint(" * "); + SwitchFactor(term.factor); + } + + private void HandleDivFirstTerm(DivFirstTerm term) { + SwitchFirstTerm(term.firstTerm); + myPrint(" / "); + SwitchFactor(term.factor); + } + + private void HandleModFirstTerm(ModFirstTerm term) { + SwitchFirstTerm(term.firstTerm); + myPrint(" % "); + SwitchFactor(term.factor); + } + + private void HandleFactorFirstTerm(FactorFirstTerm term) { + SwitchFactor(term.factor); + } + + private void HandlePlusFactorFirstTerm(PlusFactorFirstTerm term) { + myPrint("+"); + SwitchFactor(term.factor); + } + + private void HandleMinusFactorFirstTerm(MinusFactorFirstTerm term) { + myPrint("-"); + SwitchFactor(term.factor); + } + + private void HandleMultTerm(MultTerm term) { + SwitchTerm(term.term); + myPrint(" * "); + SwitchFactor(term.factor); + } + + private void HandleDivTerm(DivTerm term) { + SwitchTerm(term.term); + myPrint(" / "); + SwitchFactor(term.factor); + } + + private void HandleModTerm(ModTerm term) { + SwitchTerm(term.term); + myPrint(" % "); + SwitchFactor(term.factor); + } + + private void HandleFactorTerm(FactorTerm term) { + SwitchFactor(term.factor); + } + + private void HandleIdFactor(IdFactor factor) { + myPrint(factor.ident); + } + + private void HandleRefIdFactor(RefIdFactor factor) { + myPrint("*" + factor.ident); + } + + private void HandleAddIdFactor(AddIdFactor factor) { + myPrint("&" + factor.ident); + } + + private void HandleNumFactor(NumFactor factor) { + myPrint(""+factor.number); + } + + private void HandleFuncCallFactor(FuncCallFactor factor) { + SwitchFunctionCall(factor.funcCall); + } + + private void HandleCompFactor(CompFactor factor) { + myPrint("("); + SwitchExpression(factor.expr); + myPrint(")"); + } + + private void HandleEqBoolExpr(EqBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" == "); + SwitchExpression(expr.expr2); + } + + private void HandleNotEqBoolExpr(NotEqBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" != "); + SwitchExpression(expr.expr2); + } + + private void HandleLessBoolExpr(LessBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" < "); + SwitchExpression(expr.expr2); + } + + private void HandleGreatBoolExpr(GreatBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" > "); + SwitchExpression(expr.expr2); + } + + private void HandleLessEqBoolExpr(LessEqBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" <= "); + SwitchExpression(expr.expr2); + } + + private void HandleGreatEqBoolExpr(GreatEqBoolExpr expr) { + SwitchExpression(expr.expr1); + myPrint(" >= "); + SwitchExpression(expr.expr2); + } + + +} diff --git a/src/org/jalgo/module/pulsemem/core/FunctionHandler.java b/src/org/jalgo/module/pulsemem/core/FunctionHandler.java new file mode 100644 index 0000000..a5b39ff --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/FunctionHandler.java @@ -0,0 +1,161 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.ArrayList; +import org.jalgo.module.pulsemem.core.exceptions.EFunctionNotImplemented; +import org.jalgo.module.pulsemem.core.exceptions.EIncompatibleParameterCount; +import org.jalgo.module.pulsemem.core.exceptions.EIncompatibleParameterTypes; +import org.jalgo.module.pulsemem.core.exceptions.EReturnException; +import c00.AST; +import c00.AST.ASTTree; +import c00.AST.Block; +import c00.AST.FunctionHeading; +import c00.AST.IntFuncHead; +import c00.AST.VoidFuncHead; + + +/** + * This class holds all the information about a function. + * + * @author Joachim Protze +**/ +public class FunctionHandler { + private AST.FunctionHeading head; + private AST.Block block; + private Boolean returns=false; + private myInterpreter interpreter; + private String name; + private int [] scope; + + public String getName() { + return name; + } + + public int [] getScope(){ + return scope; + } + + public FunctionHeading getFunctionHeading() { + return head; + } + + /** + * Handles a C00-Function. Instanciated at declarationtime. Invoked at functioncalls. + * @param head is the functionHead, as declared in the functiondeclaration. + * @param block is the function-body, as declared in the functiondeclaration. + * @param interpreter is the instanciating Interpreter, to interprete the block. + */ + public FunctionHandler(FunctionHeading head, Block block, myInterpreter interpreter){ + this.head=head; + this.block=block; + if (head instanceof AST.IntFuncHead){ + returns=true; + name=((IntFuncHead)head).ident; + }else{ + name=((VoidFuncHead)head).ident; + } + this.interpreter=interpreter; + scope=new int [] {head.startLine,getTreeRoot(head).endLine}; + } + + /** + * Handles a C00-Function. Instanciated w/o body(block) as predeclaration. + * @param head is the functionHead, as declared in the functiondeclaration. + * @param interpreter is the instanciating Interpreter, to interprete the block. + */ + public FunctionHandler(FunctionHeading head, myInterpreter interpreter){ + this.head=head; + this.block=null; + if (head instanceof AST.IntFuncHead){ + returns=true; + name=((IntFuncHead)head).ident; + }else{ + name=((VoidFuncHead)head).ident; + } + this.interpreter=interpreter; + scope=new int [] {head.startLine,getTreeRoot(head).endLine}; + } + + /** + * returns the TreeRoot + * @param var + * @return the TreeRoot + */ + private ASTTree getTreeRoot(ASTTree ast) { + if (ast.parent == null ) + return ast; + return getTreeRoot(ast.parent); + } + + /** + * Handle a C00-functioncall. returns the returnvalue of the C00-Function + * @param paramList + * @return return-value + */ + public Object callFunction(ArrayList paramList){ + if (block==null) + throw new EFunctionNotImplemented(head.startLine); + ArrayList list=(ArrayList)interpreter.interpret(head); + if (paramList.size()!=list.size()){ + throw new EIncompatibleParameterCount(""+list.size(),""+paramList.size()); + } +/* for (Object i: paramList){ + if (i instanceof Variable){ + System.out.println(((Variable)i).getName()+"("+((Variable)i).getVisibilityLevel()+")"); + }else{ + System.out.println((Integer)i); + } + }*/ + for (Variable i: list){ + if (i instanceof Zeiger){ + if (paramList.get(list.indexOf(i)) instanceof Variable) + ((Zeiger)i).setTarget((Variable)paramList.get(list.indexOf(i))); + else + throw new EIncompatibleParameterTypes("Pointer","int",this.name,list.indexOf(i)); + }else{ + if (paramList.get(list.indexOf(i)) instanceof Integer) + i.setValue((Integer)paramList.get(list.indexOf(i))); + else + throw new EIncompatibleParameterTypes("int","Pointer",this.name,list.indexOf(i)); + } + } + Object ret= interpreter.interpret(block); + interpreter.setReturnFlag(false); + if (returns) + if(ret instanceof Integer){ + return ret; + }else{ + throw new EReturnException("void","int",block.endLine); + } + else + if(ret instanceof Integer){ + throw new EReturnException("int","void",block.endLine); + }else{ + return null; + } + } + + /** + * set functionBlock - used for predeclared functions + * @param block + */ + public void setBlock(AST.Block block) { + this.block = block; + } + + /** + * compares provided functionhead for lexicaly equality to the local functionhead + * intended for checking equality of predeclared functionhead and functionimplementationhead + * @param funcHead + * @return true on equality + */ + public Boolean equalHeads(FunctionHeading funcHead) { + CodeGenerator cg1 = new CodeGenerator(); + CodeGenerator cg2 = new CodeGenerator(); + cg1.SwitchFunctionHeading(funcHead); + cg2.SwitchFunctionHeading(this.head); + if (cg1.getOutput().equals(cg2.getOutput())) return true; + return cg1.getOutput().equals(cg2.getOutput()); + } + + +} diff --git a/src/org/jalgo/module/pulsemem/core/IOSimulation.java b/src/org/jalgo/module/pulsemem/core/IOSimulation.java new file mode 100644 index 0000000..20beab5 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/IOSimulation.java @@ -0,0 +1,23 @@ +package org.jalgo.module.pulsemem.core; + +/** + * Interface to Simulate the Functions printf and scanf + * the methods should simulate the i/o stream + * + * @author Joachim Protze + */ +public interface IOSimulation { + + /** + * accepts linenumber of the scanf-statement + * returns input in form of integers + * @return input in form of integers + */ + public int input(int line); + /** + * accepts output-String, linenumber of the printf-statement + * @param output-String + */ + public void output(String output, int line); + +} diff --git a/src/org/jalgo/module/pulsemem/core/PulsMemLine.java b/src/org/jalgo/module/pulsemem/core/PulsMemLine.java new file mode 100644 index 0000000..c2abe7c --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/PulsMemLine.java @@ -0,0 +1,134 @@ +package org.jalgo.module.pulsemem.core; + +import java.io.Serializable; +import java.util.List; + +import org.jalgo.module.pulsemem.core.exceptions.EPMLException; + +/** + * This class provides a pulsing memory line. + * Contains number of the codeline, returnlabel-stack and variable-stack + * + * @author Joachim Protze + */ +public class PulsMemLine extends Stack implements Serializable{ + private int codeLine; + private List ruecksprungMarken; + private int label=0; + /** + * + * @param codeLine + * @param ruecksprungMarken + * @param stack + */ + public PulsMemLine(int codeLine, List ruecksprungMarken, List stack, int visibilityLevel){ + this.codeLine=codeLine; + this.ruecksprungMarken=ruecksprungMarken; + this.stack=stack; + this.visibilityLevel=visibilityLevel; + } + /** + * + * @param codeLine + * @param ruecksprungMarken + * @param stack + * @param label + */ + public PulsMemLine(int codeLine, List ruecksprungMarken, List stack, int visibilityLevel, int label){ + this.codeLine=codeLine; + this.ruecksprungMarken=ruecksprungMarken; + this.stack=stack; + this.visibilityLevel=visibilityLevel; + this.label=label; + } + /** + * returns the C00-Codelinenumber of the PML + * @return C00-Codelinenumber of the PML + */ + public int getCodeLine() { + return codeLine; + } + /** + * returns the returnlabel-stack + * @return returnlabel-stack + */ + public List getRuecksprungMarken() { + return ruecksprungMarken; + } + /** + * formated CLI-like String of the PML + * z.B.: Zeile: 7 | a(0) = 5 | i(0) = null | a(1) = 5 | *j(1) = 5 | i(1) = null | + */ + public String toString(){ + String ret="Zeile: "+codeLine+" | "; + for (int i : ruecksprungMarken){ + ret += " $" + i + " "; + } + for (Variable i : stack){ + ret += "| " + i.toString() + " "; + } + ret += "|\n"; + return ret; + } + + /** + * + * @return + */ + public Boolean isLabel(){ + return label != 0; + } + + /** + * returns the Labelnumber of this PulsMemLine + * @return + */ + public int getLabel(){ + return label; + } + + /** + * formated CLI-like String of the PML + * z.B.: Zeile: 7 | a(0) = 5 | i(0) = null | a(1) = 5 | *j(1) = 5 | i(1) = null | + */ + public String visibleToString(){ + String ret="Zeile: "+codeLine+" | "; + for (int i : ruecksprungMarken){ + ret += " $" + i + " "; + } + for (Variable i : getVisibleStack()){ + ret += "| " + i.toString() + " "; + } + ret += "||"; + for (Variable i : getPointedStack()){ + ret += "| " + i.toString() + " "; + } + ret += "|\n"; + return ret; + } + @Override + public void addVar(Variable var) { + throw new EPMLException(); + } + @Override + public void decreaseVisibilityLevel() { + throw new EPMLException(); + } + @Override + public void increaseVisibilityLevel() { + throw new EPMLException(); + } + @Override + public void removeAllToplevelVar() { + throw new EPMLException(); + } + @Override + public void removeVar(Variable var) { + throw new EPMLException(); + } + @Override + public void setVisibilityLevel(int visibilityLevel) { + throw new EPMLException(); + } + +} diff --git a/src/org/jalgo/module/pulsemem/core/Stack.java b/src/org/jalgo/module/pulsemem/core/Stack.java new file mode 100644 index 0000000..bf3b3ce --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/Stack.java @@ -0,0 +1,163 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.ArrayList; +import java.util.List; + +import org.jalgo.module.pulsemem.core.exceptions.EMemoryError; + + +/** + * This class provides the Variables Stack + * + * @author Joachim Protze + */ +public class Stack { + protected List stack; + protected int visibilityLevel; + + /** + * Class Stack contains a variable stack and offers various functions get a filtered list of them + * + */ + public Stack(){ + stack=new ArrayList(); + visibilityLevel=0; + } + + /** + * returns a filtered List of actual visible variables + * @return a filtered List of actual visible variables + */ + public List getVisibleStack(){ + List ret=new ArrayList(); + for (Variable i : stack) + if(i.getVisibilityLevel()>=visibilityLevel || i.isGlobal()){ + Variable k=null; + for (Variable j : ret){ + if (i.getName().equals(j.getName())){ + k=j; + break; + } + } + ret.remove(k); + ret.add(i); + } + return ret; + } + + /** + * returns a filtered List of actual via Pointers visible Variables + * @return a filtered List of actual via Pointers visible Variables + */ + public List getPointedStack(){ + List ret=new ArrayList(); + for (Variable i : getVisibleStack()) + if(i instanceof Zeiger && i.isReferenced()){ + ret.add((Variable)i.getValue()); + } + return ret; + } + + /** + * returns a cloned list of all variables currently on the stack + * @return a cloned list of all variables currently on the stack + */ + public List cloneStack(){ + List ret=new ArrayList(); + for (Variable i : stack) + if (i instanceof Zeiger){ + if (!((Zeiger)i).isReferenced()){ + ((Zeiger)i).clone(); + }else{ + Variable k=null; + for (Variable j : ret){ + if (j.getName().equals(((Zeiger)i).getTarget().getName()) && j.getVisibilityLevel()==((Zeiger)i).getTarget().getVisibilityLevel()){ + k=j; + break; + } + } + ret.add(((Zeiger)i).clone(k)); + } + }else + ret.add(i.clone()); + return ret; + } + + /** + * returns a list of all variables currently on the stack + * @return a list of all variables currently on the stack + */ + public List getStack() { + return stack; + } + + /** + * returns the visibilitylevel for the variables + * @return the visibilitylevel + */ + public int getVisibilityLevel() { + return visibilityLevel; + } + + /** + * sets the visibilitylevel for the variables + * @param visibilityLevel + */ + public void setVisibilityLevel(int visibilityLevel) { + this.visibilityLevel = visibilityLevel; + } + + /** + * increases the visibilitylevel for the variables + * + */ + public void increaseVisibilityLevel() { + this.visibilityLevel++; + } + + /** + * decreases the visibilitylevel for the variables + * + */ + public void decreaseVisibilityLevel() { + this.visibilityLevel--; + } + + /** + * puts a variable to the stack + * @param var + */ + public void addVar(Variable var){ + stack.add(var); + } + + /** + * removes a variable from the stack + * @param var + */ + public void removeVar(Variable var){ + if (var.getVisibilityLevel() tmp=new ArrayList(); + for (Variable i : stack){ + if(i.getVisibilityLevel()>=visibilityLevel) + tmp.add(i); + } + for (Variable i : tmp){ + stack.remove(i); + } + decreaseVisibilityLevel(); + } + + + + +} diff --git a/src/org/jalgo/module/pulsemem/core/SwitchHandler.java b/src/org/jalgo/module/pulsemem/core/SwitchHandler.java new file mode 100644 index 0000000..68f772c --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/SwitchHandler.java @@ -0,0 +1,115 @@ +package org.jalgo.module.pulsemem.core; + +import c00.AST; +import c00.AST.CaseSequence; +import c00.AST.DefaultSwitchBlock; +import c00.AST.EmptyCaseSeq; +import c00.AST.NoBreakPairCaseSeq; +import c00.AST.NoDefaultSwitchBlock; +import c00.AST.SwitchBlock; + +/** + * This class is for handling switchblocks + * + * @author jooschi + */ +public class SwitchHandler { + + private int switchValue; + private SwitchBlock switchBlock; + private myInterpreter interpreter; + private Boolean run=false; + private Boolean useDefault=true; + + /** + * Handles a C00-switchblock. + * @param switchValue is the value of the expression, the cases are tested against + * @param switchBlock is the AST.switchBlock from the ASTTree. + * @param interpreter is the instanciating Interpreter, to interprete the leafes of the case-sequences + */ + public SwitchHandler(int switchValue, SwitchBlock switchBlock, myInterpreter interpreter){ + this.switchValue=switchValue; + this.switchBlock=switchBlock; + this.interpreter=interpreter; + } + + /** + * invoke the Switchhandler + * + */ + public void callSwitch(){ + SwitchSwitchBlock(switchBlock); + } + + /** + * differentiate between the possible switchBlocks + * @param switchBlock + * @return null + */ + private Object SwitchSwitchBlock(SwitchBlock switchBlock) { + if (switchBlock instanceof AST.NoDefaultSwitchBlock){ + interpretNoDefaultSwitchBlock((AST.NoDefaultSwitchBlock)switchBlock); + } + if (switchBlock instanceof AST.DefaultSwitchBlock){ + interpretDefaultSwitchBlock((AST.DefaultSwitchBlock)switchBlock); + } + return null; + } + + /** + * differentiate between the possible caseSequences + * @param caseSeq + * @return + */ + private Object SwitchCaseSequence(CaseSequence caseSeq) { + if (caseSeq instanceof AST.EmptyCaseSeq){ + interpretEmptyCaseSeq((AST.EmptyCaseSeq)caseSeq); + } + if (caseSeq instanceof AST.NoBreakPairCaseSeq){ + interpretNoBreakPairCaseSeq((AST.NoBreakPairCaseSeq)caseSeq); + } + return null; + } + + /** + * execute the switchBlock w/o default + * @param block + */ + private void interpretNoDefaultSwitchBlock(NoDefaultSwitchBlock block) { + SwitchCaseSequence(block.caseSeq); + } + + /** + * execute the switchBlock with default + * @param block + */ + private void interpretDefaultSwitchBlock(DefaultSwitchBlock block) { + SwitchCaseSequence(block.caseSeq); + if (useDefault || run) + interpreter.interpret(block.stmSeq); + } + + /** + * + * @param seq + */ + private void interpretEmptyCaseSeq(EmptyCaseSeq seq) { + } + + /** + * + * @param seq + */ + private void interpretNoBreakPairCaseSeq(NoBreakPairCaseSeq seq) { + if (switchValue==seq.number){ + useDefault=false; + run=true; + } + if (run==true){ + interpreter.interpret(seq.stmSeq); + if (interpreter.isBreakFlag()) + run=false; + } + SwitchCaseSequence(seq.caseSeq); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/VarInfo.java b/src/org/jalgo/module/pulsemem/core/VarInfo.java new file mode 100644 index 0000000..c0764eb --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/VarInfo.java @@ -0,0 +1,78 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.HashSet; +import java.util.Set; + +/** + * Saves nice-to-know infos about a variable + * + * @author Joschim Protze + */ +public class VarInfo { + + private int [] scope; + private Set appearance; + + /** + * + * @param begin of the scope + * @param end of the scope + * @param position of the variable + */ + public VarInfo(int begin, int end, Integer[] pos){ + scope=new int [] {begin,end}; + appearance=new HashSet(); + appearance.add(pos); + } + + public void addPos(Integer[] pos){ + appearance.add(pos); + } + + public String toString(){ + String ret="["+scope[0]+","+scope[1]+", "; + for (Integer[] i : appearance){ + ret+= "["+i[0]+","+i[1]+"]"; + } + return ret+"]"; + } + + /** + * returns the begin of the scope interval + * @return the begin of the scope interval + */ + public int getScopeBegin(){ + return scope[0]; + } + + /** + * returns the end of the scope interval + * @return the end of the scope interval + */ + public int getScopeEnd(){ + return scope[1]; + } + + /** + * returns the scope-interval as an int[2] + * begin=getScope()[0] + * end=getScope()[1] + * @return scope interval + */ + public int[] getScope(){ + return scope; + } + + /** + * for (Integer[] i : getAppearance()){ + * positionLine=i[0]; + * positionColumn=i[1]; + * //... + * } + * @return a Set<{Line,Col}> of the Variable Appearence + */ + public Set getAppearance(){ + return appearance; + } + +} diff --git a/src/org/jalgo/module/pulsemem/core/Variable.java b/src/org/jalgo/module/pulsemem/core/Variable.java new file mode 100644 index 0000000..03fa597 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/Variable.java @@ -0,0 +1,164 @@ +package org.jalgo.module.pulsemem.core; + +import org.jalgo.module.pulsemem.core.exceptions.EIncompatibleTypes; +import org.jalgo.module.pulsemem.core.exceptions.EMemoryError; +import org.jalgo.module.pulsemem.core.exceptions.EWriteConstant; +import org.jalgo.module.pulsemem.core.exceptions.ENotAPointerException; + +/** + * This class makes objects from our C00-Variables + * + * @author Joachim Protze + */ +public class Variable { + protected String name=null; + protected Integer value=null; + protected Boolean constant = false; + protected Boolean global = false; + protected int visibilityLevel=0; + protected VarInfo vi=null; + + /** + * Declare variable with initialisation + * @param name + * @param constant + * @param visibilityLevel + * @param value + */ + public Variable(String name, Boolean constant, int visibilityLevel, int value, VarInfo vi){ + this.name=name; + this.visibilityLevel=visibilityLevel; + this.value=value; + this.constant=constant; + this.vi=vi; + } + + /** + * Declare variable w/o initialisation + * @param name + * @param constant + * @param visibilityLevel + */ + public Variable(String name, Boolean constant, int visibilityLevel, VarInfo vi){ + this.name=name; + this.visibilityLevel=visibilityLevel; + this.constant=constant; + this.vi=vi; + } + + /** + * setze Informationen zur Variable + * @param Informationen zur Variable + */ + public void setVi(VarInfo vi){ + this.vi=vi; + } + + /** + * returns Informationen zur Variable + * @return Informationen zur Variable + */ + public VarInfo getVi(){ + return vi; + } + + /** + * returns the variablen-name + * @return variablen-name + */ + public String getName() { + return name; + } + + /** + * returns the actual value of the variable + * @return actual value of the variable + */ + public Object getValue() { + if (value==null) + throw new EMemoryError(this.name); + return value; + } + + /** + * set the value of the variable + * @param value + */ + public void setValue(Object value) { + if (constant) + throw new EWriteConstant(this.name); + if (!(value instanceof Integer)) + throw new EIncompatibleTypes("Int","Pointer",this.name); + this.value = (Integer)value; + } + + /** + * is the variable global declared? + * @return is the variable global declared? + */ + public Boolean isGlobal() { + return global; + } + + /** + * makes the variable global declared + * @param global + */ + public void setGlobal(Boolean global) { + this.global = global; + } + + /** + * returns dereferenced value + * @return dereferenced value + */ + public Object getTargetValue() { + throw new ENotAPointerException(this.name); + } + + /** + * returns referencation status + * @return referencation status + */ + + public Boolean isReferenced(){ + throw new ENotAPointerException(this.name); + } + + /** + * set dereferenced value + * @param value + */ + public void setTargetValue(Object value) { + throw new ENotAPointerException(this.name); + } + + /** + * returns a clone of the Object + * @return a clone of the Object + */ + public Variable clone(){ + Variable var; + if (value==null) + var=new Variable(this.name,this.constant,this.visibilityLevel,this.vi); + else + var=new Variable(this.name,this.constant,this.visibilityLevel,this.value,this.vi); + var.setGlobal(global); + return var; + } + + /** + * returns the visibility Level + * @return visibility Level + */ + public int getVisibilityLevel() { + return visibilityLevel; + } + public Boolean isConstant() { + return constant; + } + public String toString(){ +// return name + "("+visibilityLevel+")"+vi+" = " + value; + return name + "("+visibilityLevel+") = " + value; + } +} diff --git a/src/org/jalgo/module/pulsemem/core/Zeiger.java b/src/org/jalgo/module/pulsemem/core/Zeiger.java new file mode 100644 index 0000000..a040503 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/Zeiger.java @@ -0,0 +1,137 @@ +package org.jalgo.module.pulsemem.core; + +import org.jalgo.module.pulsemem.core.exceptions.ENullPointer; +import org.jalgo.module.pulsemem.core.exceptions.EPointerTargetException; + +/** + * This class makes objects from our C00-Pointers + * + * @author Joachim Protze + */ +public class Zeiger extends Variable { + protected Variable target=null; + + /** + * Declare Pointer with initialisation of destination target + * @param name + * @param target + * @param visibilityLevel + */ + public Zeiger(String name, Variable target, int visibilityLevel, VarInfo vi){ + super(name, false, visibilityLevel, vi); + this.target=target; + } + + /** + * Declare Pointer w/o initialisation of destination target + * @param name + * @param visibilityLevel + */ + public Zeiger(String name, int visibilityLevel, VarInfo vi){ + super(name, false, visibilityLevel,vi); + } + + /** + * returns the destination target + * @return destination target + */ + public Variable getTarget() { + if (target == null) + throw new ENullPointer(this.name); + return target; + } + + /** + * returns referencation status + * @return referencation status + */ + + public Boolean isReferenced(){ + return (target != null); + } + /** + * set the destination target + * @param target + */ + + public void setTarget(Variable target) { + this.target = target; + } + + /** + * returns target Variable + * @return target Variable + */ + + public Object getValue() { + if (target == null) + throw new ENullPointer(this.name); + return target; + } + + /** + * returns dereferenced value + * @return dereferenced value + */ + public Object getTargetValue() { + if (target == null) + throw new ENullPointer(this.name); + return target.getValue(); + } + + /** + * set dereferenced value + * @param value + */ + public void setValue(Object value) { + if (!(value instanceof Variable)) + throw new EPointerTargetException(this.name); + target=(Variable)value; + } + + /** + * set dereferenced value + * @param value + */ + public void setTargetValue(Object value) { + if (target == null) + throw new ENullPointer(this.name); + target.setValue(value); + } + + /** + * Clones the object with setting new destination target + * @param target + * @return cloned Pointer + */ + public Variable clone(Variable target) { + Zeiger var=new Zeiger(this.name,target,this.visibilityLevel,this.vi); + var.setGlobal(global); + return var; + } + + /** + * Clones the object w/o setting new destination target + * @return cloned Pointer + */ + public Variable clone() { + Zeiger var=new Zeiger(this.name,this.target,this.visibilityLevel,this.vi); + var.setGlobal(global); + return var; + } + + /** + * returns a String "*name(visibilityLevel) = value" + * z.B *j(1) = 5 + */ + public String toString(){ +// String ret="*" +name + "("+visibilityLevel+")"+vi+" = "; + String ret="*" +name + "("+visibilityLevel+") = "; + if (isReferenced()){ + ret+=target.toString(); + }else{ + ret+="n/a"; + } + return ret; + } +} diff --git a/src/org/jalgo/module/pulsemem/core/bufferedIOSimulation.java b/src/org/jalgo/module/pulsemem/core/bufferedIOSimulation.java new file mode 100644 index 0000000..1581663 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/bufferedIOSimulation.java @@ -0,0 +1,69 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.ArrayList; +import java.util.List; + + +public class bufferedIOSimulation implements IOSimulation{ + + private List inputBuffer=new ArrayList(); + private List outputBuffer=new ArrayList(); + + /** + * List-buffered I/O-Simulation (FIFO) - intended for testing purpose + * @param inputBuffer + */ + public bufferedIOSimulation(List inputBuffer){ + this.inputBuffer=inputBuffer; + } + public bufferedIOSimulation(){ + } + + public int input(int line) { + return inputBuffer.remove(0); + } + + public void output(String output, int line) { + outputBuffer.add(output); + } + + /** + * returns the inputbuffer + * @return inputbuffer + */ + public List getInputBuffer() { + return inputBuffer; + } + + /** + * set the inputbuffer + * @param inputBuffer + */ + public void setInputBuffer(List inputBuffer) { + this.inputBuffer = inputBuffer; + } + + /** + * fill the inputbuffer + * @param inputBuffer + */ + public void addInputBuffer(Integer inputBuffer) { + this.inputBuffer.add(inputBuffer); + } + + /** + * returns the bufferd output + * @return the bufferd output + */ + public List getOutputBuffer() { + return outputBuffer; + } + + /** + * delete all entries on output + * + */ + public void clearOutput(){ + outputBuffer=new ArrayList(); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Entries b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Entries new file mode 100644 index 0000000..105e3d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Entries @@ -0,0 +1,19 @@ +/ECycleLimitReached.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/EExecutionException.java/1.1/Wed Jan 16 19:19:11 2008/-ko/ +/EFunctionNotImplemented.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/EIncompatibleFunctionHeaders.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/EIncompatibleParameterCount.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EIncompatibleParameterTypes.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EIncompatibleTypes.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EMemoryError.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/ENotAPointerException.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/ENullPointer.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/EPMLException.java/1.1/Wed Jan 16 19:19:11 2008/-ko/ +/EPointerTargetException.java/1.1/Wed Jan 16 19:19:11 2008/-ko/ +/EPrintfException.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EReturnException.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/ETypeExpected.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EUndefinedFunctionCalled.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ +/EUserAbort.java/1.1/Wed Jan 16 19:19:11 2008/-ko/ +/EVarNotFound.java/1.1/Wed Jan 16 19:19:10 2008/-ko/ +/EWriteConstant.java/1.1/Wed Jan 16 19:19:13 2008/-ko/ diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Repository b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Repository new file mode 100644 index 0000000..fde394a --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem/core/exceptions diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Root b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.java b/src/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.java new file mode 100644 index 0000000..bec069c --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/ECycleLimitReached.java @@ -0,0 +1,20 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * This exception is thrown if the interpretation cycle count reaches it's maximum. + * + */ +public class ECycleLimitReached extends EExecutionException { + + private static final String LanguageNode = "Exception.ECycleLimitReached"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public ECycleLimitReached(int maxCycles) + { + super(Admin.getLanguageString(MessageStart) + maxCycles + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.java b/src/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.java new file mode 100644 index 0000000..1762cfa --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EExecutionException.java @@ -0,0 +1,13 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +/** + * Eine Exception die geworfen wird, wenn ein Laufzeitproblem beim Ausführen des Codes auftritt. + * @author Frank Herrlich + * + */ +public abstract class EExecutionException extends RuntimeException { + protected EExecutionException(String msg) + { + super(msg); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.java b/src/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.java new file mode 100644 index 0000000..5664493 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EFunctionNotImplemented.java @@ -0,0 +1,19 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Diese Eception wird geworfen, wenn eine nicht implementierte, aber deklarierte + * Funktion aufgerufen wird + * + */ +public class EFunctionNotImplemented extends EExecutionException { + private static final String LanguageNode = "Exception.EFunctionNotImplemented"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EFunctionNotImplemented(int line) { + super(Admin.getLanguageString(MessageStart) + line + + Admin.getLanguageString(MessageEnd)); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.java b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.java new file mode 100644 index 0000000..d55bf99 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleFunctionHeaders.java @@ -0,0 +1,20 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; +import c00.AST.FunctionHeading; + +/** + * Diese Exception wird geworfen, wenn eine Funktion implementiert wird, die vorher + * mit einem anderen Header definiert wurde. + * + */ +public class EIncompatibleFunctionHeaders extends EExecutionException { + private static final String LanguageNode = "Exception.EIncompatibleFunctionHeaders"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EIncompatibleFunctionHeaders(FunctionHeading h) { + super(Admin.getLanguageString(MessageStart) + h.startLine + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.java b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.java new file mode 100644 index 0000000..2696d34 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterCount.java @@ -0,0 +1,23 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Diese Exception wird geworfen, wenn ein anderer Typ als erwartet gefunden + * wurde. Streng genommen handelt es sich hierbei um einen syntaktischen Fehler. + * + * @author Frank Herrlich + * + */ +public class EIncompatibleParameterCount extends EExecutionException { + private static final String LanguageNode = "Exception.EIncompatibleParameterCount"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageBetween = LanguageNode + ".Message_Between"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EIncompatibleParameterCount(String ExpectedCount, String FoundCount) { + super(Admin.getLanguageString(MessageStart) + ExpectedCount + + Admin.getLanguageString(MessageBetween) + FoundCount + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.java b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.java new file mode 100644 index 0000000..ab0b040 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleParameterTypes.java @@ -0,0 +1,21 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * This exception is thrown when a function is called with the wrong + * types of parameters. + * + */ +public class EIncompatibleParameterTypes extends EExecutionException { + private static final String LanguageNode = "Exception.EIncompatibleParameterTypes"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageBetween = LanguageNode + ".Message_Between"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EIncompatibleParameterTypes(String ExpectedType, String FoundType, String name,int index) { + super(Admin.getLanguageString(MessageStart) + name + ". " + (index+1) + + Admin.getLanguageString(MessageBetween) + ExpectedType + + Admin.getLanguageString(MessageEnd) + FoundType); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.java b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.java new file mode 100644 index 0000000..2cc2ac8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EIncompatibleTypes.java @@ -0,0 +1,22 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Diese Eception wird geworfen, wenn zwei Typen inkompatibel sind. + * + * @author Frank Herrlich + * + */ +public class EIncompatibleTypes extends EExecutionException { + private static final String LanguageNode = "Exception.EIncompatibleTypes"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageBetween = LanguageNode + ".Message_Between"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EIncompatibleTypes(String typeName1, String typeName2, String varName) { + super(Admin.getLanguageString(MessageStart) + varName + + Admin.getLanguageString(MessageBetween) + typeName1 + + Admin.getLanguageString(MessageEnd) + typeName2); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.java b/src/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.java new file mode 100644 index 0000000..7b7d946 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EMemoryError.java @@ -0,0 +1,19 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Diese Exception wird geworfen, wenn auf einen nicht sichtbaren Speicherbereichzugegriffen wurde. + * @author Joachim Protze + * + */ +public class EMemoryError extends EExecutionException { + + private static final String LanguageNode = "Exception.EMemoryError"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + + public EMemoryError(String name) + { + super(Admin.getLanguageString(MessageStart) + name); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.java b/src/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.java new file mode 100644 index 0000000..efc20b4 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/ENotAPointerException.java @@ -0,0 +1,20 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * This exception is thrown when a non-pointer Variable is dereferenced. + * + */ +public class ENotAPointerException extends EExecutionException { + + private static final String LanguageNode = "Exception.ENotAPointerException"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public ENotAPointerException(String name) + { + super(Admin.getLanguageString(MessageStart) + name + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.java b/src/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.java new file mode 100644 index 0000000..74a54be --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/ENullPointer.java @@ -0,0 +1,21 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Diese Exception wird geworfen, wenn ein Pointer nicht initialisiert wurde. + * @author Frank Herrlich + * + */ +public class ENullPointer extends EExecutionException { + + private static final String LanguageNode = "Exception.ENullPointer"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public ENullPointer(String name) + { + super(Admin.getLanguageString(MessageStart) + name + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EPMLException.java b/src/org/jalgo/module/pulsemem/core/exceptions/EPMLException.java new file mode 100644 index 0000000..14beb3f --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EPMLException.java @@ -0,0 +1,17 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Exception is thrown, when a PML is modified. (Error in Java-Implementation) + */ +public class EPMLException extends EExecutionException { + + private static final String LanguageNode = "Exception.EPMLException"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + + public EPMLException() + { + super(Admin.getLanguageString(MessageStart)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.java b/src/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.java new file mode 100644 index 0000000..e8554ae --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EPointerTargetException.java @@ -0,0 +1,18 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Exception is thrown when an undefined function has been called. + * + */ +public class EPointerTargetException extends EExecutionException { + private static final String LanguageNode = "Exception.EPointerTargetException"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EPointerTargetException(String name) { + super(Admin.getLanguageString(MessageStart) + name + + Admin.getLanguageString(MessageEnd)); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.java b/src/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.java new file mode 100644 index 0000000..bbac8a6 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EPrintfException.java @@ -0,0 +1,17 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Diese Exception wird geworfen, wenn die Anazahl von Platzhaltern und Argumenten + * bei einer Printf Anweisung nicht übereinstimmt. + * + */ +public class EPrintfException extends EExecutionException { + private static final String LanguageNode = "Exception.EPrintfException"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + + public EPrintfException(int line) { + super(Admin.getLanguageString(MessageStart) + line); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EReturnException.java b/src/org/jalgo/module/pulsemem/core/exceptions/EReturnException.java new file mode 100644 index 0000000..d580682 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EReturnException.java @@ -0,0 +1,21 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Diese Exception wird geworfen, wenn eine Funktion einen Wert zurückliefert, + * der nicht dem erwartetetn Typ entspricht. + * + */ +public class EReturnException extends EExecutionException { + private static final String LanguageNode = "Exception.EReturnException"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageBetween = LanguageNode + ".Message_Between"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EReturnException(String t1, String t2, int line) { + super(Admin.getLanguageString(MessageStart) + t1 + + Admin.getLanguageString(MessageBetween) +t2 + + Admin.getLanguageString(MessageEnd)+ line); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.java b/src/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.java new file mode 100644 index 0000000..91e39c4 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/ETypeExpected.java @@ -0,0 +1,23 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Diese Exception wird geworfen, wenn ein anderer Typ als erwartet gefunden + * wurde. Streng genommen handelt es sich hierbei um einen syntaktischen Fehler. + * + * @author Frank Herrlich + * + */ +public class ETypeExpected extends EExecutionException { + private static final String LanguageNode = "Exception.ETypeExpected"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageBetween = LanguageNode + ".Message_Between"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public ETypeExpected(String typeExpectedName, String typeFoundName, int line) { + super(Admin.getLanguageString(MessageStart) + typeExpectedName + + Admin.getLanguageString(MessageBetween) + typeFoundName + + Admin.getLanguageString(MessageEnd) +line); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.java b/src/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.java new file mode 100644 index 0000000..d03d0e0 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EUndefinedFunctionCalled.java @@ -0,0 +1,16 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +/** + * Exception is thrown when an undefined function has been called. + * + */ +public class EUndefinedFunctionCalled extends EExecutionException { + private static final String LanguageNode = "Exception.EUndefinedFunctionCalled"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + + public EUndefinedFunctionCalled(int line) { + super(Admin.getLanguageString(MessageStart) + line); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.java b/src/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.java new file mode 100644 index 0000000..bda50b7 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EUserAbort.java @@ -0,0 +1,18 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * This exception is thrown if the user wants to abort the interpretation process. + * + */ +public class EUserAbort extends EExecutionException { + + private static final String LanguageNode = "Exception.EUserAbort"; + private static final String Message = LanguageNode + ".Message"; + + public EUserAbort() + { + super(Admin.getLanguageString(Message)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.java b/src/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.java new file mode 100644 index 0000000..285a3e6 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EVarNotFound.java @@ -0,0 +1,14 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.Admin; + +public class EVarNotFound extends EExecutionException{ + private static final String LanguageNode = "Exception.EVarNotFound"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EVarNotFound(String varName) { + super(Admin.getLanguageString(MessageStart) + varName + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.java b/src/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.java new file mode 100644 index 0000000..a42a508 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/exceptions/EWriteConstant.java @@ -0,0 +1,21 @@ +package org.jalgo.module.pulsemem.core.exceptions; + +import org.jalgo.module.pulsemem.*; + +/** + * Diese Exception wird geworfen, wenn auf einen nicht sichtbaren Speicherbereichzugegriffen wurde. + * @author Joachim Protze + * + */ +public class EWriteConstant extends EExecutionException { + + private static final String LanguageNode = "Exception.EWriteConstant"; + private static final String MessageStart = LanguageNode + ".Message_Start"; + private static final String MessageEnd = LanguageNode + ".Message_End"; + + public EWriteConstant(String name) + { + super(Admin.getLanguageString(MessageStart) + name + + Admin.getLanguageString(MessageEnd)); + } +} diff --git a/src/org/jalgo/module/pulsemem/core/myInterpreter.java b/src/org/jalgo/module/pulsemem/core/myInterpreter.java new file mode 100644 index 0000000..659b0fe --- /dev/null +++ b/src/org/jalgo/module/pulsemem/core/myInterpreter.java @@ -0,0 +1,1170 @@ +package org.jalgo.module.pulsemem.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jalgo.module.pulsemem.core.exceptions.ECycleLimitReached; +import org.jalgo.module.pulsemem.core.exceptions.EIncompatibleFunctionHeaders; +import org.jalgo.module.pulsemem.core.exceptions.EIncompatibleParameterCount; +import org.jalgo.module.pulsemem.core.exceptions.EPrintfException; +import org.jalgo.module.pulsemem.core.exceptions.EReturnException; +import org.jalgo.module.pulsemem.core.exceptions.ETypeExpected; +import org.jalgo.module.pulsemem.core.exceptions.EUndefinedFunctionCalled; +import org.jalgo.module.pulsemem.core.exceptions.EUserAbort; +import c00.AST; +import c00.AST.*; + + +/** + * This class is the core of the C00-Interpreter + * + * It interprets the given syntax tree and provides a pulsing memory chart. + * myInterpreter i = new myInterpreter(); + * i.runInterpreter(prog); + * System.out.print(pml.toString()); + * + * @author Joachim Protze + */ +public class myInterpreter { + private static int MAX_CYCLES = 1000000; + + private boolean continueFlag=false; + private boolean breakFlag=false; + private boolean returnFlag=false; + private List pm; + private Map vi; + private List ruecksprungMarken=new ArrayList(); + private Stack stack; + private List functions; + private IOSimulation ios; + private int cyclus=0; + private boolean aborting = false; + + /** + * + */ + public myInterpreter() { + pm=new ArrayList(); + vi=new HashMap(); +// ruecksprungMarken=new ArrayList(); + functions=new ArrayList(); + stack=new Stack(); + ios=new CliIOSimulation(); + } + + /** + * let the Interpreter interpret a C00-program in form of a AST + * @param program is instance of AST.Program + */ + public void runInterpreter(Program program){ + clear(); + interpret(program); + } + + /** + * returns an Object of type null, Boolean, int/Integer, List, Variable, List + * or List (with Object in {Integer, Variable}) + * @param ast is leaf of the AST + * @return Object of type null, Boolean, int/Integer, List, Variable, List or List (with Object in {Integer, Variable}) + */ + public Object interpret(AST.ASTTree ast){ + if (aborting) + throw new EUserAbort(); + + cyclus++; + if (cyclus>MAX_CYCLES) + throw new ECycleLimitReached(MAX_CYCLES); + + if (ast instanceof AST.Program){ + return SwitchProgram((AST.Program)ast); + } + if (ast instanceof AST.GlobalDeclarations){ + return SwitchGlobalDeclarations((AST.GlobalDeclarations)ast); + } + if (ast instanceof AST.Declarations){ + return SwitchDeclarations((AST.Declarations)ast); + } + if (ast instanceof AST.Declaration){ + return SwitchDeclaration((AST.Declaration)ast); + } + if (ast instanceof AST.ConstDeclarations){ + return SwitchConstDeclarations((AST.ConstDeclarations)ast); + } + if (ast instanceof AST.VarDeclarations){ + return SwitchVarDeclarations((AST.VarDeclarations)ast); + } + if (ast instanceof AST.FunctionImplementations){ + return SwitchFunctionImplementations((AST.FunctionImplementations)ast); + } + if (ast instanceof AST.FunctionHeading){ + return SwitchFunctionHeading((AST.FunctionHeading)ast); + } + if (ast instanceof AST.FormalParameters){ + return SwitchFormalParameters((AST.FormalParameters)ast); + } + if (ast instanceof AST.ParamSections){ + return SwitchParamSections((AST.ParamSections)ast); + } + if (ast instanceof AST.Block){ + return SwitchBlock((AST.Block)ast); + } + if (ast instanceof AST.StatementSequence){ + return SwitchStatementSequence((AST.StatementSequence)ast); + } + if (ast instanceof AST.Statement){ + return SwitchStatement((AST.Statement)ast); + } + if (ast instanceof AST.Assignment){ + return SwitchAssignment((AST.Assignment)ast); + } + if (ast instanceof AST.FunctionCall){ + return SwitchFunctionCall((AST.FunctionCall)ast); + } + if (ast instanceof AST.ActualParameters){ + return SwitchActualParameters((AST.ActualParameters)ast); + } + if (ast instanceof AST.ExpressionList){ + return SwitchExpressionList((AST.ExpressionList)ast); + } + if (ast instanceof AST.Expression){ + return SwitchExpression((AST.Expression)ast); + } + if (ast instanceof AST.FirstTerm){ + return SwitchFirstTerm((AST.FirstTerm)ast); + } + if (ast instanceof AST.Term){ + return SwitchTerm((AST.Term)ast); + } + if (ast instanceof AST.Factor){ + return SwitchFactor((AST.Factor)ast); + } + if (ast instanceof AST.BoolExpression){ + return SwitchBoolExpression((AST.BoolExpression)ast); + } + return null; + } + + /** + * register your own I/O-Simulation + * @param ios + */ + public void setIOSimulation(IOSimulation ios){ + this.ios=ios; + } + + + /** + * sets returnFlag + * @param flag + */ + public void setReturnFlag(boolean flag) { + returnFlag=flag; + } + + /** + * returns the resulting pulsing memory as a list of pulsing memory lines (PulsMemLine) + * @return the resulting pulsing memory as a list of pulsing memory lines (PulsMemLine + */ + public List getPm(){ + return pm; + } + + /** + * deletes all PMLines (called when new C-File is loaded) + */ + + public void clearPm() { + pm=new ArrayList(); + } + + /** + * returns the enclosing block (Block,Program,CompoundStatement,FunctionImplementation) + * @param var + * @return the enclosing block (Block,Program,CompoundStatement,FunctionImplementation) + */ + private ASTTree getParentBlock(ASTTree var) { + if (var.parent instanceof AST.Block || var.parent instanceof AST.Program || var.parent instanceof AST.Statement ) + return var.parent; + if (var.parent instanceof AST.PairFuncImpls ) + return ((PairFuncImpls)var.parent).block; + + return getParentBlock(var.parent); + } + + /** + * returns the enclosing block (Block,Program,CompoundStatement,FunctionImplementation) + * @param var + * @return the enclosing block (Block,Program,CompoundStatement,FunctionImplementation) + */ + private boolean isIntFunction(ASTTree var) { + if (var.parent instanceof AST.PairFuncImpls || var.parent instanceof AST.Program){ + return !(var.parent instanceof VoidFuncHead); + } + return isIntFunction(var.parent); + } + + /** + * returns the Boolean value of the breakFlag - it signals, that an + * break-Stm was found and the end of the loop is not reached yet. + * @return Boolean + */ + public boolean isBreakFlag() { + return breakFlag; + } + + /** + * returns returnFlag + * @return returnFlag + */ + public boolean isReturnFlag() { + return returnFlag; + } + + /** + * returns the value of the simulated C00-IO-Call scanf("%i",&ident); + * @return int + */ + private int myScanf(int line) { + return ios.input(line); + } + + /** + * Handles the C00-IO-Call printf("%d",ident) + * @param string + */ + private void myPrintf(String value, int line) { + ios.output(value, line); + } + + /** + * cleanup before executing a new program + * + */ + private void clear() { + pm=new ArrayList(); + vi=new HashMap(); + ruecksprungMarken=new ArrayList(); + functions=new ArrayList(); + stack=new Stack(); + continueFlag=false; + breakFlag=false; + returnFlag=false; + } + + /** + * returns a copy of the actual RM-Stack + * @return a copy of the actual RM-Stack + */ + private List cloneRM(){ + List tmp = new ArrayList(); + for (int i : ruecksprungMarken){ + tmp.add(i); + } + return tmp; + } + + /** + * creates a new PM-line + * @param line + */ + private void newPmLine(int line){ + pm.add(new PulsMemLine(line,cloneRM(),stack.cloneStack(), stack.getVisibilityLevel())); + } + + /** + * creates a new PM-label-line + * @param line + */ + private void newPmLine(int line, int label){ + pm.add(new PulsMemLine(line,cloneRM(),stack.cloneStack(), stack.getVisibilityLevel(), label)); + } + + /** + * returns the VarInfo-Object for the declared var. Creates one if not already exists. + * @param var + * @return the VarInfo-Object for the declared var. Creates one if not already exists. + */ + private VarInfo searchForVarinfo(ASTTree var){ + ASTTree block= getParentBlock(var); + VarInfo ret; + if (vi.containsKey(var.startLine+"_"+var.startColumn)){ + ret=vi.get(var.startLine+"_"+var.startColumn); + ret.addPos(new Integer [] {var.startLine,var.startColumn}); + }else{ + int offset = 0; + if ((var instanceof AST.RefLastPrmSects) || (var instanceof AST.RefPairPrmSects)) + offset = "int *".length(); + else if ((var instanceof AST.ValueLastPrmSects) || (var instanceof AST.ValuePairPrmSects)) + offset = "int ".length(); + + ret = new VarInfo(var.startLine,block.endLine,new Integer [] {var.startLine,var.startColumn + offset}); + vi.put(var.startLine+"_"+block.endLine, ret); + } + return ret; + } + + /** + * returns a Functionhandler selected by name from the funtions-List + * @param name + * @return FunctionHandler + */ + private FunctionHandler getFunctionByName(String name){ + for (FunctionHandler i : functions){ + if (i.getName().equals(name)) + return i; + } + return null; + } + + /** + * returns a Variable selected by name from the visible stack + * @param name + * @return Variable + */ + private Variable getVariableByName(String name){ + for (Variable i : stack.getVisibleStack()){ + if (i.getName().equals(name)) + return i; + } + return null; + } + + /** + * returns null-Object + * @param prog + * @return null + */ + private Object SwitchProgram(AST.Program prog){ + interpretExpandProgram((AST.ExpandProgram)prog); + return null; + } + + /** + * returns declared Variables as List + * @param decls + * @return List + */ + private Object SwitchGlobalDeclarations(AST.GlobalDeclarations decls) { + if (decls instanceof AST.VarConstGlobDecls){ + return interpretVarConstGlobDecls((AST.VarConstGlobDecls)decls); + } + if (decls instanceof AST.FuncGlobDecls){ + return interpretFuncGlobDecls((AST.FuncGlobDecls)decls); + } + if (decls instanceof AST.EmptyGlobDecls){ + return interpretEmptyGlobDecls((AST.EmptyGlobDecls)decls); + } + return null; + } + + /** + * returns declared Variables as List + * @param decls + * @return List + */ + private Object SwitchDeclarations(Declarations decls) { + if (decls instanceof AST.EmptyDecls){ + return interpretEmptyDecls((AST.EmptyDecls)decls); + } + if (decls instanceof AST.PairDecls){ + return interpretPairDecls((AST.PairDecls)decls); + } + return null; + } + + /** + * returns declared Variables as List + * @param decl + * @return List + */ + private Object SwitchDeclaration(Declaration decl) { + if (decl instanceof AST.VarDecl){ + return interpretVarDecl((AST.VarDecl)decl); + } + if (decl instanceof AST.ConstDecl){ + return interpretConstDecl((AST.ConstDecl)decl); + } + return null; + } + + /** + * returns declared Const-Variables as List + * @param constDecls + * @return List + */ + private Object SwitchConstDeclarations(ConstDeclarations constDecls) { + if (constDecls instanceof AST.LastConstDecls){ + return interpretLastConstDecls((AST.LastConstDecls)constDecls); + } + if (constDecls instanceof AST.PairConstDecls){ + return interpretPairConstDecls((AST.PairConstDecls)constDecls); + } + return null; + } + + /** + * returns declared Variables as List + * @param varDecls + * @return List + */ + private Object SwitchVarDeclarations(VarDeclarations varDecls) { + if (varDecls instanceof AST.InitVarLastDecls){ + return interpretInitVarLastDecl((AST.InitVarLastDecls)varDecls); + } + if (varDecls instanceof AST.InitVarPairDecls){ + return interpretInitVarPairDecls((AST.InitVarPairDecls)varDecls); + } + if (varDecls instanceof AST.RefVarLastDecls){ + return interpretRefVarLastDecls((AST.RefVarLastDecls)varDecls); + } + if (varDecls instanceof AST.RefVarPairDecls){ + return interpretRefVarPairDecls((AST.RefVarPairDecls)varDecls); + } + if (varDecls instanceof AST.VarLastDecls){ + return interpretVarLastDecls((AST.VarLastDecls)varDecls); + } + if (varDecls instanceof AST.VarPairDecls){ + return interpretVarPairDecls((AST.VarPairDecls)varDecls); + } + return null; + } + + /** + * returns null-Object + * @param funcImpl + * @return null + */ + private Object SwitchFunctionImplementations(FunctionImplementations funcImpl) { + if (funcImpl instanceof AST.EmptyFuncImpls){ + interpretEmptyFuncImpls((AST.EmptyFuncImpls)funcImpl); + } + if (funcImpl instanceof AST.PairFuncImpls){ + interpretPairFuncImpls((AST.PairFuncImpls)funcImpl); + } + return null; + } + + /** + * returns declared Variables as List + * @param funcHead + * @return List + */ + private Object SwitchFunctionHeading(FunctionHeading funcHead) { + if (funcHead instanceof AST.VoidFuncHead){ + return interpretVoidFuncHead((AST.VoidFuncHead)funcHead); + } + if (funcHead instanceof AST.IntFuncHead){ + return interpretIntFuncHead((AST.IntFuncHead)funcHead); + } + return null; + } + + private Object SwitchFormalParameters(FormalParameters formParam) { + if (formParam instanceof AST.EmptyFormalParams){ + return interpretEmptyFormalParams((AST.EmptyFormalParams)formParam); + } + if (formParam instanceof AST.VoidFormalParams){ + return interpretVoidFormalParams((AST.VoidFormalParams)formParam); + } + if (formParam instanceof AST.NonVoidFormalParams){ + return interpretNonVoidFormalParams((AST.NonVoidFormalParams)formParam); + } + return null; + } + + private Object SwitchParamSections(ParamSections prmSects) { + if (prmSects instanceof AST.ValueLastPrmSects){ + return interpretValueLastPrmSects((AST.ValueLastPrmSects)prmSects); + } + if (prmSects instanceof AST.RefLastPrmSects){ + return interpretRefLastPrmSects((AST.RefLastPrmSects)prmSects); + } + if (prmSects instanceof AST.ValuePairPrmSects){ + return interpretValuePairPrmSects((AST.ValuePairPrmSects)prmSects); + } + if (prmSects instanceof AST.RefPairPrmSects){ + return interpretRefPairPrmSects((AST.RefPairPrmSects)prmSects); + } + return null; + } + + private Object SwitchBlock(Block block) { + this.newPmLine(block.startLine); + return interpretExpandBlock((ExpandBlock)block); + } + + private Object SwitchStatementSequence(StatementSequence stmSeq) { + if (stmSeq instanceof AST.EmptyStmSeq){ + return interpretEmptyStmSeq((AST.EmptyStmSeq)stmSeq); + } + if (stmSeq instanceof AST.PairStmSeq){ + return interpretPairStmSeq((AST.PairStmSeq)stmSeq); + } + return null; + } + + private Object SwitchStatement(Statement stm) { + if (continueFlag==true) return null; + if (breakFlag==true) return null; + if (returnFlag==true) return null; + if (stm instanceof AST.LabelStm){ + this.newPmLine(stm.startLine, ((AST.LabelStm)stm).number); + interpretLabelStm((AST.LabelStm)stm); + return null; + } + this.newPmLine(stm.startLine); + if (stm instanceof AST.AssignStm){ + interpretAssignStm((AST.AssignStm)stm); + } + if (stm instanceof AST.PureIfStm){ + interpretPureIfStm((AST.PureIfStm)stm); + } + if (stm instanceof AST.ElseIfStm){ + interpretElseIfStm((AST.ElseIfStm)stm); + } + if (stm instanceof AST.SwitchStm){ + interpretSwitchStm((AST.SwitchStm)stm); + } + if (stm instanceof AST.WhileStm){ + interpretWhileStm((AST.WhileStm)stm); + } + if (stm instanceof AST.DoWhileStm){ + interpretDoWhileStm((AST.DoWhileStm)stm); + } + if (stm instanceof AST.ForStm){ + interpretForStm((AST.ForStm)stm); + } + if (stm instanceof AST.ContinueStm){ + interpretContinueStm((AST.ContinueStm)stm); + } + if (stm instanceof AST.BreakStm){ + interpretBreakStm((AST.BreakStm)stm); + } + if (stm instanceof AST.CompStm){ + interpretCompStm((AST.CompStm)stm); + } + if (stm instanceof AST.FuncCallStm){ + interpretFuncCallStm((AST.FuncCallStm)stm); + } + if (stm instanceof AST.EmptyReturnStm){ + interpretEmptyReturnStm((AST.EmptyReturnStm)stm); + } + if (stm instanceof AST.ExprReturnStm){ + return interpretExprReturnStm((AST.ExprReturnStm)stm); + } + if (stm instanceof AST.ExprPrintfStm){ + interpretExprPrintfStm((AST.ExprPrintfStm)stm); + } + if (stm instanceof AST.ScanfStm){ + interpretScanfStm((AST.ScanfStm)stm); + } + return null; + } + + private Object SwitchAssignment(Assignment assign) { + if (assign instanceof AST.ValueAssign){ + interpretValueAssign((AST.ValueAssign)assign); + } + if (assign instanceof AST.RefAssign){ + interpretRefAssign((AST.RefAssign)assign); + } + return null; + } + + private Object SwitchFunctionCall(FunctionCall funcCall){ + return interpretExpandFunctionCall((ExpandFuncCall)funcCall); + } + + private Object SwitchActualParameters(ActualParameters actParams) { + if (actParams instanceof AST.EmptyActParams){ + return interpretEmptyActParams((AST.EmptyActParams)actParams); + } + if (actParams instanceof AST.ExprListActParams){ + return interpretExprListActParams((AST.ExprListActParams)actParams); + } + return null; + } + + private Object SwitchExpressionList(ExpressionList exprList) { + if (exprList instanceof AST.LastExprList){ + return interpretLastExprList((AST.LastExprList)exprList); + } + if (exprList instanceof AST.PairExprList){ + return interpretPairExprList((AST.PairExprList)exprList); + } + return null; + } + + private Object SwitchExpression(Expression exp) { + if (exp instanceof AST.PlusExpr){ + return interpretPlusExpr((AST.PlusExpr)exp); + } + if (exp instanceof AST.MinusExpr){ + return interpretMinusExpr((AST.MinusExpr)exp); + } + if (exp instanceof AST.FirstTermExpr){ + return interpretFirstTermExpr((AST.FirstTermExpr)exp); + } + return null; + } + + private Object SwitchFirstTerm(FirstTerm firstTerm) { + if (firstTerm instanceof AST.MultFirstTerm){ + return interpretMultFirstTerm((AST.MultFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.DivFirstTerm){ + return interpretDivFirstTerm((AST.DivFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.ModFirstTerm){ + return interpretModFirstTerm((AST.ModFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.FactorFirstTerm){ + return interpretFactorFirstTerm((AST.FactorFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.PlusFactorFirstTerm){ + return interpretPlusFactorFirstTerm((AST.PlusFactorFirstTerm)firstTerm); + } + if (firstTerm instanceof AST.MinusFactorFirstTerm){ + return interpretMinusFactorFirstTerm((AST.MinusFactorFirstTerm)firstTerm); + } + return null; + } + + private Object SwitchTerm(Term term) { + if (term instanceof AST.MultTerm){ + return interpretMultTerm((AST.MultTerm)term); + } + if (term instanceof AST.DivTerm){ + return interpretDivTerm((AST.DivTerm)term); + } + if (term instanceof AST.ModTerm){ + return interpretModTerm((AST.ModTerm)term); + } + if (term instanceof AST.FactorTerm){ + return interpretFactorTerm((AST.FactorTerm)term); + } + return null; + } + + private Object SwitchFactor(Factor factor) { + if (factor instanceof AST.IdFactor){ + return interpretIdFactor((AST.IdFactor)factor); + } + if (factor instanceof AST.RefIdFactor){ + return interpretRefIdFactor((AST.RefIdFactor)factor); + } + if (factor instanceof AST.AddIdFactor){ + return interpretAddIdFactor((AST.AddIdFactor)factor); + } + if (factor instanceof AST.NumFactor){ + return interpretNumFactor((AST.NumFactor)factor); + } + if (factor instanceof AST.FuncCallFactor){ + return interpretFuncCallFactor((AST.FuncCallFactor)factor); + } + if (factor instanceof AST.CompFactor){ + return interpretCompFactor((AST.CompFactor)factor); + } + return null; + } + + private Object SwitchBoolExpression(BoolExpression boolExp) { + if (boolExp instanceof AST.EqBoolExpr){ + return interpretEqBoolExpr((AST.EqBoolExpr)boolExp); + } + if (boolExp instanceof AST.NotEqBoolExpr){ + return interpretNotEqBoolExpr((AST.NotEqBoolExpr)boolExp); + } + if (boolExp instanceof AST.LessBoolExpr){ + return interpretLessBoolExpr((AST.LessBoolExpr)boolExp); + } + if (boolExp instanceof AST.GreatBoolExpr){ + return interpretGreatBoolExpr((AST.GreatBoolExpr)boolExp); + } + if (boolExp instanceof AST.LessEqBoolExpr){ + return interpretLessEqBoolExpr((AST.LessEqBoolExpr)boolExp); + } + if (boolExp instanceof AST.GreatEqBoolExpr){ + return interpretGreatEqBoolExpr((AST.GreatEqBoolExpr)boolExp); + } + return null; + } + + + private void interpretExpandProgram(AST.ExpandProgram code){ + ArrayList globDeclList= (ArrayList)interpret(code.globDecl); + for (Variable i : globDeclList){ + i.setGlobal(true); + } + interpret(code.funcImpl); + ArrayList formParamList = (ArrayList)interpret(code.formParam); + if (formParamList.size()>0) + throw new EIncompatibleParameterCount("0",""+formParamList.size()); + interpret(code.block); + } + + private Object interpretEmptyGlobDecls(EmptyGlobDecls decls) { + return new ArrayList(); + } + + private Object interpretFuncGlobDecls(FuncGlobDecls decls) { + ArrayList ret=(ArrayList)interpret(decls.globDecls); + functions.add(new FunctionHandler(decls.funcHead, this)); + return ret; + } + + private Object interpretVarConstGlobDecls(VarConstGlobDecls decls) { + ArrayList ret=(ArrayList)interpret(decls.globDecls); + ret.addAll((ArrayList)interpret(decls.decl)); + return ret; + } + + private Object interpretEmptyDecls(EmptyDecls decls) { + return new ArrayList(); + } + + private Object interpretPairDecls(PairDecls decls) { + ArrayList ret=(ArrayList)interpret(decls.decls); + ret.addAll(0,(ArrayList)interpret(decls.decl)); + return ret; + } + + private Object interpretVarDecl(VarDecl decl) { + return (ArrayList)interpret(decl.varDecls); + } + + private Object interpretConstDecl(ConstDecl decl) { + return (ArrayList)interpret(decl.constDecls); + } + + private Object interpretPairConstDecls(PairConstDecls decls) { + Variable var = new Variable(decls.ident,true, stack.getVisibilityLevel(), decls.number, searchForVarinfo(decls)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(decls.constDecls); + list.add(0,var); + return list; + } + + private Object interpretLastConstDecls(LastConstDecls decls) { + ArrayList list=new ArrayList(); + Variable var = new Variable(decls.ident,true, stack.getVisibilityLevel(), decls.number,searchForVarinfo(decls)); + stack.addVar(var); + list.add(var); + return list; + } + + private Object interpretVarPairDecls(VarPairDecls decls) { + Variable var = new Variable(decls.ident,false, stack.getVisibilityLevel(), searchForVarinfo(decls)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(decls.varDecls); + list.add(0,var); + return list; + } + + private Object interpretVarLastDecls(VarLastDecls decls) { + ArrayList list=new ArrayList(); + Variable var = new Variable(decls.ident,false, stack.getVisibilityLevel(),searchForVarinfo(decls)); + stack.addVar(var); + list.add(var); + return list; + } + + private Object interpretRefVarPairDecls(RefVarPairDecls decls) { + Variable var = new Zeiger(decls.ident, stack.getVisibilityLevel(),searchForVarinfo(decls)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(decls.varDecls); + list.add(0,var); + return list; + } + + private Object interpretRefVarLastDecls(RefVarLastDecls decls) { + ArrayList list=new ArrayList(); + Variable var = new Zeiger(decls.ident, stack.getVisibilityLevel(),searchForVarinfo(decls)); + stack.addVar(var); + list.add(var); + return list; + } + + private Object interpretInitVarPairDecls(InitVarPairDecls decls) { + Variable var = new Variable(decls.ident,false, stack.getVisibilityLevel(), decls.number,searchForVarinfo(decls)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(decls.varDecls); + list.add(0,var); + return list; + } + + private Object interpretInitVarLastDecl(InitVarLastDecls decls) { + ArrayList list=new ArrayList(); + Variable var = new Variable(decls.ident,false, stack.getVisibilityLevel(), decls.number, searchForVarinfo(decls)); + stack.addVar(var); + list.add(var); + return list; + } + + private void interpretPairFuncImpls(PairFuncImpls impls) { + String name; + if (impls.funcHead instanceof AST.IntFuncHead){ + name=((IntFuncHead)impls.funcHead).ident; + }else{ + name=((VoidFuncHead)impls.funcHead).ident; + } + FunctionHandler existing = getFunctionByName(name); + if (existing == null){ + functions.add(new FunctionHandler(impls.funcHead, impls.block, this)); + }else{ + if (! existing.equalHeads(impls.funcHead)) + throw new EIncompatibleFunctionHeaders(impls.funcHead); + existing.setBlock(impls.block); + } + interpret(impls.funcImpls); + } + + private void interpretEmptyFuncImpls(EmptyFuncImpls impls) { + } + + private Object interpretIntFuncHead(IntFuncHead head) { + return interpret(head.formParams); + } + + private Object interpretVoidFuncHead(VoidFuncHead head) { + return interpret(head.formParams); + } + + private Object interpretEmptyFormalParams(EmptyFormalParams params) { + return new ArrayList(); + } + + private Object interpretVoidFormalParams(VoidFormalParams params) { + return new ArrayList(); + } + + private Object interpretNonVoidFormalParams(NonVoidFormalParams params) { + return interpret(params.prmSects); + } + + private Object interpretValueLastPrmSects(ValueLastPrmSects sects) { + ArrayList list=new ArrayList(); + Variable var = new Variable(sects.ident,false, stack.getVisibilityLevel(), searchForVarinfo(sects)); + stack.addVar(var); + list.add(var); + return list; + } + + private Object interpretRefLastPrmSects(RefLastPrmSects sects) { + ArrayList list=new ArrayList(); + Variable var = new Zeiger(sects.ident, stack.getVisibilityLevel(),searchForVarinfo(sects)); + stack.addVar(var); + list.add(var); + return list; + } + + private Object interpretValuePairPrmSects(ValuePairPrmSects sects) { + Variable var = new Variable(sects.ident,false, stack.getVisibilityLevel(),searchForVarinfo(sects)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(sects.prmSects); + list.add(0,var); + return list; + } + + private Object interpretRefPairPrmSects(RefPairPrmSects sects) { + Variable var = new Zeiger(sects.ident, stack.getVisibilityLevel(),searchForVarinfo(sects)); + stack.addVar(var); + ArrayList list=(ArrayList)interpret(sects.prmSects); + list.add(0,var); + return list; + } + + private Object interpretExpandBlock(ExpandBlock block) { + ArrayList list=(ArrayList)interpret(block.decls); + Object ret = interpret(block.stmSeq); + for (Variable i : list){ + stack.removeVar(i); + } + return ret; + } + + private Object interpretPairStmSeq(PairStmSeq seq) { + Integer ret1,ret2,ret=null; + ret1= (Integer)interpret(seq.stm); + ret2= (Integer)interpret(seq.stmSeq); + if (ret1!=null) + ret=ret1; + if (ret2!=null) + ret=ret2; + return ret; + } + + private Object interpretEmptyStmSeq(EmptyStmSeq seq) { + return null; + } + + private void interpretAssignStm(AssignStm stm) { + interpret(stm.assign); + } + + private void interpretPureIfStm(PureIfStm stm) { + if ((Boolean)interpret(stm.boolExp)) + interpret(stm.stm); + } + + private void interpretElseIfStm(ElseIfStm stm) { + if ((Boolean)interpret(stm.boolExp)) + interpret(stm.stm1); + else + interpret(stm.stm2); + } + + private void interpretSwitchStm(SwitchStm stm) { + SwitchHandler sh= new SwitchHandler((Integer)interpret(stm.exp),stm.switchBlock,this); + sh.callSwitch(); + if (breakFlag==true){breakFlag=false;} + } + + private void interpretWhileStm(WhileStm stm) { + while( (Boolean)interpret(stm.boolExp) ){ + if (breakFlag==true){breakFlag=false; break;} + if (continueFlag==true){continueFlag=false;} + interpret(stm.stm); + } + } + + private void interpretDoWhileStm(DoWhileStm stm) { + do{ + if (breakFlag==true){breakFlag=false; break;} + if (continueFlag==true){continueFlag=false;} + interpret(stm.stm); + }while( (Boolean)interpret(stm.boolExp) ); + } + + private void interpretForStm(ForStm stm) { + for (interpret(stm.assign1); (Boolean)interpret(stm.boolExp); interpret(stm.assign2)){ + if (breakFlag==true){breakFlag=false; break;} + if (continueFlag==true){continueFlag=false;} + interpret(stm.stm); + } + } + + private void interpretContinueStm(ContinueStm stm) { + continueFlag=true; + } + + private void interpretBreakStm(BreakStm stm) { + breakFlag=true; + } + + private void interpretCompStm(CompStm stm) { + ArrayList list=(ArrayList)interpret(stm.decls); + interpret(stm.stmSeq); + for (Variable i : list){ + stack.removeVar(i); + } + } + + private void interpretFuncCallStm(FuncCallStm stm) { + interpret(stm.funcCall); + } + + private Object interpretEmptyReturnStm(EmptyReturnStm stm) { + if (isIntFunction(stm)){ + throw new EReturnException("void","int",stm.startLine); + } + returnFlag=true; + return null; + } + + private Object interpretExprReturnStm(ExprReturnStm stm) { + Object ret=interpret(stm.expr); + if (! isIntFunction(stm)){ + throw new EReturnException(ret.getClass().getName(),"Void",stm.expr.startLine); + } + if (ret instanceof Variable) + throw new EReturnException("Variable","int",stm.expr.startLine); + returnFlag=true; + return (Integer)ret; + } + + private void interpretExprPrintfStm(ExprPrintfStm stm) { +// getVariableByName(stm.ident).getVi().addPos(new Integer [] {stm.startLine,stm.startColumn}); + String output=stm.string.replace("\\n", "\n"); + output=output.replace("\\t","\t"); + List varlist = (List)interpret(stm.exprList); + for (Object i : varlist){ + if (!(i instanceof Integer)){ + throw new ETypeExpected("Integer","Pointer",stm.startLine); + } + if (output.contains("%d")){ + output=output.replaceFirst("%d", ""+i); + }else{ + throw new EPrintfException(stm.startLine); + } + } + if (output.contains("%d")){ + throw new EPrintfException(stm.startLine); + } + myPrintf(output, stm.startLine); +// myPrintf((Integer)getVariableByName(stm.ident).getValue()); + } + + private void interpretScanfStm(ScanfStm stm) { + getVariableByName(stm.ident).getVi().addPos(new Integer [] {stm.startLine,stm.startColumn + "scanf(\"%i\", &".length()}); + getVariableByName(stm.ident).setValue(myScanf(stm.startLine)); + } + + private void interpretLabelStm(LabelStm stm) { + } + + private void interpretValueAssign(ValueAssign assign) { + getVariableByName(assign.ident).getVi().addPos(new Integer [] {assign.startLine,assign.startColumn}); + getVariableByName(assign.ident).setValue((Integer)interpret(assign.expr)); + } + + private void interpretRefAssign(RefAssign assign) { + getVariableByName(assign.ident).getVi().addPos(new Integer [] {assign.startLine,assign.startColumn + "*".length()}); + getVariableByName(assign.ident).setTargetValue((Integer)interpret(assign.expr)); + } + + private Object interpretExpandFunctionCall(ExpandFuncCall funcCall) { + ArrayList params= (ArrayList)interpret(funcCall.actParams); + ruecksprungMarken.add((Integer)funcCall.extra); + stack.increaseVisibilityLevel(); + FunctionHandler function=getFunctionByName(funcCall.ident); + if (function.getScope()[0]>funcCall.startLine || function.getScope()[1](); + } + + private Object interpretExprListActParams(ExprListActParams params) { + return interpret(params.exprList); + } + + private Object interpretLastExprList(LastExprList list) { + ArrayList liste=new ArrayList(); + liste.add(interpret(list.expr)); + return liste; + } + + private Object interpretPairExprList(PairExprList list) { + ArrayList liste=(ArrayList)interpret(list.exprList); + liste.add(0, (Object)interpret(list.expr)); + return liste; + } + + private Object interpretPlusExpr(PlusExpr expr) { + return (Integer)(((Integer)interpret(expr.expr)) + ((Integer)interpret(expr.term))); + } + + private Object interpretMinusExpr(MinusExpr expr) { + return (Integer)(((Integer)interpret(expr.expr)) - ((Integer)interpret(expr.term))); + } + + private Object interpretFirstTermExpr(FirstTermExpr expr) { + return interpret(expr.firstTerm); + } + + private Object interpretMultFirstTerm(MultFirstTerm term) { + return (Integer)(((Integer)interpret(term.firstTerm)) * ((Integer)interpret(term.factor))); + } + + private Object interpretDivFirstTerm(DivFirstTerm term) { + return (Integer)(((Integer)interpret(term.firstTerm)) / ((Integer)interpret(term.factor))); + } + + private Object interpretModFirstTerm(ModFirstTerm term) { + return (Integer)(((Integer)interpret(term.firstTerm)) % ((Integer)interpret(term.factor))); + } + + private Object interpretFactorFirstTerm(FactorFirstTerm term) { + return interpret(term.factor); + } + + private Object interpretPlusFactorFirstTerm(PlusFactorFirstTerm term) { + return interpret(term.factor); + } + + private Object interpretMinusFactorFirstTerm(MinusFactorFirstTerm term) { + return (Integer)(-((Integer)interpret(term.factor))); + } + + private Object interpretMultTerm(MultTerm term) { + return (Integer)(((Integer)interpret(term.term)) * ((Integer)interpret(term.factor))); + } + + private Object interpretDivTerm(DivTerm term) { + return (Integer)(((Integer)interpret(term.term)) / ((Integer)interpret(term.factor))); + } + + private Object interpretModTerm(ModTerm term) { + return (Integer)(((Integer)interpret(term.term)) % ((Integer)interpret(term.factor))); + } + + private Object interpretFactorTerm(FactorTerm term) { + return interpret(term.factor); + } + + private Object interpretIdFactor(IdFactor factor) { + getVariableByName(factor.ident).getVi().addPos(new Integer [] {factor.startLine,factor.startColumn}); + return getVariableByName(factor.ident).getValue(); + } + + private Object interpretRefIdFactor(RefIdFactor factor) { + getVariableByName(factor.ident).getVi().addPos(new Integer [] {factor.startLine,factor.startColumn}); + return getVariableByName(factor.ident).getTargetValue(); + } + + private Object interpretAddIdFactor(AddIdFactor factor) { + getVariableByName(factor.ident).getVi().addPos(new Integer [] {factor.startLine,factor.startColumn + "&".length()}); + return getVariableByName(factor.ident); + } + + private Object interpretNumFactor(NumFactor factor) { + return factor.number; + } + + private Object interpretFuncCallFactor(FuncCallFactor factor) { + return interpret(factor.funcCall); + } + + private Object interpretCompFactor(CompFactor factor) { + return interpret(factor.expr); + } + + private Object interpretEqBoolExpr(EqBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() == ((Integer)interpret(expr.expr2)).intValue(); + } + + private Object interpretNotEqBoolExpr(NotEqBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() != ((Integer)interpret(expr.expr2)).intValue(); + } + + private Object interpretLessBoolExpr(LessBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() < ((Integer)interpret(expr.expr2)).intValue(); + } + + private Object interpretGreatBoolExpr(GreatBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() > ((Integer)interpret(expr.expr2)).intValue(); + } + + private Object interpretLessEqBoolExpr(LessEqBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() <= ((Integer)interpret(expr.expr2)).intValue(); + } + + private Object interpretGreatEqBoolExpr(GreatEqBoolExpr expr) { + return ((Integer)interpret(expr.expr1)).intValue() >= ((Integer)interpret(expr.expr2)).intValue(); + } + + public void abort() { + aborting = true; + } + +} diff --git a/src/org/jalgo/module/pulsemem/de.properties b/src/org/jalgo/module/pulsemem/de.properties new file mode 100644 index 0000000..f4cf0c4 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/de.properties @@ -0,0 +1,90 @@ +#Created by JInto - www.guh-software.de +#Thu Jun 28 22:32:41 CEST 2007 +Exception.ECycleLimitReached.Message_End=) \u00FCberschritten. Fehler im C00-Code? +Exception.ECycleLimitReached.Message_Start=Maximale Rekursionstiefe ( +Exception.EFunctionNotImplemented.Message_End=) wurde aufgerufen. +Exception.EFunctionNotImplemented.Message_Start=Nicht implementierte Funktion (Zeile\: +Exception.EIncompatibleFunctionHeaders.Message_End=). Funktion wurde bereits mit einem anderen Header definiert\! +Exception.EIncompatibleFunctionHeaders.Message_Start=Fehler bei Funktionsimplementierung (Zeile\: +Exception.EIncompatibleParameterCount.Message_Between=\ Parameter aber es wurden +Exception.EIncompatibleParameterCount.Message_End=\ gefunden. +Exception.EIncompatibleParameterCount.Message_Start=Funktion erwartet +Exception.EIncompatibleParameterTypes.Message_Between=. Parameter sollte +Exception.EIncompatibleParameterTypes.Message_End=\ sein. Vorgefunden wurde\: +Exception.EIncompatibleParameterTypes.Message_Start=Fehler beim Aufruf der Funktion +Exception.EIncompatibleTypes.Message_Between=\ wurde ein +Exception.EIncompatibleTypes.Message_End=zugewiesen. Erwartet wurde +Exception.EIncompatibleTypes.Message_Start=Der Variable +Exception.EMemoryError.Message_Start=Speicherzugriffsfehler. Zugriff auf nicht initialisierte oder nicht sichtbare Variable\: +Exception.ENotAPointerException.Message_End=\ kann nicht dereferenziert werden. +Exception.ENotAPointerException.Message_Start=Nicht-Pointer Variable +Exception.ENullPointer.Message_End=\ wurde nicht initialisiert. +Exception.ENullPointer.Message_Start=Der Pointer +Exception.EPMLException.Message=PML wurde ver\u00E4ndert. Fehler in im Interpreter\! +Exception.EPointerTargetException.Message_End=\ wurde ein int-Wert zugewiesen. (Pointer m\u00FCssen auf Variablen zeigen) +Exception.EPointerTargetException.Message_Start=Dem Pointer +Exception.EPrintfException.Message_Start=Anzahl von Platzhaltern und Argumenten bei Printf-Anweisung stimmt nicht \u00FCberein. Zeile\: +Exception.EReturnException.Message_Between=. Erwarteter Typ\: +Exception.EReturnException.Message_End=\ Zeile\: +Exception.EReturnException.Message_Start=Fehler bei R\u00FCcksprung aus der Funktion\! Typ des R\u00FCckgabewerts\: +Exception.ETypeExpected.Message_Between=\ wurde erwartet, aber Typ +Exception.ETypeExpected.Message_End=wurde gefunden. Zeile\: +Exception.ETypeExpected.Message_Start=Typ +Exception.EVarNotFound.Message_End=\ wurde nicht deklariert. +Exception.EVarNotFound.Message_Start=Gesuchte Variable +Exception.EWriteConstant.Message_End=\ darf nicht schreibend zugegriffen werden\! +Exception.EWriteConstant.Message_Start=Auf die Konstante +ExportCFileAction.exportCLong=Exportiere Quellcode als C00-Datei +ExportCFileAction.exportCShort=Exportiere als C-Datei +FirstStepAction.firstStepLong=Springt zum ersten Schritt. +FirstStepAction.firstStepShort=Erster Schritt +GUIController.consoleText=Konsole +GUIController.editorText=C-Editor +GUIController.printf_End=)\: +GUIController.printf_Start=printf (Zeile\: +GUIController.pulsememetableText=Speicherabbild +GoBeamerAction.BeamerMode=Pr\u00E4sentationsmodus +ImportCFileAction.importCLong=Importiere eine C00-Datei +ImportCFileAction.importCShort=Importiere C-Datei +LastStepAction.lastStepLong=Springe zum letzten Schritt +LastStepAction.lastStepShort=Letzter Schritt +Module.Description=J-Algo Modul zur Visualisierung des pulsierenden Speichers +ModuleInfo.LicenceType=GPL +ModuleInfo.ModuleName=Pulsierender Speicher +ModuleInfo.ModuleVersion=0.5 +ModuleInfo.Programmers=Martin Brylski, Karsten Diepelt, Julian Eberius, Frank Herrlich, Joachim Protze +NextBreakpointAction.nextBreakpointLong=Springe zum n\u00E4chsten Haltepunkt. +NextBreakpointAction.nextBreakpointShort=N\u00E4chster Haltpunkt +ParseAction.startParsingLong=L\u00E4sst das Programm ablaufen und stellt den Pulsierenden Speicher dar +ParseAction.startParsingShort=Pulsierenden Speicher darstellen +PrevBreakpointAction.prevBreakpointLong=Springe zum vorigen Haltepunkt. +PrevBreakpointAction.prevBreakpointShort=Voriger Haltpunkt +PulseMemTable.Label=Label +PulseMemTable.Line=Zeile +PulseMemTable.Stack=RM-Keller +PulseMemTablePanel.LabelLine=Label-Zeile +PulseMemTablePanel.Stack=RM-Keller +StopAction.stopParsingLong=Zur\u00FCck in den Editor-Modus +StopAction.stopParsingShort=Zur\u00FCck zum Editor-Modus +WelcomeAction.welcomeLong=Zeigt den Wilkommensbildschirm +WelcomeAction.welcomeShort=Zeigt Willkommensbildschirm +gui.ExportCFileDialogText=Datei existiert bereits. \u00DCberschreiben? +gui.ExportCFileDialogTitle=\u00DCberschreiben? +gui.ExportCFileToolTip=Exportiert den aktuellen Quelltext als C00-Datei +gui.FileFilterDescription=C-Dateien ( *.c ) +gui.FirstStepToolTip=Zur\u00FCck zum ersten Haltepunkt +gui.ImportCFileToolTip=Importiert eine C00-Datei in das Quelltextfeld +gui.ImportError=Fehler beim Importieren der Datei. (Keine g\u00FCltige C00-Datei?) +gui.InputExpected_End=) erwartet eine Eingabe\! +gui.InputExpected_Start=Eine scanf-Anweisung (Zeile\: +gui.IntegerParseError_End=" ist kein g\u00FCltiger Integerwert. +gui.IntegerParseError_Start=Die Zeichenfolge " +gui.InterpretationError=Es ist ein Fehler bei der Interpretation des Quellcodes aufgetreten\! +gui.LastStepToolTip=Zeigt den kompletten pulsierenden Speicher (zum letzten Haltepunkt gehen) +gui.NextBreakpointToolTip=Geht zum n\u00E4chsten Haltepunkt +gui.OutOfMemory=Tabelle konnte nicht erstellt werden\: zu wenig Speicher\! (Versuchen sie kleine Eingabewerte\!) +gui.ParsingError=Es ist ein Fehler beim Parsen des Quellcodes aufgetreten\! +gui.PrevBreakpointToolTip=Geht zum vorherigen Haltepunkt +gui.StartParsingToolTip=L\u00E4sst das Programm ablaufen und stellt den Pulsierenden Speicher dar. +gui.StopParsingToolTip=Beendet die Visualisierung und kehrt in den Editor-Modus zur\u00FCck. +gui.UnknownInterpretationError=Es ist ein unbekannter Fehler w\u00E4hrend der Programminterpretation aufgetreten diff --git a/src/org/jalgo/module/pulsemem/en.properties b/src/org/jalgo/module/pulsemem/en.properties new file mode 100644 index 0000000..c926e08 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/en.properties @@ -0,0 +1,90 @@ +#Created by JInto - www.guh-software.de +#Thu Jun 28 22:33:20 CEST 2007 +Exception.ECycleLimitReached.Message_End=) is reached. Error in C00-Code? +Exception.ECycleLimitReached.Message_Start=Maximal recursion depth ( +Exception.EFunctionNotImplemented.Message_End=) was called. +Exception.EFunctionNotImplemented.Message_Start=Unimplemented method (line\: +Exception.EIncompatibleFunctionHeaders.Message_End=). Method is already declared with a different header\! +Exception.EIncompatibleFunctionHeaders.Message_Start=Error on method implementation +Exception.EIncompatibleParameterCount.Message_Between=\ parameters, but +Exception.EIncompatibleParameterCount.Message_End=\ were found. +Exception.EIncompatibleParameterCount.Message_Start=Method expected +Exception.EIncompatibleParameterTypes.Message_Between=. parameter should have been of type +Exception.EIncompatibleParameterTypes.Message_End=. Found was +Exception.EIncompatibleParameterTypes.Message_Start=Error on call of function +Exception.EIncompatibleTypes.Message_Between=\ was assigned to a +Exception.EIncompatibleTypes.Message_End=. Expected was +Exception.EIncompatibleTypes.Message_Start=The variable +Exception.EMemoryError.Message_Start=Memory access fault. Access on not initialized or not visible variable\: +Exception.ENotAPointerException.Message_End=\ could not be dereferenced. +Exception.ENotAPointerException.Message_Start=The non-pointer variable +Exception.ENullPointer.Message_End=\ is not initialized. +Exception.ENullPointer.Message_Start=The pointer +Exception.EPMLException.Message=PML was changed. Error in interpreter\! +Exception.EPointerTargetException.Message_End=\ (Pointer should point to variables\!) +Exception.EPointerTargetException.Message_Start=An int-value was assigned to the pointer +Exception.EPrintfException.Message_Start=Number of dummies and argument at printf-statement are not equal. line\: +Exception.EReturnException.Message_Between=. expected type\: +Exception.EReturnException.Message_End=. Line\: +Exception.EReturnException.Message_Start=Error while returning from method\! Type of return value\: +Exception.ETypeExpected.Message_Between=\ expected, but type +Exception.ETypeExpected.Message_End=found. Line\: +Exception.ETypeExpected.Message_Start=Type +Exception.EVarNotFound.Message_End=\ not declared. +Exception.EVarNotFound.Message_Start=Searched variable +Exception.EWriteConstant.Message_End=\ cannot be written\! +Exception.EWriteConstant.Message_Start=The constant +ExportCFileAction.exportCLong=Exports sourcecode as a C00-File +ExportCFileAction.exportCShort=Export C-File +FirstStepAction.firstStepLong=Goes to first step +FirstStepAction.firstStepShort=First Step +GUIController.consoleText=Console +GUIController.editorText=C-Editor +GUIController.printf_End=)\: +GUIController.printf_Start=printf (line\: +GUIController.pulsememetableText=Core Image +GoBeamerAction.BeamerMode=Beamer Mode +ImportCFileAction.importCLong=Imports a C00-File +ImportCFileAction.importCShort=Import C-File +LastStepAction.lastStepLong=Goes to last step +LastStepAction.lastStepShort=Last Step +Module.Description=J-Algo Modul visualising the concept pulsing memory +ModuleInfo.LicenceType=GPL +ModuleInfo.ModuleName=Pulsing Memory +ModuleInfo.ModuleVersion=0.5 +ModuleInfo.Programmers=Martin Brylski, Karsten Diepelt, Julian Eberius, Frank Herrlich, Joachim Protze +NextBreakpointAction.nextBreakpointLong=Goes to next breakpoint +NextBreakpointAction.nextBreakpointShort=Next Breakpoint +ParseAction.startParsingLong=Runs the programm and shows the pulsing memory +ParseAction.startParsingShort=Shows the pulsing memory +PrevBreakpointAction.prevBreakpointLong=Goes to previous breakpoint +PrevBreakpointAction.prevBreakpointShort=Previous Breakpoint +PulseMemTable.Label=Label +PulseMemTable.Line=Line +PulseMemTable.Stack=RM-Stack +PulseMemTablePanel.LabelLine=label-line +PulseMemTablePanel.Stack=RM-Stack +StopAction.stopParsingLong=Stops visualization and returns to editor mode +StopAction.stopParsingShort=Back to editor mode +WelcomeAction.welcomeLong=Shows the Welcome Screen +WelcomeAction.welcomeShort=Show Welcome Screen +gui.ExportCFileDialogText=File already exists. Override? +gui.ExportCFileDialogTitle=Override? +gui.ExportCFileToolTip=Exports current sourecode as a C00-file +gui.FileFilterDescription=C-Files ( *.c ) +gui.FirstStepToolTip=Back to the first breakpoints +gui.ImportCFileToolTip=Imports a C00-file into the sourcecode field +gui.ImportError=Error while loading file. (Not a valid C00-File?) +gui.InputExpected_End=) expects an Input. +gui.InputExpected_Start=A scanf-statement (line\: +gui.IntegerParseError_End=" is not a valid integer value. +gui.IntegerParseError_Start=The character sequence " +gui.InterpretationError=An error occured while interpreting the C-Code\! +gui.LastStepToolTip=Shows the complete pulsing memory (goes forward to the last breakpoint) +gui.NextBreakpointToolTip=Forward to the next breakpoint +gui.OutOfMemory=Could not create the table\: out of memory\! (Try smaller input values\!) +gui.ParsingError=An error occured while parsing the C-Code +gui.PrevBreakpointToolTip=Backward to the previous breakpoint +gui.StartParsingToolTip=Runs the programm and shows the pulsing memory +gui.StopParsingToolTip=stops the visualization and returns to editor mode +gui.UnknownInterpretationError=An unexpected error occured while interpreting the program diff --git a/src/org/jalgo/module/pulsemem/gui/CVS/Entries b/src/org/jalgo/module/pulsemem/gui/CVS/Entries new file mode 100644 index 0000000..05fd103 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/CVS/Entries @@ -0,0 +1,4 @@ +/GUIConstants.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ +/GUIController.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ +D/components//// +D/events//// diff --git a/src/org/jalgo/module/pulsemem/gui/CVS/Repository b/src/org/jalgo/module/pulsemem/gui/CVS/Repository new file mode 100644 index 0000000..4a25087 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem/gui diff --git a/src/org/jalgo/module/pulsemem/gui/CVS/Root b/src/org/jalgo/module/pulsemem/gui/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/gui/GUIConstants.java b/src/org/jalgo/module/pulsemem/gui/GUIConstants.java new file mode 100644 index 0000000..f3d1fca --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/GUIConstants.java @@ -0,0 +1,80 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.05.2007 */ +package org.jalgo.module.pulsemem.gui; + +import java.awt.Color; +import java.awt.Font; + +/** + * GUIConstants.java + *

          + * The interface Constants is a collection of several constant + * values, used in the GUI implementation of the PulsMem module. + *

          + * + * @version $Revision: 1.6 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public interface GUIConstants { + + /*------------------------------colors----------------------------*/ + /** The background color in the welcome screen. */ + public final static Color WELCOME_SCREEN_BACKGROUND = new Color(51, 102, + 153); + + /** The font color in the welcome screen. */ + public final static Color WELCOME_SCREEN_FOREGROUND = new Color(254, 215, 0); + + /** The font color for disabled textares */ + public final static Color DISABLED_TEXTAREA = new Color(128, 128, 128); + + /** The font color for disabled textares */ + public final static Color DISABLED_TEXTAREA_FONT = new Color(0, 0, 0); + + /** The line highlighted color */ + public final static Color LineHighlightColor = Color.YELLOW; + + /** The caret selected color */ + public final static Color CARET_SELECT_COLOR = new Color(68, 123, 205); + + /*------------------------------fonts-----------------------------*/ + /** The font used in the welcome screen. */ + public static final Font WELCOME_SCREEN_FONT = new Font("SansSerif", + Font.PLAIN, 16); + + /** The Beamerfont */ + public static final Font BEAMERFONT = new Font("Courier", Font.BOLD, 16); + + /** The Standardfont */ + public static final Font STANDARDFONT = new Font("Courier", Font.PLAIN, + 12); + + /*------------------------------Others-----------------------------*/ + /** Determine wether to enable/disable parsing/stopping items. */ + public static final int PARSE_ENABLED = 0; + + public static final int PARSE_DISABLED = 1; + +} diff --git a/src/org/jalgo/module/pulsemem/gui/GUIController.java b/src/org/jalgo/module/pulsemem/gui/GUIController.java new file mode 100644 index 0000000..1674a21 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/GUIController.java @@ -0,0 +1,999 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.05.2007 */ +package org.jalgo.module.pulsemem.gui; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.util.List; +import java.util.LinkedList; +import java.util.Set; + +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextPane; +import javax.swing.JToolBar; +import javax.swing.ScrollPaneConstants; +import javax.swing.border.TitledBorder; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.JAlgoWindow; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; +import org.jalgo.main.gui.event.StatusLineUpdater; +import org.jalgo.module.pulsemem.Admin; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.ModuleConnector; +import org.jalgo.module.pulsemem.core.IOSimulation; +import org.jalgo.module.pulsemem.core.PulsMemLine; +import org.jalgo.module.pulsemem.core.Variable; +import org.jalgo.module.pulsemem.gui.components.InlineBreakpoint; +import org.jalgo.module.pulsemem.gui.components.NOLPanel; +import org.jalgo.module.pulsemem.gui.components.PulseMemTablePanel; +import org.jalgo.module.pulsemem.gui.events.ExportCFileAction; +import org.jalgo.module.pulsemem.gui.events.FirstStepAction; +import org.jalgo.module.pulsemem.gui.events.GoBeamerAction; +import org.jalgo.module.pulsemem.gui.events.ImportCFileAction; +import org.jalgo.module.pulsemem.gui.events.LastStepAction; +import org.jalgo.module.pulsemem.gui.events.NextBreakpointAction; +import org.jalgo.module.pulsemem.gui.events.ParseAction; +import org.jalgo.module.pulsemem.gui.events.PrevBreakpointAction; +import org.jalgo.module.pulsemem.gui.events.StopAction; +import org.jalgo.module.pulsemem.gui.events.WelcomeAction; + +/** + * GUIController.java + *

          + * The class GUIController is the main class of the GUI of the + * PulsMem module. It initializes the layout of the different parts, offers + * methods to set the state of buttons etc., to show several dialogs and + * messages, and causes GUI-components to update when necessary. + *

          + * + * @version $Revision: 1.54 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class GUIController implements GUIConstants, IOSimulation { + protected ModuleConnector modConn; + + private Controller controller; + + // //////////////////////// + JComponent contentPane; + + JPanel rootPane; + + JSplitPane splitPane; + + JPanel topPane; + + JPanel leftOne; + + NOLPanel linedTextarea; + + JPanel rightOne; + + JTabbedPane bottomPane; + + JScrollPane consolePane; + + JTextPane console; + + PulseMemTablePanel memPanel; + + InlineBreakpoint lineOfBreakpoint; + + JToolbarButton importCFileToolbarItem; + + JToolbarButton exportCFileToolbarItem; + + JToolbarButton showWelcomeToolbarItem; + + JToolbarButton startParsingToolbarItem; + + JToolbarButton stopParsingToolbarItem; + + JToolbarButton prevBreakpointToolbarItem; + + JToolbarButton nextBreakpointToolbarItem; + + JToolbarButton goBeamerToolbarItem; + + JToolbarButton firstStepToolbarItem; + + JToolbarButton lastStepToolbarItem; + + JSplitPane splitLeftRight; + + ImportCFileAction importCFileAction; + + ExportCFileAction exportCFileAction; + + WelcomeAction welcomeAction; + + ParseAction parseAction; + + StopAction stopAction; + + NextBreakpointAction nextBreakpointAction; + + PrevBreakpointAction prevBreakpointAction; + + GoBeamerAction goBeamerAction; + + FirstStepAction firstStepAction; + + LastStepAction lastStepAction; + + SimpleAttributeSet redSet = new SimpleAttributeSet(); + + boolean breakingEnabled = false; + + int guiMode = GUIConstants.PARSE_DISABLED; + + List savedInput = new LinkedList(); + + protected JMenu menu; + + // //////////////////////// + + /** + * Constructs the GUIController instance for the current + * PulsMem module instance.
          + * Initializes all layout components, especially the toolbar and the menu. + * Installs an AWT-Frame on the panel provided by the main program, so that + * GUI of the PulsMem module can be created on Swing base. + * + * @param modConn + * the ModuleConnector of the PulsMem module + * @param controller + * the Controller of the PulsMem module + */ + public GUIController(ModuleConnector modConn, Controller controller) { + this.modConn = modConn; + this.controller = controller; + this.lineOfBreakpoint = new InlineBreakpoint(); + // sets a red font to the SimpleAttributeSet 'redSet'. Used for + // errorMessages in console + StyleConstants.setForeground(redSet, Color.RED); + } + + /** + * Shows the Welcome Screen of the Pulsemem-Modul. + */ + public void showWelcomeScreen() { + } + + public InlineBreakpoint getInlineBreakpoints() { + return this.lineOfBreakpoint; + } + + /** + * Shows the Pulsemem-GUI. + */ + public void showPulseMem() { + createActions(); + createToolbar(); + createMenuItems(); + createContent(); + } + + /** + * Creates the whole content in from the Pulsemem View.
          + * It offers a SplitPane, wich TopLevel contains the C-Editor and the + * MemoryTable and wich BottomLevel contain the Console and some Information + * output. + */ + private void createContent() { + this.contentPane = createJAlgoParentPane(); + this.rootPane = createRootPane(); + this.contentPane.add(this.rootPane, BorderLayout.CENTER); + + // SPLITPANE + // INCLUDES TOP AND BOTTOM PANE + this.splitPane = createSplitPane(); + this.splitLeftRight = createSplitLeftRight(); + + // TOP PANE + // INCLUDES LEFT AND RIGHT PANEL + this.topPane = createTopPanel(); + + // LEFT PANE + this.leftOne = createLeftTopPanel(); + this.linedTextarea = createLinedTeaxtarea(); + + this.leftOne.add(this.linedTextarea, BorderLayout.WEST); + this.leftOne.add(this.linedTextarea.getScrollPane(), + BorderLayout.CENTER); + + this.splitLeftRight.setLeftComponent(this.leftOne); + + // RIGHT PANEL + this.rightOne = createRightTopPanel(); + this.splitLeftRight.setRightComponent(this.rightOne); + + this.memPanel = createMemPanel(); + // in der folgenden zeile stand BorderLayout.WEST - AARGH!!! + // und ich wunder mich wochenlang warum meine anzeige so schei�e is... + this.rightOne.add(this.memPanel, BorderLayout.CENTER); + + this.topPane.add(splitLeftRight, BorderLayout.CENTER); + + // TABBEDPANE + // INCLUDES CONSOLESCROLLPANE AND INFORMATIONSCROLLPANE + this.bottomPane = createBottomPanel(); + + this.consolePane = createConsoleScrollPane(); + this.console = createConsoleTextarea(); + this.consolePane.setViewportView(this.console); + + this.bottomPane.addTab(Messages.getString( + "pulsemem", "GUIController.consoleText"), this.consolePane); //$NON-NLS-1$ + + this.splitPane.setTopComponent(this.topPane); + this.splitPane.setBottomComponent(this.bottomPane); + + this.rootPane.add(this.splitPane, BorderLayout.CENTER); + + } + + /** + * Creates a rootPane to wich all components nedded by Pulsemem can be + * added. + * + * @return the rootPane + */ + private JPanel createRootPane() { + JPanel rootPane = new JPanel(); + rootPane.setLayout(new BorderLayout()); + return rootPane; + } + + /** + * @return the parent pane of jAlgo. + */ + private JComponent createJAlgoParentPane() { + JComponent contentPane = JAlgoGUIConnector.getInstance() + .getModuleComponent(this.modConn); + contentPane.setLayout(new BorderLayout()); + contentPane.addComponentListener(new ComponentListener() { + public void componentHidden(ComponentEvent e) { + }; + + public void componentMoved(ComponentEvent e) { + }; + + public void componentResized(ComponentEvent e) { + splitPane.setDividerLocation((int) (getJAlgoWindow() + .getHeight() * 0.85) - 150); + }; + + public void componentShown(ComponentEvent e) { + }; + }); + return contentPane; + } + + /** + * Creates the BottomPane used by Pulsemem. + * + * @return the BottomPane. + */ + private JTabbedPane createBottomPanel() { + JTabbedPane bottomPane = new JTabbedPane(); + bottomPane.setMaximumSize(new Dimension(50, 50)); + bottomPane.setPreferredSize(new Dimension(50, 50)); + return bottomPane; + } + + /** + * Creates a JEditorPane with linenumbers on the left. Breakpoints could + * also be set. + * + * @return a EditorTextarea + */ + private NOLPanel createLinedTeaxtarea() { + NOLPanel linedTextarea = new NOLPanel(this.lineOfBreakpoint); + linedTextarea.setTextFont(GUIConstants.STANDARDFONT); + // linedTextarea + // .setText("#include \n\nvoid test2(int *a, int b)\n{\n while + // (*a == b)\n {\n scanf(\"%i\", &b);\n if (b == 0)\n break;\n *a = + // *a+b;\n printf(\"%d\", b);\n }\n}\n\nint main(void) \n{\n int *a, i = + // 0;\n const int b = 2;\n *a = b+i;\n if (i >= b + *a)\n {\n if (i==4) + // \n test2(&b, b);\n } else break;\n\t\n printf(\"%d\", i);\n}"); + + // adds an KeyListener to the JEditorPane contained in the NOLPanel + + linedTextarea.addKeyListener(new KeyListener() { + + public void keyPressed(KeyEvent ev) { + GUIController.this.modConn + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + + public void keyReleased(KeyEvent ev) { + GUIController.this.modConn + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + } + + public void keyTyped(KeyEvent ev) { + GUIController.this.modConn + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + repaintForm(); + lineOfBreakpoint.clear(); + } + + }); + return linedTextarea; + } + + /** + * Creates the ConsoleTextarea used by Pulsemem. + * + * @return the ConsoleTextarea. + */ + private JTextPane createConsoleTextarea() { + JTextPane console = new JTextPane(); + console.setEditable(false); + console.setMinimumSize(new Dimension(50, 50)); + console.setPreferredSize(new Dimension(50, 50)); + console.setMaximumSize(new Dimension(50, 50)); + return console; + } + + /** + * Creates the ConsoleScrollPane used by Pulsemem. + * + * @return the ConsoleScrollPane. + */ + private JScrollPane createConsoleScrollPane() { + JScrollPane consolePane = new JScrollPane(); + consolePane + .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + consolePane.setMinimumSize(new Dimension(50, 50)); + consolePane.setPreferredSize(new Dimension(50, 50)); + consolePane.setMaximumSize(new Dimension(50, 50)); + return consolePane; + } + + /** + * Creates the TopPanel used by Pulsemem. + * + * @return the TopPanel. + */ + private JPanel createTopPanel() { + JPanel topPane = new JPanel(); + topPane.setLayout(new BorderLayout()); + topPane.setMinimumSize(new Dimension(600, 300)); + topPane.setPreferredSize(new Dimension(800, 600)); + return topPane; + } + + /** + * Creates the right panel of the top panel used by Pulsemem. + * + * @return the right panel of the top panel + */ + private JPanel createRightTopPanel() { + JPanel rightOne = new JPanel(); + rightOne.setBorder(new TitledBorder(Messages.getString( + "pulsemem", "GUIController.pulsememetableText"))); //$NON-NLS-1$ + rightOne.setLayout(new BorderLayout()); + return rightOne; + } + + /** + * Creates the left panel of the top panel used by Pulsemem. + * + * @return the left panel of the top panel + */ + private JPanel createLeftTopPanel() { + JPanel leftOne = new JPanel(); + leftOne.setBorder(new TitledBorder(Messages.getString( + "pulsemem", "GUIController.editorText"))); //$NON-NLS-1$ + leftOne.setLayout(new BorderLayout()); + leftOne.setPreferredSize(new Dimension(300, 600)); + leftOne.setMinimumSize(new Dimension(300, 600)); + + leftOne.addMouseListener(new MouseListener() { + + public void mouseClicked(MouseEvent arg0) { + int line = GUIController.this.linedTextarea + .determineLineFromPoint(arg0.getPoint()); + if (arg0.getClickCount() == 1 + && GUIController.this.breakingEnabled) { + // Changes were made, saving is now possible + GUIController.this.modConn + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + if (GUIController.this.lineOfBreakpoint.containsLine(line)) { + GUIController.this.lineOfBreakpoint.removeLine(line); + updateTableBreakpoints(); + } else { + GUIController.this.lineOfBreakpoint.addLine(line); + updateTableBreakpoints(); + } + } + GUIController.this.linedTextarea.repaint(); + } + + public void mouseEntered(MouseEvent arg0) { + } + + public void mouseExited(MouseEvent arg0) { + } + + public void mousePressed(MouseEvent arg0) { + } + + public void mouseReleased(MouseEvent arg0) { + } + + }); + return leftOne; + } + + /** + * Creates the SplitPane used by Pulsemem. + * + * @return the SplitPane. + */ + private JSplitPane createSplitPane() { + JSplitPane splitPane = new JSplitPane(); + splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); + splitPane.setContinuousLayout(true); + splitPane.setOneTouchExpandable(true); + splitPane.setDividerLocation(getJAlgoWindow().getHeight() - 200); + return splitPane; + } + + /** + * Creates the vertical SplitPane used by Pulsemem. + * + * @return the SplitPane. + */ + private JSplitPane createSplitLeftRight() { + JSplitPane splitLeftRight = new JSplitPane(); + splitLeftRight.setOrientation(JSplitPane.HORIZONTAL_SPLIT); + splitLeftRight.setContinuousLayout(true); + splitLeftRight.setOneTouchExpandable(true); + splitLeftRight.setDividerLocation(300); + return splitLeftRight; + } + + /** + * Creates the PulseMemTablePanel used by PulseMem. + * + * @return the PulseMemTablePanel. + */ + private PulseMemTablePanel createMemPanel() { + PulseMemTablePanel memTable = new PulseMemTablePanel(); + memTable.setGUI(this); + return memTable; + } + + /** + * Creates the Actions. + */ + private void createActions() { + this.importCFileAction = new ImportCFileAction(this, this.controller); + + this.exportCFileAction = new ExportCFileAction(this, this.controller); + + this.welcomeAction = new WelcomeAction(this, this.controller); + + this.parseAction = new ParseAction(this, this.controller); + + this.stopAction = new StopAction(this, this.controller); + + this.nextBreakpointAction = new NextBreakpointAction(this, + this.controller); + + this.prevBreakpointAction = new PrevBreakpointAction(this, + this.controller); + + this.firstStepAction = new FirstStepAction(this, this.controller); + + this.lastStepAction = new LastStepAction(this, this.controller); + } + + /** + * Creates the Menu. + */ + private void createMenuItems() { + menu = JAlgoGUIConnector.getInstance().getModuleMenu(this.modConn); + // add all + menu.add(this.importCFileAction); + menu.add(this.exportCFileAction); + menu.addSeparator(); + menu.add(this.parseAction); + menu.add(this.stopAction); + menu.add(this.firstStepAction); + menu.add(this.prevBreakpointAction); + menu.add(this.nextBreakpointAction); + menu.add(this.lastStepAction); + menu.addSeparator(); + + this.goBeamerAction = GoBeamerAction.getInstance(this, this.controller); + menu.add(this.goBeamerAction); + + menu.getItem(4).setEnabled(false); + menu.getItem(5).setEnabled(false); + menu.getItem(6).setEnabled(false); + menu.getItem(7).setEnabled(false); + menu.getItem(8).setEnabled(false); + menu.getItem(10).setSelected(false); + } + + /** + * Creates the Toolbar. + */ + private void createToolbar() { + JToolBar toolbar = JAlgoGUIConnector.getInstance().getModuleToolbar( + this.modConn); + + // mit JToolbarButton von org.jalgo.main.gui.components.JToolbarButton + // ersetzen + this.importCFileToolbarItem = new JToolbarButton( + (Icon) this.importCFileAction.getValue(Action.SMALL_ICON), + null, null); + this.importCFileToolbarItem.setAction(this.importCFileAction); + this.importCFileToolbarItem.setText(""); //$NON-NLS-1$ + this.importCFileToolbarItem.setToolTipText(Admin + .getLanguageString("gui.ImportCFileToolTip")); + this.importCFileToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.exportCFileToolbarItem = new JToolbarButton( + (Icon) exportCFileAction.getValue(Action.SMALL_ICON), null, + null); + this.exportCFileToolbarItem.setAction(exportCFileAction); + this.exportCFileToolbarItem.setText(""); + this.exportCFileToolbarItem.setToolTipText(Admin + .getLanguageString("gui.ExportCFileToolTip")); + this.exportCFileToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + /* + * NOT USED YET showWelcomeToolbarItem = new JToolbarButton((Icon) + * welcomeAction .getValue(Action.SMALL_ICON), null, null); + * showWelcomeToolbarItem.setAction(welcomeAction); + * showWelcomeToolbarItem.setText(""); + */ + + this.startParsingToolbarItem = new JToolbarButton( + (Icon) this.parseAction.getValue(Action.SMALL_ICON), null, null); + this.startParsingToolbarItem.setAction(this.parseAction); + this.startParsingToolbarItem.setText(""); //$NON-NLS-1$ + this.startParsingToolbarItem.setToolTipText(Admin + .getLanguageString("gui.StartParsingToolTip")); + this.startParsingToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.stopParsingToolbarItem = new JToolbarButton((Icon) this.stopAction + .getValue(Action.SMALL_ICON), null, null); + this.stopParsingToolbarItem.setAction(this.stopAction); + this.stopParsingToolbarItem.setText(""); //$NON-NLS-1$ + this.stopParsingToolbarItem.setEnabled(false); + this.stopParsingToolbarItem.setToolTipText(Admin + .getLanguageString("gui.StopParsingToolTip")); + this.stopParsingToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.nextBreakpointToolbarItem = new JToolbarButton( + (Icon) this.nextBreakpointAction.getValue(Action.SMALL_ICON), + null, null); + this.nextBreakpointToolbarItem.setAction(this.nextBreakpointAction); + this.nextBreakpointToolbarItem.setText(""); //$NON-NLS-1$ + this.nextBreakpointToolbarItem.setEnabled(false); + this.nextBreakpointToolbarItem.setToolTipText(Admin + .getLanguageString("gui.NextBreakpointToolTip")); + this.nextBreakpointToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.prevBreakpointToolbarItem = new JToolbarButton( + (Icon) this.prevBreakpointAction.getValue(Action.SMALL_ICON), + null, null); + this.prevBreakpointToolbarItem.setAction(this.prevBreakpointAction); + this.prevBreakpointToolbarItem.setText(""); //$NON-NLS-1$ + this.prevBreakpointToolbarItem.setEnabled(false); + this.prevBreakpointToolbarItem.setToolTipText(Admin + .getLanguageString("gui.PrevBreakpointToolTip")); + this.prevBreakpointToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.firstStepToolbarItem = new JToolbarButton( + (Icon) this.firstStepAction.getValue(Action.SMALL_ICON), null, + null); + this.firstStepToolbarItem.setAction(this.firstStepAction); + this.firstStepToolbarItem.setText(""); //$NON-NLS-1$ + this.firstStepToolbarItem.setEnabled(false); + this.firstStepToolbarItem.setToolTipText(Admin + .getLanguageString("gui.FirstStepToolTip")); + this.firstStepToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + this.lastStepToolbarItem = new JToolbarButton( + (Icon) this.lastStepAction.getValue(Action.SMALL_ICON), null, + null); + this.lastStepToolbarItem.setAction(this.lastStepAction); + this.lastStepToolbarItem.setText(""); //$NON-NLS-1$ + this.lastStepToolbarItem.setEnabled(false); + this.lastStepToolbarItem.setToolTipText(Admin + .getLanguageString("gui.LastStepToolTip")); + this.lastStepToolbarItem.addMouseListener(StatusLineUpdater + .getInstance()); + + // add all buttons to toolbar + /* + * not used yet toolbar.add(showWelcomeToolbarItem); + * toolbar.addSeparator(); + */ + toolbar.add(this.importCFileToolbarItem); + toolbar.add(exportCFileToolbarItem); + toolbar.addSeparator(); + toolbar.add(this.startParsingToolbarItem); + toolbar.add(this.stopParsingToolbarItem); + toolbar.addSeparator(); + toolbar.add(this.firstStepToolbarItem); + toolbar.add(this.prevBreakpointToolbarItem); + toolbar.add(this.nextBreakpointToolbarItem); + toolbar.add(this.lastStepToolbarItem); + } + + private JAlgoWindow getJAlgoWindow() { + for (Frame f : Frame.getFrames()) + if (f instanceof JAlgoWindow) + return (JAlgoWindow) f; + + throw new RuntimeException("JAlgoWindow not found"); + } + + /** + * Gets the source code. + * + * @return The source code. + */ + public String getSourceCode() { + return this.linedTextarea.getText(); + } + + /** + * gets the Console. Used for writing into the console from other objects. + * + * @return the console + */ + public JTextPane getConsole() { + return console; + } + + /** + * returns the special TextareaPanel + * + * @return current NOLPanel + */ + public NOLPanel getLinedTextarea() { + return this.linedTextarea; + } + + /** + * returns the MemPanel, used to create FileOpen & FileSave Dialogs above it + * + * @return current MemPanel + */ + + public PulseMemTablePanel getMemPanel() { + return this.memPanel; + } + + /** + * returns the current GUIMode (parse disabled/enabled) + * + * @return guiMode + */ + + public int getGUIMode() { + return this.guiMode; + } + + /** + * Sets the source code. + * + * @param value + * The source code. + */ + public void setSourceCode(String value) { + this.linedTextarea.setText(value); + repaintForm(); + } + + // ACTIONS + /** + * Enables or disables the parse/stop items. + * + * @param wether + * to enable or disable parse items.
          + * GUIConstants.PARSE_ENABLED
          + * GUIConstants.PARSE_Disabled
          + */ + public void switchParseStopEnabled(int mode) { + + this.guiMode = mode; + modConn.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + if (GUIConstants.PARSE_ENABLED == mode) { + this.stopParsingToolbarItem.setEnabled(true); + this.startParsingToolbarItem.setEnabled(false); + this.nextBreakpointToolbarItem.setEnabled(true); + this.prevBreakpointToolbarItem.setEnabled(true); + this.firstStepToolbarItem.setEnabled(true); + this.lastStepToolbarItem.setEnabled(true); + this.linedTextarea.setTextareaEnabled(false); + this.breakingEnabled = true; + this.linedTextarea.drawBreakpoints(true); + + menu.getItem(3).setEnabled(false); + menu.getItem(4).setEnabled(true); + menu.getItem(5).setEnabled(true); + menu.getItem(6).setEnabled(true); + menu.getItem(7).setEnabled(true); + menu.getItem(8).setEnabled(true); + + } else if (GUIConstants.PARSE_DISABLED == mode) { + this.stopParsingToolbarItem.setEnabled(false); + this.startParsingToolbarItem.setEnabled(true); + this.nextBreakpointToolbarItem.setEnabled(false); + this.prevBreakpointToolbarItem.setEnabled(false); + this.firstStepToolbarItem.setEnabled(false); + this.lastStepToolbarItem.setEnabled(false); + this.linedTextarea.setTextareaEnabled(true); + this.breakingEnabled = false; + menu.getItem(3).setEnabled(true); + menu.getItem(4).setEnabled(false); + menu.getItem(5).setEnabled(false); + menu.getItem(6).setEnabled(false); + menu.getItem(7).setEnabled(false); + menu.getItem(8).setEnabled(false); + console.setText(""); + this.linedTextarea.drawBreakpoints(false); + memPanel.showEmptyTable(); + controller.restoreEditorModeSourceCode(); + + } + + } + + /** + * Switches between standart- and beamer-mode + * + * @param mode + * true: go to beamermode + */ + public void goToBeamerMode(boolean mode) { + if (mode) { + this.linedTextarea.setTextFont(GUIConstants.BEAMERFONT); + this.console.setFont(GUIConstants.BEAMERFONT); + this.memPanel.setBeamerMode(true); + repaintForm(); + } else { + this.linedTextarea.setTextFont(GUIConstants.STANDARDFONT); + this.console.setFont(GUIConstants.STANDARDFONT); + this.memPanel.setBeamerMode(false); + repaintForm(); + } + } + + /** + * Shows an error message. + * + * @param msg + * The error message to show. + */ + public void showErrorMessage(String msg) { + Document doc = console.getStyledDocument(); + try { + doc.insertString(doc.getEndPosition().getOffset() - 1, msg + "\n", + this.redSet); + } catch (BadLocationException e) { + // ignore the error + } + } + + /** + * Ask for Input at a scanf()-statement. + * + * @param line + * points to the line of the scaf()-statement. + */ + public int input(int line) { + + String inputStr; + int input = 0; + this.linedTextarea.setCaretToLine(line); + do { + inputStr = JOptionPane.showInputDialog(Admin + .getLanguageString("gui.InputExpected_Start") + + line + Admin.getLanguageString("gui.InputExpected_End")); //$NON-NLS-1$ + + try { + input = Integer.parseInt(inputStr); + } catch (NumberFormatException e) { + showErrorMessage(Admin + .getLanguageString("gui.IntegerParseError_Start") //$NON-NLS-1$ + + inputStr + + Admin.getLanguageString("gui.IntegerParseError_End")); //$NON-NLS-1$ + inputStr = null; + } + } while (inputStr == null); + + savedInput.add(input); + return input; + } + + /** + * Prints the output of an printf()-statement. + * + * @param string + * to be printed out. + * @param line + * pointing to the printf-statement. + */ + public void output(String output, int line) { + this.linedTextarea.setCaretToLine(line); + Document doc = console.getDocument(); + try { + String outString = Admin + .getLanguageString("GUIController.printf_Start") + + line + + Admin.getLanguageString("GUIController.printf_End") //$NON-NLS-1$ + + output + "\n"; + + doc.insertString(doc.getEndPosition().getOffset() - 1, outString, + new SimpleAttributeSet()); //$NON-NLS-1$ + } catch (BadLocationException e) { + // ignore the error + } + + } + + /** + * Commits the current InlineBreakpoint object to the table, which will be + * rebuilt then. + */ + public void updateTableBreakpoints() { + this.memPanel.setBreakpoints(this.lineOfBreakpoint); + } + + /** + * Sets the current PulseMemLine list the table gets the data from. + * + * @param pml + */ + public void setTableData(List pml) { + this.memPanel.setTableData(pml); + } + + public void showNextLine() { + this.memPanel.getPulseMemTable().displayUntilNextRow(); + showLineInTextarea(); + } + + public void showPreviousLine() { + this.memPanel.getPulseMemTable().displayUntilPreviousRow(); + showLineInTextarea(); + } + + public void showLastStep() { + this.memPanel.getPulseMemTable().displayUntilLastRow(); + showLineInTextarea(); + } + + public void showFirstStep() { + this.memPanel.getPulseMemTable().displayFirstRowOnly(); + showLineInTextarea(); + } + + /** + * Clears the saved input. Used whenever saved input becomes irrelevant + * (i.e. when importing new C00-Code) + */ + + public void clearInput() { + this.savedInput.clear(); + } + + /** + * prints a String msg to the conolse + * + * @arg String msg + */ + + public void toConsole(String msg) { + Document doc = console.getStyledDocument(); + try { + doc.insertString(doc.getEndPosition().getOffset() - 1, msg + "\n", + new SimpleAttributeSet()); + } catch (BadLocationException e) { + // ignore the error + } + } + + /** + * This is used for loading jAlgo files. The saved input is needed to + * restore the program state at the time of saving. + * + * @return a List containing the inputs the user made. + */ + + public List getInput() { + return this.savedInput; + } + + /** + * Repaints the whole form.
          + * Could help in case of faulty drawing. + */ + public void repaintForm() { + getJAlgoWindow().repaint(); + } + + /** + * Shows the line wich is the last in table in textarea.
          + * Therefor it sets the caret to the line. + */ + private void showLineInTextarea() { + int i = 0, line = 0; + PulsMemLine pussi = null; + List pml = this.memPanel.getVisPml(); + for (PulsMemLine pulsMemLine : pml) { + if (i == this.memPanel.getPulseMemTable().getNumberOfVisibleRows()) { + break; + } + line = pulsMemLine.getCodeLine(); + pussi = pulsMemLine; + i++; + } + if (line >= 1) + this.linedTextarea.setCaretToLine(line); + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/CVS/Entries b/src/org/jalgo/module/pulsemem/gui/components/CVS/Entries new file mode 100644 index 0000000..fa5101e --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/CVS/Entries @@ -0,0 +1,6 @@ +/CellObject.java/1.1/Wed Jan 16 19:19:15 2008/-ko/ +/CurrentLineHighlighter.java/1.1/Wed Jan 16 19:19:15 2008/-ko/ +/InlineBreakpoint.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ +/NOLPanel.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ +/PulseMemTable.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ +/PulseMemTablePanel.java/1.2/Thu Jan 31 20:15:11 2008/-ko/ diff --git a/src/org/jalgo/module/pulsemem/gui/components/CVS/Repository b/src/org/jalgo/module/pulsemem/gui/components/CVS/Repository new file mode 100644 index 0000000..81bdeef --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem/gui/components diff --git a/src/org/jalgo/module/pulsemem/gui/components/CVS/Root b/src/org/jalgo/module/pulsemem/gui/components/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/gui/components/CellObject.java b/src/org/jalgo/module/pulsemem/gui/components/CellObject.java new file mode 100644 index 0000000..7995012 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/CellObject.java @@ -0,0 +1,48 @@ +/** + * + */ +package org.jalgo.module.pulsemem.gui.components; + +import javax.swing.*; + +/** + * @author Karsten + * + */ +public class CellObject extends JLabel { + + //private int alignment = SwingConstants.CENTER; + + public CellObject(String text) { + super(""+text+""); + setVerticalAlignment(SwingConstants.CENTER); + setHorizontalAlignment(SwingConstants.CENTER); + setOpaque(true); + } + + public CellObject(String text,int alignment) { + super(""+text+""); + setVerticalAlignment(SwingConstants.CENTER); + setHorizontalAlignment(alignment); + setOpaque(true); + } + + public CellObject(String line1,String line2) { + super(""+line1+"
          "+line2+""); + setVerticalAlignment(SwingConstants.CENTER); + setHorizontalAlignment(SwingConstants.CENTER); + setOpaque(true); + } + + public CellObject(String line1,String line2, int alignment) { + super(""+line1+"
          "+line2+""); + setVerticalAlignment(SwingConstants.CENTER); + setHorizontalAlignment(alignment); + setOpaque(true); + } + +/* public int getAlignment() { + return alignment; + } +*/ +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.java b/src/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.java new file mode 100644 index 0000000..c091fbc --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/CurrentLineHighlighter.java @@ -0,0 +1,58 @@ +/** + * + */ + +/* Created on 15.06.2007 */ +package org.jalgo.module.pulsemem.gui.components; + +import java.awt.Color; + +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.*; + +import org.jalgo.module.pulsemem.gui.GUIConstants; + +/** + * CurrentLineHighlighter.java + *

          + * Colors the current line. + *

          + * + * @version $Revision: 1.2 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class CurrentLineHighlighter implements CaretListener { + + private Highlighter.HighlightPainter painter; + + private Object highlight; + + public CurrentLineHighlighter() { + this(null); + } + + public CurrentLineHighlighter(Color highlightColor) { + Color c = highlightColor != null ? highlightColor + : GUIConstants.LineHighlightColor; + painter = new DefaultHighlighter.DefaultHighlightPainter(c); + } + + public void caretUpdate(CaretEvent evt) { + JTextComponent comp = (JTextComponent) evt.getSource(); + if (comp != null && highlight != null) { + comp.getHighlighter().removeHighlight(highlight); + highlight = null; + } + + int pos = comp.getCaretPosition(); + Element elem = Utilities.getParagraphElement(comp, pos); + int start = elem.getStartOffset(); + int end = elem.getEndOffset(); + try { + highlight = comp.getHighlighter().addHighlight(start, end, painter); + } catch (BadLocationException ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.java b/src/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.java new file mode 100644 index 0000000..6fce287 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/InlineBreakpoint.java @@ -0,0 +1,110 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.components; + +import java.util.HashSet; +import java.io.Serializable; + +/** + * InlineBreakpoint.java + *

          + * Stores the linenumbers of breakpoints the user set. + *

          + * Singleton-Pattern removed - Ebi + * + * @version $Revision: 1.5 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class InlineBreakpoint implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -400502530084377030L; + + /** + * Stores the linnumbers wich are marked as breakpoints. + */ + private HashSet lineOfBreakpoint = new HashSet(); + + public InlineBreakpoint() { + lineOfBreakpoint.add(0); + } + + /** + * @return the wohle Set lineOfBreakpoint + */ + public HashSet getLineOfBreakpoints() { + return lineOfBreakpoint; + } + + /** + * Add a line to lineOfBreakpoint. + * + * @param lineOfBreakpoint + * the lineOfBreakpoint to set + * @return wether it is added or not
          + * in case of false it is already in set. + */ + public boolean addLine(int line) { + return this.lineOfBreakpoint.add(line); + } + + /** + * Checks wether the line is in the Set. + * + * @param line + * the linenumber to check. + * @return true if the line is in the Set. + */ + public boolean containsLine(int line) { + return lineOfBreakpoint.contains(line); + } + + /** + * Removes a line from lineOfBreakpoint. + * + * @param lineOfBreakpoint + * the lineOfBreakpoint to remove + * @return wether it is added or not
          + * in case of false it is not in set. + */ + public boolean removeLine(int line) { + return this.lineOfBreakpoint.remove(line); + + } + + /** + * Removes all breakpoints from the set. + * + */ + public void clear() { + lineOfBreakpoint.clear(); + } + + public String toString() { + return lineOfBreakpoint.toString(); + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/NOLPanel.java b/src/org/jalgo/module/pulsemem/gui/components/NOLPanel.java new file mode 100644 index 0000000..f375ab6 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/NOLPanel.java @@ -0,0 +1,347 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 05.05.2007 */ +package org.jalgo.module.pulsemem.gui.components; + +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.event.KeyListener; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; + +import javax.imageio.ImageIO; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Document; +import javax.swing.text.Highlighter; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.core.PulsMemLine; +import org.jalgo.module.pulsemem.core.Variable; +import org.jalgo.module.pulsemem.gui.GUIConstants; + +/** + * NOLPanel.java + *

          + * NOLPanel is a component extending the standard JEditorPane + * with linenumbers on the left of it. + *

          + * + * @version $Revision: 1.26 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class NOLPanel extends JPanel { + + private final int textEditPosX = 47; + + private JTextArea textarea; + + private JScrollPane scrollPane; + + private int fontHeight; + + private int fontDesc; + + private int starting_y; + + private InlineBreakpoint lineOfBreakpoint; + + private BufferedImage breaker; + + // private Image scaledBreaker; + + private int start; + + private int end; + + private int startline; + + private int endline; + + private int fontWidth; + + private boolean drawBreakpoints = false; + + private List vars; + + public NOLPanel(InlineBreakpoint lineOfBreakpointArg) { + super(); + + // get Instance of the Breakpoint handler + lineOfBreakpoint = lineOfBreakpointArg; + + // new EditorPane + textarea = new JTextArea() { + @Override + public void paint(Graphics g) { + super.paint(g); + NOLPanel.this.repaint(); + } + }; + + // new ScrollPane + scrollPane = new JScrollPane(textarea); + + textarea.setDisabledTextColor(GUIConstants.DISABLED_TEXTAREA_FONT); + + // textarea.setSelectedTextColor(GUIConstants.CARET_SELECT_COLOR); + textarea.setSelectionColor(GUIConstants.CARET_SELECT_COLOR); + + textarea.addCaretListener(new CurrentLineHighlighter()); + + // get the breakpoint symbol + try { + if ((breaker = ImageIO.read(Messages.getResourceURL("pulsemem", + "Breakpoint"))) != null) { + repaint(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void paint(Graphics g) { + super.paint(g); + fontHeight = g.getFontMetrics(textarea.getFont()).getHeight(); + fontWidth = g.getFontMetrics(textarea.getFont()).getWidths()[48]; + fontDesc = g.getFontMetrics(textarea.getFont()).getDescent(); + starting_y = -1; + + start = textarea + .viewToModel(scrollPane.getViewport().getViewPosition()); + end = textarea.viewToModel(new Point(scrollPane.getViewport() + .getViewPosition().x + + textarea.getWidth(), scrollPane.getViewport() + .getViewPosition().y + + textarea.getHeight())); + Document doc = textarea.getDocument(); + startline = doc.getDefaultRootElement().getElementIndex(start) + 1; + endline = doc.getDefaultRootElement().getElementIndex(end) + 1; + + int noc = 0; + float temp = endline / 10; + while (temp >= 1) { + temp = temp / 10; + noc++; + } + + setMinimumSize(new Dimension((noc + 3) * fontWidth, 40)); + setPreferredSize(new Dimension((noc + 3) * fontWidth, 40)); + + try { + starting_y = textarea.modelToView(start).y + - scrollPane.getViewport().getViewPosition().y + fontHeight + - fontDesc; + } catch (BadLocationException e1) { + e1.printStackTrace(); + } + + // scales the image... + // if (fontHeight == 12) { + // scaledBreaker = breaker.getScaledInstance((breaker.getWidth() * 1), + // (breaker.getHeight() * 1), Image.SCALE_SMOOTH); + // } else if (fontHeight == 16) { + // scaledBreaker = breaker.getScaledInstance((breaker.getWidth() * 2), + // (breaker.getHeight() * 2), Image.SCALE_SMOOTH); + // } + + for (int line = startline, y = starting_y; line <= endline; y += fontHeight, line++) { + int tempnoc = noc; + int mult = 0; + while (line < Math.pow(10, tempnoc)) { + tempnoc--; + mult++; + } + g.drawString(Integer.toString(line), mult * fontWidth, y); + + if (drawBreakpoints) { + if (lineOfBreakpoint.containsLine(line)) { + // g.fillOval(20, y + (fontHeight / 2), 7, 7); + if (breaker != null) + g.drawImage(breaker, (noc + 1) * fontWidth, y + - fontDesc - (breaker.getHeight() / 2) - 1, + this); + } + } + } + } + + /** + * @param pml + */ + public void highlightVarOccurences(PulsMemLine pml) { + int sRow = 0, sCol = 0, sLen = 0; + int pos; + Set app; + + Highlighter h = textarea.getHighlighter(); + h.removeAllHighlights(); + + if (!(pml == null)) { + vars = pml.getVisibleStack(); + for (Variable variable : vars) { + app = variable.getVi().getAppearance(); + for (Integer[] integers : app) { + sRow = integers[0]-1; + sCol = integers[1]; + sLen = variable.getName().length(); + + try { + pos = textarea.getLineStartOffset(sRow) + sCol; + h.addHighlight(pos, pos + sLen, DefaultHighlighter.DefaultPainter); + } catch (BadLocationException ble) { + } + } + } + } + } + + /** + * @return the scrollPane + */ + public JScrollPane getScrollPane() { + return scrollPane; + } + + /** + * Sets the Text from the Textarea. + * + * @param str + */ + public void setText(String str) { + textarea.setText(str); + } + + /** + * @return the text of the Textarea. + */ + public String getText() { + return textarea.getText(); + } + + /** + * Enables/Disables the textarea. + * + * @param b + * true if it should be enabled. + */ + public void setTextareaEnabled(boolean b) { + textarea.setEnabled(b); + } + + /** + * @return the height of the font. + */ + public int getFontHeight() { + return fontHeight; + } + + /** + * Determine wich line was clicked. + * + * @param yPoint + * @return the line wich was clicked. + */ + public int determineLineFromPoint(Point point) { + repaint(); + + // Rangecheck + if (point.y < getY()) + return 0; + + if (point.y > getY() + getHeight()) + return 0; + + if (point.x > textEditPosX) + return 0; + + final int adjustValue = 1; + + float adj = -getY() - (fontHeight / 2.0f) - adjustValue; + + JScrollBar vertical = (JScrollBar) scrollPane.getComponent(1); + int result = (int) ((point.y + adj + vertical.getValue()) / fontHeight + 1.5f); + return result; + } + + /** + * adds an ActionListener to the Textarea + * + * @param ActLst + */ + public void addKeyListener(KeyListener KeyLst) { + textarea.addKeyListener(KeyLst); + } + + /** + * Sets the font. + * + * @param font + * the font. + */ + public void setTextFont(Font font) { + textarea.setFont(font); + } + + /** + * @return the textarea + */ + public JTextArea getTextarea() { + return textarea; + } + + /** + * Sets the Caret to a specific line. + * + * @param line + * must be greater or equal to 1 + */ + public void setCaretToLine(int line) { + try { + textarea.setCaretPosition(textarea.getLineStartOffset(line - 1)); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + + /** + * sets whether the Breakpoints should be drawn or not + * + * @param boolean + */ + + public void drawBreakpoints(boolean arg) { + this.drawBreakpoints = arg; + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/PulseMemTable.java b/src/org/jalgo/module/pulsemem/gui/components/PulseMemTable.java new file mode 100644 index 0000000..a0d3917 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/PulseMemTable.java @@ -0,0 +1,465 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.pulsemem.gui.components; + +import javax.swing.*; +import javax.swing.table.*; + +import org.jalgo.main.util.Messages; + +import java.awt.*; +import org.jalgo.module.pulsemem.gui.*; + +// import org.jalgo.module.pulsemem.core.*; + +/** + * @version $Revision: 1.31 $ + * @author Karsten Diepelt + */ +public class PulseMemTable extends JScrollPane { + + private static final long serialVersionUID = -3595289495202738856L; + + private JTable tabStatic; + + private JTable tabDynamic; + + private Font tableFont = GUIConstants.STANDARDFONT; + + private int numberOfGlobalVars; + + private int numberOfVisibleRows; + + private int verticalScrollValue; + + private int horizontalScrollValue; + + private boolean dataBeenAdded = false; + + private boolean beamerMode = false; + + String columns[] = { + Messages.getString("pulsemem", "PulseMemTable.Stack"), Messages.getString("pulsemem", "PulseMemTable.Label"), " - " }; //$NON-NLS-1$ //$NON-NLS-2$ + + CellObject data[][] = { { + new CellObject("-----"), new CellObject("-----"), new CellObject(" - ") } }; //$NON-NLS-1$ //$NON-NLS-2$ + + public PulseMemTable() { + super(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + // System.out.println("pmt erstellt, initialisiere"); + numberOfGlobalVars = 1; + numberOfVisibleRows = 0; + init(); + this.repaint(); + } + + private void init() { + + tabStatic = new JTable(fixedModel); + tabDynamic = new JTable(mainModel); + + tabStatic.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + tabDynamic.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + + tabStatic.setDragEnabled(false); + tabDynamic.setDragEnabled(false); + + tabStatic.getTableHeader().setReorderingAllowed(false); + tabDynamic.getTableHeader().setReorderingAllowed(false); + + tabStatic.setFont(tableFont); + tabDynamic.setFont(tableFont); + + findAndSetBestTableSize(); + + tabStatic.setDefaultRenderer(Component.class, cellRenderer); + tabDynamic.setDefaultRenderer(Component.class, cellRenderer); + setCenterRendererForAllColumns(tabStatic, Color.white, Color.black); + setCenterRendererForAllColumns(tabDynamic, Color.white, Color.gray); + + ListSelectionModel model = tabStatic.getSelectionModel(); + tabDynamic.setSelectionModel(model); + this.setViewportView(tabDynamic); + Dimension fixedSize = tabStatic.getPreferredSize(); + fixedSize.width += 5; + JViewport view = new JViewport(); + view.setView(tabStatic); + view.setPreferredSize(fixedSize); + view.setMaximumSize(fixedSize); + this.setCorner(JScrollPane.UPPER_LEFT_CORNER, tabStatic + .getTableHeader()); + this.setRowHeaderView(view); + + // Dimension xxx = this.getViewport().getMaximumSize(); + // tabDynamic.setSize(xxx); + // this.repaint(); + } + + public void setData(String[] columns, CellObject[][] data, int nogv) { + + if (dataBeenAdded) { + this.saveVerticalScrollValue(); + if (this.numberOfVisibleRows >= data.length) { + this.numberOfVisibleRows = data.length; + } + + this.columns = columns; + this.data = data; + this.numberOfGlobalVars = nogv; + init(); + this.restoreVerticalScrollValue(); + this.repaint(); + + } else { + this.dataBeenAdded = true; + this.numberOfVisibleRows = 0; + + this.columns = columns; + this.data = data; + this.numberOfGlobalVars = nogv; + if (beamerMode) { + this.enableBeamer(); + } else { + init(); + } + this.getParent().repaint(); + } + + } + + public void setVisibleLine(int line) { + this.numberOfVisibleRows = Math.min(line, data.length); + this.saveHorizontalScrollValue(); + init(); + this.restoreHorizontalScrollValue(); + this.getVerticalScrollBar().setValue( + this.getVerticalScrollBar().getMaximum()); + } + + public void resetTable() { + this.dataBeenAdded = false; + String columns[] = { + Messages.getString("pulsemem", "PulseMemTable.Stack"), Messages.getString("pulsemem", "PulseMemTable.Label"), " - " }; //$NON-NLS-1$ //$NON-NLS-2$ + + CellObject data[][] = { { + new CellObject("-----"), new CellObject("-----"), new CellObject(" - ") } }; //$NON-NLS-1$ //$NON-NLS-2$ + + this.columns = columns; + this.data = data; + this.numberOfVisibleRows = 0; + this.numberOfGlobalVars = 1; + init(); + this.repaint(); + } + + public void displayUntilNextRow() { + if (numberOfVisibleRows < data.length) { + numberOfVisibleRows++; + this.saveHorizontalScrollValue(); + init(); + this.restoreHorizontalScrollValue(); + this.getVerticalScrollBar().setValue( + this.getVerticalScrollBar().getMaximum()); + } + } + + public void displayUntilPreviousRow() { + if (numberOfVisibleRows > 0) { + numberOfVisibleRows--; + this.saveHorizontalScrollValue(); + init(); + this.restoreHorizontalScrollValue(); + this.getVerticalScrollBar().setValue( + this.getVerticalScrollBar().getMaximum()); + } + } + + public void displayUntilLastRow() { + this.saveHorizontalScrollValue(); + this.saveVerticalScrollValue(); + numberOfVisibleRows = data.length; + init(); + this.restoreVerticalScrollValue(); + this.restoreHorizontalScrollValue(); + } + + public void displayFirstRowOnly() { + numberOfVisibleRows = 1; + this.saveHorizontalScrollValue(); + init(); + this.restoreHorizontalScrollValue(); + } + + private void saveVerticalScrollValue() { + this.verticalScrollValue = this.getVerticalScrollBar().getValue(); + } + + private void restoreVerticalScrollValue() { + this.getVerticalScrollBar().setValue(this.verticalScrollValue); + } + + private void saveHorizontalScrollValue() { + this.horizontalScrollValue = this.getHorizontalScrollBar().getValue(); + } + + private void restoreHorizontalScrollValue() { + this.getHorizontalScrollBar().setValue(this.horizontalScrollValue); + } + + private void setCenterRendererForAllColumns(JTable tab, Color fg, Color bg) { + TableCellRenderer rend = new CenterRenderer(fg, bg); + int numberOfColumns = tab.getColumnCount(); + for (int i = 0; i < numberOfColumns; i++) { + TableColumn tc = tab.getColumnModel().getColumn(i); + tc.setHeaderRenderer(rend); + } + } + + private void findAndSetBestTableSize() { + + int rows = data.length; + int cols = columns.length; + int statCols = tabStatic.getColumnCount(); + int dynCols = tabDynamic.getColumnCount(); + + int maxColumnWidth[] = new int[cols]; + maxColumnWidth[0] = 60; + maxColumnWidth[1] = 60; + for (int i = 2; i < cols; i++) { + maxColumnWidth[i] = 10; + } + + for (int i = 0; i < rows; i++) { + + if (beamerMode) { + if (i == rows - 1) { + tabStatic.setRowHeight(i, 20); + tabDynamic.setRowHeight(i, 20); + } else { + tabStatic.setRowHeight(i, 45); + tabDynamic.setRowHeight(i, 45); + } + } else { + if (i == rows - 1) { + tabStatic.setRowHeight(i, 15); + tabDynamic.setRowHeight(i, 15); + } else { + tabStatic.setRowHeight(i, 30); + tabDynamic.setRowHeight(i, 30); + } + } + for (int j = 0; j < cols; j++) { + if (data[i][j] != null) { + maxColumnWidth[j] = Math.min(Math.max(data[i][j] + .getPreferredSize().width, maxColumnWidth[j]), 100); + } + } + } + + for (int i = 0; i < statCols; i++) { + tabStatic.getColumnModel().getColumn(i).setPreferredWidth( + maxColumnWidth[i] + 5); + } + + for (int i = 0; i < dynCols; i++) { + tabDynamic.getColumnModel().getColumn(i).setPreferredWidth( + maxColumnWidth[i + statCols] + 5); + } + } + + public void enableBeamer() { + this.saveHorizontalScrollValue(); + this.saveVerticalScrollValue(); + beamerMode = true; + this.tableFont = GUIConstants.BEAMERFONT; + for (int i = 0; i < data.length; i++) { + for (int j = 0; j < columns.length; j++) { + if (data[i][j] != null) { + data[i][j].setFont(tableFont); + // data[i][j].updateUI(); + } + } + } + init(); + this.restoreVerticalScrollValue(); + this.restoreHorizontalScrollValue(); + } + + public void disableBeamer() { + this.saveHorizontalScrollValue(); + this.saveVerticalScrollValue(); + beamerMode = false; + this.tableFont = GUIConstants.STANDARDFONT; + for (int i = 0; i < data.length; i++) { + for (int j = 0; j < columns.length; j++) { + if (data[i][j] != null) { + data[i][j].setFont(tableFont); + // data[i][j].updateUI(); + } + } + } + init(); + this.restoreVerticalScrollValue(); + this.restoreHorizontalScrollValue(); + } + + /** + * Table Model for the fixed table + */ + + TableModel fixedModel = new AbstractTableModel() { + + private static final long serialVersionUID = -5438194825238398059L; + + public int getColumnCount() { + return numberOfGlobalVars + 2; + } + + public String getColumnName(int col) { + return columns[col]; + } + + public int getRowCount() { + return numberOfVisibleRows; + } + + public Object getValueAt(int row, int col) { + return data[row][col]; + } + + public Class getColumnClass(int columnIndex) { + return CellObject.class; + } + }; + + /** + * Table Model for the non-fixed table + */ + + TableModel mainModel = new AbstractTableModel() { + + private static final long serialVersionUID = 5243145608765652138L; + + public int getColumnCount() { + return columns.length - (numberOfGlobalVars + 2); + } + + public String getColumnName(int col) { + return columns[col + numberOfGlobalVars + 2]; + } + + public int getRowCount() { + return numberOfVisibleRows; + } + + public Object getValueAt(int row, int col) { + return data[row][col + numberOfGlobalVars + 2]; + } + + @SuppressWarnings("unchecked") + public Class getColumnClass(int columnIndex) { + return CellObject.class; + } + + }; + + /** + * This custom TableCellRenderer is responsible for displaying the + * CellObjects + */ + TableCellRenderer cellRenderer = new TableCellRenderer() { + + public final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); + + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, int row, + int column) { + Component cell; + if (value instanceof CellObject) { + cell = (CellObject) value; + } else { + cell = DEFAULT_RENDERER.getTableCellRendererComponent(table, + value, isSelected, hasFocus, row, column); + } + if (!isSelected) { + if (row % 2 == 0) { + cell.setBackground(Color.WHITE); + } else { + cell.setBackground(Color.LIGHT_GRAY); + } + } else { + if (row % 2 == 0) { + cell.setBackground(Color.YELLOW); + } else { + cell.setBackground(Color.ORANGE); + } + } + // cell.setFont(tableFont); + + return cell; + } + + }; + + /** + * center renderer used for columns + */ + + class CenterRenderer implements TableCellRenderer { + + Color fg; + + Color bg; + + public CenterRenderer(Color fg, Color bg) { + this.fg = fg; + this.bg = bg; + } + + public final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); + + public Component getTableCellRendererComponent(JTable table, + Object value, boolean isSelected, boolean hasFocus, int row, + int column) { + + DEFAULT_RENDERER.setVerticalAlignment(SwingConstants.CENTER); + DEFAULT_RENDERER.setHorizontalAlignment(SwingConstants.CENTER); + Component cell = DEFAULT_RENDERER.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); + cell.setBackground(bg); + cell.setForeground(fg); + return cell; + } + + } + + /** + * @return the numberOfVisibleRows + */ + public int getNumberOfVisibleRows() { + return numberOfVisibleRows; + }; + +} diff --git a/src/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.java b/src/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.java new file mode 100644 index 0000000..c038299 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/components/PulseMemTablePanel.java @@ -0,0 +1,349 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +package org.jalgo.module.pulsemem.gui.components; + +import java.awt.*; +import java.util.*; +import java.util.List; + +import javax.swing.*; + +import org.jalgo.module.pulsemem.Admin; +import org.jalgo.module.pulsemem.core.exceptions.*; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.core.*; +import org.jalgo.module.pulsemem.gui.*; + +/** + * PulseMemTablePanel.java + * + * @version $Revision: 1.46 $ + * @author Karsten Diepelt + */ +public class PulseMemTablePanel extends JPanel { + + private static final long serialVersionUID = 4932273813663983244L; + + private PulseMemTable pmt; + + private List pml; + + private InlineBreakpoint lineOfBreakpoint; + + private GUIController gui; + + public PulseMemTablePanel() { + super(new BorderLayout()); + lineOfBreakpoint = new InlineBreakpoint(); + pmt = new PulseMemTable(); + this.add(pmt, BorderLayout.CENTER); + this.repaint(); + } + + /** + * Gets and formates the name of the variable. + * @param line The line which is handled at the moment + * @param j Index of the variable. + * @return The formatted name of the variable. + */ + private String getFormattedVariableName(PulsMemLine line, int j) { + String name; + boolean isVisibleVar = line.getVisibleStack().indexOf(line.getStack().get(j)) != -1; + + name = (isVisibleVar ? "" : ""); + name += line.getStack().get(j).getName(); + name += (isVisibleVar ? "" : ""); + return name; + } + + /** + * Returns the PulseMemTable + * + * @return + */ + public PulseMemTable getPulseMemTable() { + return pmt; + } + + public void setTableData(List pmlList) { + this.pml = pmlList; + updateTable(); + } + + /** + * Sets the line number, up to which the PulsMem is shown + * Used for loading. + * + * @param line + */ + public void setVisibleLines(int line) { + this.pmt.setVisibleLine(line); + } + + /** + * shows an empty PulseMemTable + * + */ + public void showEmptyTable() { + pmt.resetTable(); + this.pml = null; + } + + /** + * This function updates the whole table data. It analyzes the list of + * PulseMemLine and the InlineBreakpoint object to re-create all table data. + * (The PulseMemTable itself just display data, this panel selects the data + * for the table to display.) + */ + public void updateTable() { + if (this.pml != null) { + List pmlVis = getVisiblePML(this.pml); + int numberOfRows = pmlVis.size(); + int numberOfColumns = 0; + int numberOfGlobalVars = 0; + boolean addDummy = false; + // find the longest line: + for (int i = 0; i < numberOfRows; i++) { + numberOfColumns = Math.max(pmlVis.get(i).getStack().size(), + numberOfColumns); + } + // find out the number of global variables, + for (int i = 0; i < numberOfRows; i++) { + PulsMemLine line = pmlVis.get(i); + numberOfGlobalVars = Math.max(checkNumberOfGlobalVars(line), + numberOfGlobalVars); + } + // find out if adding a dummy is necessary + addDummy = (numberOfColumns == numberOfGlobalVars); + + numberOfColumns += 2; + String columns[]; + if (addDummy) { + columns = new String[numberOfColumns + 1]; + columns[numberOfColumns] = " - "; + } else { + columns = new String[numberOfColumns]; + } + + columns[0] = Messages.getString( + "pulsemem", "PulseMemTablePanel.LabelLine"); //$NON-NLS-1$ + columns[1] = Messages.getString( + "pulsemem", "PulseMemTablePanel.Stack"); //$NON-NLS-1$ + for (int i = 2; i < numberOfColumns; i++) { + columns[i] = Integer.toString(i - 1); + } + CellObject data[][]; + if (addDummy) { + data = new CellObject[numberOfRows + 1][numberOfColumns + 1]; + data[numberOfRows][numberOfColumns] = new CellObject(" - "); + } else { + data = new CellObject[numberOfRows + 1][numberOfColumns]; + } + + // get data for each row + + for (int i = 0; i < numberOfRows; i++) { + try { + PulsMemLine line = pmlVis.get(i); + numberOfGlobalVars = Math.max( + checkNumberOfGlobalVars(line), numberOfGlobalVars); + // find out if line has a label + if (line.isLabel()) { + data[i][0] = new CellObject(Messages.getString( + "pulsemem", "PulseMemTable.Line") + + " " + Integer.toString(line.getCodeLine()), + Messages.getString("pulsemem", + "PulseMemTable.Label") + + " " + + Integer.toString(line.getLabel())); + } else { + data[i][0] = new CellObject(Messages.getString( + "pulsemem", "PulseMemTable.Line") + + " " + Integer.toString(line.getCodeLine())); + } + // reverse stack string + String rm = "] "; + int size = line.getRuecksprungMarken().size(); + for (int j = 0; j < size; j++) { + if (j == 0) { + rm = Integer.toString(line.getRuecksprungMarken() + .get(j)) + + rm; + } else { + rm = Integer.toString(line.getRuecksprungMarken() + .get(j)) + + "," + rm; + } + } + rm = "[" + rm; + data[i][1] = new CellObject(rm, SwingConstants.RIGHT); + // get data for variable of the line + for (int j = 0; j < line.getStack().size(); j++) { + String name; + String value = "?"; //$NON-NLS-1$ + + if (line.getStack().get(j).getName() == null) { + name = "?"; //$NON-NLS-1$ + } else { + if (line.getStack().get(j) instanceof Zeiger) { + Zeiger tmp = (Zeiger) line.getStack().get(j); + + name = "" + tmp.getName() + ""; + // name = tmp.toString(); + try { + value = "#" + + Integer + .toString(line + .getStack() + .indexOf( + tmp + .getTarget()) + 1); + } catch (EMemoryError eme) { + + } + } else { + + name = getFormattedVariableName(line, j); + + try { + if (line.getStack().get(j).getValue() != null) { + value = line.getStack().get(j).getValue().toString(); + } + } catch (Exception e) { + + } + + } + } + + data[i][j + 2] = new CellObject("

          " + name, + value + "
          "); + + } + + if (addDummy) { + data[i][numberOfColumns] = new CellObject(" - "); + } + } catch (OutOfMemoryError t) { + System.gc(); + data = null; + this.pml = null; + this.updateTable(); + System.gc(); + System.out.println("OutOfMemoryError"); + gui.switchParseStopEnabled(GUIConstants.PARSE_DISABLED); + gui.showErrorMessage(Admin.getLanguageString("gui.OutOfMemory")); + return; + + } + } + for (int i = 0; i < numberOfColumns; i++) { + data[numberOfRows][i] = new CellObject("-----"); + } + pmt.setData(columns, data, numberOfGlobalVars); + } + } + + /** + * Sets the InlineBreakpoint object for the table. + * + * @param lob + */ + public void setBreakpoints(InlineBreakpoint lob) { + this.lineOfBreakpoint = lob; + updateTable(); + } + + /** + * This function checks the number global variables in a PulsMemLine + * + * @param line + * @return + */ + private int checkNumberOfGlobalVars(PulsMemLine line) { + int anz = 0; + for (int i = 0; i < line.getStack().size(); i++) { + if (line.getStack().get(i).isGlobal()) { + anz++; + } + } + return anz; + } + + /* + * private String getPointerString(Object o) { String out = ""; if (o + * instanceof Zeiger) { Zeiger z = (Zeiger) o; out = out + " => " + + * z.getName() + "(" + Integer.toString(z.getVisibilityLevel() + 1) + ")" + + * getPointerString(z.getValue()); } else { if (o instanceof Variable) { + * Variable v = (Variable) o; out = out + " => " + v.getName() + "(" + + * Integer.toString(v.getVisibilityLevel() + 1) + ")"; } } + * + * return out; } + */ + + /** + * Returns the list of visible PulseMemLines, depending on the breakpoints + * set by the user and the labels in the source code. + * + * @param allPML + * @return + */ + public List getVisiblePML(List allPML) { + List visPML = new ArrayList(); + if (allPML!=null) { + for (int i = 0; i < allPML.size(); i++) { + if (this.lineOfBreakpoint.containsLine(allPML.get(i).getCodeLine())) { + visPML.add(allPML.get(i)); + } + } + } + + return visPML; + } + + /** + * @return the pml + */ + public List getVisPml() { + return getVisiblePML(this.pml); + } + + /** + * sets the beamer mode + * + * @param beamer + * -true: enable beamer mode + */ + public void setBeamerMode(boolean beamer) { + if (beamer) { + pmt.enableBeamer(); + } else { + pmt.disableBeamer(); + } + } + + public void setGUI (GUIController gui) { + this.gui = gui; + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/CVS/Entries b/src/org/jalgo/module/pulsemem/gui/events/CVS/Entries new file mode 100644 index 0000000..9f1f5bf --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/CVS/Entries @@ -0,0 +1,10 @@ +/ExportCFileAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/FirstStepAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/GoBeamerAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/ImportCFileAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/LastStepAction.java/1.1/Wed Jan 16 19:19:16 2008/-ko/ +/NextBreakpointAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/ParseAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/PrevBreakpointAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/StopAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ +/WelcomeAction.java/1.2/Thu Jan 31 20:15:08 2008/-ko/ diff --git a/src/org/jalgo/module/pulsemem/gui/events/CVS/Repository b/src/org/jalgo/module/pulsemem/gui/events/CVS/Repository new file mode 100644 index 0000000..9d909da --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/pulsemem/gui/events diff --git a/src/org/jalgo/module/pulsemem/gui/events/CVS/Root b/src/org/jalgo/module/pulsemem/gui/events/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.java b/src/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.java new file mode 100644 index 0000000..42e17dc --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/ExportCFileAction.java @@ -0,0 +1,124 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; +import javax.swing.JOptionPane; +import java.io.*; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Admin; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * NextBreakpointAction.java + *

          + * Will import a C-File. + *

          + */ +public class ExportCFileAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public ExportCFileAction(GUIController gui, Controller controller) { + + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "ExportCFileAction.exportCShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "ExportCFileAction.exportCLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", + "ExportCFile"))); + } + + /* + * creates JFileChooser, checks whether a file has to be overwritten (asks User in that case) + * then writes into choosen file + */ + public void actionPerformed(ActionEvent e) { + + final JFileChooser fc = new JFileChooser(); + fc.setCurrentDirectory(new File("./examples/pulsemem")); + fc.setFileFilter(new FileFilter() { //shows C-Files only + + public boolean accept(File f) { + if (f.isDirectory()) return true; + String ext = f.getName().substring(f.getName().length()-2,f.getName().length()); + return (ext.equals(".c")); + } + + public String getDescription() { + return Admin.getLanguageString("gui.FileFilterDescription"); + } + }); + + //creates SaveDialogs until a legal operation was performed + while (true){ + int returnVal = fc.showSaveDialog(this.gui.getMemPanel()); + File file = fc.getSelectedFile(); + if (returnVal == JFileChooser.APPROVE_OPTION) { + if (file.exists()) { + if (JOptionPane.showConfirmDialog( + gui.getMemPanel(), + Admin.getLanguageString("gui.ExportCFileDialogText"), + Admin.getLanguageString("gui.ExportCFileDialogTitle"), + JOptionPane.YES_NO_OPTION) == 1 ) + continue; //new SaveDialog, if user chooses not to overwrite + } + + String fileStr= file.getPath(); + if (!(fileStr.substring(fileStr.length()-2,fileStr.length()).equals(".c"))) + fileStr+=".c"; + + try { + BufferedWriter out = new BufferedWriter(new FileWriter(fileStr)); + out.write(controller.getGUIController().getSourceCode()); + out.close(); + break; //break if file was written successfully + } + catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + } else break; //break if user chooses "Cancel" in SaveDialog + } + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/FirstStepAction.java b/src/org/jalgo/module/pulsemem/gui/events/FirstStepAction.java new file mode 100644 index 0000000..3f7a466 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/FirstStepAction.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * FirstStepAction.java + *

          + * Will show the first step. + *

          + * + * @version $Revision: 1.3 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class FirstStepAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public FirstStepAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "FirstStepAction.firstStepShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "FirstStepAction.firstStepLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "StepBack"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + controller.getConnector() + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + gui.showFirstStep(); + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.java b/src/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.java new file mode 100644 index 0000000..e9472ba --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/GoBeamerAction.java @@ -0,0 +1,88 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * GoBeamer.java + *

          + * Will go in BeamerMode.
          + * Therefor change font-size and so on. + *

          + * + * @version $Revision: 1.3 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class GoBeamerAction extends JCheckBoxMenuItem implements ActionListener { + + private GUIController gui; + + private Controller controller; + + private static GoBeamerAction instance; + + /** + * @param gui + * @param controller + */ + private GoBeamerAction(GUIController gui, Controller controller) { + super( + Messages.getString("pulsemem", "GoBeamerAction.BeamerMode"), new ImageIcon(Messages.getResourceURL("main", "Icon.Beamer_mode")), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + addActionListener(this); + this.gui = gui; + this.controller = controller; + } + + /** + * Retrieves and, if necessary, initializes the singleton instance of + * BeamerModeAction. + * + * @param gc + * the GUIController + * @return the singleton instance + */ + public static GoBeamerAction getInstance(GUIController gui, + Controller controller) { + if (instance == null) { + instance = new GoBeamerAction(gui, controller); + } + return instance; + } + + /** + * Performs the action. + */ + public void actionPerformed(ActionEvent e) { + gui.goToBeamerMode(isSelected()); + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.java b/src/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.java new file mode 100644 index 0000000..14c96c4 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/ImportCFileAction.java @@ -0,0 +1,149 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileFilter; +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Admin; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.core.CodeGenerator; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; +import c00.AST; + +/** + * ImportCFileAction.java + *

          + * Imports a C00-File. + *

          + */ +public class ImportCFileAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public ImportCFileAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "ImportCFileAction.importCShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "ImportCFileAction.importCLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", + "ImportCFile"))); + } + + /* + * creates JFileChooser, opens File, reads it as a string, and sets SourceCodeField + */ + private String parseAndBeautify(String fileString) + { + try + { + AST.Program program = (AST.Program)AST.parseString(fileString, "Program"); + CodeGenerator gen = new CodeGenerator(); + gen.SwitchProgram(program); + return gen.getOutput(); + } + catch (Exception e) + { + gui.showErrorMessage(Admin.getLanguageString("gui.ImportError")); + return fileString; + } + + } + + public void actionPerformed(ActionEvent e) { + + final JFileChooser fc = new JFileChooser(); + fc.setFileFilter(new FileFilter() { //shows C-Files only + + public boolean accept(File f) { + if (f.isDirectory()) return true; + String ext = f.getName().substring(f.getName().length()-2,f.getName().length()); + return (ext.equals(".c")); + } + + public String getDescription() { + return Admin.getLanguageString("gui.FileFilterDescription"); + } + }); + fc.setCurrentDirectory(new File("./examples/pulsemem")); + int returnVal = fc.showOpenDialog(this.gui.getMemPanel()); + + if (returnVal == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + StringBuffer fileData = new StringBuffer(1000); + try { + BufferedReader reader = new BufferedReader(new FileReader(file)); + char[] buf = new char[1024]; + int numRead=0; + while((numRead=reader.read(buf)) != -1){ + String readData = String.valueOf(buf, 0, numRead); + fileData.append(readData); + buf = new char[1024]; + } + reader.close(); + } + catch (FileNotFoundException ex) { + ex.printStackTrace(); + } + catch (IOException ex) { + ex.printStackTrace(); + } + + //clear saved In- and Output + gui.clearInput(); + //delete InlineBreakpoints the user set + gui.getInlineBreakpoints().clear(); + //delete PMLines and updateTable + controller.clearPM(); + gui.getMemPanel().updateTable(); + //switch to Edit-Mode (switchParseStopEnabled) + gui.switchParseStopEnabled(GUIConstants.PARSE_DISABLED); + //change SaveStatus + controller.getConnector().setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + + //format importet Code + String formattedCode = parseAndBeautify(fileData.toString()); + gui.setSourceCode(formattedCode); + } + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/LastStepAction.java b/src/org/jalgo/module/pulsemem/gui/events/LastStepAction.java new file mode 100644 index 0000000..397e740 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/LastStepAction.java @@ -0,0 +1,58 @@ +/** + * + */ + +/* Created on 13.06.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * LastStepAction.java + *

          + * Will go to last step. + *

          + * + * @version $Revision: 1.3 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class LastStepAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public LastStepAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "LastStepAction.lastStepShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "LastStepAction.lastStepLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "StepForw"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + controller.getConnector() + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + gui.showLastStep(); + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.java b/src/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.java new file mode 100644 index 0000000..fab5281 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/NextBreakpointAction.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Admin; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * NextBreakpointAction.java + *

          + * Will show the next breakpoint. + *

          + * + * @version $Revision: 1.7 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class NextBreakpointAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public NextBreakpointAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "NextBreakpointAction.nextBreakpointShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "NextBreakpointAction.nextBreakpointLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Admin.getResourceURL("BreakForw"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + controller.getConnector() + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + gui.showNextLine(); + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/ParseAction.java b/src/org/jalgo/module/pulsemem/gui/events/ParseAction.java new file mode 100644 index 0000000..bafea10 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/ParseAction.java @@ -0,0 +1,84 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 06.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * ParseAction.java + *

          + * Will parse the C-Code. + *

          + * + * @version $Revision: 1.11 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class ParseAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public ParseAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "ParseAction.startParsingShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "ParseAction.startParsingLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "PStart"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + //return if SourceCode is empty + if (gui.getSourceCode().equals("")) + return; + gui.toConsole("Interpretiere... Bitte warten!"); + gui.switchParseStopEnabled(GUIConstants.PARSE_ENABLED); + //return if interpretAndBeautify fails + if (!controller.interpretAndBeautify()) + return; + gui.toConsole("Interpretation erfolgreich."); + + } + +} \ No newline at end of file diff --git a/src/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.java b/src/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.java new file mode 100644 index 0000000..d91b76e --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/PrevBreakpointAction.java @@ -0,0 +1,77 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * NextBreakpointAction.java + *

          + * Will show the previous breakpoint. + *

          + * + * @version $Revision: 1.6 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class PrevBreakpointAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public PrevBreakpointAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "PrevBreakpointAction.prevBreakpointShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "PrevBreakpointAction.prevBreakpointLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "BreakBack"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + controller.getConnector() + .setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + gui.showPreviousLine(); + } + +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/StopAction.java b/src/org/jalgo/module/pulsemem/gui/events/StopAction.java new file mode 100644 index 0000000..975e8fa --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/StopAction.java @@ -0,0 +1,69 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * StopAction.java + *

          + * Will stop parsing. + *

          + * + * @version $Revision: 1.5 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class StopAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + public StopAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "StopAction.stopParsingShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "StopAction.stopParsingLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "PStop"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + gui.switchParseStopEnabled(GUIConstants.PARSE_DISABLED); + } +} diff --git a/src/org/jalgo/module/pulsemem/gui/events/WelcomeAction.java b/src/org/jalgo/module/pulsemem/gui/events/WelcomeAction.java new file mode 100644 index 0000000..ce19623 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/gui/events/WelcomeAction.java @@ -0,0 +1,75 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ + +/* Created on 07.05.2007 */ +package org.jalgo.module.pulsemem.gui.events; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.AbstractAction; +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import org.jalgo.main.util.Messages; +import org.jalgo.module.pulsemem.Controller; +import org.jalgo.module.pulsemem.gui.GUIConstants; +import org.jalgo.module.pulsemem.gui.GUIController; + +/** + * WelcomeAction.java + *

          + * Will show the WelcomeScreen + *

          + * + * @version $Revision: 1.5 $ + * @author Martin Brylski - TU Dresden, SWTP 2007 + */ +public class WelcomeAction extends AbstractAction { + + private GUIController gui; + + private Controller controller; + + /** + * @param gui + * @param controller + */ + public WelcomeAction(GUIController gui, Controller controller) { + this.gui = gui; + this.controller = controller; + putValue(NAME, Messages.getString( + "pulsemem", "WelcomeAction.welcomeShort")); //$NON-NLS-1$ + putValue(SHORT_DESCRIPTION, Messages.getString( + "pulsemem", "WelcomeAction.welcomeLong")); //$NON-NLS-1$ + putValue(SMALL_ICON, new ImageIcon(Messages.getResourceURL("pulsemem", //$NON-NLS-1$ + "Welcome"))); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent arg0) { + } + +} diff --git a/src/org/jalgo/module/pulsemem/res.properties b/src/org/jalgo/module/pulsemem/res.properties new file mode 100644 index 0000000..e1642b7 --- /dev/null +++ b/src/org/jalgo/module/pulsemem/res.properties @@ -0,0 +1,19 @@ +#Created by JInto - www.guh-software.de +#Tue Jun 19 12:32:56 CEST 2007 +BreakBack=/pulsemem_pix/backward_nav.gif +BreakForw=/pulsemem_pix/forward_nav.gif +Breakpoint=/pulsemem_pix/generic_element.gif +CFile=/pulsemem_pix/workset_wiz.png +Example=/pulsemem_pix/quick_fix.png +ExportCFile=/pulsemem_pix/exportCFile.gif +HelpSet_Name=/help/jhelp/pulsemem_help.hs +ImportCFile=/pulsemem_pix/importCFile.gif +Main_Icon=/pulsemem_pix/icon.gif +NewFile=/pulsemem_pix/newfile_wiz.png +PRestart=/pulsemem_pix/restart_task.gif +PStart=/pulsemem_pix/start_task.gif +PStop=/pulsemem_pix/progress_stop.gif +Session=/pulsemem_pix/importzip_wiz.png +StepBack=/pulsemem_pix/shift_l_edit.gif +StepForw=/pulsemem_pix/shift_r_edit.gif +Welcome=/pulsemem_pix/trash.gif diff --git a/src/org/jalgo/module/testModule/CVS/Entries b/src/org/jalgo/module/testModule/CVS/Entries new file mode 100644 index 0000000..f8aa802 --- /dev/null +++ b/src/org/jalgo/module/testModule/CVS/Entries @@ -0,0 +1,3 @@ +/ModuleConnector.java/1.15/Thu Jan 31 20:15:11 2008// +/ModuleInfo.java/1.16/Thu Jan 31 20:15:11 2008// +/res.properties/1.1/Wed Mar 29 11:51:56 2006// diff --git a/src/org/jalgo/module/testModule/CVS/Repository b/src/org/jalgo/module/testModule/CVS/Repository new file mode 100644 index 0000000..eb84849 --- /dev/null +++ b/src/org/jalgo/module/testModule/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/testModule diff --git a/src/org/jalgo/module/testModule/CVS/Root b/src/org/jalgo/module/testModule/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/testModule/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/testModule/ModuleConnector.java b/src/org/jalgo/module/testModule/ModuleConnector.java new file mode 100644 index 0000000..bc32209 --- /dev/null +++ b/src/org/jalgo/module/testModule/ModuleConnector.java @@ -0,0 +1,88 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.testModule; + +import java.awt.BorderLayout; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JToolBar; +import javax.swing.SwingConstants; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.gui.components.JToolbarButton; +import org.jalgo.main.util.Messages; + + +public class ModuleConnector +extends AbstractModuleConnector { + + @Override + public void init() { + JComponent contentPane = + JAlgoGUIConnector.getInstance().getModuleComponent(this); + JLabel helloJAlgo = new JLabel( + "Hello j-Algo!", + new ImageIcon(Messages.getResourceURL("main", "ui.Logo")), + SwingConstants.CENTER); + contentPane.add(helloJAlgo, BorderLayout.CENTER); + + JMenu menu = JAlgoGUIConnector.getInstance().getModuleMenu(this); + JMenuItem item = new JMenuItem("a menu item"); + menu.add(item); + + JToolBar toolbar = + JAlgoGUIConnector.getInstance().getModuleToolbar(this); + JToolbarButton button = new JToolbarButton( + new ImageIcon(Messages.getResourceURL("main", "ui.Logo_small")), + "a tooltip", + ""); + toolbar.add(button); + } + + @Override + public void run() { + System.out.println("testModule is running"); + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + // here is no action performed in test module + } + + @Override + public ByteArrayOutputStream getDataForFile() { + return null; + } + + @Override + public void print() { + // here is no action performed in test module + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/testModule/ModuleInfo.java b/src/org/jalgo/module/testModule/ModuleInfo.java new file mode 100644 index 0000000..efab491 --- /dev/null +++ b/src/org/jalgo/module/testModule/ModuleInfo.java @@ -0,0 +1,82 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.testModule; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "TestModule"; + } + + public String getVersion() { + return "2.0"; + } + + public String getAuthor() { + return "The author"; + } + + public String getDescription() { + return "A module for testing purposes. It shows simply, how to create " + + "a module"; + } + + public URL getLogoURL() { + return Messages.getResourceURL("main", "ui.Logo_small"); + } + + public String getLicense() { + return "GPL"; + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("testModule","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/testModule/res.properties b/src/org/jalgo/module/testModule/res.properties new file mode 100644 index 0000000..d5607b6 --- /dev/null +++ b/src/org/jalgo/module/testModule/res.properties @@ -0,0 +1 @@ +HelpSet_Name=/help/jhelp/test_help.hs \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/Application.java b/src/org/jalgo/module/unifikation/Application.java new file mode 100644 index 0000000..5b24416 --- /dev/null +++ b/src/org/jalgo/module/unifikation/Application.java @@ -0,0 +1,286 @@ +package org.jalgo.module.unifikation; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector.SaveStatus; +import org.jalgo.main.util.Messages; +import org.jalgo.module.unifikation.algo.model.Formating; +import org.jalgo.module.unifikation.algo.view.Algo; +import org.jalgo.module.unifikation.editor.Editor; +import org.jalgo.module.unifikation.parser.ISetParser; +import org.jalgo.module.unifikation.parser.SetParser; +import org.jalgo.module.unifikation.WelcomeScreen; + +/** + * the main application + * @author Alex + * + */ +public class Application { + + private ApplicationState state; + public JComponent contentPane; + public JToolBar toolbar; + public JMenu menu; + private String problem; + private IAppView currentView; + private ModuleConnector moduleConnector; + private JCheckBoxMenuItem menubeamer; + private WelcomeScreen welcomeScreen; + + // Toolbar buttons + public JButton undoAll; + public JButton undoBlockStep; + public JButton undoStep; + public JButton performAll; + public JButton performBlockStep; + public JButton performStep; + + + /** + * installs the Welcomescreen + * @param contentPane + * @param toolbar + * @param menu + * @param moduleConnector2 + */ + public void startWelcomescreen(JComponent contentPane, JToolBar toolbar, JMenu menu, ModuleConnector moduleConnector) { + this.contentPane=contentPane; + this.toolbar=toolbar; + this.menu=menu; + this.moduleConnector=moduleConnector; + + menubeamer = new JCheckBoxMenuItem("Pr" + Constants.lowercasedAE + "sentationsmodus"); + menubeamer.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Formating.toggleBeamerMode(); + currentView.updateSetView(); + } + }); + menu.add(menubeamer); + + + contentPane.removeAll(); + welcomeScreen = new WelcomeScreen(this); + + contentPane.add(welcomeScreen); + } + + /** + * initializes the application + * @param moduleConnector + */ + public void init(){ + + contentPane.removeAll(); + + this.state=ApplicationState.Preview; + + + setFinished("M={(,)}"); + + } + + public String getProblem() { + return problem; + } + + public String getActualHTMLProblem() { + problem = null; + if(state.equals(ApplicationState.Editor)) + problem = ((Editor) currentView).editWorkspace.getText(); + return problem; + } + + /** + * should be called by a view, when its work is done + * this will switch to next view + */ + public void setFinished(String problem){ + this.setProblem(problem); + contentPane.removeAll(); + toolbar.removeAll(); + + switch(state){ + case Preview: + case Algo: + currentView=new Editor(); + state=ApplicationState.Editor; + this.enableSaving(); + break; + case Editor: + currentView=new Algo(); + state=ApplicationState.Algo; + //menubeamer.setEnabled(true); + this.disableSaving(); + break; + } + + currentView.setApplication(this); + currentView.setContentPane(contentPane); + + //Repaint UI - really needed! + toolbar.updateUI(); + contentPane.updateUI(); + } + + public void setProblem(String problem) { + //cut off html tags + int iStart=problem.lastIndexOf(""); + int iEnd=problem.lastIndexOf(""); + if(iStart>=0 && iEnd>iStart){ + problem=problem.substring(iStart+6,iEnd); + } + //cut off control chars + this.problem = problem.trim(); + } + + public IAppView getCurrentView() { + return currentView; + } + + /** + * Save Problem to File + */ + public ByteArrayOutputStream saveFile() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ISetParser parser=new SetParser(); + String text=this.getActualHTMLProblem(); + if(parser.parse(text)==false) + { + JOptionPane.showMessageDialog(null, "Keine g�ltige Menge", "JAlgo(Unifikation) -Fehler", JOptionPane.ERROR_MESSAGE); + notifyChange(); + } + try { + ObjectOutputStream objOut = new ObjectOutputStream(out); + objOut.writeObject(text); + out.close(); + return out; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Changes SaveState to CHANGES_TO_SAVE + */ + public void notifyChange(){ + ISetParser parser=new SetParser(); + String text=this.getActualHTMLProblem(); + if(parser.parse(text)) + moduleConnector.setSaveStatus(SaveStatus.CHANGES_TO_SAVE); + else + moduleConnector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + } + + + /** + * Enables Saving + */ + public void enableSaving(){ + moduleConnector.setSavingBlocked(false); + } + + /** + * Disables Saving + */ + public void disableSaving(){ + moduleConnector.setSavingBlocked(true); + moduleConnector.setSaveStatus(SaveStatus.NOTHING_TO_SAVE); + } + /** + * Load Problem from File + */ + public void loadFile(ByteArrayInputStream data) { + try { + ObjectInputStream in = new ObjectInputStream(data); + try { + ISetParser parser=new SetParser(); + String text=(String) in.readObject(); + if(parser.parse(text)) + { + //do this to force switch to editor + this.state=ApplicationState.Algo; + //switch + this.setFinished(text); + this.enableSaving(); + } + else + JOptionPane.showMessageDialog(null, "Keine g" + Constants.lowercasedUE + "ltige Menge", "JAlgo(Unifikation) -Fehler", JOptionPane.ERROR_MESSAGE); + + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Installs the toolbar + */ + public void installToolbar() { + undoAll = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_all"))); + undoAll.setToolTipText("zur" + Constants.lowercasedUE + "ck zur Ausgangsmenge"); + undoBlockStep = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_blockstep"))); + undoBlockStep.setToolTipText("Komplettschritt zur" + Constants.lowercasedUE + "ck"); + undoStep = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Undo_step"))); + undoStep.setToolTipText("Einzelschritt zur" + Constants.lowercasedUE + "ck"); + performStep = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_step"))); + performStep.setToolTipText("Einzelschritt vor"); + performBlockStep = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_blockstep"))); + performBlockStep.setToolTipText("Komplettschritt vor"); + performAll = new JButton (new ImageIcon(Messages.getResourceURL("main", "Icon.Perform_all"))); + performAll.setToolTipText("Durchl" + Constants.lowercasedAE + "uft Algorithmus bis zum Ende"); + + toolbar.add(undoAll); + toolbar.add(undoBlockStep); + toolbar.add(undoStep); + toolbar.add(performStep); + toolbar.add(performBlockStep); + toolbar.add(performAll); + toolbar.addSeparator(); + } + + /** + * Enables the toolbar buttons + */ + public void enableToolbar(){ + undoAll.setEnabled(true); + undoBlockStep.setEnabled(true); + undoStep.setEnabled(true); + performStep.setEnabled(true); + performBlockStep.setEnabled(true); + performAll.setEnabled(true); + } + + /** + * Disables the toolbar buttons + */ + public void disableToolbar(){ + undoAll.setEnabled(false); + undoBlockStep.setEnabled(false); + undoStep.setEnabled(false); + performStep.setEnabled(false); + performBlockStep.setEnabled(false); + performAll.setEnabled(false); + } + +} diff --git a/src/org/jalgo/module/unifikation/ApplicationState.java b/src/org/jalgo/module/unifikation/ApplicationState.java new file mode 100644 index 0000000..eba9142 --- /dev/null +++ b/src/org/jalgo/module/unifikation/ApplicationState.java @@ -0,0 +1,5 @@ +package org.jalgo.module.unifikation; + +public enum ApplicationState { + Preview,Editor,Algo; +} diff --git a/src/org/jalgo/module/unifikation/CVS/Entries b/src/org/jalgo/module/unifikation/CVS/Entries new file mode 100644 index 0000000..94fb643 --- /dev/null +++ b/src/org/jalgo/module/unifikation/CVS/Entries @@ -0,0 +1,15 @@ +/Application.java/1.1/Mon Aug 16 12:05:47 2010// +/ApplicationState.java/1.1/Mon Aug 16 12:05:47 2010// +/Constants.java/1.1/Mon Aug 16 12:05:47 2010// +/IAppView.java/1.1/Mon Aug 16 12:05:47 2010// +/ModuleConnector.java/1.1/Mon Aug 16 12:05:47 2010// +/ModuleInfo.java/1.1/Mon Aug 16 12:05:47 2010// +/WelcomeScreen.java/1.1/Mon Aug 16 12:05:47 2010// +/WelcomeScreenButton.java/1.1/Mon Aug 16 12:05:47 2010// +D/algo//// +/de.properties/1.1/Wed Dec 8 13:01:53 2010// +D/editor//// +D/junit//// +/package-info.java/1.1/Mon Aug 16 12:05:47 2010// +D/parser//// +/res.properties/1.1/Wed Dec 8 13:01:53 2010// diff --git a/src/org/jalgo/module/unifikation/CVS/Repository b/src/org/jalgo/module/unifikation/CVS/Repository new file mode 100644 index 0000000..c91ec12 --- /dev/null +++ b/src/org/jalgo/module/unifikation/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation diff --git a/src/org/jalgo/module/unifikation/CVS/Root b/src/org/jalgo/module/unifikation/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/Constants.java b/src/org/jalgo/module/unifikation/Constants.java new file mode 100644 index 0000000..b11f694 --- /dev/null +++ b/src/org/jalgo/module/unifikation/Constants.java @@ -0,0 +1,48 @@ +package org.jalgo.module.unifikation; + +import java.awt.Dimension; +import java.awt.Font; + +import org.jalgo.module.unifikation.algo.model.Formating; + +public interface Constants { + + public static final String ALPHA="\u03B1"; + public static final String BETA="\u03B2"; + public static final String GAMMA="\u03B3"; + public static final String DELTA="\u03B4"; + public static final String EPSILON="\u03B5"; + public static final String THETA="\u03B8"; + + //most general unifier + public static final String PHI="\u03C6"; + public static final String UNIFIEDARROW="\u21A6"; + + + //Editor + public static final Dimension ButtonSize = new Dimension(45,30); + public static final String Placeholder="\u25A1"; + public static final int ButtonGap = 5; + public static final Font ButtonFont = new Font("Tahoma",Font.PLAIN,14); + public static final Font ButtonAlgoFont = new Font("Tahoma",Font.PLAIN,11); + public static final Font TextFont = new Font("Tahoma",Font.PLAIN,14); + + public static final String NBodyCSS = "body {font-family:Times New Roman;font-size : "+(Formating.activeSizeNormal)+"px; font-weight:bold;}\r\n"+ + "a {color: black; text-decoration:none}"+ + "sub {font-size : "+(Formating.activeSizeNormal-4)+"px; }" + + ".constsymb {color: "+Formating.Function+"}" + + ".var {color: "+Formating.Variable+"}"; + + public static final String BBodyCSS = "body {font-family:Times New Roman;font-size : "+(Formating.activeSizeBeamer)+"px; font-weight:bold;}\r\n"+ + "a{color: black; text-decoration:none}" + + "sub {font-size : "+(Formating.activeSizeBeamer-4)+"px; }" + + ".constsymb {color: "+Formating.Function+"}" + + ".var {color: "+Formating.Variable+"}"; + + + //unicode umlauts + + public static final String lowercasedUE = "\u00FC"; + public static final String lowercasedOE = "\u00F6"; + public static final String lowercasedAE = "\u00E4"; +} diff --git a/src/org/jalgo/module/unifikation/IAppView.java b/src/org/jalgo/module/unifikation/IAppView.java new file mode 100644 index 0000000..09e8177 --- /dev/null +++ b/src/org/jalgo/module/unifikation/IAppView.java @@ -0,0 +1,21 @@ +package org.jalgo.module.unifikation; + +import javax.swing.JComponent; + +/** + * Interface for different Views (Editor, Algo...) + * + */ +public interface IAppView{ + public void setApplication(Application app); + public void setContentPane(JComponent contentPane); + /** + * Refreshes the view where set is shown + */ + public void updateSetView(); + /** + * Sets the help text + * @param helpText Text to set + */ + public void setHelpText(String helpText); +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/ModuleConnector.java b/src/org/jalgo/module/unifikation/ModuleConnector.java new file mode 100644 index 0000000..6b704e6 --- /dev/null +++ b/src/org/jalgo/module/unifikation/ModuleConnector.java @@ -0,0 +1,72 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.unifikation; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.swing.JComponent; +import javax.swing.JMenu; +import javax.swing.JToolBar; + +import org.jalgo.main.AbstractModuleConnector; +import org.jalgo.main.gui.JAlgoGUIConnector; + +public class ModuleConnector +extends AbstractModuleConnector { + private Application application=null; + + @Override + public void init() { + application=new Application(); + } + + @Override + public void run() { + //Get Panel + JComponent contentPane = + JAlgoGUIConnector.getInstance().getModuleComponent(this); + + JToolBar toolbar = + JAlgoGUIConnector.getInstance().getModuleToolbar(this); + + JMenu menu = + JAlgoGUIConnector.getInstance().getModuleMenu(this); + application.startWelcomescreen(contentPane,toolbar,menu,this); + + } + + @Override + public void setDataFromFile(ByteArrayInputStream data) { + application.loadFile(data); + } + + @Override + public ByteArrayOutputStream getDataForFile() { + return application.saveFile(); + } + + @Override + public void print() { + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/ModuleInfo.java b/src/org/jalgo/module/unifikation/ModuleInfo.java new file mode 100644 index 0000000..fde240a --- /dev/null +++ b/src/org/jalgo/module/unifikation/ModuleInfo.java @@ -0,0 +1,81 @@ +/* + * j-Algo - j-Algo is an algorithm visualization tool, especially useful for + * students and lecturers of computer science. It is written in Java and platform + * independent. j-Algo is developed with the help of Dresden University of + * Technology. + * + * Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.net + * + * 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 + */ +package org.jalgo.module.unifikation; + +import java.net.URL; + +import org.jalgo.main.IModuleInfo; +import org.jalgo.main.util.Messages; + +public class ModuleInfo +implements IModuleInfo { + + /** The singleton instance */ + private static IModuleInfo instance; + + /** + * The only constructor is unusable from outside this class. This is part of + * the singleton design pattern. + */ + private ModuleInfo() { + // unusable from outside + } + + /** + * Retrieves the singleton instance of IModuleInfo. + * + * @return the singleton instance + */ + public static IModuleInfo getInstance() { + if (instance == null) instance = new ModuleInfo(); + return instance; + } + + public String getName() { + return "Unifikation"; + } + + public String getVersion() { + return "1.0"; + } + + public String getAuthor() { + return "Kai-Uwe Storek, Alexander Grund, Paul Eichst" + Constants.lowercasedAE + "dt, Thomas Weber, Sebastian Simon"; + } + + public String getDescription() { + return "Dieses Modul simuliert die Unifikation von Termen anhand des Unifikationsalgorithmus von Bistarelli und Montanari."; + } + + public URL getLogoURL() { + return Messages.getResourceURL("unifikation", "Icon"); + } + + public String getLicense() { + return "GPL"; + } + + public URL getHelpSetURL(){ + return Messages.getResourceURL("unifikation","HelpSet_Name"); + } +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/WelcomeScreen.java b/src/org/jalgo/module/unifikation/WelcomeScreen.java new file mode 100644 index 0000000..6018ffc --- /dev/null +++ b/src/org/jalgo/module/unifikation/WelcomeScreen.java @@ -0,0 +1,185 @@ +package org.jalgo.module.unifikation; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import org.jalgo.main.gui.JAlgoGUIConnector; +import org.jalgo.main.util.Messages; + +/** + * initializes the welcome screen + **/ + +public class WelcomeScreen extends JPanel implements ActionListener, MouseListener { + + private static final Color WELCOME_BACKGROUND_COLOR = new Color(92, 105, 53); + private static final Color WELCOME_FONT_COLOR = new Color(255, 255, 255); + + private static final long serialVersionUID = -8999126383596097317L; + + private Application app; + private WelcomeScreenButton newButton; + private WelcomeScreenButton loadButton; + private JLabel descLabel; + + public WelcomeScreen(Application app){ + this.app = app; + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + + descLabel = new JLabel(); + + descLabel.setAlignmentX(Component.CENTER_ALIGNMENT); + + descLabel.setFont(new Font("Tahoma", Font.BOLD , 17)); + descLabel.setForeground(WELCOME_FONT_COLOR); + + newButton = new WelcomeScreenButton(new ImageIcon(Messages.getResourceURL("unifikation", "Icon.welcomeNew")), + + new ImageIcon(Messages.getResourceURL("unifikation", "Icon.welcomeNewOver")), + + "Neues Unifikationspaar"); + + loadButton = new WelcomeScreenButton(new ImageIcon(Messages.getResourceURL("unifikation", "Icon.welcomeLoad")), + + new ImageIcon(Messages.getResourceURL("unifikation", "Icon.welcomeLoadOver")), + + "Unifikationspaar laden"); + + JPanel buttonPane = new JPanel(); + + buttonPane.setBackground(WELCOME_BACKGROUND_COLOR); + + buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); + + buttonPane.add(newButton); + + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + + buttonPane.add(loadButton); + + buttonPane.add(Box.createRigidArea(new Dimension(20, 0))); + + newButton.addActionListener(this); + + loadButton.addActionListener(this); + + newButton.addMouseListener(this); + + loadButton.addMouseListener(this); + + add(Box.createVerticalStrut(150)); + + add(buttonPane); + + add(Box.createVerticalStrut(50)); + + add(descLabel); + } + + //@Override + + public void actionPerformed(ActionEvent e) { + + if(e.getSource().equals(newButton)) { + + app.init(); + + } + + + + if(e.getSource().equals(loadButton)) { + + JAlgoGUIConnector.getInstance().showOpenDialog(true, true); + + } + + } + + + + //@Override + + public void mouseClicked(MouseEvent e) { + + // TODO Auto-generated method stub + + + + } + + + + //@Override + + public void mouseEntered(MouseEvent e) { + + descLabel.setText(((WelcomeScreenButton)e.getSource()).getDescText()); + + ((WelcomeScreenButton)e.getSource()).setSelected(true); + + } + + + + //@Override + + public void mouseExited(MouseEvent e) { + + descLabel.setText(""); + + ((WelcomeScreenButton)e.getSource()).setSelected(false); + + } + + + + //@Override + + public void mousePressed(MouseEvent e) { + + // TODO Auto-generated method stub + + + + } + + + + //@Override + + public void mouseReleased(MouseEvent e) { + + // TODO Auto-generated method stub + + + + } + + /** + *sets the background color for the welcome screen + */ + + protected void paintComponent(Graphics g) { + + g.setColor(WELCOME_BACKGROUND_COLOR); + + g.fillRect(0, 0, getWidth(), getHeight()); + + } +} diff --git a/src/org/jalgo/module/unifikation/WelcomeScreenButton.java b/src/org/jalgo/module/unifikation/WelcomeScreenButton.java new file mode 100644 index 0000000..10b4032 --- /dev/null +++ b/src/org/jalgo/module/unifikation/WelcomeScreenButton.java @@ -0,0 +1,57 @@ +package org.jalgo.module.unifikation; + +import java.awt.Dimension; + +import javax.swing.ImageIcon; +import javax.swing.JToggleButton; +import javax.swing.border.EmptyBorder; + +/** + * defines the button for the welcome screen + */ + +public class WelcomeScreenButton extends JToggleButton{ + + private static final long serialVersionUID = -1771155701778223947L; + private String descText; + + + public WelcomeScreenButton(ImageIcon defaultIcon, ImageIcon rolloverIcon, String descText) { + + this.descText = descText; + + setIcon(defaultIcon); + + setDisabledIcon(defaultIcon); + + + + setSelectedIcon(rolloverIcon); + + setPressedIcon(rolloverIcon); + + + + setFocusPainted(false); + + setBorder(new EmptyBorder(0, 0, 0, 0)); + + setBorderPainted(false); + + setMinimumSize(new Dimension(80, 80)); + + setMaximumSize(getMinimumSize()); + + setPreferredSize(getMinimumSize()); + + } + + + + public String getDescText() { + + return descText; + + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/CVS/Entries b/src/org/jalgo/module/unifikation/algo/CVS/Entries new file mode 100644 index 0000000..6094d99 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/CVS/Entries @@ -0,0 +1,4 @@ +D/HTMLParser//// +D/controller//// +D/model//// +D/view//// diff --git a/src/org/jalgo/module/unifikation/algo/CVS/Repository b/src/org/jalgo/module/unifikation/algo/CVS/Repository new file mode 100644 index 0000000..e18a023 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/algo diff --git a/src/org/jalgo/module/unifikation/algo/CVS/Root b/src/org/jalgo/module/unifikation/algo/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Entries b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Entries new file mode 100644 index 0000000..5e30e6f --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Entries @@ -0,0 +1,4 @@ +/SpecialDocument.java/1.1/Mon Aug 16 12:05:47 2010// +/SpecialEditorKit.java/1.1/Mon Aug 16 12:05:47 2010// +/XParserDelegator.java/1.1/Mon Aug 16 12:05:47 2010// +/package-info.java/1.1/Mon Aug 16 12:05:47 2010// diff --git a/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Repository b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Repository new file mode 100644 index 0000000..28248c1 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/algo/HTMLParser diff --git a/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Root b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/HTMLParser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.java b/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.java new file mode 100644 index 0000000..75dc25e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialDocument.java @@ -0,0 +1,38 @@ +package org.jalgo.module.unifikation.algo.HTMLParser; + +import java.net.URL; + +import javax.swing.text.Document; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.StyleSheet; + +public class SpecialDocument extends HTMLDocument { + /** + * + */ + private static final long serialVersionUID = -154851356706035436L; + + public static final HTML.Tag FIXTAG = new HTML.UnknownTag("fixtag"); + + public SpecialDocument(StyleSheet styles) { + super(styles); + } + + public HTMLEditorKit.ParserCallback getReader(int pos) { + Object desc = getProperty(Document.StreamDescriptionProperty); + if (desc instanceof URL) { + setBase((URL)desc); + } + return new MyHTMLReader(pos); + } + + class MyHTMLReader extends HTMLDocument.HTMLReader { + public MyHTMLReader(int offset) { + super(offset); + registerTag(FIXTAG, new SpecialAction()); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.java b/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.java new file mode 100644 index 0000000..5c92aad --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/HTMLParser/SpecialEditorKit.java @@ -0,0 +1,217 @@ +package org.jalgo.module.unifikation.algo.HTMLParser; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; + +import javax.swing.JEditorPane; +import javax.swing.text.Element; +import javax.swing.text.View; +import javax.swing.text.ViewFactory; +import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.InlineView; +import javax.swing.text.html.HTMLEditorKit.LinkController; + +public class SpecialEditorKit extends HTMLEditorKit { + private static final long serialVersionUID = -5630181697612056591L; + + MyLinkController handler=new MyLinkController(); + @Override + public void install(JEditorPane c) { + MouseListener[] oldMouseListeners=c.getMouseListeners(); + MouseMotionListener[] oldMouseMotionListeners=c.getMouseMotionListeners(); + super.install(c); + //the following code removes link handler added by original + //HTMLEditorKit + + for (MouseListener l: c.getMouseListeners()) { + c.removeMouseListener(l); + } + for (MouseListener l: oldMouseListeners) { + c.addMouseListener(l); + } + + for (MouseMotionListener l: c.getMouseMotionListeners()) { + c.removeMouseMotionListener(l); + } + for (MouseMotionListener l: oldMouseMotionListeners) { + c.addMouseMotionListener(l); + } + + //add our link handler instead of removed one + c.addMouseListener(handler); + c.addMouseMotionListener(handler); + } + + @Override + public ViewFactory getViewFactory() { + return new VerboseViewFactory(); + } + + /*protected Parser defaultParser=null; + + @Override + protected Parser getParser(){ + if(defaultParser==null){ + defaultParser=new XParserDelegator(); + } + return defaultParser; + } + + + @Override + public Document createDefaultDocument() { + StyleSheet styles = getStyleSheet(); + StyleSheet ss = new StyleSheet(); + + ss.addStyleSheet(styles); + + HTMLDocument doc = new SpecialDocument(ss); + doc.setParser(getParser()); + doc.setAsynchronousLoadPriority(4); + doc.setTokenThreshold(100); + return doc; + }*/ + + + class VerboseViewFactory extends HTMLEditorKit.HTMLFactory implements ViewFactory{ + + public View create(Element element) { + View ret=super.create(element); + if(ret.getClass().getName().endsWith("InlineView")){ + //fix the size + ret=new FixSizeInlineView(element); + } + return ret; + } + } + + /* + * View that does not display something + * @author Alex + * + */ + /* + class InvisibleView extends View{ + public InvisibleView(Element elem) { + super(elem); + } + + @Override + public void paint(Graphics g, Shape allocation) { + } + + @Override + public float getPreferredSpan(int axis) { + return 0; + } + + @Override + public Shape modelToView(int pos, Shape a, Bias b) + throws BadLocationException { + return null; + } + + @Override + public int viewToModel(float x, float y, Shape a, Bias[] biasReturn) { + return 0; + } + }*/ + + +} + +/** + * View that fixes size of background color and underline + * @author Alex + * + */ +class FixSizeInlineView extends InlineView{ + private int y=0; + + public FixSizeInlineView(Element elem) { + super(elem); + } + + public int getY(){ + return y; + } + + public void paint(Graphics g, Shape allocation) { + Color cl=this.getBackground(); + if(cl!=null || this.isUnderline()){ + Rectangle rect=(Rectangle) allocation; + if(this.isSubscript()){ + //sup-style + int Offset=(int) (rect.height/2); + int ct=getParent().getViewCount(); + int cY=rect.y; + + for(int i=0;iMouseListener getHoverListener(Class c){ + IButtonAction action=null; + try { + action=c.getConstructor(Algo.class).newInstance(appView); + } catch (Exception e1) { + e1.printStackTrace(); + } + return new HoverListener(action); + } + + /** + * Gets a action listener with onClick behavior specified by given class + * @param c Class to use for firing events to + * @return Button listener as requested + */ + public ActionListener getClickListener(Class c){ + IButtonAction action=null; + try { + action=c.getConstructor(Algo.class).newInstance(appView); + } catch (Exception e1) { + e1.printStackTrace(); + } + return new ClickListener(action); + } + + /** + * Basic hover listener + * @author Alex + * + */ + class HoverListener implements MouseListener{ + private final IButtonAction action; + public HoverListener(IButtonAction action){ + this.action=action; + } + + /** + * Delegates to onClick event of handler class + * Does nothing for now + */ + public void mouseClicked(MouseEvent e) { + /*if(e.getButton()==1 && ((JButton) e.getSource()).isEnabled()==true){ + action.onClick(); + }*/ + } + + /** + * Sets help text as specified in handler class + */ + public void mouseEntered(MouseEvent e) { + if(((JButton) e.getSource()).isEnabled()==true){ + String helpText=action.getHoverText(); + if(helpText==null) helpText=""; + appView.setHelpText(helpText); + } + } + + /** + * Resets help text + */ + public void mouseExited(MouseEvent e) { + if(((JButton) e.getSource()).isEnabled()==true){ + appView.setHelpText(""); + } + } + + public void mousePressed(MouseEvent e) { + } + public void mouseReleased(MouseEvent e) { + } + } +} +/** + * Basic click listener + * @author Alex + * + */ +class ClickListener implements ActionListener{ + private final IButtonAction action; + public ClickListener(IButtonAction action){ + this.action=action; + } + + public void actionPerformed(ActionEvent arg0) { + action.onClick(); + } +} + + diff --git a/src/org/jalgo/module/unifikation/algo/controller/CVS/Entries b/src/org/jalgo/module/unifikation/algo/controller/CVS/Entries new file mode 100644 index 0000000..c9a99e5 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/CVS/Entries @@ -0,0 +1,21 @@ +/ButtonListenerFactory.java/1.1/Mon Aug 16 12:05:48 2010// +/DecompButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/DoBlockStepButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/DoStepButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/EditorButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/ElimButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/HLLPairs.java/1.1/Mon Aug 16 12:05:48 2010// +/HelpMode.java/1.1/Mon Aug 16 12:05:48 2010// +/IButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/IButtonActionAlgo.java/1.1/Mon Aug 16 12:05:48 2010// +/NotUnifiableButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/PerformAllButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/RuleCheckButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/SelectPairResult.java/1.1/Mon Aug 16 12:05:48 2010// +/SubButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/SwapButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/UndoAllButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/UndoBlockStepButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/UndoStepButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/UnifiedButtonAction.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/unifikation/algo/controller/CVS/Repository b/src/org/jalgo/module/unifikation/algo/controller/CVS/Repository new file mode 100644 index 0000000..0e98c7a --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/algo/controller diff --git a/src/org/jalgo/module/unifikation/algo/controller/CVS/Root b/src/org/jalgo/module/unifikation/algo/controller/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.java new file mode 100644 index 0000000..76f37e1 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/DecompButtonAction.java @@ -0,0 +1,30 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.algo.view.Algo; + +public class DecompButtonAction extends IButtonActionAlgo { + + public DecompButtonAction(Algo algo) { + super(algo); + } + + public String getHoverText() { + return "Dekompositionsregel:
          Wenn M ein Paar der Form (\u03B4(s1, ..., sk), \u03B4(t1, ..., tk)) enth" + Constants.lowercasedAE + "lt, wobei \u03B4 \u03B5 \u03A3 ein k-stelliger Konstruktor ist und s1, ..., sk, t1, ..., tk Terme " + Constants.lowercasedUE + "ber Konstruktoren und Variablen sind, dann l" + Constants.lowercasedOE + "sche das Paar \n(\u03B4(s1, ..., sk),\u03B4(t1, ..., tk)) aus M und f" + Constants.lowercasedUE + "ge die Paare (s1, t1), ..., (sk, tk) hinzu."; + } + + public void onClick() { + if (theAlgo.getProblemSet().getSelectedPPair() == null) theAlgo.setErrorText("Sie haben kein Paar ausgew"+ Constants.lowercasedAE +"hlt auf das Sie diese Regel anwenden wollen."); + else theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getSelectedPair()!=-1){ + if(theAlgo.getProblemSet().decomposition()){ + theAlgo.notifySetChanged(); + } + else { + theAlgo.getProblemSet().updateLastRuleError(); + theAlgo.setErrorText(theAlgo.getProblemSet().getLastRuleErrorText()); + } + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.java new file mode 100644 index 0000000..ce1f79b --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/DoBlockStepButtonAction.java @@ -0,0 +1,23 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class DoBlockStepButtonAction extends IButtonActionAlgo { + + public DoBlockStepButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + //1 full step forward + if(theAlgo.getHistory().nextFull()){ + theAlgo.notifyStepChanged(); + }else{ + //auto step + HelpMode.getInstance().doFullStep(theAlgo); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.java new file mode 100644 index 0000000..4785791 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/DoStepButtonAction.java @@ -0,0 +1,23 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class DoStepButtonAction extends IButtonActionAlgo { + + public DoStepButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + //1 half step forward + if(theAlgo.getHistory().next()){ + theAlgo.notifyStepChanged(); + }else{ + //auto step + HelpMode.getInstance().doHalfStep(theAlgo); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.java new file mode 100644 index 0000000..5cd9a7e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/EditorButtonAction.java @@ -0,0 +1,17 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class EditorButtonAction extends IButtonActionAlgo { + + public EditorButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + theAlgo.onDoneClick(); + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.java new file mode 100644 index 0000000..df17fe8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/ElimButtonAction.java @@ -0,0 +1,31 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.algo.view.Algo; + +public class ElimButtonAction extends IButtonActionAlgo { + + public ElimButtonAction(Algo algo) { + super(algo); + } + + public String getHoverText() { + return "Elimination:
          Wenn M ein Paar (x, x) f" + Constants.lowercasedUE + "r eine Variable x enth" + Constants.lowercasedAE + "lt, dann l" + Constants.lowercasedOE + "sche dieses Paar aus M."; + } + + public void onClick() { + if (theAlgo.getProblemSet().getSelectedPPair() == null) theAlgo.setErrorText("Sie haben kein Paar ausgew"+ Constants.lowercasedAE +"hlt auf das Sie diese Regel anwenden wollen."); + else theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getSelectedPair()!=-1){ + if(theAlgo.getProblemSet().elimination()) + { + theAlgo.notifySetChanged(); + } + else { + theAlgo.getProblemSet().updateLastRuleError(); + theAlgo.setErrorText(theAlgo.getProblemSet().getLastRuleErrorText()); + } + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/HLLPairs.java b/src/org/jalgo/module/unifikation/algo/controller/HLLPairs.java new file mode 100644 index 0000000..e6eb3c7 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/HLLPairs.java @@ -0,0 +1,77 @@ +package org.jalgo.module.unifikation.algo.controller; + +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.Element; +import javax.swing.text.html.HTML; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class HLLPairs implements HyperlinkListener { + private Algo theAlgo = null; + + public HLLPairs(Algo theAlgo) { + this.theAlgo=theAlgo; + } + + /** + * Handles events of Hyperlinks (MouseOver...) + */ + public void hyperlinkUpdate(HyperlinkEvent e) { + Element el = e.getSourceElement(); + + if(e.getEventType() == HyperlinkEvent.EventType.ENTERED){ + //work around for tablet PCs + if(theAlgo.isMouseDown()) OnClick(e,el); + else OnMouseOver(e,el); + }else if(e.getEventType() == HyperlinkEvent.EventType.EXITED) + OnMouseOut(e,el); + else if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) + OnClick(e,el); + } + + /** + * Called when mouse enters an element + */ + private void OnMouseOver(HyperlinkEvent e, Element el){ + int pair=Integer.valueOf(GetLinkTarget(el)).intValue(); + if(theAlgo.getProblemSet().getHoverPair()!=pair && theAlgo.getProblemSet().getSelectedPair()!=pair){ + theAlgo.getProblemSet().setHoverPair(pair); + theAlgo.notifyHoverChanged(); + } + } + + /** + * Called when mouse leaves an element + */ + private void OnMouseOut(HyperlinkEvent e, Element el){ + theAlgo.getProblemSet().setHoverPair(-1); + theAlgo.notifyHoverChanged(); + } + + /** + * Called when an element is clicked + */ + private void OnClick(HyperlinkEvent e, Element el){ + int pair=Integer.valueOf(GetLinkTarget(el)).intValue(); + if(theAlgo.getProblemSet().getSelectedPair()!=pair){ + theAlgo.getProblemSet().setSelectedPair(pair); + }else theAlgo.getProblemSet().setSelectedPair(-1); + theAlgo.notifySelectionChanged(); + theAlgo.setMouseDown(false); + } + + /** + * gets the href attribute value from an element + * @param elem + * @return value of href attribute + */ + //Original: http://www.tutorials.de/forum/swing-java2d-3d-swt-jface/163395-jeditorpane-und-links.html + //TODO: Bessere Variante? + private String GetLinkTarget(Element elem) { + AttributeSet attributeSet = elem.getAttributes(); + Object linkAttr = attributeSet.getAttribute(HTML.Tag.A); + return (String) ((AttributeSet) linkAttr).getAttribute(HTML.Attribute.HREF); + } +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/HelpMode.java b/src/org/jalgo/module/unifikation/algo/controller/HelpMode.java new file mode 100644 index 0000000..b547da0 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/HelpMode.java @@ -0,0 +1,107 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; +import org.jalgo.module.unifikation.algo.model.History; +import org.jalgo.module.unifikation.algo.model.ProblemSet; +import org.jalgo.module.unifikation.algo.model.Rule; + +/** + * The Help mode that is used as a help to solve the problem + * implements the singleton pattern + * @author Alex + * + */ +public class HelpMode { + /** The singleton instance */ + private static HelpMode instance; + + /** + * private constructor + * part of the singleton pattern + */ + private HelpMode(){ + } + + /** + * Retrieves the singleton instance of HelpMode. + * + * @return the singleton instance + */ + public static HelpMode getInstance() { + if (instance == null) instance = new HelpMode(); + return instance; + } + + /** + * Makes sure a pair is selected if possible and returns what was done + * @param theAlgo Algo view to use + * @return Action done + */ + private SelectPairResult selectPair(Algo theAlgo){ + ProblemSet set=theAlgo.getProblemSet(); + if(set.getSelectedPair()>=0 && set.getUsableRule()!=Rule.NoRule) + return SelectPairResult.AlreadyOK; + int newPair=set.getUsablePair(); + if(newPair<0){ + if(!theAlgo.getState().next()) return SelectPairResult.NothingDone; + return SelectPairResult.NoPair; + } + set.setSelectedPair(newPair); + return SelectPairResult.NewSelected; + } + + /** + * Does a half step of the help + * @param theAlgo Algo view to use + * @return True if pair was just selected (so another half step can be applied) + */ + public boolean doHalfStep(Algo theAlgo){ + //1st step: Select a pair + SelectPairResult sel=selectPair(theAlgo); + if(sel==SelectPairResult.AlreadyOK){ + //1st step was done, do 2nd step: get and use Rule + theAlgo.getProblemSet().useRule(theAlgo.getProblemSet().getUsableRule()); + theAlgo.notifySetChanged(); + }else if(sel!=SelectPairResult.NothingDone) theAlgo.notifySelectionChanged(); + return (sel==SelectPairResult.NewSelected); + } + + /** + * Does a full step of the help + * @param theAlgo Algo view to use + * @return True + */ + public boolean doFullStep(Algo theAlgo){ + //do just a half step and check if we can do the second after that + if(doHalfStep(theAlgo)) doHalfStep(theAlgo); + return true; + } + + /** + * Does all steps of the help + * @param theAlgo Algo view to use + * @return True + */ + public boolean doAllSteps(Algo theAlgo){ + int newPair; + boolean somethingDone=false; + ProblemSet set=theAlgo.getProblemSet(); + History history=theAlgo.getHistory(); + while(true){ + newPair=set.getUsablePair(); + if(newPair<0) break; + somethingDone=true; + set.setSelectedPair(newPair); + history.setSelected(newPair); + set.useRule(set.getUsableRule()); + history.addStep(set); + } + if(theAlgo.getState().next()){ + somethingDone=true; + theAlgo.getState().next(); + } + if(somethingDone) theAlgo.notifyStepChanged(); + return true; + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/IButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/IButtonAction.java new file mode 100644 index 0000000..9caa774 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/IButtonAction.java @@ -0,0 +1,27 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.IAppView; + +/** + * Interface for button actions + * @author Alex + * + */ +public abstract class IButtonAction { + + public IButtonAction(IAppView appView){ + } + + /** + * Called when the button is clicked + */ + public abstract void onClick(); + + /** + * Gets the text, that should be displayed when button is hovered + * @return Text, that should be displayed when button is hovered + */ + public String getHoverText(){ + return null; + } +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.java b/src/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.java new file mode 100644 index 0000000..e631156 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/IButtonActionAlgo.java @@ -0,0 +1,13 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public abstract class IButtonActionAlgo extends IButtonAction { + protected final Algo theAlgo; + + public IButtonActionAlgo(Algo algo) { + super(algo); + this.theAlgo=algo; + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.java new file mode 100644 index 0000000..0c6b956 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/NotUnifiableButtonAction.java @@ -0,0 +1,28 @@ +package org.jalgo.module.unifikation.algo.controller; + +import javax.swing.JOptionPane; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class NotUnifiableButtonAction extends IButtonActionAlgo { + + public NotUnifiableButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getPairNotFinal() != -1) + { + theAlgo.getState().next(); + theAlgo.notifySelectionChanged(); + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Korrekt, die Terme sind nicht unifizierbar."); + } + else { + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Leider falsch."); + } + } + + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.java new file mode 100644 index 0000000..82488ec --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/PerformAllButtonAction.java @@ -0,0 +1,22 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class PerformAllButtonAction extends IButtonActionAlgo { + + public PerformAllButtonAction(Algo algo) { + super(algo); + } + + public void onClick() { + theAlgo.setErrorText(""); + + //shows all steps + if(theAlgo.getHistory().nextAll()){ + theAlgo.notifyStepChanged(); + }else{ + //auto step + HelpMode.getInstance().doAllSteps(theAlgo); + } + } +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.java new file mode 100644 index 0000000..d049332 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/RuleCheckButtonAction.java @@ -0,0 +1,26 @@ +package org.jalgo.module.unifikation.algo.controller; + +import javax.swing.JOptionPane; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class RuleCheckButtonAction extends IButtonActionAlgo { + + public RuleCheckButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + if(theAlgo.getState().next()) + { + theAlgo.notifySelectionChanged(); + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Korrekt. Es ist keine Regel mehr anwendbar. Sind die Ausgangsterme unifiziert oder nicht unifizerbar?"); + } + else { + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Es sind noch weitere Regeln anwendbar."); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/SelectPairResult.java b/src/org/jalgo/module/unifikation/algo/controller/SelectPairResult.java new file mode 100644 index 0000000..8d2e414 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/SelectPairResult.java @@ -0,0 +1,25 @@ +package org.jalgo.module.unifikation.algo.controller; + +/** + * Results for the selectPair function of auto-mode + * @author Alex + * + */ +public enum SelectPairResult { + /** + * There is a pair currently selected and a rule can be applied + */ + AlreadyOK, + /** + * A new pair has been selected and a rule can be applied + */ + NewSelected, + /** + * No pair was found, where a rule can be applied + */ + NoPair, + /** + * Nothing was done + */ + NothingDone; +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/SubButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/SubButtonAction.java new file mode 100644 index 0000000..303fcd9 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/SubButtonAction.java @@ -0,0 +1,30 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.algo.view.Algo; + +public class SubButtonAction extends IButtonActionAlgo { + + public SubButtonAction(Algo algo) { + super(algo); + } + + public String getHoverText() { + return "Substitution:
          Wenn M das Paar (x, t) enth" + Constants.lowercasedAE + "lt und x kommt in t nicht vor (occur check), dann ersetze in jedem anderen Paar von M die Variable x durch den Term t."; + } + + public void onClick() { + if (theAlgo.getProblemSet().getSelectedPPair() == null) theAlgo.setErrorText("Sie haben kein Paar ausgew"+ Constants.lowercasedAE +"hlt auf das Sie diese Regel anwenden wollen."); + else theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getSelectedPair()!=-1){ + if(theAlgo.getProblemSet().substitution()) + { + theAlgo.notifySetChanged(); + } + else { + theAlgo.setErrorText(theAlgo.getProblemSet().getLastRuleErrorText()); + } + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.java new file mode 100644 index 0000000..8f38a6c --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/SwapButtonAction.java @@ -0,0 +1,31 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.algo.view.Algo; + +public class SwapButtonAction extends IButtonActionAlgo { + + public SwapButtonAction(Algo algo) { + super(algo); + } + + public String getHoverText() { + return "Vertauschung:
          Wenn M ein Paar (t, x) enth" + Constants.lowercasedAE + "lt und t ist keine Variable, dann l" + Constants.lowercasedOE + "sche dieses Paar aus M und f" + Constants.lowercasedUE + "ge das Paar (x, t) hinzu."; + } + + public void onClick() { + if (theAlgo.getProblemSet().getSelectedPPair() == null) theAlgo.setErrorText("Sie haben kein Paar ausgew"+ Constants.lowercasedAE +"hlt auf das Sie diese Regel anwenden wollen."); + else theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getSelectedPair()!=-1){ + if(theAlgo.getProblemSet().swap()) + { + theAlgo.notifySetChanged(); + } + else { + theAlgo.getProblemSet().updateLastRuleError(); + theAlgo.setErrorText(theAlgo.getProblemSet().getLastRuleErrorText()); + } + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.java new file mode 100644 index 0000000..1625677 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/UndoAllButtonAction.java @@ -0,0 +1,24 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class UndoAllButtonAction extends IButtonActionAlgo { + + public UndoAllButtonAction(Algo algo) { + super(algo); + } + + public void onClick() { + theAlgo.setErrorText(""); + boolean somethingDone=false; + while(theAlgo.getState().prev()){ + somethingDone=true; + } + //jumps to first step + if(theAlgo.getHistory().prevAll()){ + somethingDone=true; + } + if(somethingDone) theAlgo.notifyStepChanged(); + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.java new file mode 100644 index 0000000..d926057 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/UndoBlockStepButtonAction.java @@ -0,0 +1,25 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class UndoBlockStepButtonAction extends IButtonActionAlgo { + + public UndoBlockStepButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + if(theAlgo.getState().prev()){ + //State changed + theAlgo.notifySelectionChanged(); + return; + } + //1 full step back + if(theAlgo.getHistory().prevFull()){ + theAlgo.notifyStepChanged(); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.java new file mode 100644 index 0000000..8fe62f4 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/UndoStepButtonAction.java @@ -0,0 +1,25 @@ +package org.jalgo.module.unifikation.algo.controller; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class UndoStepButtonAction extends IButtonActionAlgo { + + public UndoStepButtonAction(Algo algo) { + super(algo); + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + if(theAlgo.getState().prev()){ + //State changed + theAlgo.notifySelectionChanged(); + return; + } + //1 half step back + if(theAlgo.getHistory().prev()){ + theAlgo.notifyStepChanged(); + } + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.java b/src/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.java new file mode 100644 index 0000000..be7bb6e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/UnifiedButtonAction.java @@ -0,0 +1,29 @@ +package org.jalgo.module.unifikation.algo.controller; + +import javax.swing.JOptionPane; + +import org.jalgo.module.unifikation.algo.view.Algo; + +public class UnifiedButtonAction extends IButtonActionAlgo { + + public UnifiedButtonAction(Algo algo) { + super(algo); + + } + + @Override + public void onClick() { + theAlgo.setErrorText(""); + if(theAlgo.getProblemSet().getPairNotFinal() == -1) { + theAlgo.getState().next(); + theAlgo.notifySelectionChanged(); + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Korrekt! Die Menge von Termen ist unifiziert."); + } + + else { + JOptionPane.showMessageDialog(theAlgo.getContentPane(),"Leider falsch."); + } + } + + +} diff --git a/src/org/jalgo/module/unifikation/algo/controller/package-info.java b/src/org/jalgo/module/unifikation/algo/controller/package-info.java new file mode 100644 index 0000000..ac0493e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/controller/package-info.java @@ -0,0 +1,5 @@ +/** + * Controller, which connects the view and the model + */ + +package org.jalgo.module.unifikation.algo.controller; diff --git a/src/org/jalgo/module/unifikation/algo/model/ATerm.java b/src/org/jalgo/module/unifikation/algo/model/ATerm.java new file mode 100644 index 0000000..8195631 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/ATerm.java @@ -0,0 +1,19 @@ +package org.jalgo.module.unifikation.algo.model; + +public abstract class ATerm implements ITerm { + @Override + public boolean equals(Object obj){ + if(!(obj instanceof ITerm)) return false; + return this.toString().equalsIgnoreCase(obj.toString()); + } + + @Override + public int hashCode(){ + return super.hashCode(); + } + + public boolean equalsName(ITerm other){ + return getName(false).equalsIgnoreCase(other.getName(false)); + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/model/CVS/Entries b/src/org/jalgo/module/unifikation/algo/model/CVS/Entries new file mode 100644 index 0000000..547f468 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/CVS/Entries @@ -0,0 +1,15 @@ +/ATerm.java/1.1/Mon Aug 16 12:05:47 2010// +/ColorConstructorSymbol.java/1.1/Mon Aug 16 12:05:47 2010// +/ColorVariable.java/1.1/Mon Aug 16 12:05:47 2010// +/ConstructorSymbol.java/1.1/Mon Aug 16 12:05:47 2010// +/Formating.java/1.1/Mon Aug 16 12:05:47 2010// +/HTMLProblemSet.java/1.1/Mon Aug 16 12:05:47 2010// +/HTMLVariable.java/1.1/Mon Aug 16 12:05:47 2010// +/History.java/1.1/Mon Aug 16 12:05:47 2010// +/IModelFormat.java/1.1/Mon Aug 16 12:05:47 2010// +/ITerm.java/1.1/Mon Aug 16 12:05:47 2010// +/Pair.java/1.1/Mon Aug 16 12:05:47 2010// +/ProblemSet.java/1.1/Mon Aug 16 12:05:47 2010// +/Rule.java/1.1/Mon Aug 16 12:05:47 2010// +/Variable.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:47 2010// diff --git a/src/org/jalgo/module/unifikation/algo/model/CVS/Repository b/src/org/jalgo/module/unifikation/algo/model/CVS/Repository new file mode 100644 index 0000000..ba39ca7 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/algo/model diff --git a/src/org/jalgo/module/unifikation/algo/model/CVS/Root b/src/org/jalgo/module/unifikation/algo/model/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.java b/src/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.java new file mode 100644 index 0000000..a19aa95 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/ColorConstructorSymbol.java @@ -0,0 +1,23 @@ +package org.jalgo.module.unifikation.algo.model; + +public class ColorConstructorSymbol extends ConstructorSymbol { + + public ColorConstructorSymbol(String name) { + super(name); + } + + protected String formatBracket(String text){ + return Formating.addColor(text, Formating.Char); + } + + protected String formatChar(String text){ + return Formating.addColor(text, Formating.Char); + } + + public String getName(boolean doFormat) { + if(doFormat) + return Formating.addColor(name, Formating.Function); + else return name; + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/model/ColorVariable.java b/src/org/jalgo/module/unifikation/algo/model/ColorVariable.java new file mode 100644 index 0000000..46fde9e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/ColorVariable.java @@ -0,0 +1,15 @@ +package org.jalgo.module.unifikation.algo.model; + +public class ColorVariable extends HTMLVariable { + + public ColorVariable(String name) { + super(name); + } + + public String getName(boolean doFormat) { + String result=super.getName(doFormat); + if(doFormat) + return Formating.addColor(result, Formating.Variable); + else return result; + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.java b/src/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.java new file mode 100644 index 0000000..69de596 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/ConstructorSymbol.java @@ -0,0 +1,97 @@ +package org.jalgo.module.unifikation.algo.model; + +import java.util.*; + +public class ConstructorSymbol extends ATerm { + protected final String name; + private List parameter; + + public ConstructorSymbol(final String name){ + this.name=name; + this.parameter=new LinkedList(); + } + + public boolean addParameter(final ITerm param){ + return parameter.add(param); + } + + public List getParameters(){ + return parameter; + } + + public String getName(boolean doFormat) { + return name; + } + + public String toString(){ + String result=getName(false); + result+=getParamList(-1); + return result; + } + + public String getFormatText() { + return getFormatText(0); + } + + public String getFormatText(int recDepth) { + String result=getName(true); + result+=getParamList(recDepth); + return result; + } + + /** + * formats brackets + */ + protected String formatBracket(String text){ + return text; + } + + /** + * formats other chars (commas...) + */ + protected String formatChar(String text){ + return text; + } + + /** + * returns string representation of the parameters list + * recDepth<0 -->no formating + */ + protected String getParamList(int recDepth){ + boolean doFormat=(recDepth>=0); + StringBuffer result=new StringBuffer(); + int size=parameter.size(); + if(size>0){ + if(doFormat) result.append(formatBracket("( ")); + else result.append("( "); + for (ITerm param : parameter){ + if(doFormat){ + result.append(param.getFormatText(recDepth+1)); + }else result.append(param); + size--; + if(size>0){ + if(doFormat) result.append(formatChar(", ")); + else result.append(", "); + } + } + if(doFormat) result.append(formatBracket(" )")); + else result.append(" )"); + } + return result.toString(); + } + + public boolean containsVar(Variable var) { + for (ITerm param : parameter){ + if(param.containsVar(var)) return true; + } + return false; + } + + public ITerm substitute(Variable varFrom, ITerm termTo) { + for (int i=0;i"+text+""; + } + + /** + * Formats the text with a background color + * @param text Text to format + * @param color + * @return colored text + */ + public static String addBackgroundColor(String text, String color){ + if(text.equals("")) return ""; + return ""+text+""; + } + + /** + * Formats the text with a given size + * @param text Text to format + * @param size + * @return resized text + */ + public static String addSize(String text, int size){ + if(text.equals("")) return ""; + return ""+text+""; + } + + /** + * Gets the text size for current state and to active flag of the text + * @param active True if state is active + * @return Current text size + */ + public static int getTextSize(boolean active){ + if(beamerMode){ + if(active) return activeSizeBeamer; + else return inactiveSizeBeamer; + }else{ + if(active) return activeSizeNormal; + else return inactiveSizeNormal; + } + } + + /** + * Formats the text with a size according to its state + * @param text Text to format + * @param active True if state is active + * @return resized text + */ + public static String setTextSize(String text, boolean active){ + if(text.equals("")) return ""; + return addSize(text,getTextSize(active)); + } + + /** + * Formats the text to show that it has been used + * @param text Text to format + * @return Formated text + */ + public static String addUsedMark(String text){ + if(text.equals("")) return ""; + return ""+text+""; + } + + /** + * Checks if currently in beamer Mode + * @return True if in beamer mode + */ + public static boolean isBeamerMode(){ + return beamerMode; + } + + /** + * Toggles beamer mode + * @return state of beamer mode after change + */ + public static boolean toggleBeamerMode(){ + beamerMode=!beamerMode; + return beamerMode; + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.java b/src/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.java new file mode 100644 index 0000000..85ad650 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/HTMLProblemSet.java @@ -0,0 +1,39 @@ +package org.jalgo.module.unifikation.algo.model; + +/** + * Problem set with HTML formating + * @author Alex + * + */ +public class HTMLProblemSet extends ProblemSet { + public String getFormatText(boolean finished){ + StringBuffer result=new StringBuffer("M="+formatBracket("{ ")); + int remaining=pairs.size(); + int i=0; + for (Pair pair : pairs){ + String sPair=pair.getFormatText(); + if(isActive()){ + if(finished){ + if(!this.isPairInFinalForm(i)) + sPair=Formating.addUsedMark(sPair); + } + else{ + sPair=""+sPair+""; + if(getSelectedPair()==i){ + sPair=Formating.addBackgroundColor(sPair, Formating.Selected); + }else if(getHoverPair()==i){ + sPair=Formating.addBackgroundColor(sPair, Formating.Hover); + } + } + }else if(getSelectedPair()==i){ + sPair=Formating.addUsedMark(sPair); + } + result.append(sPair); + remaining--; + if(remaining>0) result.append(formatChar(",     ")); + i++; + } + result.append(formatChar(" }")); + return result.toString(); + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/HTMLVariable.java b/src/org/jalgo/module/unifikation/algo/model/HTMLVariable.java new file mode 100644 index 0000000..4f4e0d2 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/HTMLVariable.java @@ -0,0 +1,14 @@ +package org.jalgo.module.unifikation.algo.model; + +public class HTMLVariable extends Variable { + public HTMLVariable(String name) { + super(name); + } + + protected String getIndex(boolean doFormat){ + String result=super.getIndex(doFormat); + if(doFormat && result!="") result=""+result+""; + return result; + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/model/History.java b/src/org/jalgo/module/unifikation/algo/model/History.java new file mode 100644 index 0000000..29fbd17 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/History.java @@ -0,0 +1,290 @@ +package org.jalgo.module.unifikation.algo.model; + +import java.util.LinkedList; +import java.util.List; + +import org.jalgo.module.unifikation.parser.ISetParser; +import org.jalgo.module.unifikation.parser.SetParser; + +/** + * Holds all steps made for a history function + * @author Alex + * + */ +public class History { + /** + * Steps as a String + */ + private List steps; + /** + * Used rule that made the pair + */ + private List usedrules; + /** + * Selected pair in each step + */ + private List stepsSelPair; + /** + * index of current step + */ + private int curStep; + /** + * Show selected pair + */ + private boolean showSelected; + + + /** + * sign to split lines (line end symbol) + */ + private static final String lineEnd="

          "; + + public History(){ + steps=new LinkedList(); + usedrules=new LinkedList(); + stepsSelPair=new LinkedList(); + this.reset(); + } + + /** + * Deletes all following steps from history + */ + private void clearFollowingSteps(){ + steps.subList(curStep+1,steps.size()).clear(); + usedrules.subList(curStep+1,usedrules.size()).clear(); + stepsSelPair.subList(curStep+1,stepsSelPair.size()).clear(); + } + + /** + * Adds a step to history, clears all following steps from the current step before + * @param step Set to add + * @return true if successfully added + */ + public boolean addStep(ProblemSet step){ + //remove all following steps saved, since a change is made + clearFollowingSteps(); + //deactivate it + boolean active=step.isActive(); + step.setActive(false); + //store it + usedrules.add(step.getLastUsedRule()); + boolean result=steps.add(step.getFormatText()); + if(result){ + curStep++; + result=stepsSelPair.add(-1); + if(!result) + { + steps.remove(steps.size()-1); + usedrules.remove(usedrules.size()-1); + } + else{ + showSelected=false; + //update last Step + if(curStep>0){ + ProblemSet set=getSet(curStep-1); + set.setSelectedPair(stepsSelPair.get(curStep-1)); + set.setActive(false); + steps.set(curStep-1, set.getFormatText()); + } + } + } + //restore active state + step.setActive(active); + return result; + } + + /** + * Sets the current selected pair + * @param selPair index of pair currently selected + */ + public void setSelected(final int selPair){ + if(selPair<-1) return; + if(curStep>=0){ + if(stepsSelPair.get(curStep)!=selPair){ + clearFollowingSteps(); + stepsSelPair.set(curStep, selPair); + } + showSelected=(selPair>=0); + } + } + + /** + * Gets the full history till current step (exclude) as a formated String + * @return Formated String of the history + */ + public String getHistory(){ + StringBuffer result=new StringBuffer(); + //for(int i=0;i0){ + for(int i=curStep-1;i>=0;i--){ + //result.append(steps.get(i)+usedrules.get(i+1)+lineEnd); + result.insert(0, steps.get(i)+Formating.setTextSize(" \u2192 "+usedrules.get(i+1).toString(), false)+lineEnd); + if(i<=curStep-3 && result.length()>=20000){ + result.insert(0, "

          \u219F   ...   \u219F
          "+lineEnd); + break; + } + } + result.append(lineEnd); + } + return result.toString(); + } + + /** + * Gets the amount of steps stored + * @return Amount of steps stored + */ + public int getStepCount(){ + return steps.size(); + } + + /** + * Gets the current step index
          + * 0: first Step
          + * -1: no Step + * @return Current step index + */ + public int getCurrentStep(){ + return curStep; + } + + /** + * Gets the specified step as text + * @param index Index of the step + * @return String of the step + */ + public String getStepText(int index){ + if(index<0 || index>=steps.size()) return ""; + return steps.get(index); + } + + /** + * Gets the specified step as a set + * @param index + * @return Set of the step or null for error + */ + public ProblemSet getSet(int index){ + if(index<0 || index>=steps.size()) return null; + ISetParser parser=new SetParser(); + parser.parse(getStepText(index)); + ProblemSet result=parser.getResult(); + result.setLastUsedRule(usedrules.get(index)); + return result; + } + + /** + * Gets the current step as a set + * @return Set of current step or null for error + */ + public ProblemSet getCurrentSet(){ + ProblemSet result=getSet(curStep); + if(showSelected) result.setSelectedPair(stepsSelPair.get(curStep)); + return result; + } + + /** + * Steps a step back in history + * @return True if it was possible + */ + public boolean prev(){ + if(showSelected){ + if(curStep<0) return false; + showSelected=false; + return true; + }else if(curStep>0){ + curStep--; + showSelected=true; + return true; + }else return false; + } + + /** + * Steps a full step back in history + * @return True if it was possible + */ + public boolean prevFull(){ + if(curStep>0){ + curStep--; + showSelected=false; + return true; + }else return false; + } + + /** + * Steps all steps back in the history + * @return True if it was possible + */ + public boolean prevAll(){ + if(curStep>0){ + curStep=0; + showSelected=false; + return true; + }else return false; + } + + /** + * Steps a step forward in history + * @return True if it was possible + */ + public boolean next(){ + if(!showSelected){ + if(curStep>=0 && stepsSelPair.get(curStep)>=0){ + showSelected=true; + return true; + }else return false; + }else if(curStep=0 && step getParameters(); + + /** + * Checks if this term contains (or IS) a specified variable + * @return True if variable is in term + */ + public boolean containsVar(Variable var); + + /** + * Checks if this and other term have the same name + * @param other Other term + * @return True if name is the same + */ + public boolean equalsName(ITerm other); + + /** + * Substitutes varFrom to termTo and returns the resulting term + * @param varFrom Variable to replace + * @param termTo Term that is replaced for varFrom + * @return Resulting term (Can be self, if nothing was done) + */ + public ITerm substitute(Variable varFrom, ITerm termTo); +} diff --git a/src/org/jalgo/module/unifikation/algo/model/Pair.java b/src/org/jalgo/module/unifikation/algo/model/Pair.java new file mode 100644 index 0000000..f6a0d8d --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/Pair.java @@ -0,0 +1,234 @@ +package org.jalgo.module.unifikation.algo.model; + + + +/** + * Represents a pair in the set + * @author Alex + * + */ +public class Pair { + private ITerm firstTerm=null; + private ITerm secondTerm=null; + private String lastError; + + + public Pair(){} + + public Pair(ITerm term1, ITerm term2){ + firstTerm=term1; + secondTerm=term2; +} + + /** + * formats brackets + */ + protected String formatBracket(String text){ + return text; + } + + /** + * returns the last error from a rule-check + * @return + */ + public String getLastError() { + return this.lastError; + } + + /** + * formats other chars (commas...) + */ + protected String formatChar(String text){ + return text; + } + + /** + * returns the unformatted representation of the pair + */ + public String toString(){ + if(firstTerm==null || secondTerm==null) return "invalid pair"; + return "("+firstTerm+", "+secondTerm+")"; + } + + /** + * returns the formated representation of the pair + * @return formated representation of the pair + */ + public String getFormatText(){ + if(firstTerm==null || secondTerm==null) return "invalid pair"; + String result=formatBracket("(")+firstTerm.getFormatText(); + result+=formatChar(", "); + result+=secondTerm.getFormatText()+formatBracket(")"); + return result; + } + + /** + * adds the first term + * @param term + */ + public void addFirstTerm(final ITerm term){ + firstTerm=term; + } + + /** + * adds the second term + * @param term + */ + public void addSecondTerm(final ITerm term){ + secondTerm=term; + } + + public ITerm getFirstTerm(){ + return firstTerm; + } + + public ITerm getSecondTerm(){ + return secondTerm; + } + + /** + * Checks if pair is in final form as specified in unification algo:
          + * (x,t(...)) with x not in t + * @return True if pair is in final form + */ + public boolean isInFinalForm(){ + return (firstTerm instanceof Variable && + !secondTerm.containsVar((Variable) firstTerm)); + } + + /** + * test if permutation could be used + * @return boolean + */ + + public boolean swapCheck() + { + if(secondTerm instanceof Variable) { + if(firstTerm instanceof ConstructorSymbol) { + return true; + } + else { + this.lastError="Vertauschung nicht anwendbar, da der 1.Term eine Variable ist."; + return false; + } + } + else { + this.lastError="Vertauschung nicht anwendbar, da 2.Term keine Variable ist."; + return false; + } + + } + + /** + * test if decomposition could be used + * @return boolean + */ + public boolean decompositionCheck() + { + if(firstTerm instanceof ConstructorSymbol){ + if(secondTerm instanceof ConstructorSymbol) { + if(firstTerm.equalsName(secondTerm)) { + if(firstTerm.getParameters().size()==secondTerm.getParameters().size()) { + return true; + } + else { + this.lastError="Dekompositionsregel nicht anwendbar, da die Anzahl der Parameter der Konstruktoren unterschiedlich ist."; //eigentlich durch Parser unmöglich + return false; + } + } + else { + this.lastError="Dekompositionsregel nicht anwendbar, da es sich um unterschiedliche Konstruktoren handelt."; + return false; + } + } + else { + this.lastError="Dekompositionsregel nicht anwendbar, da 2.Term kein Konstruktor ist."; + return false; + } + } + else { + this.lastError="Dekompositionsregel nicht anwendbar, da 1.Term kein Konstruktor ist."; + return false; + } + } + + /** + * checks whether the two terms of this pair can be eliminated or not + * @return + */ + public boolean eliminationCheck() + { + if (firstTerm instanceof Variable) { + + if (secondTerm instanceof Variable) { + + if(secondTerm.equals(firstTerm)) { + return true; + } + else { + this.lastError="Eliminationsregel nicht anwendbar, da es sich um unterschiedliche Variablen handelt."; + return false; + } + } + else { + this.lastError="Eliminationsregel nicht anwendbar, da der 2.Term keine Variable ist."; + return false; + } + } + else { + this.lastError="Eliminationsregel nicht anwendbar, da der 1.Term keine Variable ist."; + return false; + } + } + + /** + * checks whether the first terms can substitute with the second term + * @return + */ + public boolean substitutionCheck() + { + if(firstTerm instanceof Variable) { + if (!secondTerm.containsVar((Variable) firstTerm)) { + return true; + } + else { + this.lastError="Substitutionsregel nicht anwendbar, da der 2.Term die Variable " + firstTerm.getName(true) + " beinhaltet."; + return false; + } + } + else { + this.lastError="Substitutionsregel nicht anwendbar, da der 1.Term keine Variable ist."; + return false; + } + } + + /** + * Checks if this pair contains a specified variable + * @return True if variable is in pair + */ + public boolean containsVar(Variable var){ + return firstTerm.containsVar(var) || secondTerm.containsVar(var); + } + + /** + * Substitutes varFrom to termTo + * @param varFrom Variable to replace + * @param termTo Term that is replaced for varFrom + */ + public void substitute(Variable varFrom, ITerm termTo){ + firstTerm=firstTerm.substitute(varFrom, termTo); + secondTerm=secondTerm.substitute(varFrom, termTo); + } + + /** + * swaps if possible + */ + public boolean swap() //Manual swap function + { + if(!swapCheck()) return false; + ITerm cache = firstTerm; + firstTerm = secondTerm; + secondTerm = cache; + return true; + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/ProblemSet.java b/src/org/jalgo/module/unifikation/algo/model/ProblemSet.java new file mode 100644 index 0000000..79bdce1 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/ProblemSet.java @@ -0,0 +1,437 @@ +package org.jalgo.module.unifikation.algo.model; + +import java.util.LinkedList; +import java.util.List; + + +/* + * represents the set of pairs for which the unification problem is to be solved + */ +public class ProblemSet implements IModelFormat{ + protected List pairs; + private int selectedPair; + private int hoverPair; + private boolean active; + private String lastRuleCheckError; + private Rule lastUsedRule = Rule.NoRule; + + public ProblemSet(){ + pairs=new LinkedList(); + hoverPair=-1; + selectedPair=-1; + active=true; + } + + /** + * sets the set to active + * @param active true=active + */ + public void setActive(boolean active) { + this.active = active; + } + + /** + * returns if set is active + * @return true=active + */ + public boolean isActive() { + return active; + } + + /** + * sets the hovered pair + * @param hoverPair index of pair, -1 for none + */ + public void setHoverPair(int hoverPair) { + this.hoverPair = hoverPair; + } + + /** + * gets the hovered pair + * @return index of hovered pair + */ + public int getHoverPair() { + return hoverPair; + } + + /** + * sets the selected pair + * @param selectedPairindex of pair, -1 for none + */ + public void setSelectedPair(int selectedPair) { + this.selectedPair = selectedPair; + } + + /** + * gets the selected pair + * @return index of selected pair + */ + public int getSelectedPair() { + return selectedPair; + } + + /** + * @return unformatted representation of the set + */ + public String toString(){ + StringBuffer result=new StringBuffer("M={ "); + int remaining=pairs.size(); + for (Pair pair : pairs){ + result.append(pair); + remaining--; + if(remaining>0) result.append(", "); + } + result.append(" }"); + return result.toString(); + } + + /** + * returns a string with the last error that a rule-check generated + * @return error message + */ + public String getLastRuleErrorText() { + return this.lastRuleCheckError; + } + + /** + * updates the private String lastRuleCheckError with the last error message from the selected pair + */ + public void updateLastRuleError() { + this.lastRuleCheckError=this.getSelectedPPair().getLastError(); + } + /** + * sets the last error that a rule-check generated + * @param errorText + */ + public void setLastRuleErrorText(String errorText) { + this.lastRuleCheckError =errorText; + } + + /** + * formats brackets + */ + protected String formatBracket(String text){ + return text; + } + + /** + * formats other chars (commas...) + */ + protected String formatChar(String text){ + return text; + } + + /** + * @param finished true if algo is finished + * @return formated representation of the set + */ + public String getFormatText(boolean finished){ + StringBuffer result=new StringBuffer("M="+formatBracket("{ ")); + int remaining=pairs.size(); + for (Pair pair : pairs){ + result.append(pair.getFormatText()); + remaining--; + if(remaining>0) result.append(formatChar(", ")); + } + result.append(formatChar(" }")); + return result.toString(); + } + + /** + * @return formated representation of the set + */ + public String getFormatText(){ + return this.getFormatText(false); + } + + + /** + * adds a pair and returns whether it was successful + * @param pair + * @return successful add + */ + public boolean addPair(final Pair pair){ + return pairs.add(pair); + } + + /** + * adds a pair at a specific position. Avoids duplicate entries + * @param index + * @param pair + */ + public void addPair(int index,final Pair pair){ + for(Pair curPair:pairs){ + if(curPair.toString().equalsIgnoreCase(pair.toString())) return; + } + pairs.add(index, pair); + } + + /** + * removes the pair if present in list + * @return boolean if success + */ + public boolean removePair(Pair pair){ + + return this.pairs.remove(pair); + } + + /** + * gets the selected pair + * @return selected pair + */ + public Pair getSelectedPPair() + { + return (getPair(getSelectedPair())); + } + + /** + * gets the last used rule + * @return rule + */ + public Rule getLastUsedRule() + { + return this.lastUsedRule; + } + + /** + * Returns pair defined by index or null if invalid index + * @param index Index of pair in set + * @return Pair at index or null + */ + public Pair getPair(int index){ + if(index>=0 && index parametersTerm1 = this.getSelectedPPair().getFirstTerm().getParameters(); + final List parametersTerm2 = this.getSelectedPPair().getSecondTerm().getParameters(); + int pos = this.getSelectedPair()+1; + + for(int i=0; i < parametersTerm1.size(); i++){ + Pair newPair = new Pair( parametersTerm1.get(i) , parametersTerm2.get(i)); + this.addPair(pos,newPair); + pos++; + } + this.removePair(getSelectedPPair()); + this.lastUsedRule=Rule.Decomposition; + return true; + } + return false; + } + + /** + * if possible, this function executes the substitution + * @return false or true + */ + public boolean substitution() + { + + if (canUseRule(Rule.Substitution)) + { + Pair selPair = getSelectedPPair(); + for(Pair curPair : pairs){ + if(curPair==selPair) continue; + curPair.substitute((Variable) selPair.getFirstTerm(), selPair.getSecondTerm()); + this.lastUsedRule=Rule.Substitution; + } + return (true); + } + else return (false); + } + + /** + * if possible, this function swaps a pair + * @return false or true + */ + public boolean swap() + { + Pair cache = getSelectedPPair(); + if (canUseRule(Rule.Swap)) + { + cache.swap(); + String cacheS=cache.toString(); + for(Pair curPair:pairs){ + if(curPair==cache) continue; + if(curPair.toString().equalsIgnoreCase(cacheS)){ + pairs.remove(cache); + break; + } + } + this.lastUsedRule=Rule.Swap; + return (true); + }else return (false); + } + + //method for jUnit test + /** + * removes all pairs of the ProblemSet + */ + public void removeAllPairs(){ + pairs.clear(); + } + + public void setLastUsedRule(Rule rule) { + this.lastUsedRule=rule; + } + + /** + * return the number of pairs + * @return number of pairs + */ + public int getNumberOfPairs(){ + return pairs.size(); + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/Rule.java b/src/org/jalgo/module/unifikation/algo/model/Rule.java new file mode 100644 index 0000000..855c5eb --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/Rule.java @@ -0,0 +1,48 @@ +package org.jalgo.module.unifikation.algo.model; + +/** + * Enum field for rules that can be applied to a set + * @author Alex + * + */ +public enum Rule { + /** + * Neutral element. e.g. for check which rule can be applied + */ + NoRule, + /** + * Swapping in a pair + */ + Swap, + /** + * Elimination of a pair + */ + Elimination, + /** + * Decomposition of a pair + */ + Decomposition, + /** + * Substitution of a term for a variable + */ + Substitution; + + @Override + public String toString(){ + switch(this) + { + case Swap: + return "Vertauschung"; + case Elimination: + return "Elimination"; + case Decomposition: + return "Dekomposition"; + case Substitution: + return "Substitution"; + case NoRule: + return "Keine Regel"; + } + return ""; + + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/Variable.java b/src/org/jalgo/module/unifikation/algo/model/Variable.java new file mode 100644 index 0000000..c34dbaf --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/Variable.java @@ -0,0 +1,51 @@ +package org.jalgo.module.unifikation.algo.model; + +import java.util.List; + +public class Variable extends ATerm { + protected final String name; + private final int index; + + public Variable(final String name){ + this.name=name.substring(0, 1).toLowerCase(); + if(name.length()>1) this.index=Integer.parseInt(name.substring(1)); + else this.index=-1; + } + + public String toString(){ + return getName(false); + } + + public boolean addParameter(final ITerm param){ + return false; + } + + protected String getIndex(boolean doFormat){ + if(index>=0) return String.valueOf(index); + else return ""; + } + + public String getFormatText() { + return getFormatText(0); + } + public String getFormatText(int recDepth) { + return getName(true); + } + + public String getName(boolean doFormat) { + return name+getIndex(doFormat); + } + + public List getParameters() { + return null; + } + + public boolean containsVar(Variable var) { + return getName(false).equalsIgnoreCase(var.getName(false)); + } + + public ITerm substitute(Variable varFrom, ITerm termTo) { + if(this.equals(varFrom)) return termTo; + else return this; + } +} diff --git a/src/org/jalgo/module/unifikation/algo/model/package-info.java b/src/org/jalgo/module/unifikation/algo/model/package-info.java new file mode 100644 index 0000000..3d9477e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/model/package-info.java @@ -0,0 +1,5 @@ +/** + * Manages the information of the problem set and notifies observers when that information changes + */ + +package org.jalgo.module.unifikation.algo.model; diff --git a/src/org/jalgo/module/unifikation/algo/view/Algo.java b/src/org/jalgo/module/unifikation/algo/view/Algo.java new file mode 100644 index 0000000..9fe297e --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/Algo.java @@ -0,0 +1,467 @@ +package org.jalgo.module.unifikation.algo.view; + + + +import java.awt.Color; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +import javax.swing.BorderFactory; +import javax.swing.GroupLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JEditorPane; +import javax.swing.JScrollPane; +import javax.swing.LayoutStyle; +import javax.swing.border.EtchedBorder; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.unifikation.Application; +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.IAppView; +import org.jalgo.module.unifikation.algo.HTMLParser.SpecialEditorKit; +import org.jalgo.module.unifikation.algo.controller.ButtonListenerFactory; +import org.jalgo.module.unifikation.algo.controller.DecompButtonAction; +import org.jalgo.module.unifikation.algo.controller.DoBlockStepButtonAction; +import org.jalgo.module.unifikation.algo.controller.DoStepButtonAction; +import org.jalgo.module.unifikation.algo.controller.EditorButtonAction; +import org.jalgo.module.unifikation.algo.controller.ElimButtonAction; +import org.jalgo.module.unifikation.algo.controller.HLLPairs; +import org.jalgo.module.unifikation.algo.controller.NotUnifiableButtonAction; +import org.jalgo.module.unifikation.algo.controller.PerformAllButtonAction; +import org.jalgo.module.unifikation.algo.controller.RuleCheckButtonAction; +import org.jalgo.module.unifikation.algo.controller.SubButtonAction; +import org.jalgo.module.unifikation.algo.controller.SwapButtonAction; +import org.jalgo.module.unifikation.algo.controller.UndoAllButtonAction; +import org.jalgo.module.unifikation.algo.controller.UndoBlockStepButtonAction; +import org.jalgo.module.unifikation.algo.controller.UndoStepButtonAction; +import org.jalgo.module.unifikation.algo.controller.UnifiedButtonAction; +import org.jalgo.module.unifikation.algo.model.Formating; +import org.jalgo.module.unifikation.algo.model.History; +import org.jalgo.module.unifikation.algo.model.ProblemSet; +import org.jalgo.module.unifikation.parser.ISetParser; +import org.jalgo.module.unifikation.parser.SetParser; + + +/** + * algo class + * initializes the algo-windows and works as a connector to application + * + * + * + */ +public class Algo implements IAppView, MouseListener { + + private Application app=null; + private JEditorPane content; + protected JEditorPane jEditorPaneRegel; + public JEditorPane jErrorPane; + private JComponent contentPane; + protected History history; + //private EditorFormat editorFormat; + + protected JButton editorButton; + protected JButton jButtonNoMoreRules; + protected JButton jButtonNotUnifiable; + protected JButton jButtonUnified; + protected JButton jButtonDekomp; + protected JButton jButtonSubst; + protected JButton jButtonVertau; + protected JButton jButtonElimin; + + private boolean mouseDown; + + protected ProblemSet curSet; + private IAlgoState curState; + + public Algo(){ + history=new History(); + curState=null; + mouseDown=false; + //editorFormat=new EditorFormat(); + } + + public JComponent getContentPane() { + return this.content; + } + + public IAlgoState getState(){ + return this.curState; + } + + public void setApplication(Application app) { + this.app=app; + contentPane = app.contentPane; + } + + public ProblemSet getProblemSet(){ + return curSet; + } + + public History getHistory(){ + return history; + } + + public boolean isMouseDown(){ + return mouseDown; + } + + public void setMouseDown(boolean mouseDown){ + this.mouseDown=mouseDown; + } + + /** + * Gets the contentPane so it can create the GUI + */ + public void setContentPane(JComponent contentPaneOLD) { + ISetParser parser=new SetParser(); + if(parser.parse(app.getProblem())){ + curSet=parser.getResult(); + }else{ + app.setFinished(app.getProblem()); + return; + } + + + GroupLayout thisLayout = new GroupLayout(contentPane); + contentPane.setLayout(thisLayout); + + //create helpbox + jEditorPaneRegel = new JEditorPane("text/html",""); + jEditorPaneRegel.setEditable(false); + jEditorPaneRegel.setBackground(Color.WHITE); + jEditorPaneRegel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); + + //create errorbox + jErrorPane = new JEditorPane("text/html",""); + jErrorPane.setEditable(false); + jErrorPane.setBackground(Color.WHITE); + jErrorPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); + jErrorPane.setText(""+Formating.addColor("W" + Constants.lowercasedAE + "hlen Sie ein Paar aus um eine Regel anzuwenden oder nutzen Sie die Pfeile in der Toolbar als Hilfe um Schritte automatisch auszuf" + Constants.lowercasedUE + "hren.","#FF0000")+""); + + ButtonListenerFactory blFactory=new ButtonListenerFactory(this); + //Toolbar aktivieren + app.installToolbar(); + editorButton = new JButton((new ImageIcon(Messages.getResourceURL("unifikation", "Icon.Editor")))); + editorButton.setToolTipText("Menge editieren"); + app.toolbar.add(editorButton); + editorButton.addActionListener(blFactory.getClickListener(EditorButtonAction.class)); + app.performBlockStep.addActionListener(blFactory.getClickListener(DoBlockStepButtonAction.class)); + app.undoBlockStep.addActionListener(blFactory.getClickListener(UndoBlockStepButtonAction.class)); + app.performStep.addActionListener(blFactory.getClickListener(DoStepButtonAction.class)); + app.undoStep.addActionListener(blFactory.getClickListener(UndoStepButtonAction.class)); + app.undoAll.addActionListener(blFactory.getClickListener(UndoAllButtonAction.class)); + app.performAll.addActionListener(blFactory.getClickListener(PerformAllButtonAction.class)); + + //create activity pane + + content = new JEditorPane("text/html",""); + content.setEditorKit(new SpecialEditorKit()); + JScrollPane jScrollPane1 = new JScrollPane(content); + jScrollPane1.setBorder(null); + content.setBackground(Color.WHITE); + content.setEditable(false); + content.addHyperlinkListener(new HLLPairs(this)); + content.addMouseListener(this); + content.setFocusable(false); + + + //create buttons + + jButtonNoMoreRules = new JFadeButton(); + jButtonNoMoreRules.setText("keine Regel anwendbar"); + jButtonNoMoreRules.setFont(Constants.ButtonAlgoFont); + jButtonNoMoreRules.addActionListener(blFactory.getClickListener(RuleCheckButtonAction.class)); + + jButtonNotUnifiable = new JFadeButton(); + jButtonNotUnifiable.setText("nicht unifizierbar"); + jButtonNotUnifiable.setFont(Constants.ButtonAlgoFont); + jButtonNotUnifiable.addActionListener(blFactory.getClickListener(NotUnifiableButtonAction.class)); + + jButtonUnified = new JFadeButton(); + jButtonUnified.setText("unifiziert"); + jButtonUnified.setFont(Constants.ButtonAlgoFont); + jButtonUnified.addActionListener(blFactory.getClickListener(UnifiedButtonAction.class)); + + jButtonDekomp = new JButton(); + jButtonDekomp.setText("Dekomposition"); + jButtonDekomp .setFont(Constants.ButtonAlgoFont); + jButtonDekomp.addActionListener(blFactory.getClickListener(DecompButtonAction.class)); + jButtonDekomp.addMouseListener(blFactory.getHoverListener(DecompButtonAction.class)); + + jButtonSubst = new JButton(); + jButtonSubst.setText("Substitution"); + jButtonSubst.setFont(Constants.ButtonAlgoFont); + jButtonSubst.addActionListener(blFactory.getClickListener(SubButtonAction.class)); + jButtonSubst.addMouseListener(blFactory.getHoverListener(SubButtonAction.class)); + + jButtonVertau = new JButton(); + jButtonVertau.setText("Vertauschung"); + jButtonVertau.setFont(Constants.ButtonAlgoFont); + jButtonVertau.addActionListener(blFactory.getClickListener(SwapButtonAction.class)); + jButtonVertau.addMouseListener(blFactory.getHoverListener(SwapButtonAction.class)); + + jButtonElimin = new JButton(); + jButtonElimin.setText("Elimination"); + jButtonElimin.setFont(Constants.ButtonAlgoFont); + jButtonElimin.addActionListener(blFactory.getClickListener(ElimButtonAction.class)); + jButtonElimin.addMouseListener(blFactory.getHoverListener(ElimButtonAction.class)); + + //create layout + thisLayout.setVerticalGroup(thisLayout.createSequentialGroup() + .addContainerGap(12, 12) + .addComponent(jScrollPane1, 0, 349, Short.MAX_VALUE) + .addGap(12) + .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) + .addComponent(jButtonDekomp, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonSubst, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonVertau, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonElimin, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonNoMoreRules, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonUnified, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addComponent(jButtonNotUnifiable, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) + .addComponent(jEditorPaneRegel, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE) + .addComponent(jErrorPane, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE)) + .addContainerGap(26, 26)); + + thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup() + .addContainerGap(5, 5) + .addGroup(thisLayout.createParallelGroup() + .addGroup(thisLayout.createSequentialGroup() + .addComponent(jButtonDekomp, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButtonSubst, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButtonVertau, GroupLayout.PREFERRED_SIZE, 98, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButtonElimin, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE) + .addGap(20) + .addComponent(jButtonNoMoreRules, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButtonUnified, GroupLayout.PREFERRED_SIZE, 78, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButtonNotUnifiable, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE) + ) + .addGroup(thisLayout.createSequentialGroup() + .addComponent(jEditorPaneRegel, 0, 834, Short.MAX_VALUE) + .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jErrorPane, 0, 434, Short.MAX_VALUE)) + .addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, 0, 834, Short.MAX_VALUE) + ) + .addContainerGap(5, 5)); + + //Do this only after everything has been created! + history.reset(); + curState=new StateAlgoRunning(); + this.notifySetChanged(); + + } + + /** + * Enables/Disables rule buttons + * @param enabled new state of the buttons + */ + public void switchRuleButtons(boolean enabled){ + jButtonDekomp.setEnabled(enabled); + jButtonSubst.setEnabled(enabled); + jButtonVertau.setEnabled(enabled); + jButtonElimin.setEnabled(enabled); + } + + /** + * Switch the buttons which decide if unifiable or not + * @param enabled new state of the buttons + */ + public void switchUnifiableButtons(boolean enabled){ + jButtonNotUnifiable.setEnabled(enabled); + jButtonUnified.setEnabled(enabled); + } + + /** + * called when "Done"-Button is clicked + */ + public void onDoneClick(){ + //Remove listener!!! + content.removeMouseListener(this); + //Close this view + app.setFinished(app.getProblem()); + } + + private void updateContent(String sSet){ + content.setText("" + +"" + +Formating.setTextSize(history.getHistory(),false) + +Formating.setTextSize(sSet,true) + +""); + } + + /** + * Updates the algo view where set is shown + */ + public void updateSetView(){ + curState.updateView(); + } + + public class StateAlgoRunning implements IAlgoState{ + + public StateAlgoRunning(){ + curSet.setSelectedPair(-1); + curSet.setHoverPair(-1); + curSet.setActive(true); + jButtonNoMoreRules.setEnabled(true); + switchUnifiableButtons(false); + switchRuleButtons(false); + } + + public boolean next() { + if(curSet.getUsablePair()<0){ + curState=new StateNoRuleUsable(); + return true; + }else return false; + } + + public boolean prev() { + return false; + } + + public void updateView() { + switchRuleButtons(curSet.getSelectedPair()>=0); + updateContent(curSet.getFormatText()); + } + } + + public class StateNoRuleUsable implements IAlgoState{ + public StateNoRuleUsable(){ + curSet.setSelectedPair(-1); + curSet.setHoverPair(-1); + curSet.setActive(true); + jButtonNoMoreRules.setEnabled(false); + switchUnifiableButtons(true); + switchRuleButtons(false); + } + + public boolean next() { + curState=new StateAlgoFinished(); + return true; + } + + public boolean prev() { + curState=new StateAlgoRunning(); + return true; + } + + public void updateView() { + updateContent(Formating.addBackgroundColor(curSet.getFormatText(),"#CCCCCC")); + } + } + + public class StateAlgoFinished implements IAlgoState{ + private boolean unified; + + public StateAlgoFinished(){ + unified=curSet.getPairNotFinal()<0; + curSet.setSelectedPair(-1); + curSet.setHoverPair(-1); + curSet.setActive(true); + jButtonNoMoreRules.setEnabled(false); + switchUnifiableButtons(false); + switchRuleButtons(false); + } + + public boolean next() { + return false; + } + + public boolean prev() { + curState=new StateNoRuleUsable(); + return true; + } + + public void updateView() { + StringBuffer sSet=new StringBuffer(curSet.getFormatText(true)); + if(unified){ + sSet.append("
          " + Constants.PHI + " : "); + for(int i=0;i"+helpText+""); + } + + public void setErrorText(String errorText) { + this.jErrorPane.setText(""+Formating.addColor(errorText,"#FF0000")+""); + } + + public void mouseClicked(MouseEvent arg0) { + } + + public void mouseEntered(MouseEvent arg0) { + } + + public void mouseExited(MouseEvent arg0) { + } + + public void mousePressed(MouseEvent arg0) { + if(arg0.getButton()==1){ + mouseDown=true; + } + } + + public void mouseReleased(MouseEvent arg0) { + if(arg0.getButton()==1){ + mouseDown=false; + } + } +} diff --git a/src/org/jalgo/module/unifikation/algo/view/CVS/Entries b/src/org/jalgo/module/unifikation/algo/view/CVS/Entries new file mode 100644 index 0000000..14f03cf --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/CVS/Entries @@ -0,0 +1,5 @@ +/Algo.java/1.1/Mon Aug 16 12:05:49 2010// +/EditorFormat.java/1.1/Mon Aug 16 12:05:49 2010// +/IAlgoState.java/1.1/Mon Aug 16 12:05:49 2010// +/JFadeButton.java/1.1/Mon Aug 16 12:05:49 2010// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/unifikation/algo/view/CVS/Repository b/src/org/jalgo/module/unifikation/algo/view/CVS/Repository new file mode 100644 index 0000000..1ca5a20 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/algo/view diff --git a/src/org/jalgo/module/unifikation/algo/view/CVS/Root b/src/org/jalgo/module/unifikation/algo/view/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/algo/view/EditorFormat.java b/src/org/jalgo/module/unifikation/algo/view/EditorFormat.java new file mode 100644 index 0000000..e904fc3 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/EditorFormat.java @@ -0,0 +1,124 @@ +package org.jalgo.module.unifikation.algo.view; + +import java.awt.Color; + +import javax.swing.JEditorPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import javax.swing.text.html.HTMLDocument; + +import org.jalgo.module.unifikation.algo.model.Formating; + +public class EditorFormat { + private int hoverStart,hoverLen,selectStart,selectLen; + private int NewHoverStart,NewHoverLen,NewSelectStart,NewSelectLen; + private StringBuffer lastInput; + + public EditorFormat(){ + lastInput=new StringBuffer(); + reset(); + } + + public void reset(){ + hoverStart=-1; + selectStart=-1; + NewHoverStart=-1; + NewSelectStart=-1; + lastInput.setLength(0); + } + + public String update(String s){ + long start=System.currentTimeMillis(); + StringBuffer buf=new StringBuffer(); + NewHoverStart=-1; + NewSelectStart=-1; + buf.append(s.replace(" ", " ")); + int pos2,pos3,pos4,offset,offset2; + String color; + offset=0;pos3=0; + String search="0){ + pos3=buf.indexOf("<",pos3); + while(pos3>=0 && pos3",pos3); + offset+=pos2-pos3+1; + pos3=buf.indexOf("<",pos2+1); + } + pos2=buf.indexOf("\"",pos+search.length()); + color=buf.substring(pos+search.length(),pos2); + if(color.equalsIgnoreCase(Formating.Hover)){ + NewHoverStart=pos-offset+1; + }else{ + NewSelectStart=pos-offset+1; + } + pos2=buf.indexOf(">",pos2); + buf.delete(pos, pos2+1); + offset2=0; + pos2=buf.indexOf("",pos); + pos3=buf.indexOf("<",pos3); + while(pos3>=0 && pos3",pos2+7); + } + pos4=buf.indexOf(">",pos3); + offset2+=pos4-pos3+1; + pos3=buf.indexOf("<",pos4+1); + } + buf.delete(pos2, pos2+7); + if(color.equalsIgnoreCase(Formating.Hover)){ + NewHoverLen=pos2-pos-offset2; + }else{ + NewSelectLen=pos2-pos-offset2; + } + pos3=pos; + pos=buf.indexOf(search,pos); + } + //System.out.println(NewHoverStart+""); + //System.out.println(NewHoverLen+""); + System.out.println("Update:"+(System.currentTimeMillis()-start)); + if(buf.toString().equalsIgnoreCase(lastInput.toString())){ + return ""; + }else{ + lastInput.setLength(0); + lastInput.append(buf); + return buf.toString().replace(" ", "  "); + } + } + + public void doFormat(JEditorPane editor){ + long start2=System.currentTimeMillis(); + HTMLDocument doc = (HTMLDocument) editor.getDocument (); + SimpleAttributeSet attr = new SimpleAttributeSet(); + int start=-1; + try { + start = doc.getText(0, doc.getLength()).trim().lastIndexOf("M="); + } catch (BadLocationException e) { + start=0; + } + if(hoverStart>=0){ + StyleConstants.setBackground(attr, editor.getBackground()); + doc.setCharacterAttributes(start+hoverStart, hoverLen, attr, false); + } + if(selectStart>=0){ + StyleConstants.setBackground(attr, editor.getBackground()); + doc.setCharacterAttributes(start+selectStart, selectLen, attr, false); + } + hoverStart=NewHoverStart; + hoverLen=NewHoverLen; + selectStart=NewSelectStart; + selectLen=NewSelectLen; + if(hoverStart>=0){ + StyleConstants.setBackground(attr, Color.decode(Formating.Hover)); + doc.setCharacterAttributes(start+hoverStart, hoverLen, attr, false); + } + if(selectStart>=0){ + StyleConstants.setBackground(attr, Color.decode(Formating.Selected)); + doc.setCharacterAttributes(start+selectStart, selectLen, attr, false); + } + System.out.println("Format:"+(System.currentTimeMillis()-start2)); + } + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/algo/view/IAlgoState.java b/src/org/jalgo/module/unifikation/algo/view/IAlgoState.java new file mode 100644 index 0000000..6e87bd1 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/IAlgoState.java @@ -0,0 +1,25 @@ +package org.jalgo.module.unifikation.algo.view; + +/** + * Represents the state the Algo is currently in + * @author Alex + * + */ +public interface IAlgoState { + + /** + * Updates the view (Buttons, text...) + */ + public void updateView(); + /** + * Switches to next state + * @return True if it was possible + */ + public boolean next(); + /** + * Switches to previous state + * @return True if it was possible + */ + public boolean prev(); + +} diff --git a/src/org/jalgo/module/unifikation/algo/view/JFadeButton.java b/src/org/jalgo/module/unifikation/algo/view/JFadeButton.java new file mode 100644 index 0000000..fca0c91 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/JFadeButton.java @@ -0,0 +1,160 @@ +package org.jalgo.module.unifikation.algo.view; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.Timer; + +public class JFadeButton extends JButton { + + /** + * + */ + private static final long serialVersionUID = 8230265807260757953L; + + private Color fadeColor=Color.red; + private int fadeInterval=50; + private int fadeDuration=1500; + private Timer fadeTimer=null; + private boolean startOnEnable=true; + + /** + * Sets start color for fading + * @param fadeColor + */ + public void setFadeColor(Color fadeColor) { + this.fadeColor = fadeColor; + } + + /** + * Get current start color for fading + * @return current start color for fading + */ + public Color getFadeColor() { + return fadeColor; + } + + /** + * Get interval for fading + * @return interval for fading in ms + */ + public int getFadeInterval() { + return fadeInterval; + } + + /** + * Set the interval for updating the fade effect + * @param fadeInterval interval for updating the fade effect in ms + */ + public void setFadeInterval(int fadeInterval) { + this.fadeInterval = fadeInterval; + } + + /** + * Gets the fading duration + * @return fading duration in ms + */ + public int getFadeDuration() { + return fadeDuration; + } + + /** + * Sets the duration during which the fading effect is completed + * @param fadeDuration in ms + */ + public void setFadeDuration(int fadeDuration) { + this.fadeDuration = fadeDuration; + } + + /** + * Sets if fading should start when button is just enabled + * @param startOnEnable + */ + public void setStartOnEnable(boolean startOnEnable) { + this.startOnEnable = startOnEnable; + } + + /** + * Gets if fading should start when button is just enabled + * @return True if fading should start when button is just enabled + */ + public boolean isStartOnEnable() { + return startOnEnable; + } + + /** + * Starts the fading if it is not currently running + * @return True if it was started + */ + public boolean fade(){ + if(fadeTimer!=null) return false; + fadeTimer=new Timer(fadeInterval,new fadeTask()); + fadeTimer.start(); + return true; + } + + @Override + public void setEnabled(boolean b){ + if(b && !this.isEnabled()){ + super.setEnabled(true); + fade(); + }else super.setEnabled(b); + } + + public void paintComponent(Graphics g) { + if(fadeTimer==null || !this.isEnabled()){ + super.paintComponent(g); + }else{ + g.setColor(this.getBackground()); + int w = getWidth(); // Size might have changed if + int h = getHeight(); // user resized window. + g.clearRect(0, 0, w, h); + g.fillRoundRect(1, 1, w-3, h-3, 3, 3); + this.setContentAreaFilled(false); + super.paintComponent(g); + this.setContentAreaFilled(true); + g.setColor(Color.gray); + g.drawRoundRect(1, 1, w-3, h-3, 3, 3); + } + } + + private class fadeTask implements ActionListener{ + private Color fromColor,targetColor; + private int curCall,times; + + public Color combine(Color c1, Color c2, double alpha) { + int r = (int) (alpha * c1.getRed() + (1 - alpha) * c2.getRed()); + int g = (int) (alpha * c1.getGreen() + (1 - alpha) * c2.getGreen()); + int b = (int) (alpha * c1.getBlue() + (1 - alpha) * c2.getBlue()); + return new Color(r, g, b); + } + + public fadeTask(){ + super(); + targetColor=getBackground(); + fromColor=fadeColor; + times=fadeDuration/fadeInterval; + curCall=0; + setOpaque(true); + actionPerformed(null); + } + + public void actionPerformed(ActionEvent arg0) { + if(curCall>=times || (fadeTimer!=null && !isEnabled())){ + setBackground(targetColor); + fadeTimer.stop(); + fadeTimer=null; + setOpaque(false); + }else{ + setBackground(combine(targetColor,fromColor,((double)curCall)/((double)times))); + curCall++; + } + updateUI(); + } + + } + +} diff --git a/src/org/jalgo/module/unifikation/algo/view/package-info.java b/src/org/jalgo/module/unifikation/algo/view/package-info.java new file mode 100644 index 0000000..07e9de8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/algo/view/package-info.java @@ -0,0 +1,5 @@ +/** + * GUI for the algorithm view + */ + +package org.jalgo.module.unifikation.algo.view; diff --git a/src/org/jalgo/module/unifikation/de.properties b/src/org/jalgo/module/unifikation/de.properties new file mode 100644 index 0000000..29a3ed3 --- /dev/null +++ b/src/org/jalgo/module/unifikation/de.properties @@ -0,0 +1 @@ +Parser.CommonError=Fehlerhafte Menge eingegeben. diff --git a/src/org/jalgo/module/unifikation/editor/ActionListeners.java b/src/org/jalgo/module/unifikation/editor/ActionListeners.java new file mode 100644 index 0000000..1633910 --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/ActionListeners.java @@ -0,0 +1,586 @@ +//JOptionPane.showMessageDialog(null, editWorkspace.getText(), "HTMLCode", JOptionPane.INFORMATION_MESSAGE); + +package org.jalgo.module.unifikation.editor; + +import java.awt.HeadlessException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.io.IOException; + +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.HTMLEditorKit; + +import org.jalgo.module.unifikation.Constants; + +public class ActionListeners { + private static boolean NumberExpected=false; + private static int PrevCaretPos=5; + private static String ErrorTextKomma = "Syntax:
          Nicht erlaubt nach:
          {, (, ','"; + private static String ErrorTextFunc = "Syntax:
          Nur erlaubt nach:
          ( oder ','"; + private static String NoErrorText = "Syntax:"; + + public static HyperlinkListener getErrorLinkListener(final Editor TheEdit) + { + HyperlinkListener hl = new HyperlinkListener() + { + public void hyperlinkUpdate(HyperlinkEvent e) { + if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) + { + String link = (String) ((AttributeSet) e.getSourceElement().getAttributes().getAttribute(HTML.Tag.A)).getAttribute(HTML.Attribute.HREF); + TheEdit.editWorkspace.requestFocus(); + TheEdit.editWorkspace.setCaretPosition(Integer.parseInt(link)); + } + } + }; + return hl; + } + + public static CaretListener getEditCaretListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + CaretListener cl = new CaretListener(){ + public void caretUpdate(CaretEvent e) { + if(NumberExpected==true) + { + try { + NumberExpected=false; + editWorkspace.getDocument().remove(PrevCaretPos, 1); + } catch (BadLocationException e1) { + e1.printStackTrace(); + } + } + NumberExpected=false; + PrevCaretPos=e.getDot(); + //Wenn Cursor vor { dann springe nach { + if(e.getDot()<4) + editWorkspace.setCaretPosition(4); + //Wenn Cursor nach } dann springe vor } + if(e.getDot()==(editWorkspace.getDocument().getLength())) + editWorkspace.setCaretPosition(editWorkspace.getDocument().getLength()-1); + //Wenn SelectionStart vor { beginnt -> SetCursor nach { + if(editWorkspace.getSelectionStart()<4) + editWorkspace.setCaretPosition(4); + //Wenn SelectionEnd nach } -> SetCursor vor } + if(editWorkspace.getSelectionEnd()==editWorkspace.getDocument().getLength()) + editWorkspace.setCaretPosition(editWorkspace.getDocument().getLength()-1); + + }}; + return cl; + } + + public static KeyListener getEditKeyListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + KeyListener kl = new KeyListener(){ + public void keyPressed(KeyEvent e) { + //Kein strg+v + if(e.getKeyCode()==86) + {e.consume();return;} + //Wenn Backspace hinter { -> Consume + if((e.getKeyChar()==KeyEvent.VK_BACK_SPACE) && (editWorkspace.getCaretPosition()==4) ) + {e.consume();return;} + //Wenn Enft vor } -> Consume + if((e.getKeyChar()==KeyEvent.VK_DELETE) && (editWorkspace.getCaretPosition()>=editWorkspace.getDocument().getLength()-1) ) + {e.consume();return;} + //Wenn Selection vor { -> consume alles + if(editWorkspace.getSelectionStart()<4) + {e.consume();return;} + //Wenn Selection nach } -> Consume alles + if(editWorkspace.getSelectionEnd()==editWorkspace.getDocument().getLength()) + {e.consume();return;} + //Enter fällt aus + if(e.getKeyChar()==KeyEvent.VK_ENTER) + {e.consume();return;} + //Tab fällt aus + if(e.getKeyChar()==KeyEvent.VK_TAB) + {e.consume();return;} + //Del bei Index erwartet + if(NumberExpected==true && e.getKeyChar()==KeyEvent.VK_BACK_SPACE) + { + try { + NumberExpected=false; + editWorkspace.getDocument().remove(PrevCaretPos-1, 2); + } catch (BadLocationException e1) { + e1.printStackTrace(); + } + e.consume(); + } + + TheEdit.getApplication().notifyChange(); + } + + public void keyReleased(KeyEvent e) {} + + public void keyTyped(KeyEvent e) { + TheEdit.getErrors(); + TheEdit.getApplication().notifyChange(); + //Wenn Selection vor { -> consume alles (Buchstaben) + if(editWorkspace.getSelectionStart()<4) + {e.consume();return;} + //Wenn Selection nach } -> Consume alles (Buchstaben) + if(editWorkspace.getSelectionEnd()==editWorkspace.getDocument().getLength()) + {e.consume();return;} + //Buchstaben abfangen + char key = e.getKeyChar(); + switch(key){ + case 'a': + writeFunction(Constants.ALPHA,TheEdit); + e.consume(); + break; + case 'b': + writeFunction(Constants.BETA,TheEdit); + e.consume(); + break; + case 'g': + writeFunction(Constants.GAMMA,TheEdit); + e.consume(); + break; + case 'd': + writeFunction(Constants.DELTA,TheEdit); + e.consume(); + break; + case 'e': + writeFunction(Constants.EPSILON,TheEdit); + e.consume(); + break; + case 't': + writeFunction(Constants.THETA,TheEdit); + e.consume(); + break; + case 'u': + writeLetter("u",TheEdit); + e.consume(); + break; + case 'v': + writeLetter("v",TheEdit); + e.consume(); + break; + case 'w': + writeLetter("w",TheEdit); + e.consume(); + break; + case 'x': + writeLetter("x",TheEdit); + e.consume(); + break; + case 'y': + writeLetter("y",TheEdit); + e.consume(); + break; + case 'z': + writeLetter("z",TheEdit); + e.consume(); + break; + case ',': + writeKomma(TheEdit); + e.consume(); + break; + case 'p': + writeLetter("p",TheEdit); + e.consume(); + break; + case 'n': + writeNumber(Constants.Placeholder,TheEdit); + e.consume(); + break; + case '(': + writeLetter("(",TheEdit); + e.consume(); + break; + case ')': + writeLetter(")",TheEdit); + e.consume(); + break; + case '1': + writeNumber("1",TheEdit); + e.consume(); + break; + case '2': + writeNumber("2",TheEdit); + e.consume(); + break; + case '3': + writeNumber("3",TheEdit); + e.consume(); + break; + case '4': + writeNumber("4",TheEdit); + e.consume(); + break; + case '5': + writeNumber("5",TheEdit); + e.consume(); + break; + case '6': + writeNumber("6",TheEdit); + e.consume(); + break; + case '7': + writeNumber("7",TheEdit); + e.consume(); + break; + case '8': + writeNumber("8",TheEdit); + e.consume(); + break; + case '9': + writeNumber("9",TheEdit); + e.consume(); + break; + + default: + //editWorkspace.setText(e.toString()); + e.consume(); + break; + } + }}; + return kl; + } + + public static ActionListener getButtonFunctionListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + writeFunction(((JButton)e.getSource()).getText().substring(0,1),TheEdit); + editWorkspace.requestFocus(); + } + }; + return al; + } + + public static ActionListener getButtonLetterListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + writeLetter(((JButton)e.getSource()).getText(),TheEdit); + editWorkspace.requestFocus(); + } + }; + + return al; + } + + public static ActionListener getButtonKommaListener(final Editor TheEdit) + { + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + writeKomma(TheEdit); + } + }; + + return al; + } + + public static ActionListener getButtonNPairListener(final Editor TheEdit) + { + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + writeLetter("p",TheEdit); + } + }; + + return al; + } + + public static ActionListener getButtonBackSpaceListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + editWorkspace.dispatchEvent(new KeyEvent(editWorkspace, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),0,8, (char) KeyEvent.VK_BACK_SPACE)); + TheEdit.getErrors(); + editWorkspace.requestFocus(); + TheEdit.getApplication().notifyChange(); + } + }; + + return al; + } + + public static ActionListener getButtonDelListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + editWorkspace.dispatchEvent(new KeyEvent(editWorkspace, KeyEvent.KEY_PRESSED, System.currentTimeMillis(),0,127, (char) KeyEvent.VK_DELETE)); + TheEdit.getErrors(); + editWorkspace.requestFocus(); + TheEdit.getApplication().notifyChange(); + } + }; + + return al; + } + + //ATTENTION + public static ActionListener getButtonX1234Listener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + final HTMLEditorKit editWorkspaceKit = (HTMLEditorKit)TheEdit.editWorkspace.getEditorKit(); + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + try { + if(validationTestFuncChar(editWorkspace.getDocument().getText(editWorkspace.getCaretPosition()-1, 2))) + { + String bttext = ((JButton)e.getSource()).getText(); + bttext= bttext.substring(6, bttext.length()-7); + editWorkspaceKit.insertHTML((HTMLDocument) editWorkspace.getDocument(), editWorkspace.getCaretPosition(), ""+bttext+"", 0, 0, HTML.Tag.SPAN); + TheEdit.getApplication().notifyChange(); + TheEdit.lblSyntax.setText(NoErrorText); + TheEdit.getErrors(); + }else TheEdit.lblSyntax.setText(ErrorTextFunc); + } catch (BadLocationException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + editWorkspace.requestFocus(); + } + }; + return al; + } + + public static ActionListener getButtonXNListener(final Editor TheEdit) + { + final JEditorPane editWorkspace = TheEdit.editWorkspace; + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + writeNumber(Constants.Placeholder,TheEdit); + editWorkspace.requestFocus(); + } + }; + + return al; + } + + public static ActionListener getButtonHelpListener(final Editor TheEdit) + { + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + if(TheEdit.contentPane.getLayout().equals(TheEdit.helpLayout)) + TheEdit.contentPane.setLayout(TheEdit.noHelpLayout); + else + TheEdit.contentPane.setLayout(TheEdit.helpLayout); + + TheEdit.contentPane.updateUI(); + } + }; + return al; + } + + public static ActionListener getButtonStartListener(final Editor TheEdit) + { + ActionListener al = new ActionListener(){ + public void actionPerformed(ActionEvent e) { + try { + TheEdit.doStart(); + } catch (HeadlessException e1) { + e1.printStackTrace(); + } + } + }; + + return al; + } + + private static boolean validationTestFuncChar(String Characters) + { + switch(Characters.toCharArray()[1]) + { + case 'x': + return false; + case 'y': + return false; + case 'z': + return false; + case 'u': + return false; + case 'v': + return false; + case 'w': + return false; + } + //JAlgoGUIConnector.getInstance().showInfoMessage(String.valueOf(Characters.toCharArray()[1])); + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.ALPHA)) + return false; + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.BETA)) + return false; + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.GAMMA)) + return false; + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.DELTA)) + return false; + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.EPSILON)) + return false; + if(String.valueOf(Characters.toCharArray()[1]).equals(Constants.THETA)) + return false; + + switch(Characters.toCharArray()[0]) + { + case '(': + return true; + case ',': + return true; + } + return false; + } + + private static boolean validationTestKomma(String Characters) + { + if(Characters.toCharArray()[0]=='(' && Characters.toCharArray()[1]==')') + return true; + + switch(Characters.toCharArray()[0]) + { + case '(': + return false; + case ',': + return false; + case '{': + return false; + } + return true; + } + + private static void writeNumber(String Number,Editor TheEdit) + { + final JEditorPane editWorkspace =TheEdit.editWorkspace; + if(NumberExpected==true) + { + NumberExpected=false; + final HTMLEditorKit editWorkspaceKit = (HTMLEditorKit)TheEdit.editWorkspace.getEditorKit(); + + try { + editWorkspace.getDocument().remove(editWorkspace.getCaretPosition()-1, 2); + editWorkspaceKit.insertHTML((HTMLDocument) editWorkspace.getDocument(), editWorkspace.getCaretPosition(), "x"+Number+"", 0, 0, HTML.Tag.SPAN); + TheEdit.getApplication().notifyChange(); + TheEdit.getErrors(); + } catch (BadLocationException e1) {e1.printStackTrace(); + } catch (IOException e1) {e1.printStackTrace(); + } + }else + { + final HTMLEditorKit editWorkspaceKit = (HTMLEditorKit)TheEdit.editWorkspace.getEditorKit(); + try { + if(validationTestFuncChar(editWorkspace.getDocument().getText(editWorkspace.getCaretPosition()-1, 2))) + { + editWorkspaceKit.insertHTML((HTMLDocument) editWorkspace.getDocument(), editWorkspace.getCaretPosition(), "x"+Number+"", 0, 0, HTML.Tag.SPAN); + if(Number.equals(Constants.Placeholder)) + { + editWorkspace.setCaretPosition(editWorkspace.getCaretPosition()-1); + NumberExpected=true; + } + TheEdit.getApplication().notifyChange(); + TheEdit.lblSyntax.setText(NoErrorText); + }else TheEdit.lblSyntax.setText(ErrorTextFunc); + TheEdit.getErrors(); + } catch (BadLocationException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + + private static void writeKomma(Editor TheEdit) + { + final JEditorPane editWorkspace =TheEdit.editWorkspace; + if(NumberExpected==true) + { + NumberExpected=false; + try { + editWorkspace.getDocument().remove(editWorkspace.getCaretPosition(), 1); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + try { + if(validationTestKomma(editWorkspace.getDocument().getText(editWorkspace.getCaretPosition()-1, 2))) + { + editWorkspace.getDocument().insertString(editWorkspace.getCaretPosition(),",", null); + TheEdit.getApplication().notifyChange(); + TheEdit.lblSyntax.setText(NoErrorText); + TheEdit.getErrors(); + }else TheEdit.lblSyntax.setText(ErrorTextKomma); + } catch (BadLocationException e1) { + e1.printStackTrace(); + } + editWorkspace.requestFocus(); + } + + private static void writeLetter(String Letter,Editor TheEdit) + { + final JEditorPane editWorkspace =TheEdit.editWorkspace; + if(NumberExpected==true) + { + NumberExpected=false; + try { + editWorkspace.getDocument().remove(editWorkspace.getCaretPosition(), 1); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } + try { + if(Letter.equals("(") || Letter.equals(")") ) + { + editWorkspace.getDocument().insertString(editWorkspace.getCaretPosition(),Letter, null); + editWorkspace.requestFocus(); + TheEdit.getApplication().notifyChange(); + TheEdit.getErrors(); + return; + } + if(Letter.equals("p")) + { + editWorkspace.getDocument().insertString(editWorkspace.getCaretPosition(),"(,)", null); + editWorkspace.setCaretPosition(editWorkspace.getCaretPosition()-2); + editWorkspace.requestFocus(); + TheEdit.getApplication().notifyChange(); + TheEdit.getErrors(); + return; + } + if(validationTestFuncChar(editWorkspace.getDocument().getText(editWorkspace.getCaretPosition()-1, 2))) + { + try { + final HTMLEditorKit editWorkspaceKit = (HTMLEditorKit)TheEdit.editWorkspace.getEditorKit(); + editWorkspaceKit.insertHTML((HTMLDocument) editWorkspace.getDocument(), editWorkspace.getCaretPosition(), ""+Letter+"", 0, 0, HTML.Tag.SPAN); + } catch (IOException e) {e.printStackTrace();} + TheEdit.getApplication().notifyChange(); + TheEdit.lblSyntax.setText(NoErrorText); + TheEdit.getErrors(); + }else TheEdit.lblSyntax.setText(ErrorTextFunc); + } catch (BadLocationException e1) {e1.printStackTrace();} + } + + private static void writeFunction(String Letter,Editor TheEdit) + { + final JEditorPane editWorkspace =TheEdit.editWorkspace; + final HTMLEditorKit editWorkspaceKit = (HTMLEditorKit)TheEdit.editWorkspace.getEditorKit(); + try { + if(validationTestFuncChar(editWorkspace.getDocument().getText(editWorkspace.getCaretPosition()-1, 2))) + { + try { + editWorkspaceKit.insertHTML((HTMLDocument) editWorkspace.getDocument(), editWorkspace.getCaretPosition(), ""+Letter+"()", 0, 0, HTML.Tag.SPAN); + } catch (IOException e) {e.printStackTrace();} + + editWorkspace.setCaretPosition(editWorkspace.getCaretPosition()-1); + + TheEdit.getApplication().notifyChange(); + TheEdit.lblSyntax.setText(NoErrorText); + TheEdit.getErrors(); + }else TheEdit.lblSyntax.setText(ErrorTextFunc); + } catch (BadLocationException e1) {e1.printStackTrace();} + } + +} diff --git a/src/org/jalgo/module/unifikation/editor/CVS/Entries b/src/org/jalgo/module/unifikation/editor/CVS/Entries new file mode 100644 index 0000000..0d05ef4 --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/CVS/Entries @@ -0,0 +1,4 @@ +/ActionListeners.java/1.1/Mon Aug 16 12:05:48 2010// +/Editor.java/1.1/Mon Aug 16 12:05:48 2010// +/VKeyboard.java/1.1/Mon Aug 16 12:05:48 2010// +/package-info.java/1.1/Mon Aug 16 12:05:48 2010// diff --git a/src/org/jalgo/module/unifikation/editor/CVS/Repository b/src/org/jalgo/module/unifikation/editor/CVS/Repository new file mode 100644 index 0000000..a38a79b --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/editor diff --git a/src/org/jalgo/module/unifikation/editor/CVS/Root b/src/org/jalgo/module/unifikation/editor/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/editor/Editor.java b/src/org/jalgo/module/unifikation/editor/Editor.java new file mode 100644 index 0000000..36f3b3c --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/Editor.java @@ -0,0 +1,247 @@ +package org.jalgo.module.unifikation.editor; + +import java.awt.Color; +import java.io.IOException; +import java.util.List; + +import javax.swing.BorderFactory; +import javax.swing.GroupLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JToolBar; +import javax.swing.SwingConstants; +import javax.swing.text.BadLocationException; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.StyleSheet; + +import org.jalgo.main.util.Messages; +import org.jalgo.module.unifikation.Application; +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.IAppView; +import org.jalgo.module.unifikation.algo.model.Formating; +import org.jalgo.module.unifikation.parser.ISetParser; +import org.jalgo.module.unifikation.parser.ParserError; +import org.jalgo.module.unifikation.parser.SetParser; + +/* + * editor class + * initializes the editor and works as a connector to application + */ +public class Editor implements IAppView { + private Application app=null; + public JEditorPane editWorkspace; + public JEditorPane lblSyntax; + public GroupLayout helpLayout; + public GroupLayout noHelpLayout; + public JComponent contentPane; + + public void setApplication(Application app) { + this.app=app; + } + + public Application getApplication() { + return app; + } + + /** + * Write ParseErros at the SyntaxLbl + */ + public void getErrors() + { + ISetParser parser=new SetParser(); + String text=editWorkspace.getText(); + parser.parse(text); + List errors=parser.getErrors(); + StringBuffer errorString=new StringBuffer(); + if(errors!=null && errors.size()>0){ + errorString.append("Syntax:
          "); + for(ParserError error:errors){ + Integer pos = error.getPosition()+1; + switch (error.getType()) + { + case ParserError: + errorString.append(""+error.getType()+" an Postion "+pos+"
          "); + break; + case InvalidArity: + try { + errorString.append(""+error.getType()+" von "+editWorkspace.getDocument().getText(error.getPosition()+1,1)+" an Postion "+pos +"
          "); + } catch (BadLocationException e) { + e.printStackTrace(); + } + break; + } + } + errorString.append(""); + }else errorString.append("g" + Constants.lowercasedUE + "ltiger Ausdruck"); + lblSyntax.setText(errorString.toString()); + } + + /** + * Starts the AlgoView if no ParserError appears + */ + public void doStart(){ + ISetParser parser=new SetParser(); + String text=editWorkspace.getText(); + if(parser.parse(text)){ + app.setFinished(text); + }else{ + getErrors(); + } + } + + /* + * Gets the contentPane so it can create the GUI + */ + public void setContentPane(JComponent contentPane) { + + this.contentPane=contentPane; + //Create HelpLabel + String HelpText = "Anleitung
          " + + "Erstellen Sie hier die Menge f" + Constants.lowercasedUE + "r die Unifikationsaufgabe. " + + "Benutzen Sie dazu entweder die virtuelle Tastatur unter dem Eingabebereich" + + " oder ihre echte Tastatur. Fahren Sie mit der Maus " + Constants.lowercasedUE + "ber die virtuellen Tasten, um die" + + " entsprechenden echten Tasten anzuzeigen.

          Sind Sie mit dem Erstellen fertig," + + " klicken Sie auf \"Start\", um das Unifikationsproblem zu l" + Constants.lowercasedOE + "sen.

          " + + "Beispiel:
          " + + "M={(x, u),(x, "+Constants.ALPHA+"( y, x1))}

          Sollte es bei der Eingabe zu Syntaxfehlern kommen, k"+Constants.lowercasedOE+"nnen Sie unten " + + "rechts auf den Fehler klicken und der Cursor springt an die angegebene Position."; + JLabel lblHelp = new JLabel(HelpText); + lblHelp.setBackground(new Color(255,255,128)); + lblHelp.setOpaque(true); + lblHelp.setVerticalAlignment(SwingConstants.TOP); + lblHelp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + lblHelp.setFont(Constants.TextFont); + + //Toolbar deaktivieren + app.installToolbar(); + app.disableToolbar(); + + //Create SyntaxErrorLabel + lblSyntax = new JEditorPane("text/html","" + + "Syntax:"); + lblSyntax.setOpaque(false); + lblSyntax.setEditable(false); + lblSyntax.setBackground(new Color(224,223,227)); + //lblSyntax.setVerticalAlignment(SwingConstants.TOP); + lblSyntax.setBorder(null); + lblSyntax.addHyperlinkListener(ActionListeners.getErrorLinkListener(this)); + + JScrollPane scrollSyntax = new JScrollPane(lblSyntax); + scrollSyntax.setBorder(null); + //Create StartButton + JButton btnStart = new JButton("Start"); + btnStart.setFont(Constants.ButtonFont); + btnStart.addActionListener(ActionListeners.getButtonStartListener(this)); + + //Create Workspace + editWorkspace = new JEditorPane(); + + HTMLEditorKit editWorkspaceKit = new HTMLEditorKit(); + HTMLDocument editWorkspaceDoc = new HTMLDocument(); + + editWorkspace.setEditorKit(editWorkspaceKit); + editWorkspace.setDocument(editWorkspaceDoc); + //editWorkspace.setBorder(BorderFactory.createMatteBorder( + //1, 1, 1, 1, Color.red)); + + try { + editWorkspaceKit.insertHTML(editWorkspaceDoc, 0, app.getProblem(), 0, 0, null); + } catch (BadLocationException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + editWorkspace.setCaretPosition(editWorkspace.getDocument().getLength()-3); + editWorkspace.addCaretListener(ActionListeners.getEditCaretListener(this)); + editWorkspace.addKeyListener(ActionListeners.getEditKeyListener(this)); + + //Create VirtualKeyBoard + JPanel panTastatur = VKeyboard.getVKeyboard(this); + + //Create ToggelHelp Toolbar + JToolBar toolbar = app.toolbar; + JButton button = new JButton( + new ImageIcon(Messages.getResourceURL("main", "ui.Help_contents"))); + button.setToolTipText("Editorhilfe einblenden"); + button.addActionListener(ActionListeners.getButtonHelpListener(this)); + toolbar.add(button); + + //Setup NoHelpLayout + noHelpLayout = new GroupLayout((JComponent)contentPane); + noHelpLayout.setVerticalGroup(noHelpLayout.createSequentialGroup() + .addContainerGap(12, 12) + .addComponent(editWorkspace, 0, 129, Short.MAX_VALUE) + .addGap(5) + .addGroup(noHelpLayout.createParallelGroup() + .addGroup(GroupLayout.Alignment.LEADING, noHelpLayout.createSequentialGroup() + .addComponent(btnStart, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE) + .addComponent(scrollSyntax, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) + .addComponent(panTastatur, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE))); + noHelpLayout.setHorizontalGroup(noHelpLayout.createSequentialGroup() + .addGap(12) + .addGroup(noHelpLayout.createParallelGroup() + .addGroup(GroupLayout.Alignment.LEADING, noHelpLayout.createSequentialGroup() + .addComponent(panTastatur, 0, 161, Short.MAX_VALUE) + .addGap(7) + .addGroup(noHelpLayout.createParallelGroup() + .addComponent(scrollSyntax, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) + .addComponent(btnStart, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE))) + .addComponent(editWorkspace, GroupLayout.Alignment.LEADING, 0, 368, Short.MAX_VALUE)) + .addGap(12)); + + //Setup HelpLayout + helpLayout = new GroupLayout((JComponent)contentPane); + helpLayout.setVerticalGroup(helpLayout.createSequentialGroup() + .addContainerGap(12, 12) + .addGroup(helpLayout.createParallelGroup() + .addComponent(lblHelp, GroupLayout.Alignment.LEADING, 0, 18, Short.MAX_VALUE) + .addComponent(editWorkspace, GroupLayout.Alignment.LEADING, 0, 18, Short.MAX_VALUE)) + .addGap(5) + .addGroup(helpLayout.createParallelGroup() + .addGroup(GroupLayout.Alignment.LEADING, helpLayout.createSequentialGroup() + .addComponent(btnStart, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE) + .addComponent(scrollSyntax, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)) + .addComponent(panTastatur, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE))); + helpLayout.setHorizontalGroup(helpLayout.createSequentialGroup() + .addGap(12) + .addGroup(helpLayout.createParallelGroup() + .addComponent(panTastatur, GroupLayout.Alignment.LEADING, 0, 235, Short.MAX_VALUE) + .addComponent(editWorkspace, GroupLayout.Alignment.LEADING, 0, 235, Short.MAX_VALUE)) + .addGap(7) + .addGroup(helpLayout.createParallelGroup() + .addGroup(GroupLayout.Alignment.LEADING, helpLayout.createSequentialGroup() + .addComponent(btnStart, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)) + .addGroup(GroupLayout.Alignment.LEADING, helpLayout.createSequentialGroup() + .addComponent(lblHelp, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE)) + .addGroup(GroupLayout.Alignment.LEADING, helpLayout.createSequentialGroup() + .addComponent(scrollSyntax, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) + .addGap(12)))); + + contentPane.setLayout(helpLayout); + this.updateSetView(); + editWorkspace.requestFocus(); + } + + public void updateSetView() { + HTMLDocument editWorkspaceDoc = (HTMLDocument) this.editWorkspace.getDocument(); + StyleSheet editWorkspaceSS = editWorkspaceDoc.getStyleSheet(); + if(Formating.isBeamerMode()==true) + { + editWorkspaceSS.addRule(Constants.BBodyCSS); + contentPane.setLayout(noHelpLayout); + }else + { + editWorkspaceSS.addRule(Constants.NBodyCSS); + } + } + + public void setHelpText(String helpText) { + } + +} diff --git a/src/org/jalgo/module/unifikation/editor/VKeyboard.java b/src/org/jalgo/module/unifikation/editor/VKeyboard.java new file mode 100644 index 0000000..5e28d5c --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/VKeyboard.java @@ -0,0 +1,243 @@ +package org.jalgo.module.unifikation.editor; + + +import java.awt.Font; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JPanel; + +import org.jalgo.module.unifikation.Constants; + + +public class VKeyboard { + public static JPanel getVKeyboard(final Editor TheEdit){ + JPanel panKeyboard = new JPanel(); + panKeyboard.setLayout(null); + //panKeyboard.setBackground(new Color(123,123,123)); + + //Tasten erstellen + //////////////ZEILE1///////////////////////////////////// + JButton btnAlpha = new JButton(Constants.ALPHA+"()"); + btnAlpha.setToolTipText("Taste: a"); + btnAlpha.setSize(Constants.ButtonSize); + btnAlpha.setFont(Constants.ButtonFont); + btnAlpha.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnAlpha.setLocation(0*(Constants.ButtonSize.width+Constants.ButtonGap), 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnAlpha.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnBeta = new JButton(Constants.BETA+"()"); + btnBeta.setToolTipText("Taste: b"); + btnBeta.setSize(Constants.ButtonSize); + btnBeta.setFont(Constants.ButtonFont); + btnBeta.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnBeta.setLocation(1*(Constants.ButtonSize.width+Constants.ButtonGap), 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnBeta.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnGamma = new JButton(Constants.GAMMA+"()"); + btnGamma.setToolTipText("Taste: g"); + btnGamma.setSize(Constants.ButtonSize); + btnGamma.setFont(Constants.ButtonFont); + btnGamma.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnGamma.setLocation(2*(Constants.ButtonSize.width+Constants.ButtonGap), 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnGamma.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnDelta = new JButton(Constants.DELTA+"()"); + btnDelta.setToolTipText("Taste: d"); + btnDelta.setSize(Constants.ButtonSize); + btnDelta.setFont(Constants.ButtonFont); + btnDelta.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnDelta.setLocation(3*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnDelta.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnEpsilon = new JButton(Constants.EPSILON+"()"); + btnEpsilon.setToolTipText("Taste: e"); + btnEpsilon.setSize(Constants.ButtonSize); + btnEpsilon.setFont(Constants.ButtonFont); + btnEpsilon.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnEpsilon.setLocation(4*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnEpsilon.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnTheta = new JButton(Constants.THETA+"()"); + btnTheta.setToolTipText("Taste: t"); + btnTheta.setSize(Constants.ButtonSize); + btnTheta.setFont(Constants.ButtonFont); + btnTheta.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnTheta.setLocation(5*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnTheta.addActionListener(ActionListeners.getButtonFunctionListener(TheEdit)); + + JButton btnNPair = new JButton("( , )"); + btnNPair.setToolTipText("Taste: p"); + btnNPair.setSize(Constants.ButtonSize); + btnNPair.setFont(Constants.ButtonFont); + btnNPair.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnNPair.setLocation(6*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnNPair.addActionListener(ActionListeners.getButtonNPairListener(TheEdit)); + + JButton btnKomma = new JButton(","); + btnKomma.setSize(Constants.ButtonSize); + btnKomma.setFont(Constants.ButtonFont); + btnKomma.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnKomma.setLocation(7*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 0*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnKomma.addActionListener(ActionListeners.getButtonKommaListener(TheEdit)); + + //////////////ZEILE2///////////////////////////////////// + JButton btnX = new JButton("x"); + btnX.setToolTipText("Taste: x"); + btnX.setSize(Constants.ButtonSize); + btnX.setFont(Constants.ButtonFont); + btnX.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX.setLocation(0*(Constants.ButtonSize.width+Constants.ButtonGap), 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnY = new JButton("y"); + btnY.setToolTipText("Taste: y"); + btnY.setSize(Constants.ButtonSize); + btnY.setFont(Constants.ButtonFont); + btnY.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnY.setLocation(1*(Constants.ButtonSize.width+Constants.ButtonGap), 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnY.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnZ = new JButton("z"); + btnZ.setToolTipText("Taste: z"); + btnZ.setSize(Constants.ButtonSize); + btnZ.setFont(Constants.ButtonFont); + btnZ.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnZ.setLocation(2*(Constants.ButtonSize.width+Constants.ButtonGap), 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnZ.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnU = new JButton("u"); + btnU.setToolTipText("Taste: u"); + btnU.setSize(Constants.ButtonSize); + btnU.setFont(Constants.ButtonFont); + btnU.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnU.setLocation(3*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnU.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnV = new JButton("v"); + btnV.setToolTipText("Taste: v"); + btnV.setSize(Constants.ButtonSize); + btnV.setFont(Constants.ButtonFont); + btnV.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnV.setLocation(4*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnV.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnW = new JButton("w"); + btnW.setToolTipText("Taste: w"); + btnW.setSize(Constants.ButtonSize); + btnW.setFont(Constants.ButtonFont); + btnW.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnW.setLocation(5*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnW.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnBackspace = new JButton("\u2190"); + btnBackspace.setToolTipText("Taste: \u2190"); + btnBackspace.setSize(Constants.ButtonSize); + btnBackspace.setFont(new Font("Times New Roman",Font.PLAIN,14)); + btnBackspace.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnBackspace.setLocation(6*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnBackspace.addActionListener(ActionListeners.getButtonBackSpaceListener(TheEdit)); + + JButton btnDelete = new JButton("Entf"); + btnDelete.setToolTipText("Taste: Entf"); + btnDelete.setSize(Constants.ButtonSize); + btnDelete.setFont(Constants.ButtonFont); + btnDelete.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnDelete.setLocation(7*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 1*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnDelete.addActionListener(ActionListeners.getButtonDelListener(TheEdit)); + + //////////////ZEILE3///////////////////////////////////// + JButton btnX1 = new JButton("x1"); + btnX1.setToolTipText("Taste: 1"); + btnX1.setSize(Constants.ButtonSize); + btnX1.setFont(Constants.ButtonFont); + btnX1.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX1.setLocation(0*(Constants.ButtonSize.width+Constants.ButtonGap), 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX1.addActionListener(ActionListeners.getButtonX1234Listener(TheEdit)); + + JButton btnX2 = new JButton("x2"); + btnX2.setToolTipText("Taste: 2"); + btnX2.setSize(Constants.ButtonSize); + btnX2.setFont(Constants.ButtonFont); + btnX2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX2.setLocation(1*(Constants.ButtonSize.width+Constants.ButtonGap), 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX2.addActionListener(ActionListeners.getButtonX1234Listener(TheEdit)); + + JButton btnX3 = new JButton("x3"); + btnX3.setToolTipText("Taste: 3"); + btnX3.setSize(Constants.ButtonSize); + btnX3.setFont(Constants.ButtonFont); + btnX3.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX3.setLocation(2*(Constants.ButtonSize.width+Constants.ButtonGap), 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX3.addActionListener(ActionListeners.getButtonX1234Listener(TheEdit)); + + JButton btnX4 = new JButton("x4"); + btnX4.setToolTipText("Taste: 4"); + btnX4.setSize(Constants.ButtonSize); + btnX4.setFont(Constants.ButtonFont); + btnX4.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX4.setLocation(3*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX4.addActionListener(ActionListeners.getButtonX1234Listener(TheEdit)); + + JButton btnX5 = new JButton("x5"); + btnX5.setToolTipText("Taste: 5"); + btnX5.setSize(Constants.ButtonSize); + btnX5.setFont(Constants.ButtonFont); + btnX5.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnX5.setLocation(4*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnX5.addActionListener(ActionListeners.getButtonX1234Listener(TheEdit)); + + JButton btnXN = new JButton("xn"); + btnXN.setToolTipText("Taste: n"); + btnXN.setSize(Constants.ButtonSize); + btnXN.setFont(Constants.ButtonFont); + btnXN.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnXN.setLocation(5*(Constants.ButtonSize.width+Constants.ButtonGap)+15, 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnXN.addActionListener(ActionListeners.getButtonXNListener(TheEdit)); + + JButton btnCL = new JButton("("); + btnCL.setToolTipText("Taste: ("); + btnCL.setSize(Constants.ButtonSize); + btnCL.setFont(Constants.ButtonFont); + btnCL.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnCL.setLocation(6*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnCL.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + JButton btnCR = new JButton(")"); + btnCR.setToolTipText("Taste: )"); + btnCR.setSize(Constants.ButtonSize); + btnCR.setFont(Constants.ButtonFont); + btnCR.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); + btnCR.setLocation(7*(Constants.ButtonSize.width+Constants.ButtonGap)+30, 2*(Constants.ButtonSize.height+Constants.ButtonGap)); + btnCR.addActionListener(ActionListeners.getButtonLetterListener(TheEdit)); + + //Tasten anfügen + panKeyboard.add(btnAlpha); + panKeyboard.add(btnBeta); + panKeyboard.add(btnGamma); + panKeyboard.add(btnDelta); + panKeyboard.add(btnEpsilon); + panKeyboard.add(btnTheta); + panKeyboard.add(btnNPair); + panKeyboard.add(btnKomma); + panKeyboard.add(btnX); + panKeyboard.add(btnY); + panKeyboard.add(btnZ); + panKeyboard.add(btnU); + panKeyboard.add(btnV); + panKeyboard.add(btnW); + panKeyboard.add(btnBackspace); + panKeyboard.add(btnDelete); + panKeyboard.add(btnX1); + panKeyboard.add(btnX2); + panKeyboard.add(btnX3); + panKeyboard.add(btnX4); + panKeyboard.add(btnX5); + panKeyboard.add(btnXN); + panKeyboard.add(btnCL); + panKeyboard.add(btnCR); + + return panKeyboard; + } + +} diff --git a/src/org/jalgo/module/unifikation/editor/package-info.java b/src/org/jalgo/module/unifikation/editor/package-info.java new file mode 100644 index 0000000..403f92b --- /dev/null +++ b/src/org/jalgo/module/unifikation/editor/package-info.java @@ -0,0 +1,5 @@ +/** + * GUI for the editor view + */ + +package org.jalgo.module.unifikation.editor; diff --git a/src/org/jalgo/module/unifikation/junit/CVS/Entries b/src/org/jalgo/module/unifikation/junit/CVS/Entries new file mode 100644 index 0000000..291a9ec --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/CVS/Entries @@ -0,0 +1,3 @@ +/TestRules.java/1.1/Mon Aug 16 12:05:49 2010// +/TestSetParser.java/1.1/Mon Aug 16 12:05:49 2010// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/unifikation/junit/CVS/Repository b/src/org/jalgo/module/unifikation/junit/CVS/Repository new file mode 100644 index 0000000..28fec93 --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/junit diff --git a/src/org/jalgo/module/unifikation/junit/CVS/Root b/src/org/jalgo/module/unifikation/junit/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/junit/TestRules.java b/src/org/jalgo/module/unifikation/junit/TestRules.java new file mode 100644 index 0000000..f30605c --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/TestRules.java @@ -0,0 +1,324 @@ +package org.jalgo.module.unifikation.junit; + +import static org.junit.Assert.*; + +import org.jalgo.module.unifikation.Constants; +import org.jalgo.module.unifikation.algo.model.ConstructorSymbol; +import org.jalgo.module.unifikation.algo.model.ITerm; +import org.jalgo.module.unifikation.algo.model.Pair; +import org.jalgo.module.unifikation.algo.model.ProblemSet; +import org.jalgo.module.unifikation.algo.model.Variable; +import org.junit.Before; +import org.junit.Test; + +public class TestRules { + //already existing terms: x,y,z,u,alpha,beta,gamma,delta + //alpha(x),alpha(z),beta(z),alpha(beta()),alpha(beta(z)) + //delta(z),beta(delta(z)) + + private Pair substPair1; + private Pair substPair2; + private Pair substPair3; + private Pair substPair4; + private Pair substPair5; + private Pair substPair6; + private Pair substPair7; + private Pair decompPair1; + private Pair decompPair2; + private Pair decompPair3; + private Pair decompPair4; + private Pair elimPair1; + private Pair elimPair2; + private Pair elimPair3; + private Pair elimPair4; + private Pair elimPair5; + private Pair swapPair1; + private Pair swapPair2; + private Pair swapPair3; + private Pair swapPair4; + private Pair swapPair5; + private Pair swapPair6; + private Pair swapPair1Result; + private Pair swapPair2Result; + private Pair swapPair3Result; + private Pair swapPair4Result; + private Pair swapPair5Result; + private Pair swapPair6Result; + + private ProblemSet problemSet; + + private Variable varX; + private Variable varY; + private Variable varZ; + private Variable varU; + + private ConstructorSymbol constrAlpha; + private ConstructorSymbol constrBeta; + + private ITerm alphaWithX; + private ITerm alphaWithZ; + private ITerm betaWithZ; + private ITerm alphaWithBeta; + private ITerm alphaWithBetaWithZ; + private ITerm deltaWithZ; + private ITerm betaWithDeltaWithZ; + + @Before + public void setUp() throws Exception { + + //term setUp + //variables + varX = new Variable("x"); + varY = new Variable("y"); + varZ = new Variable("z"); + varU = new Variable("u"); + + //constructors + constrAlpha = new ConstructorSymbol(Constants.ALPHA); + constrBeta = new ConstructorSymbol(Constants.BETA); + + //terms with arguments + alphaWithX = new ConstructorSymbol(Constants.ALPHA); + alphaWithX.addParameter(varX); + alphaWithZ = new ConstructorSymbol(Constants.ALPHA); + alphaWithZ.addParameter(varZ); + + alphaWithBeta = new ConstructorSymbol(Constants.ALPHA); + alphaWithBeta.addParameter(constrBeta); + betaWithZ = new ConstructorSymbol(Constants.BETA); + betaWithZ.addParameter(varZ); + alphaWithBetaWithZ = new ConstructorSymbol(Constants.ALPHA); + alphaWithBetaWithZ.addParameter(betaWithZ); + deltaWithZ = new ConstructorSymbol(Constants.DELTA); + deltaWithZ.addParameter(varZ); + betaWithDeltaWithZ = new ConstructorSymbol(Constants.BETA); + betaWithDeltaWithZ.addParameter(deltaWithZ); + + //pairs for rules + //substitution + substPair1 = new Pair(varX, alphaWithZ); + substPair2 = new Pair(varX, alphaWithX); + substPair3 = new Pair(alphaWithZ, varX); + substPair4 = new Pair(varX, varX); + substPair5 = new Pair(alphaWithBeta, alphaWithBetaWithZ); + substPair6 = new Pair(varU, alphaWithBetaWithZ); + substPair7 = new Pair(varU, varU); + + //decomposition + decompPair1 = new Pair(varX, varX); + decompPair2 = new Pair(alphaWithX, alphaWithZ); + decompPair3 = new Pair(betaWithDeltaWithZ, betaWithZ); + decompPair4 = new Pair(varX, varY); + + //elimination + elimPair1 = new Pair(varX, varX); + elimPair2 = new Pair(varX, varY); + elimPair3 = new Pair(varX, alphaWithX); + elimPair4 = new Pair(betaWithZ, betaWithZ); + elimPair5 = new Pair(constrAlpha, constrAlpha); + + //swap + swapPair1 = new Pair(constrAlpha, varX); + swapPair1Result = new Pair(varX, constrAlpha); + swapPair2 = new Pair(varX, constrAlpha); + swapPair2Result = new Pair(varX, constrAlpha); + swapPair3 = new Pair(varX, varX); + swapPair3Result = new Pair(varX, varX); + swapPair4 = new Pair(alphaWithBetaWithZ, varU); + swapPair4Result = new Pair(varU, alphaWithBetaWithZ); + swapPair5 = new Pair(alphaWithBeta, alphaWithX); + swapPair5Result = new Pair(alphaWithBeta, alphaWithX); + swapPair6 = new Pair(varX, varY); + swapPair6Result = new Pair(varX, varY); + + problemSet = new ProblemSet(); + } + + @Test + public void testSubstitutionCheck(){ + assertTrue(substPair1.substitutionCheck()); + assertFalse(substPair2.substitutionCheck()); + assertFalse(substPair3.substitutionCheck()); + assertFalse(substPair4.substitutionCheck()); + assertFalse(substPair5.substitutionCheck()); + assertTrue(substPair6.substitutionCheck()); + } + + @Test + public void testDecompositionCheck(){ + assertFalse(decompPair1.decompositionCheck()); + assertTrue(decompPair2.decompositionCheck()); + assertTrue(decompPair3.decompositionCheck()); + assertFalse(decompPair4.decompositionCheck()); + } + + @Test + public void testEliminationCheck(){ + assertTrue(elimPair1.eliminationCheck()); + assertFalse(elimPair2.eliminationCheck()); + assertFalse(elimPair3.eliminationCheck()); + assertFalse(elimPair4.eliminationCheck()); + assertFalse(elimPair5.eliminationCheck()); + } + + @Test + public void testSwapCheck(){ + assertTrue(swapPair1.swapCheck()); + assertFalse(swapPair2.swapCheck()); + assertFalse(swapPair3.swapCheck()); + assertTrue(swapPair4.swapCheck()); + assertFalse(swapPair5.swapCheck()); + assertFalse(swapPair6.swapCheck()); + } + + @Test + public void testSubstitution(){ + //{(x, alpha(z)) , (x, x)} + problemSet.addPair(substPair1); + problemSet.addPair(substPair4); + problemSet.setSelectedPair(0); + assertTrue(problemSet.substitution()); + + //{(x, alpha(x)) , (x, x)} + problemSet.removeAllPairs(); + problemSet.addPair(substPair2); + problemSet.addPair(substPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.substitution()); + + //{(alpha(z), x) , (x, x)} + problemSet.removeAllPairs(); + problemSet.addPair(substPair3); + problemSet.addPair(substPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.substitution()); + + //{(x, x) , (x, x)} + problemSet.removeAllPairs(); + problemSet.addPair(substPair4); + problemSet.addPair(substPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.substitution()); + + //{(alpha(beta()), gamma(x)) , (x, x)} + problemSet.removeAllPairs(); + problemSet.addPair(substPair5); + problemSet.addPair(substPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.substitution()); + + //{(u, alpha(beta(z))) , (u, u)} + problemSet.removeAllPairs(); + problemSet.addPair(substPair6); + problemSet.addPair(substPair7); + problemSet.setSelectedPair(0); + assertTrue(problemSet.substitution()); + } + + @Test + public void testDecomposition(){ + problemSet.removeAllPairs(); + problemSet.addPair(decompPair1); + problemSet.setSelectedPair(0); + assertFalse(problemSet.decomposition()); + + problemSet.removeAllPairs(); + problemSet.addPair(decompPair2); + problemSet.setSelectedPair(0); + assertTrue(problemSet.decomposition()); + + problemSet.removeAllPairs(); + problemSet.addPair(decompPair3); + problemSet.setSelectedPair(0); + assertTrue(problemSet.decomposition()); + + problemSet.removeAllPairs(); + problemSet.addPair(decompPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.decomposition()); + } + + @Test + public void testElimination(){ + problemSet.removeAllPairs(); + problemSet.addPair(elimPair1); + problemSet.setSelectedPair(0); + assertTrue(problemSet.elimination()); + + problemSet.removeAllPairs(); + problemSet.addPair(elimPair2); + problemSet.setSelectedPair(0); + assertFalse(problemSet.elimination()); + + problemSet.removeAllPairs(); + problemSet.addPair(elimPair3); + problemSet.setSelectedPair(0); + assertFalse(problemSet.elimination()); + + problemSet.removeAllPairs(); + problemSet.addPair(elimPair4); + problemSet.setSelectedPair(0); + assertFalse(problemSet.elimination()); + + problemSet.removeAllPairs(); + problemSet.addPair(elimPair5); + problemSet.setSelectedPair(0); + assertFalse(problemSet.elimination()); + } + + @Test + public void testSwap(){ + problemSet.removeAllPairs(); + problemSet.addPair(swapPair1); + problemSet.setSelectedPair(0); + assertTrue(problemSet.swap()); + + problemSet.removeAllPairs(); + problemSet.addPair(swapPair2); + problemSet.setSelectedPair(0); + assertFalse(problemSet.swap()); + + problemSet.removeAllPairs(); + problemSet.addPair(swapPair3); + problemSet.setSelectedPair(0); + assertFalse(problemSet.swap()); + + problemSet.removeAllPairs(); + problemSet.addPair(swapPair4); + problemSet.setSelectedPair(0); + assertTrue(problemSet.swap()); + + problemSet.removeAllPairs(); + problemSet.addPair(swapPair5); + problemSet.setSelectedPair(0); + assertFalse(problemSet.swap()); + + problemSet.removeAllPairs(); + problemSet.addPair(swapPair6); + problemSet.setSelectedPair(0); + assertFalse(problemSet.swap()); + } + + @Test + public void testSwapByComparison(){ + swapPair1.swap(); + assertEquals(swapPair1.toString(), swapPair1Result.toString()); + + swapPair2.swap(); + assertEquals(swapPair2.toString(), swapPair2Result.toString()); + + swapPair3.swap(); + assertEquals(swapPair3.toString(), swapPair3Result.toString()); + + swapPair4.swap(); + assertEquals(swapPair4.toString(), swapPair4Result.toString()); + + swapPair5.swap(); + assertEquals(swapPair5.toString(), swapPair5Result.toString()); + + swapPair6.swap(); + assertEquals(swapPair6.toString(), swapPair6Result.toString()); + } + + +} diff --git a/src/org/jalgo/module/unifikation/junit/TestSetParser.java b/src/org/jalgo/module/unifikation/junit/TestSetParser.java new file mode 100644 index 0000000..5c1d967 --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/TestSetParser.java @@ -0,0 +1,106 @@ +package org.jalgo.module.unifikation.junit; + + +import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; + +import org.jalgo.module.unifikation.*; +import org.jalgo.module.unifikation.parser.*; + +public class TestSetParser { + + private ISetParser parser; + private ParserError lexerError; + private ParserError parserError; + private ParserError invalidArity; + + @Before + public void setUp() throws Exception { + + parser = new SetParser(); + + //Errors + lexerError = new ParserError(ParserErrorType.LexerError); + parserError = new ParserError(ParserErrorType.ParserError); + invalidArity = new ParserError(ParserErrorType.InvalidArity); + + } + + @Test + public void testSetParser(){ + //Test für Übergabe des Nullpointers + assertFalse("Fehler bei Nullpointerübergabe an Parser", parser.parse(null)); + + //Test korrekter Terme + assertTrue("Fehler beim Parsen von M={(x1,x1)}. Expected: 'true' but was 'false'", parser.parse("M={(x1,x1)}")); + assertTrue("Fehler beim Parsen von M={(alpha(x1,x2,gamma(x3)),theta(x1))}. Expected: 'true' but was 'false'", parser.parse("M={(" + Constants.ALPHA + "(x1,x2," + Constants.GAMMA + "(x3))," + Constants.THETA + "(x1))}")); + assertTrue("Fehler beim Parsen von M={(x1 , alpha(x1))}. Expected: 'true' but was 'false'.", parser.parse("M={(x1," + Constants.ALPHA + "(x1))}")); + assertTrue("Fehler beim Parsen von M={(gamma(epsilon(theta())) , alpha(beta(delta(alpha(x1)))))}. Expected: 'true' but was 'false'.", parser.parse("M={(" + Constants.GAMMA + "(" + Constants.EPSILON + "(" + Constants.THETA + "))," + Constants.ALPHA + "(" + Constants.BETA + "(" + Constants.DELTA + "(" + Constants.ALPHA + "(x1)))))}")); + assertTrue("Fehler beim Parsen von M={(alpha(x,y,z,u,v,m),beta(x0,x17,x23,x189,x92834,x3848984)}. Expected: 'true' but was 'false'", parser.parse("M={(" + Constants.ALPHA + "(x,y,z,u,v,w)," + Constants.BETA + "(x1,x17,x23,x189,x92834,x3848984))}")); + + //Test inkorrekter Terme + //leeres Problem + assertFalse("Fehler beim Parsen von M={(,)}. Expected: 'false' but was 'true'. Input: leere Menge", parser.parse("M={(,)}")); + + //fehlendes Komma + assertFalse("Fehler beim Parsen von M={(x1 x1)}. Expected: 'false' but was 'true'. Input: fehlendes Komma", parser.parse("M={(x1 x1)}")); + assertFalse("Fehler beim Parsen von M={(alpha(x1,x2 gamma(x3)),theta(x1))}. Expected: 'false' but was 'true'. Input: fehlendes Komma", parser.parse("M={(" + Constants.ALPHA + "(x1,x2" + Constants.GAMMA + "(x3))," + Constants.THETA + "(x1))}")); + + //falsche Stelligkeit + assertFalse("Fehler beim Parsen von M={(alpha(gamma(x1,alpha),x3) , alpha(gamma(x1,x3),x3))}. Expected: 'false' but was 'true'. Input: Term mit falscher Stelligkeit", parser.parse("M={(" + Constants.ALPHA + "(" + Constants.GAMMA + "(x1," + Constants.ALPHA + "),x3) , " + Constants.ALPHA +"(" + Constants.GAMMA + "(x1,x3),x3))}")); + assertFalse("Fehler beim Parsen von M={(gamma(epsilon(theta())) , alpha(beta(delta(alpha()))))}. Expected: 'false' but was 'true'. Input: Term mit falscher Stelligkeit", parser.parse("M={(" + Constants.GAMMA + "(" + Constants.EPSILON + "(" + Constants.THETA + "))," + Constants.ALPHA + "(" + Constants.BETA + "(" + Constants.DELTA + "(" + Constants.ALPHA + "))))}")); + + //fehlende Klammer + assertFalse("Fehler beim Parsen von M={(x1 , alpha(x1)}. Expected: 'false' but was 'true'. Input: fehlende Klamme", parser.parse("M={(x1," + Constants.ALPHA + "(x1)}")); + assertFalse("Fehler beim Parsen von M={(alpha(x1,x2,gamma x3)),theta(x1))}. Expected: 'false' but was 'true'. Input: fehlende Klamme", parser.parse("M={(" + Constants.ALPHA + "(x1,x2," + Constants.GAMMA + "x3))," + Constants.THETA + "(x1))}")); + assertFalse("Fehler beim Parsen von M={(x1 , alpha(x1)). Expected: 'false' but was 'true'. Input: fehlende Klamme", parser.parse("M={(x1," + Constants.ALPHA + "(x1)")); + assertFalse("Fehler beim Parsen von M=(x1 , alpha(x1))}. Expected: 'false' but was 'true'. Input: fehlende Klamme", parser.parse("M=(x1," + Constants.ALPHA + "(x1)}")); + + //undefinierte Zeichen + assertFalse("Fehler beim Parsen von M={(alpha(a,b,c,d,e,g),beta(x0,x17,x23,x189,x92834,x3848984)}. Expected: 'false' but was 'true'", parser.parse("M={(" + Constants.ALPHA + "(a,b,c,d,e,f)," + Constants.BETA + "(x1,x17,x23,x189,x92834,x3848984))}")); + assertFalse("Fehler beim Parsen von M={(alpha(x,y,z,u,v,w),beta(x-1,x-17)}. Expected: 'false' but was 'true'", parser.parse("M={(" + Constants.ALPHA + "(x,y,z,u,v,w)," + Constants.BETA + "(x-1,x-17))}")); + assertFalse("Fehler beim Parsen von M={(alpha(x,y,z,u,v,w),beta(xtest,xtest2)}. Expected: 'false' but was 'true'", parser.parse("M={(" + Constants.ALPHA + "(x,y,z,u,v,w)," + Constants.BETA + "(xtest,xtest2))}")); + + } + + @Test + public void testGetErrorsParser(){ + + //leeres Problem erwartet ParserError + parser.parse("M={(,)}"); + assertSame("M={(,)} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + + //fehlendes Komma erwartet ParserError + parser.parse("M={(x1 x1)}"); + assertSame("M={(x1 x1)} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + parser.parse("M={(" + Constants.ALPHA + "(x1,x2" + Constants.GAMMA + "(x3))," + Constants.THETA + "(x1))}"); + assertSame("M={(alpha(x1,x2 gamma(x3)),theta(x1))} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + + //falsche Stelligkeit erwartet InvalidArity + parser.parse("M={(" + Constants.ALPHA + "(" + Constants.GAMMA + "(x1," + Constants.ALPHA + "),x3) , " + Constants.ALPHA +"(" + Constants.GAMMA + "(x1,x3),x3))}"); + assertSame("M={(alpha(gamma(x1,alpha),x3) , alpha(gamma(x1,x3),x3))} erwartete invalidArity.", parser.getErrors().get(0).getType(),invalidArity.getType()); + parser.parse("M={(" + Constants.GAMMA + "(" + Constants.EPSILON + "(" + Constants.THETA + "))," + Constants.ALPHA + "(" + Constants.BETA + "(" + Constants.DELTA + "(" + Constants.ALPHA + "))))}"); + assertSame("M={(gamma(epsilon(theta())) , alpha(beta(delta(alpha()))))} erwartete invalidArity.", parser.getErrors().get(0).getType(),invalidArity.getType()); + + //fehlende Klammer erwartet ParserError + parser.parse("M={(x1," + Constants.ALPHA + "(x1)}"); + assertSame("M={(x1, alpha(x1)} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + parser.parse("M={(" + Constants.ALPHA + "(x1,x2," + Constants.GAMMA + "x3))," + Constants.THETA + "(x1))}"); + assertSame("M={(alpha(x1,x2,gamma x3)),theta(x1))} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + parser.parse("M={(x1," + Constants.ALPHA + "(x1)"); + assertSame("M={(x1 , alpha(x1)) erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + parser.parse("M=(x1," + Constants.ALPHA + "(x1)}"); + assertSame("M=(x1 , alpha(x1))} erwartete ParserError.", parser.getErrors().get(0).getType(),parserError.getType()); + + //undefinierte Zeichen erwartet LexerError + parser.parse("M={(" + Constants.ALPHA + "(a,b,c,d,e,f)," + Constants.BETA + "(x1,x17,x23,x189,x92834,x3848984))}"); + assertSame("M={(alpha(a,b,c,d,e,g),beta(x0,x17,x23,x189,x92834,x3848984)} erwartete LexerError.", parser.getErrors().get(0).getType(),lexerError.getType()); + parser.parse("M={(" + Constants.ALPHA + "(x,y,z,u,v,w)," + Constants.BETA + "(x-1,x-17))}"); + assertSame("M={(alpha(x,y,z,u,v,w),beta(x-1,x-17)} erwartete LexerError.", parser.getErrors().get(0).getType(),lexerError.getType()); + parser.parse("M={(" + Constants.ALPHA + "(x,y,z,u,v,w)," + Constants.BETA + "(xtest,xtest2))}"); + assertSame("M={(alpha(x,y,z,u,v,w),beta(xtest,xtest2)} erwartete LexerError.", parser.getErrors().get(0).getType(),lexerError.getType()); + + } + +} diff --git a/src/org/jalgo/module/unifikation/junit/package-info.java b/src/org/jalgo/module/unifikation/junit/package-info.java new file mode 100644 index 0000000..960e92e --- /dev/null +++ b/src/org/jalgo/module/unifikation/junit/package-info.java @@ -0,0 +1,5 @@ +/** + * jUnit tests for the parser and the rules of the algorithm + */ + +package org.jalgo.module.unifikation.junit; diff --git a/src/org/jalgo/module/unifikation/package-info.java b/src/org/jalgo/module/unifikation/package-info.java new file mode 100644 index 0000000..a028064 --- /dev/null +++ b/src/org/jalgo/module/unifikation/package-info.java @@ -0,0 +1,6 @@ +/** + * Connecting to the j-Algo Module and initializing the current view + */ + +package org.jalgo.module.unifikation; + diff --git a/src/org/jalgo/module/unifikation/parser/CVS/Entries b/src/org/jalgo/module/unifikation/parser/CVS/Entries new file mode 100644 index 0000000..eefbcc7 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/CVS/Entries @@ -0,0 +1,11 @@ +/FormatConstraints.java/1.1/Mon Aug 16 12:05:49 2010// +/ISetParser.java/1.1/Mon Aug 16 12:05:49 2010// +/ParserError.java/1.1/Mon Aug 16 12:05:49 2010// +/ParserErrorType.java/1.1/Mon Aug 16 12:05:49 2010// +/SetParser.java/1.1/Mon Aug 16 12:05:49 2010// +/UnificationSetLexer.java/1.1/Mon Aug 16 12:05:49 2010// +/UnificationSetLexerErrorReporter.java/1.1/Mon Aug 16 12:05:49 2010// +/UnificationSetParser.java/1.1/Mon Aug 16 12:05:49 2010// +/UnificationSetParserErrorReporter.java/1.1/Mon Aug 16 12:05:49 2010// +D/output//// +/package-info.java/1.1/Mon Aug 16 12:05:49 2010// diff --git a/src/org/jalgo/module/unifikation/parser/CVS/Repository b/src/org/jalgo/module/unifikation/parser/CVS/Repository new file mode 100644 index 0000000..5035c86 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/CVS/Repository @@ -0,0 +1 @@ +j-algo/src/org/jalgo/module/unifikation/parser diff --git a/src/org/jalgo/module/unifikation/parser/CVS/Root b/src/org/jalgo/module/unifikation/parser/CVS/Root new file mode 100644 index 0000000..c8e00d8 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/CVS/Root @@ -0,0 +1 @@ +:pserver:anonymous@j-algo.cvs.sourceforge.net:/cvsroot/j-algo diff --git a/src/org/jalgo/module/unifikation/parser/FormatConstraints.java b/src/org/jalgo/module/unifikation/parser/FormatConstraints.java new file mode 100644 index 0000000..c52a479 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/FormatConstraints.java @@ -0,0 +1,48 @@ +package org.jalgo.module.unifikation.parser; + +import java.util.ArrayList; +import java.util.List; + + +/** + * Defines constraints for the input format of a set + * @author Alex + * + */ +public class FormatConstraints { + private List ValidTags; + + public FormatConstraints(){ + ValidTags=new ArrayList(); + ValidTags.add("sub"); + ValidTags.add("span"); + ValidTags.add("font"); + ValidTags.add("br"); + ValidTags.add("u"); + } + + /** + * Checks if a HTML tag is valid for parsing + * @return true if tag is valid + */ + public boolean isTagValid(String tag){ + //to short tags + if(tag.length()<2) return false; + //remove surrounding <> + if(tag.charAt(0)=='<' && tag.charAt(tag.length()-1)=='>'){ + tag=tag.substring(1,tag.length()-1).trim(); + //check for and remove delimiter / at beginning + if(tag.length()>0 && tag.charAt(0)=='/'){ + tag=tag.substring(1,tag.length()).trim(); + } + //check for and remove delimiter / at end + if(tag.length()>0 && tag.charAt(tag.length()-1)=='/'){ + tag=tag.substring(0,tag.length()-1).trim(); + } + } + for(String s: ValidTags){ + if(tag.startsWith(s)) return true; + } + return false; + } +} diff --git a/src/org/jalgo/module/unifikation/parser/ISetParser.java b/src/org/jalgo/module/unifikation/parser/ISetParser.java new file mode 100644 index 0000000..654f8ce --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/ISetParser.java @@ -0,0 +1,24 @@ +package org.jalgo.module.unifikation.parser; + +import java.util.List; + +import org.jalgo.module.unifikation.algo.model.ProblemSet; + +public interface ISetParser { + /** + * Parses a String (with or w/o HTML) + * @param input String to parse + * @return true if input could be parsed + */ + public boolean parse(final String input); + + /** + * @return Error classes for occurred errors + */ + public List getErrors(); + + /** + * @return ProblemSet as parsed from the string; null=error occurred + */ + public ProblemSet getResult(); +} diff --git a/src/org/jalgo/module/unifikation/parser/ParserError.java b/src/org/jalgo/module/unifikation/parser/ParserError.java new file mode 100644 index 0000000..1a11da0 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/ParserError.java @@ -0,0 +1,88 @@ +package org.jalgo.module.unifikation.parser; + +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.tree.Tree; + +/** + * Represents an error occurred during parsing + * @author Alex + * + */ +public class ParserError{ + private ParserErrorType type=null; + private String data=null; + private int position=-1; + + public ParserError(){ + } + + public ParserError(ParserErrorType type){ + this.type=type; + } + + public ParserError(ParserErrorType type, String data){ + this.type=type; + this.data=data; + } + + public ParserError(ParserErrorType type, String data, int position){ + this.type=type; + this.data=data; + this.position=position; + } + + public ParserError(ParserErrorType type, Tree elem){ + this.type=type; + if(elem!=null){ + this.data=UnificationSetParser.tokenNames[elem.getType()]; + this.position=elem.getCharPositionInLine(); + } + } + + public ParserError(ParserErrorType type, RecognitionException e){ + this.type=type; + if(e!=null){ + this.data=e.getLocalizedMessage(); + this.position=e.charPositionInLine; + } + } + + public String toString(){ + String res=""+type; + if(position>=0) res+=" an Position "+position; + if(data!=null) res+=" :'"+data+"'"; + return res; + } + + /** + * + * @return type of error + */ + public ParserErrorType getType(){ + return type; + } + + /** + * + * @return data of error, if available; else: null + */ + public String getData(){ + return data; + } + + /** + * Get the position in the input String (w/o HTML) where the error occurred + * @return position of error, if available; else: -1 + */ + public int getPosition(){ + return position; + } + + /** + * Adds an offset to the position (for relative positions) + * @param offset + */ + public void addPosition(int offset){ + position+=offset; + } +} diff --git a/src/org/jalgo/module/unifikation/parser/ParserErrorType.java b/src/org/jalgo/module/unifikation/parser/ParserErrorType.java new file mode 100644 index 0000000..40b11fd --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/ParserErrorType.java @@ -0,0 +1,50 @@ +package org.jalgo.module.unifikation.parser; + +public enum ParserErrorType { + /** + * body tag without ending tag + */ + InvalidBodyTag, + /** + * invalid tag (not supported by parser) + */ + InvalidTag, + /** + * Internal Error (wrong grammar...) + * should never happen + */ + InternalError, + /** + * invalid token (char or sequence of chars) + */ + InvalidToken, + /** + * missing token (char or sequence of chars) (e.g. missing M={}) + */ + MissingToken, + /** + * exception thrown by Lexer + */ + LexerError, + /** + * exception thrown by parser + */ + ParserError, + /** + * Invalid arity + */ + InvalidArity + ; + @Override + public String toString(){ + switch(this) + { + case ParserError: + return "Fehler"; + case InvalidArity: + return "Stelligkeitsfehler"; + default: + return super.toString(); + } + } +} diff --git a/src/org/jalgo/module/unifikation/parser/SetParser.java b/src/org/jalgo/module/unifikation/parser/SetParser.java new file mode 100644 index 0000000..f9b6c80 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/SetParser.java @@ -0,0 +1,285 @@ +package org.jalgo.module.unifikation.parser; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CharStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.tree.Tree; +import org.jalgo.module.unifikation.algo.model.*; + +/** + * Parser for sets for unification problems + * @author Alex + * + */ +public class SetParser implements ISetParser { + private List errors; + private ProblemSet resultSet; + private FormatConstraints formatConstraints; + + public SetParser(){ + errors=null; + resultSet=null; + formatConstraints=new FormatConstraints(); + } + + public List getErrors() { + return errors; + } + + public ProblemSet getResult() { + return resultSet; + } + + public boolean parse(String input) { + //prepare + resultSet=null; + errors=new LinkedList(); + //Clean input + input=this.cleanString(input); + if(input==null) return false; + //do parsing + CharStream cs = new ANTLRStringStream(input); + //Lexer + UnificationSetLexerErrorReporter uLexer = new UnificationSetLexerErrorReporter(cs); + CommonTokenStream tokens = new CommonTokenStream(uLexer); + //Parser + UnificationSetParserErrorReporter uParser = new UnificationSetParserErrorReporter(tokens); + UnificationSetParserErrorReporter.unificationset_return parserResult=null; + try { + parserResult=uParser.unificationset(); + } catch (RecognitionException e) { + errors.add(new ParserError(ParserErrorType.ParserError,e)); + return false; + } + //Check for errors + if(uLexer.getNumberOfSyntaxErrors()>0){ + for(RecognitionException e:uLexer.getErrors()){ + errors.add(new ParserError(ParserErrorType.LexerError,e)); + } + return false; + } + if(uParser.getNumberOfSyntaxErrors()>0){ + for(RecognitionException e:uParser.getErrors()){ + errors.add(new ParserError(ParserErrorType.ParserError,e)); + } + return false; + } + + //check for arity + Set constructorSymbols = uParser.constructorArity.keySet(); + + for (String constructorSymbol : constructorSymbols){ + //for each symbol + Map> curArity=uParser.constructorArity.get(constructorSymbol); + if(curArity.size()>1){ + //more than 1 arity found + //find the one with most entries and set that to valid + Integer rightArity=-1; + int maxCount=-1; + Set arity=curArity.keySet(); + for(Integer ar : arity){ + //for each arity + if(curArity.get(ar).size()>maxCount){ + maxCount=curArity.get(ar).size(); + rightArity=ar; + } + } + //add wrong ones as errors + for(Integer ar : arity){ + //for each arity + if(ar.equals(rightArity)){ + for(Integer pos : curArity.get(ar)){ + errors.add(new ParserError(ParserErrorType.InvalidArity,ar.toString(),pos.intValue())); + } + } + } + } + } + + Tree AST=(Tree) parserResult.getTree(); + if(AST==null){ + errors.add(new ParserError(ParserErrorType.InternalError)); + return false; + } + if(AST.getType()!=UnificationSetParser.SET){ + errors.add(new ParserError(ParserErrorType.InvalidToken,AST)); + return false; + } + resultSet=new HTMLProblemSet(); + + //parse Pairs + for(int i=0;i + * approximated! does not count invalid chars or whitespace + * @param tree + * @return index of char after current tree + */ + private int getTreeEnd(Tree tree){ + return tree.getCharPositionInLine()+tree.getText().length(); + } + + /** + * Parses a pair and returns it + * @param inTree (sub-)AST-tree to parse + * @return Pair or null on error + */ + private Pair parsePair(Tree inTree){ + if(inTree.getType()!=UnificationSetParser.PAIR){ + errors.add(new ParserError(ParserErrorType.InvalidToken,inTree)); + return null; + } + if(inTree.getChildCount()!=2){ + if(inTree.getChildCount()<2){ + errors.add(new ParserError(ParserErrorType.MissingToken,"TERM",getTreeEnd(inTree))); + }else{ + for(int i=2;i1) varIndex=inTree.getChild(1).getText(); + return new ColorVariable(varName+varIndex); + } + + private ConstructorSymbol parseConstructor(Tree inTree){ + if(inTree.getChildCount()==0){ + //should not happen + errors.add(new ParserError(ParserErrorType.MissingToken,"",inTree.getCharPositionInLine())); + return null; + } + ConstructorSymbol result=new ColorConstructorSymbol(inTree.getChild(0).getText()); + for(int i=1;i + int iStart=HTML.indexOf("=0){ + iEnd=HTML.indexOf(""); + if(iEnd<0){ + errors.add(new ParserError(ParserErrorType.InvalidBodyTag)); + return null; + } + HTML=HTML.substring(iStart+"".length(),iEnd).trim(); + } + + //Loop through all remaining tags + iStart=HTML.indexOf('<'); + iEnd=0; + while(iStart>=0){ + //Append everything in front of tag + Result.append(HTML.substring(iEnd,iStart)); + //Get tag + iEnd=HTML.indexOf('>',iStart+1); + if(iEnd<0) return null; + String tag=HTML.substring(iStart,iEnd+1); + //validate tag + if(!formatConstraints.isTagValid(tag)){ + errors.add(new ParserError(ParserErrorType.InvalidTag,tag)); + return null; + } + iEnd++; + //getNext + iStart=HTML.indexOf('<',iEnd); + } + Result.append(HTML.substring(iEnd)); + StringBuffer SBres = new StringBuffer(); + //Handle entities ("&xxxx;") + Pattern specialPattern = Pattern.compile("&([^;]{3,5});"); + Matcher specialMatcher = specialPattern.matcher(Result); + while (specialMatcher.find()) { + specialMatcher.appendReplacement(SBres, getSpecialChar(specialMatcher.group(1))); + } + specialMatcher.appendTail(SBres); + return SBres.toString(); + } +} diff --git a/src/org/jalgo/module/unifikation/parser/UnificationSetLexer.java b/src/org/jalgo/module/unifikation/parser/UnificationSetLexer.java new file mode 100644 index 0000000..11ddad7 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/UnificationSetLexer.java @@ -0,0 +1,845 @@ +// $ANTLR 3.2 Sep 23, 2009 12:02:23 C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g 2010-06-07 19:13:24 + + package org.jalgo.module.unifikation.parser; + + +import org.antlr.runtime.*; +import java.util.Stack; +import java.util.List; +import java.util.ArrayList; + +public class UnificationSetLexer extends Lexer { + public static final int OPENBRACE=14; + public static final int U=7; + public static final int DELTA=23; + public static final int W=9; + public static final int V=8; + public static final int SET=16; + public static final int INT=26; + public static final int EPSILON=24; + public static final int EOF=-1; + public static final int BETA=21; + public static final int Y=5; + public static final int ALPHA=20; + public static final int X=4; + public static final int Z=6; + public static final int LBRACKET=10; + public static final int THETA=25; + public static final int WS=27; + public static final int VARIABLE=19; + public static final int COMMA=13; + public static final int CLOSEBRACE=15; + public static final int STARTSET=12; + public static final int PAIR=17; + public static final int RBRACKET=11; + public static final int GAMMA=22; + public static final int CONSTRUCTOR=18; + + // delegates + // delegators + + public UnificationSetLexer() {;} + public UnificationSetLexer(CharStream input) { + this(input, new RecognizerSharedState()); + } + public UnificationSetLexer(CharStream input, RecognizerSharedState state) { + super(input,state); + + } + public String getGrammarFileName() { return "C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g"; } + + // $ANTLR start "X" + public final void mX() throws RecognitionException { + try { + int _type = X; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:7:3: ( 'x' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:7:5: 'x' + { + match('x'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "X" + + // $ANTLR start "Y" + public final void mY() throws RecognitionException { + try { + int _type = Y; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:8:3: ( 'y' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:8:5: 'y' + { + match('y'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "Y" + + // $ANTLR start "Z" + public final void mZ() throws RecognitionException { + try { + int _type = Z; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:9:3: ( 'z' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:9:5: 'z' + { + match('z'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "Z" + + // $ANTLR start "U" + public final void mU() throws RecognitionException { + try { + int _type = U; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:10:3: ( 'u' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:10:5: 'u' + { + match('u'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "U" + + // $ANTLR start "V" + public final void mV() throws RecognitionException { + try { + int _type = V; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:11:3: ( 'v' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:11:5: 'v' + { + match('v'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "V" + + // $ANTLR start "W" + public final void mW() throws RecognitionException { + try { + int _type = W; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:12:3: ( 'w' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:12:5: 'w' + { + match('w'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "W" + + // $ANTLR start "LBRACKET" + public final void mLBRACKET() throws RecognitionException { + try { + int _type = LBRACKET; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:13:10: ( '(' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:13:12: '(' + { + match('('); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "LBRACKET" + + // $ANTLR start "RBRACKET" + public final void mRBRACKET() throws RecognitionException { + try { + int _type = RBRACKET; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:14:10: ( ')' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:14:12: ')' + { + match(')'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "RBRACKET" + + // $ANTLR start "STARTSET" + public final void mSTARTSET() throws RecognitionException { + try { + int _type = STARTSET; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:15:10: ( 'm=' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:15:12: 'm=' + { + match("m="); + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "STARTSET" + + // $ANTLR start "COMMA" + public final void mCOMMA() throws RecognitionException { + try { + int _type = COMMA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:16:7: ( ',' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:16:9: ',' + { + match(','); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "COMMA" + + // $ANTLR start "OPENBRACE" + public final void mOPENBRACE() throws RecognitionException { + try { + int _type = OPENBRACE; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:17:11: ( '{' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:17:13: '{' + { + match('{'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "OPENBRACE" + + // $ANTLR start "CLOSEBRACE" + public final void mCLOSEBRACE() throws RecognitionException { + try { + int _type = CLOSEBRACE; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:18:12: ( '}' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:18:14: '}' + { + match('}'); + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "CLOSEBRACE" + + // $ANTLR start "ALPHA" + public final void mALPHA() throws RecognitionException { + try { + int _type = ALPHA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:73:8: ( '\\u03B1' | 'a' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='a'||input.LA(1)=='\u03B1' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "ALPHA" + + // $ANTLR start "BETA" + public final void mBETA() throws RecognitionException { + try { + int _type = BETA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:74:7: ( '\\u03B2' | 'b' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='b'||input.LA(1)=='\u03B2' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "BETA" + + // $ANTLR start "GAMMA" + public final void mGAMMA() throws RecognitionException { + try { + int _type = GAMMA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:75:8: ( '\\u03B3' | 'c' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='c'||input.LA(1)=='\u03B3' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "GAMMA" + + // $ANTLR start "DELTA" + public final void mDELTA() throws RecognitionException { + try { + int _type = DELTA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:76:8: ( '\\u03B4' | 'd' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='d'||input.LA(1)=='\u03B4' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "DELTA" + + // $ANTLR start "EPSILON" + public final void mEPSILON() throws RecognitionException { + try { + int _type = EPSILON; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:77:9: ( '\\u03B5' | 'e' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='e'||input.LA(1)=='\u03B5' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "EPSILON" + + // $ANTLR start "THETA" + public final void mTHETA() throws RecognitionException { + try { + int _type = THETA; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:78:7: ( '\\u03B8' | 't' ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( input.LA(1)=='t'||input.LA(1)=='\u03B8' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "THETA" + + // $ANTLR start "INT" + public final void mINT() throws RecognitionException { + try { + int _type = INT; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:80:5: ( ( '0' .. '9' )+ ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:80:7: ( '0' .. '9' )+ + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:80:7: ( '0' .. '9' )+ + int cnt1=0; + loop1: + do { + int alt1=2; + int LA1_0 = input.LA(1); + + if ( ((LA1_0>='0' && LA1_0<='9')) ) { + alt1=1; + } + + + switch (alt1) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:80:7: '0' .. '9' + { + matchRange('0','9'); + + } + break; + + default : + if ( cnt1 >= 1 ) break loop1; + EarlyExitException eee = + new EarlyExitException(1, input); + throw eee; + } + cnt1++; + } while (true); + + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "INT" + + // $ANTLR start "WS" + public final void mWS() throws RecognitionException { + try { + int _type = WS; + int _channel = DEFAULT_TOKEN_CHANNEL; + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:83:5: ( ( ' ' | '\\t' | '\\r' | '\\n' )+ ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:83:9: ( ' ' | '\\t' | '\\r' | '\\n' )+ + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:83:9: ( ' ' | '\\t' | '\\r' | '\\n' )+ + int cnt2=0; + loop2: + do { + int alt2=2; + int LA2_0 = input.LA(1); + + if ( ((LA2_0>='\t' && LA2_0<='\n')||LA2_0=='\r'||LA2_0==' ') ) { + alt2=1; + } + + + switch (alt2) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) { + input.consume(); + + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + recover(mse); + throw mse;} + + + } + break; + + default : + if ( cnt2 >= 1 ) break loop2; + EarlyExitException eee = + new EarlyExitException(2, input); + throw eee; + } + cnt2++; + } while (true); + + _channel=HIDDEN; + + } + + state.type = _type; + state.channel = _channel; + } + finally { + } + } + // $ANTLR end "WS" + + public void mTokens() throws RecognitionException { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:8: ( X | Y | Z | U | V | W | LBRACKET | RBRACKET | STARTSET | COMMA | OPENBRACE | CLOSEBRACE | ALPHA | BETA | GAMMA | DELTA | EPSILON | THETA | INT | WS ) + int alt3=20; + switch ( input.LA(1) ) { + case 'x': + { + alt3=1; + } + break; + case 'y': + { + alt3=2; + } + break; + case 'z': + { + alt3=3; + } + break; + case 'u': + { + alt3=4; + } + break; + case 'v': + { + alt3=5; + } + break; + case 'w': + { + alt3=6; + } + break; + case '(': + { + alt3=7; + } + break; + case ')': + { + alt3=8; + } + break; + case 'm': + { + alt3=9; + } + break; + case ',': + { + alt3=10; + } + break; + case '{': + { + alt3=11; + } + break; + case '}': + { + alt3=12; + } + break; + case 'a': + case '\u03B1': + { + alt3=13; + } + break; + case 'b': + case '\u03B2': + { + alt3=14; + } + break; + case 'c': + case '\u03B3': + { + alt3=15; + } + break; + case 'd': + case '\u03B4': + { + alt3=16; + } + break; + case 'e': + case '\u03B5': + { + alt3=17; + } + break; + case 't': + case '\u03B8': + { + alt3=18; + } + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + alt3=19; + } + break; + case '\t': + case '\n': + case '\r': + case ' ': + { + alt3=20; + } + break; + default: + NoViableAltException nvae = + new NoViableAltException("", 3, 0, input); + + throw nvae; + } + + switch (alt3) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:10: X + { + mX(); + + } + break; + case 2 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:12: Y + { + mY(); + + } + break; + case 3 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:14: Z + { + mZ(); + + } + break; + case 4 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:16: U + { + mU(); + + } + break; + case 5 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:18: V + { + mV(); + + } + break; + case 6 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:20: W + { + mW(); + + } + break; + case 7 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:22: LBRACKET + { + mLBRACKET(); + + } + break; + case 8 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:31: RBRACKET + { + mRBRACKET(); + + } + break; + case 9 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:40: STARTSET + { + mSTARTSET(); + + } + break; + case 10 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:49: COMMA + { + mCOMMA(); + + } + break; + case 11 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:55: OPENBRACE + { + mOPENBRACE(); + + } + break; + case 12 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:65: CLOSEBRACE + { + mCLOSEBRACE(); + + } + break; + case 13 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:76: ALPHA + { + mALPHA(); + + } + break; + case 14 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:82: BETA + { + mBETA(); + + } + break; + case 15 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:87: GAMMA + { + mGAMMA(); + + } + break; + case 16 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:93: DELTA + { + mDELTA(); + + } + break; + case 17 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:99: EPSILON + { + mEPSILON(); + + } + break; + case 18 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:107: THETA + { + mTHETA(); + + } + break; + case 19 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:113: INT + { + mINT(); + + } + break; + case 20 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:1:117: WS + { + mWS(); + + } + break; + + } + + } + + + + +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.java b/src/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.java new file mode 100644 index 0000000..9dab4a5 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/UnificationSetLexerErrorReporter.java @@ -0,0 +1,44 @@ +package org.jalgo.module.unifikation.parser; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.runtime.CharStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; + +/** + * Extends generated lexer to show and save errors + * @author Alex + * + */ +public class UnificationSetLexerErrorReporter extends UnificationSetLexer { + private List errors; + + public UnificationSetLexerErrorReporter() { + errors=new LinkedList(); + } + + public UnificationSetLexerErrorReporter(CharStream input) { + super(input); + errors=new LinkedList(); + } + + public UnificationSetLexerErrorReporter(CharStream input, + RecognizerSharedState state) { + super(input, state); + errors=new LinkedList(); + } + + @Override + public void reportError(RecognitionException e) { + super.reportError(e); + errors.add(e); + state.syntaxErrors++; + } + + public List getErrors(){ + return errors; + } + +} diff --git a/src/org/jalgo/module/unifikation/parser/UnificationSetParser.java b/src/org/jalgo/module/unifikation/parser/UnificationSetParser.java new file mode 100644 index 0000000..6fa2183 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/UnificationSetParser.java @@ -0,0 +1,1097 @@ +// $ANTLR 3.2 Sep 23, 2009 12:02:23 C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g 2010-06-07 19:13:24 + + package org.jalgo.module.unifikation.parser; + import java.util.Map; + import java.util.HashMap; + import java.util.TreeMap; + import java.util.List; + import java.util.ArrayList; + + +import org.antlr.runtime.*; +import java.util.Stack; +import java.util.List; +import java.util.ArrayList; + + +import org.antlr.runtime.tree.*; + +public class UnificationSetParser extends Parser { + public static final String[] tokenNames = new String[] { + "", "", "", "", "X", "Y", "Z", "U", "V", "W", "LBRACKET", "RBRACKET", "STARTSET", "COMMA", "OPENBRACE", "CLOSEBRACE", "SET", "PAIR", "CONSTRUCTOR", "VARIABLE", "ALPHA", "BETA", "GAMMA", "DELTA", "EPSILON", "THETA", "INT", "WS" + }; + public static final int OPENBRACE=14; + public static final int U=7; + public static final int DELTA=23; + public static final int W=9; + public static final int V=8; + public static final int SET=16; + public static final int INT=26; + public static final int EPSILON=24; + public static final int BETA=21; + public static final int EOF=-1; + public static final int Y=5; + public static final int ALPHA=20; + public static final int X=4; + public static final int Z=6; + public static final int LBRACKET=10; + public static final int THETA=25; + public static final int WS=27; + public static final int VARIABLE=19; + public static final int COMMA=13; + public static final int CLOSEBRACE=15; + public static final int STARTSET=12; + public static final int PAIR=17; + public static final int RBRACKET=11; + public static final int GAMMA=22; + public static final int CONSTRUCTOR=18; + + // delegates + // delegators + + + public UnificationSetParser(TokenStream input) { + this(input, new RecognizerSharedState()); + } + public UnificationSetParser(TokenStream input, RecognizerSharedState state) { + super(input, state); + + } + + protected TreeAdaptor adaptor = new CommonTreeAdaptor(); + + public void setTreeAdaptor(TreeAdaptor adaptor) { + this.adaptor = adaptor; + } + public TreeAdaptor getTreeAdaptor() { + return adaptor; + } + + public String[] getTokenNames() { return UnificationSetParser.tokenNames; } + public String getGrammarFileName() { return "C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g"; } + + + //Constructorsymbol->arity->position + public Map>> constructorArity=new HashMap>>(); + private void AddConstructorArity(String constructorSymbol, int arity, Token tPos){ + int pos=-1; + if(tPos!=null) pos=tPos.getCharPositionInLine(); + if(!constructorArity.containsKey(constructorSymbol)){ + constructorArity.put(constructorSymbol, new TreeMap>()); + } + Map> arityMap=constructorArity.get(constructorSymbol); + if(!arityMap.containsKey(arity)){ + arityMap.put(arity, new ArrayList()); + } + arityMap.get(arity).add(pos); + } + + + public static class unificationset_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "unificationset" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:57:1: unificationset : set ; + public final UnificationSetParser.unificationset_return unificationset() throws RecognitionException { + UnificationSetParser.unificationset_return retval = new UnificationSetParser.unificationset_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + UnificationSetParser.set_return set1 = null; + + + + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:57:16: ( set ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:57:18: set + { + root_0 = (CommonTree)adaptor.nil(); + + pushFollow(FOLLOW_set_in_unificationset177); + set1=set(); + + state._fsp--; + + root_0 = (CommonTree)adaptor.becomeRoot(set1.getTree(), root_0); + + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "unificationset" + + public static class set_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "set" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:1: set : STARTSET OPENBRACE ws ( pair ( ws COMMA ws pair )* ws )? CLOSEBRACE -> ^( SET ( pair )* ) ; + public final UnificationSetParser.set_return set() throws RecognitionException { + UnificationSetParser.set_return retval = new UnificationSetParser.set_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token STARTSET2=null; + Token OPENBRACE3=null; + Token COMMA7=null; + Token CLOSEBRACE11=null; + UnificationSetParser.ws_return ws4 = null; + + UnificationSetParser.pair_return pair5 = null; + + UnificationSetParser.ws_return ws6 = null; + + UnificationSetParser.ws_return ws8 = null; + + UnificationSetParser.pair_return pair9 = null; + + UnificationSetParser.ws_return ws10 = null; + + + CommonTree STARTSET2_tree=null; + CommonTree OPENBRACE3_tree=null; + CommonTree COMMA7_tree=null; + CommonTree CLOSEBRACE11_tree=null; + RewriteRuleTokenStream stream_OPENBRACE=new RewriteRuleTokenStream(adaptor,"token OPENBRACE"); + RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); + RewriteRuleTokenStream stream_CLOSEBRACE=new RewriteRuleTokenStream(adaptor,"token CLOSEBRACE"); + RewriteRuleTokenStream stream_STARTSET=new RewriteRuleTokenStream(adaptor,"token STARTSET"); + RewriteRuleSubtreeStream stream_pair=new RewriteRuleSubtreeStream(adaptor,"rule pair"); + RewriteRuleSubtreeStream stream_ws=new RewriteRuleSubtreeStream(adaptor,"rule ws"); + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:5: ( STARTSET OPENBRACE ws ( pair ( ws COMMA ws pair )* ws )? CLOSEBRACE -> ^( SET ( pair )* ) ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:7: STARTSET OPENBRACE ws ( pair ( ws COMMA ws pair )* ws )? CLOSEBRACE + { + STARTSET2=(Token)match(input,STARTSET,FOLLOW_STARTSET_in_set185); + stream_STARTSET.add(STARTSET2); + + OPENBRACE3=(Token)match(input,OPENBRACE,FOLLOW_OPENBRACE_in_set187); + stream_OPENBRACE.add(OPENBRACE3); + + pushFollow(FOLLOW_ws_in_set189); + ws4=ws(); + + state._fsp--; + + stream_ws.add(ws4.getTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:29: ( pair ( ws COMMA ws pair )* ws )? + int alt2=2; + int LA2_0 = input.LA(1); + + if ( (LA2_0==LBRACKET) ) { + alt2=1; + } + switch (alt2) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:30: pair ( ws COMMA ws pair )* ws + { + pushFollow(FOLLOW_pair_in_set192); + pair5=pair(); + + state._fsp--; + + stream_pair.add(pair5.getTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:35: ( ws COMMA ws pair )* + loop1: + do { + int alt1=2; + int LA1_0 = input.LA(1); + + if ( (LA1_0==WS) ) { + int LA1_1 = input.LA(2); + + if ( (LA1_1==COMMA) ) { + alt1=1; + } + + + } + else if ( (LA1_0==COMMA) ) { + alt1=1; + } + + + switch (alt1) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:37: ws COMMA ws pair + { + pushFollow(FOLLOW_ws_in_set196); + ws6=ws(); + + state._fsp--; + + stream_ws.add(ws6.getTree()); + COMMA7=(Token)match(input,COMMA,FOLLOW_COMMA_in_set198); + stream_COMMA.add(COMMA7); + + pushFollow(FOLLOW_ws_in_set200); + ws8=ws(); + + state._fsp--; + + stream_ws.add(ws8.getTree()); + pushFollow(FOLLOW_pair_in_set202); + pair9=pair(); + + state._fsp--; + + stream_pair.add(pair9.getTree()); + + } + break; + + default : + break loop1; + } + } while (true); + + pushFollow(FOLLOW_ws_in_set206); + ws10=ws(); + + state._fsp--; + + stream_ws.add(ws10.getTree()); + + } + break; + + } + + CLOSEBRACE11=(Token)match(input,CLOSEBRACE,FOLLOW_CLOSEBRACE_in_set210); + stream_CLOSEBRACE.add(CLOSEBRACE11); + + + + // AST REWRITE + // elements: pair + // token labels: + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + retval.tree = root_0; + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (CommonTree)adaptor.nil(); + // 58:72: -> ^( SET ( pair )* ) + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:75: ^( SET ( pair )* ) + { + CommonTree root_1 = (CommonTree)adaptor.nil(); + root_1 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(SET, "SET"), root_1); + + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:58:81: ( pair )* + while ( stream_pair.hasNext() ) { + adaptor.addChild(root_1, stream_pair.nextTree()); + + } + stream_pair.reset(); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0; + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "set" + + public static class pair_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "pair" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:60:1: pair : LBRACKET ws first= term COMMA second= term ws RBRACKET -> ^( PAIR $first $second) ; + public final UnificationSetParser.pair_return pair() throws RecognitionException { + UnificationSetParser.pair_return retval = new UnificationSetParser.pair_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token LBRACKET12=null; + Token COMMA14=null; + Token RBRACKET16=null; + UnificationSetParser.term_return first = null; + + UnificationSetParser.term_return second = null; + + UnificationSetParser.ws_return ws13 = null; + + UnificationSetParser.ws_return ws15 = null; + + + CommonTree LBRACKET12_tree=null; + CommonTree COMMA14_tree=null; + CommonTree RBRACKET16_tree=null; + RewriteRuleTokenStream stream_LBRACKET=new RewriteRuleTokenStream(adaptor,"token LBRACKET"); + RewriteRuleTokenStream stream_RBRACKET=new RewriteRuleTokenStream(adaptor,"token RBRACKET"); + RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); + RewriteRuleSubtreeStream stream_term=new RewriteRuleSubtreeStream(adaptor,"rule term"); + RewriteRuleSubtreeStream stream_ws=new RewriteRuleSubtreeStream(adaptor,"rule ws"); + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:60:6: ( LBRACKET ws first= term COMMA second= term ws RBRACKET -> ^( PAIR $first $second) ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:60:8: LBRACKET ws first= term COMMA second= term ws RBRACKET + { + LBRACKET12=(Token)match(input,LBRACKET,FOLLOW_LBRACKET_in_pair227); + stream_LBRACKET.add(LBRACKET12); + + pushFollow(FOLLOW_ws_in_pair229); + ws13=ws(); + + state._fsp--; + + stream_ws.add(ws13.getTree()); + pushFollow(FOLLOW_term_in_pair233); + first=term(); + + state._fsp--; + + stream_term.add(first.getTree()); + COMMA14=(Token)match(input,COMMA,FOLLOW_COMMA_in_pair235); + stream_COMMA.add(COMMA14); + + pushFollow(FOLLOW_term_in_pair239); + second=term(); + + state._fsp--; + + stream_term.add(second.getTree()); + pushFollow(FOLLOW_ws_in_pair241); + ws15=ws(); + + state._fsp--; + + stream_ws.add(ws15.getTree()); + RBRACKET16=(Token)match(input,RBRACKET,FOLLOW_RBRACKET_in_pair243); + stream_RBRACKET.add(RBRACKET16); + + + + // AST REWRITE + // elements: second, first + // token labels: + // rule labels: retval, second, first + // token list labels: + // rule list labels: + // wildcard labels: + retval.tree = root_0; + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + RewriteRuleSubtreeStream stream_second=new RewriteRuleSubtreeStream(adaptor,"rule second",second!=null?second.tree:null); + RewriteRuleSubtreeStream stream_first=new RewriteRuleSubtreeStream(adaptor,"rule first",first!=null?first.tree:null); + + root_0 = (CommonTree)adaptor.nil(); + // 60:61: -> ^( PAIR $first $second) + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:60:63: ^( PAIR $first $second) + { + CommonTree root_1 = (CommonTree)adaptor.nil(); + root_1 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(PAIR, "PAIR"), root_1); + + adaptor.addChild(root_1, stream_first.nextTree()); + adaptor.addChild(root_1, stream_second.nextTree()); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0; + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "pair" + + public static class term_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "term" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:62:1: term : ( constructor | variable ); + public final UnificationSetParser.term_return term() throws RecognitionException { + UnificationSetParser.term_return retval = new UnificationSetParser.term_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + UnificationSetParser.constructor_return constructor17 = null; + + UnificationSetParser.variable_return variable18 = null; + + + + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:62:6: ( constructor | variable ) + int alt3=2; + int LA3_0 = input.LA(1); + + if ( ((LA3_0>=ALPHA && LA3_0<=THETA)) ) { + alt3=1; + } + else if ( ((LA3_0>=X && LA3_0<=W)) ) { + alt3=2; + } + else { + NoViableAltException nvae = + new NoViableAltException("", 3, 0, input); + + throw nvae; + } + switch (alt3) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:62:8: constructor + { + root_0 = (CommonTree)adaptor.nil(); + + pushFollow(FOLLOW_constructor_in_term262); + constructor17=constructor(); + + state._fsp--; + + adaptor.addChild(root_0, constructor17.getTree()); + + } + break; + case 2 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:62:22: variable + { + root_0 = (CommonTree)adaptor.nil(); + + pushFollow(FOLLOW_variable_in_term266); + variable18=variable(); + + state._fsp--; + + adaptor.addChild(root_0, variable18.getTree()); + + } + break; + + } + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "term" + + public static class constructor_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "constructor" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:1: constructor : symbol= constructorsymbol ( ws LBRACKET ws (ids+= term ( ws COMMA ws ids+= term )* ws )? RBRACKET )? -> ^( CONSTRUCTOR constructorsymbol ( term )* ) ; + public final UnificationSetParser.constructor_return constructor() throws RecognitionException { + UnificationSetParser.constructor_return retval = new UnificationSetParser.constructor_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token LBRACKET20=null; + Token COMMA23=null; + Token RBRACKET26=null; + List list_ids=null; + UnificationSetParser.constructorsymbol_return symbol = null; + + UnificationSetParser.ws_return ws19 = null; + + UnificationSetParser.ws_return ws21 = null; + + UnificationSetParser.ws_return ws22 = null; + + UnificationSetParser.ws_return ws24 = null; + + UnificationSetParser.ws_return ws25 = null; + + RuleReturnScope ids = null; + CommonTree LBRACKET20_tree=null; + CommonTree COMMA23_tree=null; + CommonTree RBRACKET26_tree=null; + RewriteRuleTokenStream stream_LBRACKET=new RewriteRuleTokenStream(adaptor,"token LBRACKET"); + RewriteRuleTokenStream stream_RBRACKET=new RewriteRuleTokenStream(adaptor,"token RBRACKET"); + RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA"); + RewriteRuleSubtreeStream stream_term=new RewriteRuleSubtreeStream(adaptor,"rule term"); + RewriteRuleSubtreeStream stream_constructorsymbol=new RewriteRuleSubtreeStream(adaptor,"rule constructorsymbol"); + RewriteRuleSubtreeStream stream_ws=new RewriteRuleSubtreeStream(adaptor,"rule ws"); + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:13: (symbol= constructorsymbol ( ws LBRACKET ws (ids+= term ( ws COMMA ws ids+= term )* ws )? RBRACKET )? -> ^( CONSTRUCTOR constructorsymbol ( term )* ) ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:15: symbol= constructorsymbol ( ws LBRACKET ws (ids+= term ( ws COMMA ws ids+= term )* ws )? RBRACKET )? + { + pushFollow(FOLLOW_constructorsymbol_in_constructor277); + symbol=constructorsymbol(); + + state._fsp--; + + stream_constructorsymbol.add(symbol.getTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:40: ( ws LBRACKET ws (ids+= term ( ws COMMA ws ids+= term )* ws )? RBRACKET )? + int alt6=2; + int LA6_0 = input.LA(1); + + if ( (LA6_0==WS) ) { + int LA6_1 = input.LA(2); + + if ( (LA6_1==LBRACKET) ) { + alt6=1; + } + } + else if ( (LA6_0==LBRACKET) ) { + alt6=1; + } + switch (alt6) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:41: ws LBRACKET ws (ids+= term ( ws COMMA ws ids+= term )* ws )? RBRACKET + { + pushFollow(FOLLOW_ws_in_constructor280); + ws19=ws(); + + state._fsp--; + + stream_ws.add(ws19.getTree()); + LBRACKET20=(Token)match(input,LBRACKET,FOLLOW_LBRACKET_in_constructor282); + stream_LBRACKET.add(LBRACKET20); + + pushFollow(FOLLOW_ws_in_constructor284); + ws21=ws(); + + state._fsp--; + + stream_ws.add(ws21.getTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:56: (ids+= term ( ws COMMA ws ids+= term )* ws )? + int alt5=2; + int LA5_0 = input.LA(1); + + if ( ((LA5_0>=X && LA5_0<=W)||(LA5_0>=ALPHA && LA5_0<=THETA)) ) { + alt5=1; + } + switch (alt5) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:57: ids+= term ( ws COMMA ws ids+= term )* ws + { + pushFollow(FOLLOW_term_in_constructor289); + ids=term(); + + state._fsp--; + + stream_term.add(ids.getTree()); + if (list_ids==null) list_ids=new ArrayList(); + list_ids.add(ids.getTree()); + + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:67: ( ws COMMA ws ids+= term )* + loop4: + do { + int alt4=2; + int LA4_0 = input.LA(1); + + if ( (LA4_0==WS) ) { + int LA4_1 = input.LA(2); + + if ( (LA4_1==COMMA) ) { + alt4=1; + } + + + } + else if ( (LA4_0==COMMA) ) { + alt4=1; + } + + + switch (alt4) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:68: ws COMMA ws ids+= term + { + pushFollow(FOLLOW_ws_in_constructor292); + ws22=ws(); + + state._fsp--; + + stream_ws.add(ws22.getTree()); + COMMA23=(Token)match(input,COMMA,FOLLOW_COMMA_in_constructor294); + stream_COMMA.add(COMMA23); + + pushFollow(FOLLOW_ws_in_constructor296); + ws24=ws(); + + state._fsp--; + + stream_ws.add(ws24.getTree()); + pushFollow(FOLLOW_term_in_constructor301); + ids=term(); + + state._fsp--; + + stream_term.add(ids.getTree()); + if (list_ids==null) list_ids=new ArrayList(); + list_ids.add(ids.getTree()); + + + } + break; + + default : + break loop4; + } + } while (true); + + pushFollow(FOLLOW_ws_in_constructor305); + ws25=ws(); + + state._fsp--; + + stream_ws.add(ws25.getTree()); + + } + break; + + } + + RBRACKET26=(Token)match(input,RBRACKET,FOLLOW_RBRACKET_in_constructor309); + stream_RBRACKET.add(RBRACKET26); + + + } + break; + + } + + AddConstructorArity((symbol!=null?input.toString(symbol.start,symbol.stop):null),list_ids==null?0:list_ids.size(),(symbol!=null?((Token)symbol.start):null)); + + + // AST REWRITE + // elements: term, constructorsymbol + // token labels: + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + retval.tree = root_0; + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (CommonTree)adaptor.nil(); + // 64:185: -> ^( CONSTRUCTOR constructorsymbol ( term )* ) + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:187: ^( CONSTRUCTOR constructorsymbol ( term )* ) + { + CommonTree root_1 = (CommonTree)adaptor.nil(); + root_1 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(CONSTRUCTOR, "CONSTRUCTOR"), root_1); + + adaptor.addChild(root_1, stream_constructorsymbol.nextTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:64:219: ( term )* + while ( stream_term.hasNext() ) { + adaptor.addChild(root_1, stream_term.nextTree()); + + } + stream_term.reset(); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0; + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "constructor" + + public static class constructorsymbol_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "constructorsymbol" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:66:1: constructorsymbol : ( ALPHA | BETA | GAMMA | DELTA | EPSILON | THETA ); + public final UnificationSetParser.constructorsymbol_return constructorsymbol() throws RecognitionException { + UnificationSetParser.constructorsymbol_return retval = new UnificationSetParser.constructorsymbol_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token set27=null; + + CommonTree set27_tree=null; + + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:66:19: ( ALPHA | BETA | GAMMA | DELTA | EPSILON | THETA ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + root_0 = (CommonTree)adaptor.nil(); + + set27=(Token)input.LT(1); + if ( (input.LA(1)>=ALPHA && input.LA(1)<=THETA) ) { + input.consume(); + adaptor.addChild(root_0, (CommonTree)adaptor.create(set27)); + state.errorRecovery=false; + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + throw mse; + } + + + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "constructorsymbol" + + public static class variable_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "variable" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:1: variable : varid ( INT )? -> ^( VARIABLE varid ( INT )? ) ; + public final UnificationSetParser.variable_return variable() throws RecognitionException { + UnificationSetParser.variable_return retval = new UnificationSetParser.variable_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token INT29=null; + UnificationSetParser.varid_return varid28 = null; + + + CommonTree INT29_tree=null; + RewriteRuleTokenStream stream_INT=new RewriteRuleTokenStream(adaptor,"token INT"); + RewriteRuleSubtreeStream stream_varid=new RewriteRuleSubtreeStream(adaptor,"rule varid"); + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:11: ( varid ( INT )? -> ^( VARIABLE varid ( INT )? ) ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:13: varid ( INT )? + { + pushFollow(FOLLOW_varid_in_variable350); + varid28=varid(); + + state._fsp--; + + stream_varid.add(varid28.getTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:19: ( INT )? + int alt7=2; + int LA7_0 = input.LA(1); + + if ( (LA7_0==INT) ) { + alt7=1; + } + switch (alt7) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:19: INT + { + INT29=(Token)match(input,INT,FOLLOW_INT_in_variable352); + stream_INT.add(INT29); + + + } + break; + + } + + + + // AST REWRITE + // elements: INT, varid + // token labels: + // rule labels: retval + // token list labels: + // rule list labels: + // wildcard labels: + retval.tree = root_0; + RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); + + root_0 = (CommonTree)adaptor.nil(); + // 68:24: -> ^( VARIABLE varid ( INT )? ) + { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:26: ^( VARIABLE varid ( INT )? ) + { + CommonTree root_1 = (CommonTree)adaptor.nil(); + root_1 = (CommonTree)adaptor.becomeRoot((CommonTree)adaptor.create(VARIABLE, "VARIABLE"), root_1); + + adaptor.addChild(root_1, stream_varid.nextTree()); + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:68:43: ( INT )? + if ( stream_INT.hasNext() ) { + adaptor.addChild(root_1, stream_INT.nextNode()); + + } + stream_INT.reset(); + + adaptor.addChild(root_0, root_1); + } + + } + + retval.tree = root_0; + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "variable" + + public static class varid_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "varid" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:69:1: varid : ( X | Y | Z | U | V | W ); + public final UnificationSetParser.varid_return varid() throws RecognitionException { + UnificationSetParser.varid_return retval = new UnificationSetParser.varid_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token set30=null; + + CommonTree set30_tree=null; + + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:69:7: ( X | Y | Z | U | V | W ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g: + { + root_0 = (CommonTree)adaptor.nil(); + + set30=(Token)input.LT(1); + if ( (input.LA(1)>=X && input.LA(1)<=W) ) { + input.consume(); + adaptor.addChild(root_0, (CommonTree)adaptor.create(set30)); + state.errorRecovery=false; + } + else { + MismatchedSetException mse = new MismatchedSetException(null,input); + throw mse; + } + + + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "varid" + + public static class ws_return extends ParserRuleReturnScope { + CommonTree tree; + public Object getTree() { return tree; } + }; + + // $ANTLR start "ws" + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:71:1: ws : ( WS )? ; + public final UnificationSetParser.ws_return ws() throws RecognitionException { + UnificationSetParser.ws_return retval = new UnificationSetParser.ws_return(); + retval.start = input.LT(1); + + CommonTree root_0 = null; + + Token WS31=null; + + CommonTree WS31_tree=null; + + try { + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:71:5: ( ( WS )? ) + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:71:7: ( WS )? + { + root_0 = (CommonTree)adaptor.nil(); + + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:71:7: ( WS )? + int alt8=2; + int LA8_0 = input.LA(1); + + if ( (LA8_0==WS) ) { + alt8=1; + } + switch (alt8) { + case 1 : + // C:\\Users\\Alex\\Desktop\\java\\unifikationset\\UnificationSet.g:71:7: WS + { + WS31=(Token)match(input,WS,FOLLOW_WS_in_ws389); + WS31_tree = (CommonTree)adaptor.create(WS31); + adaptor.addChild(root_0, WS31_tree); + + + } + break; + + } + + + } + + retval.stop = input.LT(-1); + + retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); + adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); + + } + catch (RecognitionException re) { + reportError(re); + recover(input,re); + retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); + + } + finally { + } + return retval; + } + // $ANTLR end "ws" + + // Delegated rules + + + + + public static final BitSet FOLLOW_set_in_unificationset177 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_STARTSET_in_set185 = new BitSet(new long[]{0x0000000000004000L}); + public static final BitSet FOLLOW_OPENBRACE_in_set187 = new BitSet(new long[]{0x0000000008008400L}); + public static final BitSet FOLLOW_ws_in_set189 = new BitSet(new long[]{0x0000000000008400L}); + public static final BitSet FOLLOW_pair_in_set192 = new BitSet(new long[]{0x000000000800A000L}); + public static final BitSet FOLLOW_ws_in_set196 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_COMMA_in_set198 = new BitSet(new long[]{0x0000000008000400L}); + public static final BitSet FOLLOW_ws_in_set200 = new BitSet(new long[]{0x0000000000000400L}); + public static final BitSet FOLLOW_pair_in_set202 = new BitSet(new long[]{0x000000000800A000L}); + public static final BitSet FOLLOW_ws_in_set206 = new BitSet(new long[]{0x0000000000008000L}); + public static final BitSet FOLLOW_CLOSEBRACE_in_set210 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_LBRACKET_in_pair227 = new BitSet(new long[]{0x000000000BF003F0L}); + public static final BitSet FOLLOW_ws_in_pair229 = new BitSet(new long[]{0x000000000BF003F0L}); + public static final BitSet FOLLOW_term_in_pair233 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_COMMA_in_pair235 = new BitSet(new long[]{0x000000000BF003F0L}); + public static final BitSet FOLLOW_term_in_pair239 = new BitSet(new long[]{0x0000000008000800L}); + public static final BitSet FOLLOW_ws_in_pair241 = new BitSet(new long[]{0x0000000000000800L}); + public static final BitSet FOLLOW_RBRACKET_in_pair243 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_constructor_in_term262 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_variable_in_term266 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_constructorsymbol_in_constructor277 = new BitSet(new long[]{0x0000000008000402L}); + public static final BitSet FOLLOW_ws_in_constructor280 = new BitSet(new long[]{0x0000000000000400L}); + public static final BitSet FOLLOW_LBRACKET_in_constructor282 = new BitSet(new long[]{0x000000000BF00BF0L}); + public static final BitSet FOLLOW_ws_in_constructor284 = new BitSet(new long[]{0x000000000BF00BF0L}); + public static final BitSet FOLLOW_term_in_constructor289 = new BitSet(new long[]{0x0000000008002800L}); + public static final BitSet FOLLOW_ws_in_constructor292 = new BitSet(new long[]{0x0000000000002000L}); + public static final BitSet FOLLOW_COMMA_in_constructor294 = new BitSet(new long[]{0x000000000BF003F0L}); + public static final BitSet FOLLOW_ws_in_constructor296 = new BitSet(new long[]{0x000000000BF003F0L}); + public static final BitSet FOLLOW_term_in_constructor301 = new BitSet(new long[]{0x0000000008002800L}); + public static final BitSet FOLLOW_ws_in_constructor305 = new BitSet(new long[]{0x0000000000000800L}); + public static final BitSet FOLLOW_RBRACKET_in_constructor309 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_set_in_constructorsymbol0 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_varid_in_variable350 = new BitSet(new long[]{0x0000000004000002L}); + public static final BitSet FOLLOW_INT_in_variable352 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_set_in_varid0 = new BitSet(new long[]{0x0000000000000002L}); + public static final BitSet FOLLOW_WS_in_ws389 = new BitSet(new long[]{0x0000000000000002L}); + +} \ No newline at end of file diff --git a/src/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.java b/src/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.java new file mode 100644 index 0000000..02969ff --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/UnificationSetParserErrorReporter.java @@ -0,0 +1,45 @@ +package org.jalgo.module.unifikation.parser; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.antlr.runtime.TokenStream; + +/** + * Extends generated parser to show and save errors + * @author Alex + * + */ +public class UnificationSetParserErrorReporter extends UnificationSetParser { + private List errors; + + public UnificationSetParserErrorReporter(TokenStream input) { + super(input); + errors=new LinkedList(); + } + + public UnificationSetParserErrorReporter(TokenStream input, RecognizerSharedState state) { + super(input, state); + errors=new LinkedList(); + } + + public void reportError(RecognitionException e) { + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if ( state.errorRecovery ) { + //System.err.print("[SPURIOUS] "); + return; + } + state.syntaxErrors++; // don't count spurious + state.errorRecovery = true; + + errors.add(e); + } + + public List getErrors() { + return errors; + } + +} diff --git a/src/org/jalgo/module/unifikation/parser/package-info.java b/src/org/jalgo/module/unifikation/parser/package-info.java new file mode 100644 index 0000000..5b8d4c0 --- /dev/null +++ b/src/org/jalgo/module/unifikation/parser/package-info.java @@ -0,0 +1,5 @@ +/** + * Parser for validating the user's input + */ + +package org.jalgo.module.unifikation.parser; diff --git a/src/org/jalgo/module/unifikation/res.properties b/src/org/jalgo/module/unifikation/res.properties new file mode 100644 index 0000000..8d14804 --- /dev/null +++ b/src/org/jalgo/module/unifikation/res.properties @@ -0,0 +1,8 @@ +HelpSet_Name=/help/jhelp/test_help.hs +Icon=/unifikation_pix/icon.jpg + +Icon.welcomeNew=/unifikation_pix/WelcomeNew.jpg +Icon.welcomeNewOver=/unifikation_pix/WelcomeNewHover.jpg +Icon.welcomeLoad=/unifikation_pix/WelcomeLoad.jpg +Icon.welcomeLoadOver=/unifikation_pix/WelcomeLoadHover.jpg +Icon.Editor=/unifikation_pix/pencilbutton.png